check-i18n-parity.mjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. // Verifies parity across locale files (en / de / fr / it / ja / pt-BR / zh-CN / zh-TW):
  2. // 1. Leaf-key sets are identical
  3. // 2. Each leaf's {{placeholder}} set is identical
  4. // 3. Plural suffixes: every en key ending in _plural / _one / _other must
  5. // exist in every other locale, and other locales must not introduce an
  6. // _one key that en does not have.
  7. // 4. NEW: leaves in a non-English locale must not be identical to en, unless
  8. // the value is a brand name / technical token / pure punctuation, OR the
  9. // key+locale pair is explicitly listed in IDENTICAL_TO_EN_ALLOWED below.
  10. // Catches the "copy English text into non-English locale to satisfy the
  11. // key-count parity gate" anti-pattern that accumulated 700+ shipped
  12. // strings of debt before the gate was tightened. Add an explicit entry
  13. // ONLY when the string is a real word/term in that target locale.
  14. // Malformed input (missing `export default`, parse errors, non-string leaves,
  15. // unsupported property kinds) fails loudly instead of silently passing the gate.
  16. // Exits 1 with a diagnostic report on any failure, else exits 0.
  17. import fs from 'node:fs';
  18. import path from 'node:path';
  19. import url from 'node:url';
  20. const scriptDir = path.dirname(url.fileURLToPath(import.meta.url));
  21. const frontendDir = path.resolve(scriptDir, '..');
  22. const localesDir = path.join(frontendDir, 'src/i18n/locales');
  23. const tsPath = path.join(frontendDir, 'node_modules/typescript/lib/typescript.js');
  24. const tsModule = await import(url.pathToFileURL(tsPath).href);
  25. const ts = tsModule.default ?? tsModule;
  26. function collectLeaves(node, prefix, leaves) {
  27. if (!ts.isObjectLiteralExpression(node)) return;
  28. for (const prop of node.properties) {
  29. if (!ts.isPropertyAssignment(prop)) {
  30. console.error(
  31. `Unsupported property kind ${ts.SyntaxKind[prop.kind]} at "${prefix}" ` +
  32. `(locale files must use plain \`key: value\` assignments — no spread, shorthand, methods, or accessors).`,
  33. );
  34. process.exit(1);
  35. }
  36. let name;
  37. if (ts.isIdentifier(prop.name)) name = prop.name.text;
  38. else if (ts.isStringLiteral(prop.name) || ts.isNoSubstitutionTemplateLiteral(prop.name)) name = prop.name.text;
  39. else if (ts.isComputedPropertyName(prop.name)) {
  40. console.error(`ComputedPropertyName not allowed in locale file at path "${prefix}"`);
  41. process.exit(1);
  42. } else {
  43. console.error(`Unsupported property-name kind ${ts.SyntaxKind[prop.name.kind]} at "${prefix}"`);
  44. process.exit(1);
  45. }
  46. const p = prefix ? `${prefix}.${name}` : name;
  47. if (ts.isObjectLiteralExpression(prop.initializer)) {
  48. collectLeaves(prop.initializer, p, leaves);
  49. } else {
  50. const value = extractStringValue(prop.initializer, p);
  51. leaves.set(p, value);
  52. }
  53. }
  54. }
  55. function extractStringValue(node, keyPath) {
  56. if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
  57. if (ts.isTemplateExpression(node)) {
  58. let out = node.head.text;
  59. for (const span of node.templateSpans) {
  60. out += '${' + span.expression.getText() + '}';
  61. out += span.literal.text;
  62. }
  63. return out;
  64. }
  65. console.error(
  66. `Non-string leaf at "${keyPath}" (kind=${ts.SyntaxKind[node.kind]}): ${node.getText()}\n` +
  67. `Locale files must only contain string or template literals as leaf values.`,
  68. );
  69. process.exit(1);
  70. }
  71. function loadLocale(filePath) {
  72. const src = fs.readFileSync(filePath, 'utf8');
  73. const sf = ts.createSourceFile(filePath, src, ts.ScriptTarget.Latest, true);
  74. if (sf.parseDiagnostics && sf.parseDiagnostics.length > 0) {
  75. console.error(`${filePath}: ${sf.parseDiagnostics.length} parse error(s):`);
  76. for (const d of sf.parseDiagnostics.slice(0, 10)) {
  77. const msg = typeof d.messageText === 'string' ? d.messageText : d.messageText.messageText;
  78. const { line, character } = sf.getLineAndCharacterOfPosition(d.start ?? 0);
  79. console.error(` ${line + 1}:${character + 1} ${msg}`);
  80. }
  81. process.exit(1);
  82. }
  83. const leaves = new Map();
  84. let foundExport = false;
  85. ts.forEachChild(sf, (n) => {
  86. if (ts.isExportAssignment(n)) {
  87. foundExport = true;
  88. collectLeaves(n.expression, '', leaves);
  89. }
  90. });
  91. if (!foundExport) {
  92. console.error(`${filePath}: no \`export default\` found — locale files must use \`export default { ... }\`.`);
  93. process.exit(1);
  94. }
  95. if (leaves.size === 0) {
  96. console.error(`${filePath}: \`export default\` resolved to zero leaves — file is empty or not a nested object.`);
  97. process.exit(1);
  98. }
  99. return leaves;
  100. }
  101. const placeholderRe = /\{\{[^{}]+\}\}/g;
  102. // Heuristic: values that are ALWAYS allowed to match en, regardless of locale.
  103. // Brand names, technical tokens, pure punctuation, very short strings, version
  104. // numbers, hex codes, and ALL-CAPS acronyms. Cognates that happen to be the
  105. // same word in a specific locale go in IDENTICAL_TO_EN_ALLOWED instead.
  106. function isAlwaysAllowedIdentical(value) {
  107. if (!value) return true;
  108. if (/^[\s\W_]+$/.test(value)) return true; // pure punctuation/whitespace
  109. if (value.length <= 2) return true; // single character or 2-char abbrev
  110. if (/^[A-Z][A-Z0-9_]+$/.test(value)) return true; // ALL_CAPS_TOKEN
  111. if (/^v?\d+(\.\d+)+/.test(value)) return true; // version-like
  112. if (/^#[0-9a-fA-F]{3,8}$/.test(value)) return true; // hex color
  113. if (/^\{\{[^}]+\}\}$/.test(value)) return true; // pure placeholder
  114. if (/^\{\{[^}]+\}\}([\s/\-–·,]+\{\{[^}]+\}\})+$/.test(value)) return true; // placeholders joined by punctuation only ({{a}} / {{b}})
  115. if (/^[0-9a-fA-F]{6}$/.test(value)) return true; // bare hex color
  116. if (/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(value)) return true; // email
  117. if (/^https?:\/\//.test(value)) return true; // URL
  118. if (/^ON,\s+true,\s+1$/.test(value)) return true; // literal example "ON, true, 1"
  119. // Brand / technical names that ship verbatim everywhere.
  120. if (/^(Bambuddy|BamBuddy|SpoolBuddy|Bambu Lab|Bambu Studio|Bambu Studio 2\.6\+|Bambu Studio sidecar URL|OrcaSlicer|OrcaSlicer sidecar URL|MakerWorld|Spoolman|\(Spoolman\)|Spoolman URL|Tailscale|GitHub|GitLab|Gitea|Forgejo|Discord|MQTT|FTP|HTTPS?|JSON|YAML|RTSP|TLS|SSL|CSRF|OIDC|SSO|SSO \/ OIDC|LDAP|TOTP|2FA|MFA|API|AMS|CRC|SHA256|SHA-256|kWh|MB|GB|KB|RGBA?|HSL|RGB|UTC|ISO|UI|HTTP|HTTP Method|H2D|H2D Pro|X1C|X1E|P1S|P1P|A1|A1 Mini|H2C|N3F|N3S|PETG|PLA|ABS|PA|TPU|PEI|PA-CF|PVA|HIPS|ASA|PC|PETG-HF|G\.code|G-code|gcode|cm³|°C|°F|GCODE|SOURCE|ntfy|Pushover|Telegram|Webhook|Webhook URL|Home Assistant|Home Assistant URL|CallMeBot\/WhatsApp|Bambuddy URL|Cool Plate|Cool Plate SuperTack|Engineering Plate|High Temp Plate|Smooth PEI Plate|Textured PEI Plate|Ext-L|Ext-R|ISO \(YYYY-MM-DD\))$/.test(value)) return true;
  121. return false;
  122. }
  123. // Per-(locale, value) allow-list for strings that are a real word/term in
  124. // that target locale and so legitimately match en.ts. Curated — add an entry
  125. // here ONLY after verifying that the word is correct (not just a shortcut to
  126. // silence the check).
  127. //
  128. // Convention: same shape as the locales themselves — { de: Set, fr: Set, ... }.
  129. // Values are matched exactly. To allow a value across many locales, list it in
  130. // each one (verbosity is the point: every locale's allow-list is an explicit
  131. // translator decision).
  132. // German loanwords / cognates from English are extensive. Most short technical
  133. // UI labels are identical in DE. List below curates the legitimate ones.
  134. const DE_COGNATES = [
  135. 'Name', 'Status', 'Tag', 'Tags', 'Online', 'Offline', 'Standard', 'Modus',
  136. 'Stop', 'Reset', 'Test', 'Code', 'Token', 'Server', 'Port', 'Bug', 'Job',
  137. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  138. 'AMS Filament Backup', // Bambu Lab product/firmware feature name
  139. 'Pause', 'Power', 'System', 'Problem', 'Designer', 'Extruder', 'Firmware',
  140. 'Material', 'Original', 'Position', 'Webhook', 'Workflow', 'Slicer',
  141. 'Pipeline', 'Pipelines', 'Filament {{n}}', // #1425 — Slicer Pipelines (DE)
  142. 'parallel', // #1425 PR C polish — "parallel" is the same word in German
  143. 'Region', 'Normal', 'Orange', 'Branch', 'Budget', 'Commit', 'Global',
  144. 'Version', 'Slot', 'Live', 'Rate', 'Host', 'Trend', 'Min', 'Admin', 'Cloud',
  145. 'Filament', 'Filaments', 'Software', 'Hardware', 'Avatar', 'Pin', 'Modal',
  146. 'Active', 'Plate', 'Layer', 'Total', 'Plus', 'Pro', 'Mini', 'Studio',
  147. 'Temperatur', 'Process', 'Service', 'Cache', 'Color', 'Login', 'Logout',
  148. 'Action', 'Description', 'Sender', 'Setup', 'Bundle', 'Cluster', 'Tier',
  149. 'Standard (100%)', 'Sport (124%)', 'Ludicrous (166%)',
  150. 'Smart Plugs', 'Smart Switches', 'Smart Plug', 'High Flow',
  151. 'Optional', 'optional', 'Filter', 'Filters', 'optional)',
  152. 'Material:', 'Default:', 'Name *', '(System)', '(Inv)',
  153. 'Spoolman URL', 'Bundle', 'Slicer Bundles', 'Imported',
  154. 'STARTTLS (Port 587)', 'SSL/TLS (Port 465)', 'Sport', 'Standard',
  155. 'EC984C,#6CD4BC,A66EB9,D87694',
  156. 'Hex', 'Warm', 'Neutral', 'Navigation', 'Screenshot', 'Architecture',
  157. 'Backend & Auth', 'Stream Overlay', 'Bambuddy Backend URL',
  158. 'Material (optional)', 'Custom Headers (JSON)', '({{count}}/8)',
  159. 'Box label (62 × 29 mm)',
  160. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  161. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  162. 'China', 'Proxy', 'Start',
  163. 'Diagnose', // DE: same spelling/meaning as EN — camera diagnostic button label
  164. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  165. ];
  166. // French cognates — many UI labels overlap with English exactly.
  167. const FR_COGNATES = [
  168. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  169. 'AMS Filament Backup', // Bambu Lab product/firmware feature name
  170. 'Status', 'Tag', 'Tags', 'Online', 'Offline', 'Standard', 'Filament',
  171. 'Filaments', 'Software', 'Hardware', 'Stop', 'Reset', 'Test', 'Code',
  172. 'Token', 'Server', 'Port', 'Plate', 'Layer', 'Active', 'Total', 'Avatar',
  173. 'Job', 'Modal', 'Pin', 'Pro', 'Mini', 'Studio', 'Excellent', 'Description',
  174. 'Pipeline', 'Pipelines', 'Filament {{n}}', // #1425 — Slicer Pipelines (FR)
  175. 'Copies', '{{n}} copies', 'max {{n}}', // #1425 PR C — French uses these forms verbatim
  176. 'round robin', // borrowed English term used as-is in French tech contexts
  177. 'Action', 'Actions', 'Date', 'Type', 'Cache', 'Service', 'Configuration',
  178. 'Archives', 'Maintenance', 'Notifications', 'Notification', 'Position',
  179. 'Pause', 'Solution', 'Source', 'Version', 'Format', 'Documentation',
  180. 'Mode', 'Format', 'Default', 'Auto', 'Image', 'Audio', 'Video', 'Hex',
  181. 'Camera', 'Avatar', 'Information', 'Initialization', 'Inactive', 'Active',
  182. 'Print', 'Console', 'Cluster', 'Tier', 'Status URL',
  183. 'Smart Plugs', 'Smart Switches', 'Smart Plug', 'High Flow',
  184. 'Material:', 'Default:', 'Name *', '(System)', '(Inv)',
  185. 'Process', 'Service', 'Service', 'Connect', 'Network', 'Local',
  186. 'Sport (124%)', 'Ludicrous (166%)', 'Standard (100%)',
  187. 'STARTTLS (Port 587)', 'SSL/TLS (Port 465)',
  188. 'Bundle', 'Slicer Bundles', 'Imported',
  189. 'Page', 'Note', 'Tare', 'Est.', 'Cloud', 'Style', 'Notes', 'Stock',
  190. 'Accent', 'Orange', 'Global', 'Stable', 'Archive', 'visible', 'minutes',
  191. 'Message', 'Slicer', 'Rotation', 'Original', 'Direction', 'Architecture',
  192. 'notifications', 'Maintenance OK', 'total', 'Provider', 'Token name',
  193. '{{count}} filament', '{{count}} filaments', '{{count}} permissions',
  194. '{{count}} downloads', '{{count}} item', '{{count}} selected',
  195. '({{count}} item)', 'Provisioning...', 'Pressure Advance',
  196. '{{name}} ({{count}} copies)', // FR plural of "copie" is also "copies"
  197. 'Box label (62 × 29 mm)',
  198. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  199. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  200. '({{count}}/8)', 'Custom Headers (JSON)', 'Permissions',
  201. 'Expand dispatch details', 'Collapse dispatch details',
  202. 'Cancelling upload...', 'Backup in progress...', 'Searching directory...',
  203. 'EC984C,#6CD4BC,A66EB9,D87694',
  204. 'Proxy', 'Navigation', 'Budget', 'Commit', 'Designer',
  205. 'Compact', // cam-wall status overlay mode — same word in French
  206. 'ntfy, Pushover, Discord, etc.',
  207. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  208. ];
  209. // Italian cognates.
  210. const IT_COGNATES = [
  211. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  212. 'AMS Filament Backup', // Bambu Lab product/firmware feature name
  213. 'Email', // common loanword in Italian, used verbatim in UI labels
  214. 'Pipeline', 'slicing', // #1425 — Slicer Pipelines (cognate in IT)
  215. 'max {{n}}', // #1425 PR C — same form in Italian (max + number)
  216. 'round robin', // borrowed English term used as-is in Italian tech contexts
  217. 'Status', 'Tag', 'Tags', 'Online', 'Offline', 'Standard', 'Filament',
  218. 'Filaments', 'Software', 'Hardware', 'Stop', 'Reset', 'Test', 'Code',
  219. 'Token', 'Server', 'Port', 'Plate', 'Layer', 'Modal', 'Pin', 'Pro', 'Mini',
  220. 'Studio', 'Cache', 'Service', 'Avatar', 'Slicer', 'Action', 'Actions',
  221. 'Format', 'Modal', 'Login', 'Logout', 'Color', 'Plus', 'Job', 'Live',
  222. 'Position', 'Original', 'Material', 'Cluster', 'Tier', 'Auto', 'Hex',
  223. 'Bundle', 'Slicer Bundles', 'Imported', 'Smart Plugs', 'Smart Switches',
  224. 'Smart Plug', 'High Flow', 'Sport (124%)', 'Ludicrous (166%)',
  225. 'Standard (100%)', 'STARTTLS (Port 587)', 'SSL/TLS (Port 465)',
  226. 'Slot', 'Host', 'File', 'Cloud', 'Admin', 'Silk', '(Inv)', 'Slice',
  227. 'Backup', 'Legacy', 'Branch', 'Auto On', 'Display', 'Password',
  228. 'Auto Off', 'Dashboard', 'Timestamp', 'Pressure Advance', 'Provisioning...',
  229. '(25%, 50%, 75%)', 'Provider', 'Provider: {{type}}', 'Base: {{name}}',
  230. 'Slicing…', 'Designer', 'Firmware', 'Timelapse', 'Commit', 'Budget',
  231. '({{count}}/8)', 'Custom Headers (JSON)', 'ETA {{minutes}} min',
  232. '{{name}} - Timelapse', 'Box label (62 × 29 mm)',
  233. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  234. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  235. 'Hex: #{{hex}}',
  236. 'EC984C,#6CD4BC,A66EB9,D87694',
  237. 'Proxy', 'Designer',
  238. 'Off', // cam-wall status overlay mode — common loanword in Italian UI
  239. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  240. ];
  241. // Japanese: very few cognates because of script difference. Almost
  242. // everything needs translation. Only true loanwords / proper nouns stay.
  243. const JA_COGNATES = [
  244. 'OK', 'Bambu', 'Code',
  245. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  246. 'EU (DD/MM/YYYY)', 'US (MM/DD/YYYY)', 'ON, true, 1',
  247. '({{count}}/8)', 'Custom Headers (JSON)',
  248. 'Box label (62 × 29 mm)',
  249. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  250. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  251. 'EC984C,#6CD4BC,A66EB9,D87694',
  252. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  253. ];
  254. // Portuguese (BR) cognates.
  255. const PT_BR_COGNATES = [
  256. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  257. 'AMS Filament Backup', // Bambu Lab product/firmware feature name
  258. 'Pipeline', 'Pipelines', // #1425 — Slicer Pipelines (PT-BR)
  259. 'round robin', // borrowed English term used as-is in Portuguese tech contexts
  260. 'Status', 'Tag', 'Tags', 'Online', 'Offline', 'Standard', 'Filament',
  261. 'Software', 'Hardware', 'Stop', 'Reset', 'Test', 'Code', 'Token', 'Server',
  262. 'Port', 'Plate', 'Layer', 'Modal', 'Pin', 'Pro', 'Mini', 'Studio', 'Cache',
  263. 'Service', 'Avatar', 'Total', 'Active', 'Login', 'Logout', 'Color', 'Hex',
  264. 'Slot', 'Live', 'Rate', 'Host', 'Trend', 'Original', 'Auto', 'Bundle',
  265. 'Imported', 'Action', 'Actions', 'Slicer Bundles', 'Sport (124%)',
  266. 'Ludicrous (166%)', 'Standard (100%)', 'STARTTLS (Port 587)',
  267. 'SSL/TLS (Port 465)', 'Smart Plugs', 'Smart Switches', 'High Flow',
  268. 'Position', 'Mode', 'Setup', 'Modal',
  269. 'Local', 'Metal', 'China', 'Admin', 'Silk', 'Backup', '(Inv)', 'Branch',
  270. 'Normal', 'Material', 'Material:', 'Multicolor', 'Designer', 'Firmware',
  271. 'Timelapse', 'Est.', 'total', 'Commit', 'Global',
  272. 'Base: {{name}}', 'ETA {{minutes}} min', '{{count}} item',
  273. '{{count}} downloads', '({{count}} item)', '(25%, 50%, 75%)',
  274. '({{count}}/8)', 'Custom Headers (JSON)', '{{name}} - Timelapse',
  275. 'Box label (62 × 29 mm)',
  276. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  277. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  278. 'Cancelling upload...', 'EC984C,#6CD4BC,A66EB9,D87694',
  279. 'Expand dispatch details', 'Collapse dispatch details',
  280. 'e.g., Home Assistant, OctoPrint', 'ntfy, Pushover, Discord, etc.',
  281. 'Proxy', 'total: {{minutes}} min',
  282. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  283. ];
  284. // Chinese (Simplified): very few cognates beyond brand names.
  285. const ZH_CN_COGNATES = [
  286. 'OK', 'Bambu',
  287. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  288. '({{count}}/8)', 'Custom Headers (JSON)',
  289. 'Box label (62 × 29 mm)',
  290. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  291. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  292. 'EC984C,#6CD4BC,A66EB9,D87694',
  293. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  294. ];
  295. const ZH_TW_COGNATES = [
  296. 'OK', 'Bambu',
  297. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  298. '({{count}}/8)', 'Custom Headers (JSON)',
  299. 'Box label (62 × 29 mm)',
  300. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  301. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  302. 'EC984C,#6CD4BC,A66EB9,D87694',
  303. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  304. ];
  305. // Korean: script difference means almost nothing is identical.
  306. // Allow loanwords/acronyms, format strings, and proper nouns that stay verbatim.
  307. const KO_COGNATES = [
  308. 'OK', 'Bambu', 'N/A',
  309. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  310. '({{count}}/8)', '(25%, 50%, 75%)',
  311. 'Custom Headers (JSON)',
  312. 'Box label (62 × 29 mm)',
  313. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  314. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  315. 'EC984C,#6CD4BC,A66EB9,D87694',
  316. '{{weight}}g', // unit suffix format string
  317. 'MakerWorld: {{designer}}', // brand + placeholder
  318. 'email', // OIDC claim name placeholder
  319. '{{printer}}: {{error}}', // pure placeholders
  320. '{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}', // pure placeholders
  321. 'Obico ML API URL', // product name (Obico)
  322. '{{filament}} @ {{temp}}°C', // drying badge format
  323. ];
  324. // Spanish cognates — words/phrases that are genuinely identical in Spanish.
  325. const ES_COGNATES = [
  326. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  327. 'AMS Filament Backup', // Bambu Lab product/firmware feature name
  328. 'Pipeline', 'Pipelines', // #1425 — Slicer Pipelines (ES)
  329. 'round robin', // borrowed English term used as-is in Spanish tech contexts
  330. 'Error', 'Firmware', 'General', 'Control', 'Total', 'total', 'Material',
  331. 'Material:', 'Color', 'Hex', 'Local', 'Global', 'China', 'Editable',
  332. 'Normal', 'Metal', 'Multicolor', 'Proxy', 'Host', 'Factor', 'Original',
  333. 'Sport (124%)', 'Ludicrous (166%)', 'MakerWorld: {{designer}}',
  334. '{{printer}}: {{error}}', 'Base: {{name}}',
  335. '{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}', 'total: {{minutes}} min',
  336. '({{count}}/8)', 'Hex: #{{hex}}', '(25%, 50%, 75%)',
  337. 'EC984C,#6CD4BC,A66EB9,D87694', 'Est.',
  338. 'ntfy, Pushover, Discord, etc.',
  339. 'Box label (62 × 29 mm)',
  340. 'Avery L7160 — A4 sheet (38.1 × 63.5 mm × 21)',
  341. 'Avery 5160 — US Letter sheet (25.4 × 66.7 mm × 30)',
  342. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  343. ];
  344. // Turkish cognates — technical UI labels that Turkish speakers use verbatim
  345. // from English (loanwords + acronyms + format strings). Curated, not a shortcut.
  346. const TR_COGNATES = [
  347. 'Filament', 'Firmware', 'Disk', 'Hex', 'Test', 'Port', 'Model', 'Metal',
  348. 'Bambu Cloud', 'Orca Cloud', // brand names — same in every locale
  349. 'AMS Filament Backup', // Bambu Lab product/firmware feature name
  350. 'Pipeline', 'Filament {{n}}', // #1425 — Slicer Pipelines (TR)
  351. 'Min', 'Normal', 'Platform', 'Net', 'Trend', 'Commit', 'Global', 'Proxy',
  352. 'N/A', 'email',
  353. 'STARTTLS (Port 587)', 'SSL/TLS (Port 465)',
  354. '({{count}}/8)', 'Hex: #{{hex}}', 'MakerWorld: {{designer}}',
  355. '{{count}} filament', '{{printer}}: {{error}}', '{{weight}}g',
  356. 'Filament {{index}} ({{type}})',
  357. 'EC984C,#6CD4BC,A66EB9,D87694',
  358. '{{filament}} @ {{temp}}°C', // drying badge: filament code + universal °C
  359. ];
  360. const IDENTICAL_TO_EN_ALLOWED = {
  361. de: new Set(DE_COGNATES),
  362. fr: new Set(FR_COGNATES),
  363. it: new Set(IT_COGNATES),
  364. ja: new Set(JA_COGNATES),
  365. ko: new Set(KO_COGNATES),
  366. es: new Set(ES_COGNATES),
  367. 'pt-BR': new Set(PT_BR_COGNATES),
  368. 'zh-CN': new Set(ZH_CN_COGNATES),
  369. 'zh-TW': new Set(ZH_TW_COGNATES),
  370. tr: new Set(TR_COGNATES),
  371. };
  372. // Pure comparison logic, exported so tests can verify each failure mode
  373. // without going through file IO or the TypeScript parser.
  374. // Input: locales = { code: Map<leafKey, leafString> } (must contain 'en')
  375. // Output: { failed, reports: Array<{ label, items }> }
  376. export function compareLocales(locales) {
  377. if (!locales.en) throw new Error("compareLocales requires a locales.en entry");
  378. const reports = [];
  379. const add = (label, items) => {
  380. if (items.length) reports.push({ label, items });
  381. };
  382. const enKeys = new Set(locales.en.keys());
  383. // Check 1: key set equality
  384. for (const [code, map] of Object.entries(locales)) {
  385. if (code === 'en') continue;
  386. const keys = new Set(map.keys());
  387. const missing = [...enKeys].filter((k) => !keys.has(k)).sort();
  388. const extra = [...keys].filter((k) => !enKeys.has(k)).sort();
  389. add(`${code}: missing keys vs en`, missing);
  390. add(`${code}: extra keys vs en`, extra);
  391. }
  392. // Check 2: placeholder set equality per leaf
  393. for (const [code, map] of Object.entries(locales)) {
  394. if (code === 'en') continue;
  395. const mismatches = [];
  396. for (const [key, enValue] of locales.en) {
  397. const otherValue = map.get(key);
  398. if (otherValue === undefined) continue;
  399. const enPlaceholders = new Set((enValue.match(placeholderRe) ?? []));
  400. const otherPlaceholders = new Set((otherValue.match(placeholderRe) ?? []));
  401. const missingPh = [...enPlaceholders].filter((p) => !otherPlaceholders.has(p));
  402. const extraPh = [...otherPlaceholders].filter((p) => !enPlaceholders.has(p));
  403. if (missingPh.length || extraPh.length) {
  404. mismatches.push(`${key}: en=${[...enPlaceholders].join(',') || '∅'} vs ${code}=${[...otherPlaceholders].join(',') || '∅'}`);
  405. }
  406. }
  407. add(`${code}: placeholder mismatch vs en`, mismatches);
  408. }
  409. // Check 3: plural suffix presence + reverse _one guard
  410. for (const [code, map] of Object.entries(locales)) {
  411. if (code === 'en') continue;
  412. const pluralIssues = [];
  413. for (const key of enKeys) {
  414. if (key.endsWith('_plural') && !map.has(key)) pluralIssues.push(`missing _plural key: ${key}`);
  415. if (key.endsWith('_one') && !map.has(key)) pluralIssues.push(`missing _one key: ${key}`);
  416. if (key.endsWith('_other') && !map.has(key)) pluralIssues.push(`missing _other key: ${key}`);
  417. }
  418. for (const key of map.keys()) {
  419. if (key.endsWith('_one') && !enKeys.has(key)) {
  420. pluralIssues.push(`unexpected _one not present in en: ${key}`);
  421. }
  422. }
  423. add(`${code}: plural key mismatch`, pluralIssues);
  424. }
  425. // Check 4: identical-to-en leaks. A non-English leaf whose value exactly
  426. // matches en.ts must either pass the always-allowed heuristic OR be listed
  427. // in IDENTICAL_TO_EN_ALLOWED[code]. Otherwise it's almost certainly an
  428. // untranslated English string that slipped through past parity gates.
  429. for (const [code, map] of Object.entries(locales)) {
  430. if (code === 'en') continue;
  431. const allowed = IDENTICAL_TO_EN_ALLOWED[code] ?? new Set();
  432. const leaks = [];
  433. for (const [key, enValue] of locales.en) {
  434. const localeValue = map.get(key);
  435. if (localeValue === undefined) continue;
  436. if (localeValue !== enValue) continue;
  437. if (isAlwaysAllowedIdentical(enValue)) continue;
  438. if (allowed.has(enValue)) continue;
  439. const preview = enValue.length > 60 ? `${enValue.slice(0, 57)}...` : enValue;
  440. leaks.push(`${key}: "${preview}"`);
  441. }
  442. add(`${code}: leaves identical to en (untranslated?)`, leaks);
  443. }
  444. return { failed: reports.length > 0, reports };
  445. }
  446. // en is the reference locale; every other locale discovered in the locales
  447. // directory is checked identically and a drift in any of them fails CI.
  448. // Skip file IO / process.exit when imported as a library (e.g. from tests).
  449. const isMainModule = import.meta.url === url.pathToFileURL(process.argv[1] ?? '').href;
  450. if (isMainModule) {
  451. const discovered = fs
  452. .readdirSync(localesDir)
  453. .filter((f) => f.endsWith('.ts'))
  454. .map((f) => f.slice(0, -3))
  455. .sort();
  456. if (!discovered.includes('en')) {
  457. console.error(`No en.ts found in ${localesDir} — cannot run parity check without a reference locale.`);
  458. process.exit(1);
  459. }
  460. const codes = ['en', ...discovered.filter((c) => c !== 'en')];
  461. const locales = Object.fromEntries(
  462. codes.map((c) => [c, loadLocale(path.join(localesDir, `${c}.ts`))]),
  463. );
  464. const MAX_REPORT = 20;
  465. const { reports } = compareLocales(locales);
  466. if (reports.length) {
  467. console.error(`\n=== Locale parity failures (en is the reference) ===`);
  468. for (const { label, items } of reports) {
  469. console.error(`\n[${label}] (${items.length})`);
  470. items.slice(0, MAX_REPORT).forEach((i) => console.error(` ${i}`));
  471. if (items.length > MAX_REPORT) console.error(` ... and ${items.length - MAX_REPORT} more`);
  472. }
  473. }
  474. console.log('\nLocale leaf counts:');
  475. for (const [code, map] of Object.entries(locales)) {
  476. const tier = code === 'en' ? 'ref' : 'locale';
  477. console.log(` ${code.padEnd(6)} ${String(map.size).padEnd(6)} [${tier}]`);
  478. }
  479. if (reports.length > 0) {
  480. console.error(`\n❌ i18n parity check failed.`);
  481. process.exit(1);
  482. }
  483. const others = codes.filter((c) => c !== 'en');
  484. console.log(`\n✓ All locales in parity with en (${others.join(' / ')}).`);
  485. }