@babelize/engine 0.3.5 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/config.d.ts +14 -58
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.js +11 -1
  4. package/dist/local/hosted-provider.js +1 -0
  5. package/dist/local/translate-core.d.ts +13 -2
  6. package/dist/local/translate-core.js +27 -9
  7. package/dist/local/translate-messages.d.ts +5 -0
  8. package/dist/local/translate-messages.js +1 -1
  9. package/dist/modules/finalization/nextjs-finalize.d.ts +19 -2
  10. package/dist/modules/finalization/nextjs-finalize.js +46 -4
  11. package/dist/modules/injection/inject.js +46 -1
  12. package/dist/modules/locale-builder/adopted.d.ts +29 -2
  13. package/dist/modules/locale-builder/adopted.js +185 -16
  14. package/dist/modules/locale-builder/locales.js +11 -2
  15. package/dist/modules/locale-builder/message-modules.d.ts +40 -0
  16. package/dist/modules/locale-builder/message-modules.js +263 -0
  17. package/dist/modules/lockfile/schema.d.ts +5 -157
  18. package/dist/modules/translator/client/byok.provider.js +8 -2
  19. package/dist/modules/translator/formality.d.ts +40 -0
  20. package/dist/modules/translator/formality.js +313 -0
  21. package/dist/modules/translator/translate.d.ts +18 -0
  22. package/dist/modules/translator/translate.js +78 -11
  23. package/dist/modules/workspace/existing-setup.d.ts +3 -1
  24. package/dist/modules/workspace/existing-setup.js +32 -15
  25. package/dist/orchestrator.js +51 -7
  26. package/dist/providers/default-translation-provider.js +2 -2
  27. package/dist/providers/types.d.ts +5 -0
  28. package/dist/qa/check-project.d.ts +7 -0
  29. package/dist/qa/check-project.js +12 -2
  30. package/dist/qa/locale-files.d.ts +8 -5
  31. package/dist/qa/locale-files.js +37 -9
  32. package/dist/qa/locale-qa.d.ts +10 -1
  33. package/dist/qa/locale-qa.js +9 -0
  34. package/dist/qa/review.js +1 -1
  35. package/dist/runtime/types.d.ts +21 -1
  36. package/dist/types.d.ts +2 -0
  37. package/dist/utils/translator-caller.d.ts +19 -0
  38. package/dist/utils/translator-caller.js +55 -21
  39. package/package.json +3 -3
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FALLBACK_QA_WARNING = void 0;
4
+ exports.effectiveFormality = effectiveFormality;
5
+ exports.rulesFingerprint = rulesFingerprint;
4
6
  exports.loadProjectTranslationRules = loadProjectTranslationRules;
5
7
  exports.translateLocales = translateLocales;
6
8
  exports.backfillTranslationMemory = backfillTranslationMemory;
@@ -25,6 +27,7 @@ const glossary_match_1 = require("../../utils/glossary-match");
25
27
  const icu_spans_1 = require("../../utils/icu-spans");
26
28
  const icu_branches_1 = require("./icu-branches");
27
29
  const budget_1 = require("./budget");
30
+ const formality_1 = require("./formality");
28
31
  const BATCH_SIZE = 15;
29
32
  /** QA note on keys the backup (NLLB) translator produced. */
30
33
  exports.FALLBACK_QA_WARNING = 'translated with the backup translator; will be retried with the AI translator next run';
@@ -36,6 +39,23 @@ const TRANSLATE_CONCURRENCY = 3; // Max concurrent locales/batches
36
39
  * many sentences (the translator service's batch limit).
37
40
  */
38
41
  const BRANCH_BATCH_SIZE = 50;
42
+ /** The form of address translations into `locale` use: configured, else detected, else auto (undefined). */
43
+ function effectiveFormality(rules, locale) {
44
+ return (0, formality_1.formalityFor)(rules.formality, locale) ?? rules.detectedFormality?.[locale];
45
+ }
46
+ /**
47
+ * The lockfile fingerprint of the project rules a translation was made
48
+ * under: the glossary's, plus the configured form of address. A key is
49
+ * re-translated when it changes. Auto adds nothing, so projects without a
50
+ * formality setting keep their fingerprints.
51
+ */
52
+ function rulesFingerprint(source, locale, rules) {
53
+ const glossary = (0, glossary_1.glossaryFingerprint)(source, locale, rules.glossary);
54
+ const formality = (0, formality_1.formalityFor)(rules.formality, locale);
55
+ if (!formality)
56
+ return glossary;
57
+ return glossary ? `${glossary}:${formality}` : formality;
58
+ }
39
59
  /**
40
60
  * A plain source whose stored translation is ICU only fits a project whose
41
61
  * runtime formats ICU. A stored ICU translation stored before a check it now
@@ -151,6 +171,7 @@ function hasMixedScripts(text) {
151
171
  async function loadProjectTranslationRules(projectId, rules) {
152
172
  let glossary = glossary_1.EMPTY_GLOSSARY;
153
173
  let brandVoice = null;
174
+ let formality = null;
154
175
  let complete = true;
155
176
  if (!rules)
156
177
  return { glossary, brandVoice, complete };
@@ -184,7 +205,31 @@ async function loadProjectTranslationRules(projectId, rules) {
184
205
  complete = false;
185
206
  logger_1.engineLogger.warn('Failed to load brand voice', { error: err });
186
207
  }
187
- return { glossary, brandVoice, complete };
208
+ if (rules.getFormality) {
209
+ try {
210
+ formality = await rules.getFormality(projectId);
211
+ if (formality && Object.keys(formality).length > 0)
212
+ logger_1.engineLogger.info('Formality configured', { formality });
213
+ }
214
+ catch (err) {
215
+ complete = false;
216
+ logger_1.engineLogger.warn('Failed to load formality settings', { error: err });
217
+ }
218
+ }
219
+ return { glossary, brandVoice, ...(formality ? { formality } : {}), complete };
220
+ }
221
+ /**
222
+ * The rules of a run without a cloud project (CLI/MCP, no projectId):
223
+ * `.babelize/config.json` `glossary`, `brandVoice` and `formality`.
224
+ */
225
+ async function loadWorkspaceRules(workspacePath) {
226
+ const config = await (0, check_project_1.readProjectLocaleConfig)(workspacePath).catch(() => ({}));
227
+ return {
228
+ glossary: await loadWorkspaceGlossary(workspacePath),
229
+ brandVoice: config.brandVoice ?? null,
230
+ ...(config.formality ? { formality: config.formality } : {}),
231
+ complete: true,
232
+ };
188
233
  }
189
234
  /**
190
235
  * The glossary of a run without a cloud project (CLI/MCP, no projectId):
@@ -239,7 +284,7 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
239
284
  const rules = options.rules
240
285
  ?? (projectId
241
286
  ? await loadProjectTranslationRules(projectId, providers.rules)
242
- : { glossary: await loadWorkspaceGlossary(workspace.path), brandVoice: null, complete: true });
287
+ : await loadWorkspaceRules(workspace.path));
243
288
  const glossary = rules.glossary;
244
289
  const neverTranslateTerms = glossary.neverTranslate;
245
290
  const brandVoice = rules.brandVoice;
@@ -295,7 +340,7 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
295
340
  // LLM translators (BYOK, or an injected one such as Babelize-hosted)
296
341
  // take the brand voice in the prompt; NLLB output is polished after.
297
342
  const hasBrandVoiceInPrompt = !!((byokConfig || (providers.translator && !providers.translator.plainText)) && brandVoice);
298
- const translationResult = await translateEntries(entriesToTranslate, sourceLangCode, targetLangCode, projectId, onProgress, glossary, targetLocale, cacheProvider, byokConfig, contextMap, extractionContextMap, hasBrandVoiceInPrompt ? (brandVoice || undefined) : undefined, dryRun, forceTranslation, providers, rulesComplete, options, claimBudget);
343
+ const translationResult = await translateEntries(entriesToTranslate, sourceLangCode, targetLangCode, projectId, onProgress, glossary, targetLocale, cacheProvider, byokConfig, contextMap, extractionContextMap, hasBrandVoiceInPrompt ? (brandVoice || undefined) : undefined, dryRun, forceTranslation, providers, rulesComplete, options, claimBudget, effectiveFormality(rules, targetLocale), (0, formality_1.formalityFor)(rules.formality, targetLocale));
299
344
  const entriesResult = translationResult.result;
300
345
  const batchStats = translationResult.stats;
301
346
  const batchMetadata = translationResult.metadata;
@@ -363,7 +408,10 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
363
408
  };
364
409
  // gettext catalogues are merged into the existing .po files once the
365
410
  // whole run's translations are known (see django/catalog.ts).
366
- if (!dryRun && workspace.localeFormat !== 'po')
411
+ // An adopted folder-per-locale setup (#370) has no <locale>.json: the
412
+ // orchestrator writes its files once the run's values are merged.
413
+ const folderLayout = !!workspace.existingSetup?.layout && workspace.existingSetup.layout !== 'flat';
414
+ if (!dryRun && workspace.localeFormat !== 'po' && !folderLayout)
367
415
  await (0, file_utils_1.writeJsonFile)(targetPath, translatedData, true);
368
416
  return {
369
417
  locale: targetLocale,
@@ -422,13 +470,23 @@ async function translateLocales(workspace, sourceLocale, targetLocales, forceTra
422
470
  metadata: perLocaleMetadata
423
471
  };
424
472
  }
425
- async function translateEntries(entries, sourceLang, targetLang, projectId, onProgress, glossary = glossary_1.EMPTY_GLOSSARY, targetLocale = '', cacheProvider, byokConfig, contextMap, extractionContextMap, brandVoice, dryRun = false, forceTranslation = false, providers = {}, rulesComplete = true, options = {}, claimBudget) {
473
+ async function translateEntries(entries, sourceLang, targetLang, projectId, onProgress, glossary = glossary_1.EMPTY_GLOSSARY, targetLocale = '', cacheProvider, byokConfig, contextMap, extractionContextMap, brandVoice, dryRun = false, forceTranslation = false, providers = {}, rulesComplete = true, options = {}, claimBudget,
474
+ /** Form of address for this locale (configured or detected); undefined is auto. */
475
+ formality,
476
+ /** The configured one only: it goes into the lockfile fingerprint. */
477
+ configuredFormality) {
426
478
  const result = {};
427
479
  const metadata = {};
428
480
  const keys = Object.keys(entries);
429
481
  // Cache and TM key: the FLORES code, plus the region for regional variants
430
482
  // (pt-BR vs pt-PT share por_Latn but must not share translations).
431
483
  const storeLang = targetLocale && (0, language_codes_1.isSupported)(targetLocale) ? (0, language_codes_1.storageLangCode)(targetLocale) : targetLang;
484
+ // A set form of address gets its own cache entries (`deu_Latn#formal`):
485
+ // the shared cache must not hand a formal project an informal translation.
486
+ // Translation memory is context-free and shared across the owner's
487
+ // projects, so such a locale neither reads nor writes it.
488
+ const cacheLang = formality ? `${storeLang}#${formality}` : storeLang;
489
+ const useTm = !formality;
432
490
  let uncachedEntries = [];
433
491
  let cacheHits = 0;
434
492
  let tmHits = 0;
@@ -450,7 +508,7 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
450
508
  const entryContext = contextMap?.[key];
451
509
  const textForHash = entryContext ? `${text}:::${entryContext}` : text;
452
510
  const textHash = (0, cache_keys_1.hashText)(textForHash);
453
- const cacheKey = (0, cache_keys_1.translationCacheKey)(sourceLang, storeLang, textHash);
511
+ const cacheKey = (0, cache_keys_1.translationCacheKey)(sourceLang, cacheLang, textHash);
454
512
  const cached = cacheProvider && !forceTranslation ? await cacheProvider.get(cacheKey) : { hit: false, data: null };
455
513
  // A stored value that is the untranslated source (cached before this was
456
514
  // rejected) is a miss, so the string is translated again instead of failing forever.
@@ -469,7 +527,7 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
469
527
  // since cache entries written before TM stored pre-glossary text may
470
528
  // have them baked in — strings with project glossary rules or an
471
529
  // in-prompt brand voice, which must not leak into other projects.
472
- if (rulesComplete && !entryContext && !brandVoice && !projectWording(text)) {
530
+ if (rulesComplete && useTm && !entryContext && !brandVoice && !projectWording(text)) {
473
531
  cacheBackfill.push({ key, sourceText: text, translatedText: cached.data });
474
532
  }
475
533
  }
@@ -480,7 +538,7 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
480
538
  const memory = providers.memory;
481
539
  const translator = providers.translator ?? (0, default_translation_provider_1.createDefaultTranslationProvider)(byokConfig);
482
540
  let tmContext = null;
483
- if (projectId && memory) {
541
+ if (projectId && memory && useTm) {
484
542
  try {
485
543
  tmContext = await memory.getProjectContext(projectId);
486
544
  }
@@ -543,7 +601,7 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
543
601
  tmHits++;
544
602
  metadata[entry.key] = { fromMemory: true, inTm: true };
545
603
  // Warm the cache (never with this project's glossary wording)
546
- const cacheKey = (0, cache_keys_1.translationCacheKey)(sourceLang, storeLang, entry.hash);
604
+ const cacheKey = (0, cache_keys_1.translationCacheKey)(sourceLang, cacheLang, entry.hash);
547
605
  if (cacheProvider && !projectWording(entry.value)) {
548
606
  cacheProvider.set(cacheKey, lookup.translatedText, cache_keys_1.TRANSLATION_CACHE_TTL_SECONDS).catch((err) => {
549
607
  logger_1.engineLogger.error('Failed to warm Redis cache from TM', { cacheKey, error: err });
@@ -733,6 +791,7 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
733
791
  targetLang,
734
792
  brandVoice,
735
793
  targetLocale,
794
+ ...(formality ? { formality } : {}),
736
795
  glossary: batchGlossary.length > 0 ? batchGlossary : undefined,
737
796
  hints,
738
797
  });
@@ -999,7 +1058,7 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
999
1058
  // glossary re-translate anything stored that no longer complies.
1000
1059
  if (projectWording(entry.value))
1001
1060
  continue;
1002
- const cacheKey = (0, cache_keys_1.translationCacheKey)(sourceLang, storeLang, entry.hash);
1061
+ const cacheKey = (0, cache_keys_1.translationCacheKey)(sourceLang, cacheLang, entry.hash);
1003
1062
  if (cacheProvider) {
1004
1063
  cacheProvider.set(cacheKey, outcome.value, cache_keys_1.TRANSLATION_CACHE_TTL_SECONDS).catch((err) => {
1005
1064
  logger_1.engineLogger.error('Failed to cache translation', { cacheKey, error: err });
@@ -1025,13 +1084,18 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
1025
1084
  // Every key this run produced gets metadata (possibly empty) so the lockfile
1026
1085
  // replaces the previous run's — cache hits, fallbacks and mixed-script keys
1027
1086
  // included — instead of keeping a stale fromMemory/fuzzyMatches.
1087
+ // Form of address: a string using the other form than the one set (or, on
1088
+ // auto, the minority form of this batch) gets a QA note.
1089
+ const addressIssues = (0, formality_1.formalityIssues)(result, targetLocale, formality);
1028
1090
  for (const key of Object.keys(result)) {
1029
1091
  const meta = { ...(metadata[key] ?? {}) };
1092
+ if (addressIssues[key])
1093
+ meta.qa = [...(meta.qa ?? []), addressIssues[key]];
1030
1094
  // The glossary rules this translation was made (or checked) under: the
1031
1095
  // lockfile re-translates the key when they change. Not recorded when the
1032
1096
  // rules failed to load, so the next run that has them redoes the key.
1033
1097
  if (rulesComplete) {
1034
- const fingerprint = (0, glossary_1.glossaryFingerprint)(entries[key], targetLocale, glossary);
1098
+ const fingerprint = rulesFingerprint(entries[key], targetLocale, { glossary, formality: configuredFormality ? { [targetLocale]: configuredFormality } : null });
1035
1099
  if (fingerprint)
1036
1100
  meta.glossaryHash = fingerprint;
1037
1101
  }
@@ -1108,6 +1172,9 @@ async function backfillTranslationMemory(projectId, sourceLocale, flatSource, tr
1108
1172
  for (const [locale, translations] of Object.entries(translationsByLocale)) {
1109
1173
  if (locale === sourceLocale || !(0, language_codes_1.isSupported)(locale))
1110
1174
  continue;
1175
+ // A set form of address is this project's choice; shared TM stays neutral.
1176
+ if ((0, formality_1.formalityFor)(rules.formality, locale))
1177
+ continue;
1111
1178
  const inserts = [];
1112
1179
  const skipped = [];
1113
1180
  for (const [key, translatedText] of Object.entries(translations)) {
@@ -9,7 +9,9 @@ import type { ExistingI18nSetup } from '../../runtime/types';
9
9
  * Returns null when there is nothing to adopt: no i18n library, no locale
10
10
  * files, or the files are where Babelize writes them (`defaultLocaleDir`,
11
11
  * i.e. a setup Babelize generated). Throws, with what to do, when the app
12
- * has a setup whose files can't be used as they are.
12
+ * has a setup whose files can't be used as they are. Flat `<locale>.json`
13
+ * files, a folder per locale of JSON namespaces and TypeScript/JS message
14
+ * modules are adopted (#370).
13
15
  */
14
16
  export declare function detectExistingSetup(opts: {
15
17
  workspacePath: string;
@@ -42,6 +42,7 @@ const fast_glob_1 = __importDefault(require("fast-glob"));
42
42
  const i18n_1 = require("../../detection/i18n");
43
43
  const locale_files_1 = require("../../qa/locale-files");
44
44
  const file_utils_1 = require("../../utils/file-utils");
45
+ const message_modules_1 = require("../locale-builder/message-modules");
45
46
  /**
46
47
  * An app that already ships its own i18n setup — vue-i18n with
47
48
  * frontend/locales/, next-intl with messages/, react-i18next with
@@ -52,7 +53,9 @@ const file_utils_1 = require("../../utils/file-utils");
52
53
  * Returns null when there is nothing to adopt: no i18n library, no locale
53
54
  * files, or the files are where Babelize writes them (`defaultLocaleDir`,
54
55
  * i.e. a setup Babelize generated). Throws, with what to do, when the app
55
- * has a setup whose files can't be used as they are.
56
+ * has a setup whose files can't be used as they are. Flat `<locale>.json`
57
+ * files, a folder per locale of JSON namespaces and TypeScript/JS message
58
+ * modules are adopted (#370).
56
59
  */
57
60
  async function detectExistingSetup(opts) {
58
61
  const deps = Object.keys({ ...opts.packageJson?.dependencies, ...opts.packageJson?.devDependencies });
@@ -63,32 +66,45 @@ async function detectExistingSetup(opts) {
63
66
  if (await (0, file_utils_1.pathExists)(path.join(opts.workspacePath, opts.defaultLocaleDir, `${opts.sourceLocale}.json`)))
64
67
  return null;
65
68
  const appRoot = path.join(opts.workspacePath, opts.appDir);
66
- const sets = await (0, locale_files_1.findLocaleFileSets)(appRoot);
69
+ const sets = await (0, locale_files_1.findLocaleFileSets)(appRoot, { modules: true });
67
70
  if (sets.length === 0)
68
71
  return null;
69
72
  const libraryName = i18n_1.I18N_LIBRARY_NAMES[library];
70
73
  const rel = (set) => toPosix(path.join(opts.appDir, set.dir));
71
74
  const withSource = sets.filter((s) => s.files[opts.sourceLocale]);
72
- const flat = withSource.filter((s) => s.layout === 'flat');
73
- if (flat.length === 0) {
74
- const nested = withSource.find((s) => s.layout === 'namespaced');
75
- if (nested) {
76
- throw new Error(`This project already uses ${libraryName} with namespaced locale files (${rel(nested)}/<locale>/<namespace>.json). ` +
77
- `Babelize translates flat locale files (<locale>.json) only, and won't set up a second i18n configuration next to yours. Nothing was changed.`);
78
- }
75
+ if (withSource.length === 0) {
79
76
  const biggest = sets.reduce((a, b) => (Object.keys(b.files).length > Object.keys(a.files).length ? b : a));
80
77
  const found = Object.keys(biggest.files).sort();
81
78
  throw new Error(`This project already uses ${libraryName} with locale files in ${rel(biggest)} (${found.join(', ')}), but none for the source language "${opts.sourceLocale}". ` +
82
79
  `Set the source language to the one your ${rel(biggest)} files are written in. Nothing was changed.`);
83
80
  }
84
- // Several candidates: the one with the most languages, then the shallowest.
85
- const best = flat.sort((a, b) => Object.keys(b.files).length - Object.keys(a.files).length || a.dir.split('/').length - b.dir.split('/').length)[0];
81
+ // Several candidates: the one with the most languages, then the shallowest,
82
+ // then flat files over a folder per locale.
83
+ const order = { flat: 0, namespaced: 1, modules: 2 };
84
+ const best = withSource.sort((a, b) => Object.keys(b.files).length - Object.keys(a.files).length ||
85
+ a.dir.split('/').length - b.dir.split('/').length ||
86
+ order[a.layout] - order[b.layout])[0];
86
87
  const locales = Object.keys(best.files).sort();
87
88
  const localeDir = rel(best);
88
- return {
89
- setup: { library, localeDir, languageLists: await findLanguageLists(appRoot, opts.appDir, locales, opts.sourceLocale) },
90
- locales,
89
+ const setup = {
90
+ library,
91
+ localeDir,
92
+ languageLists: await findLanguageLists(appRoot, opts.appDir, locales, opts.sourceLocale),
91
93
  };
94
+ if (best.layout !== 'flat') {
95
+ setup.layout = best.layout;
96
+ setup.namespaces = best.files[opts.sourceLocale].map((f) => path.posix.basename(f)).sort();
97
+ if (best.layout === 'modules') {
98
+ const sourceDir = path.join(appRoot, best.dir, opts.sourceLocale);
99
+ for (const ext of message_modules_1.MESSAGE_MODULE_EXTENSIONS) {
100
+ if (await (0, file_utils_1.pathExists)(path.join(sourceDir, `index${ext}`))) {
101
+ setup.indexFile = `index${ext}`;
102
+ break;
103
+ }
104
+ }
105
+ }
106
+ }
107
+ return { setup, locales };
92
108
  }
93
109
  const CODE_FILES = '**/*.{js,jsx,ts,tsx,mjs,cjs,vue}';
94
110
  const MAX_SCANNED_FILES = 3000;
@@ -104,7 +120,8 @@ async function findLanguageLists(appRoot, appDir, locales, sourceLocale) {
104
120
  return [];
105
121
  const files = await (0, fast_glob_1.default)(CODE_FILES, {
106
122
  cwd: appRoot,
107
- ignore: locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS.map((d) => `**/${d}/**`),
123
+ // Tests list languages too, but registering one there doesn't ship it.
124
+ ignore: [...locale_files_1.DEFAULT_LOCALE_IGNORE_DIRS.map((d) => `**/${d}/**`), '**/*.{test,spec}.*', '**/*.stories.*'],
108
125
  onlyFiles: true,
109
126
  deep: 8,
110
127
  followSymbolicLinks: false,
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.RunAbortedError = void 0;
37
37
  exports.runEngineV2 = runEngineV2;
38
38
  const fs = __importStar(require("fs-extra"));
39
+ const path = __importStar(require("path"));
39
40
  const logger_1 = require("./utils/logger");
40
41
  const types_1 = require("@babelize/types");
41
42
  const workspace_1 = require("./modules/workspace");
@@ -45,7 +46,7 @@ const keygen_1 = require("./modules/keygen");
45
46
  const locale_builder_1 = require("./modules/locale-builder");
46
47
  const adopted_1 = require("./modules/locale-builder/adopted");
47
48
  const translate_1 = require("./modules/translator/translate");
48
- const glossary_1 = require("./modules/glossary");
49
+ const formality_1 = require("./modules/translator/formality");
49
50
  const translator_caller_1 = require("./utils/translator-caller");
50
51
  const injection_1 = require("./modules/injection");
51
52
  const summary_1 = require("./modules/summary");
@@ -132,9 +133,18 @@ async function runEngineV2(config) {
132
133
  // The app's own i18n setup (#367): its locale files, as they are before
133
134
  // the run, are the source of truth. Other languages' files are the
134
135
  // project's and are never removed.
136
+ // Message modules also read the other languages': a new language's are written like theirs (#370).
135
137
  const adopted = workspace.existingSetup
136
- ? await (0, adopted_1.readAdoptedLocales)(workspace, [config.sourceLocale, ...config.targetLocales])
138
+ ? await (0, adopted_1.readAdoptedLocales)(workspace, [...new Set([
139
+ config.sourceLocale,
140
+ ...config.targetLocales,
141
+ ...(workspace.existingSetup.layout === 'modules' ? workspace.existingLocales : []),
142
+ ])])
137
143
  : null;
144
+ // Babelize's own JSON locale files from an earlier run, as they are before
145
+ // this one: a translation someone corrected by hand wins over the
146
+ // lockfile, as it does in an adopted setup and in .po files.
147
+ const ownLocaleFiles = !adopted && workspace.localeFormat === 'json' ? await (0, adopted_1.readAdoptedLocales)(workspace, config.targetLocales) : null;
138
148
  // Remove stale locale files from previous runs that are no longer in targetLocales.
139
149
  // git reset --hard only resets tracked files; generated locale files are untracked
140
150
  // and persist across runs, causing stale languages to appear in outputs.
@@ -200,6 +210,7 @@ async function runEngineV2(config) {
200
210
  // (key, locale) pairs left for the next run: the run's maxTranslations ran out.
201
211
  let skippedForBudget = 0;
202
212
  let keyUsage;
213
+ let formalityNotes = [];
203
214
  let translationMetadata = {};
204
215
  if (config.projectId) {
205
216
  config.onProgress?.('Checking lockfile for cached translations...', 'lockfile', 'running');
@@ -238,6 +249,8 @@ async function runEngineV2(config) {
238
249
  // Likewise the translations in an adopted setup's locale files.
239
250
  if (adopted)
240
251
  lockfile = (0, adopted_1.seedLockfileFromLocaleFiles)(lockfile, flatKeys, targetFiles(adopted, config.targetLocales));
252
+ else if (ownLocaleFiles)
253
+ lockfile = (0, adopted_1.seedLockfileFromLocaleFiles)(lockfile, flatKeys, ownLocaleFiles, { onlyOverRecorded: true });
241
254
  // Pseudo-localization (--provider pseudo) is not a translation: a real
242
255
  // run treats pseudo values in the lockfile as missing and translates them.
243
256
  // The glossary is loaded once, here: keys whose glossary rules changed
@@ -245,9 +258,13 @@ async function runEngineV2(config) {
245
258
  // If the rules failed to load, stored translations are kept as they are
246
259
  // rather than redone without the glossary.
247
260
  const rules = await (0, translate_1.loadProjectTranslationRules)(config.projectId, config.providers?.rules);
261
+ // An adopted setup's existing translations show the form of address the
262
+ // app uses; new ones follow it where none is configured (#371).
263
+ if (adopted)
264
+ formalityNotes = detectAdoptedFormality(rules, adopted, config.targetLocales);
248
265
  const lockfileRead = {
249
266
  pseudo: config.providers?.translator?.pseudo === true,
250
- glossaryHash: rules.complete ? (source, locale) => (0, glossary_1.glossaryFingerprint)(source, locale, rules.glossary) : undefined,
267
+ glossaryHash: rules.complete ? (source, locale) => (0, translate_1.rulesFingerprint)(source, locale, rules) : undefined,
251
268
  };
252
269
  const partition = (0, lockfile_1.partitionKeys)(lockfile, flatKeys, config.targetLocales, lockfileRead);
253
270
  lockfileStats = (0, lockfile_1.computeLockfileStats)(partition);
@@ -465,7 +482,7 @@ async function runEngineV2(config) {
465
482
  config, startTime, workspace, allTranslatedPerLocale,
466
483
  lockfileStats, tmHits, translationMetadata,
467
484
  translatedThisRun, skippedForBudget, keyUsage,
468
- formatStrings, frameworkConfig, gettext, overrideReport,
485
+ formatStrings, frameworkConfig, gettext, overrideReport, formalityNotes,
469
486
  });
470
487
  return result;
471
488
  }
@@ -590,6 +607,25 @@ function freshTranslations(translation, metadata) {
590
607
  return n;
591
608
  }
592
609
  /** The target locales' files of an adopted setup (null: no file yet). */
610
+ /**
611
+ * For each target locale with no configured form of address, the one its
612
+ * existing file clearly uses (an adopted setup), recorded in
613
+ * `rules.detectedFormality`. Returns a report note per detected locale.
614
+ */
615
+ function detectAdoptedFormality(rules, adopted, targetLocales) {
616
+ const notes = [];
617
+ for (const locale of targetLocales) {
618
+ const file = adopted[locale];
619
+ if (!file || !(0, formality_1.hasFormalitySplit)(locale) || (0, formality_1.formalityFor)(rules.formality, locale))
620
+ continue;
621
+ const detected = (0, formality_1.detectFormality)(Object.values((0, keygen_1.flattenLocaleData)(file.data)).filter((v) => typeof v === 'string'), locale);
622
+ if (!detected)
623
+ continue;
624
+ rules.detectedFormality = { ...rules.detectedFormality, [locale]: detected };
625
+ notes.push(`${locale} formality: ${detected} (detected from the existing translations). Set "formality" in .babelize/config.json to change it.`);
626
+ }
627
+ return notes;
628
+ }
593
629
  function targetFiles(adopted, targetLocales) {
594
630
  return Object.fromEntries(targetLocales.map((l) => [l, adopted[l] ?? null]));
595
631
  }
@@ -603,16 +639,18 @@ function adoptLocales(workspace, adopted, locales, sourceLocale, alsoKeep = [])
603
639
  const source = adopted[sourceLocale];
604
640
  if (!source)
605
641
  return locales;
642
+ // A new language's modules are written like another language's (#370).
643
+ const others = (locale) => Object.fromEntries(Object.entries(adopted).filter(([l]) => l !== locale && l !== sourceLocale));
606
644
  const out = locales.map((l) => {
607
645
  const existing = adopted[l.locale] ?? null;
608
646
  // Without a lockfile the translator returns only the missing keys: the file supplies the rest.
609
647
  const values = { ...(existing ? (0, keygen_1.flattenLocaleData)(existing.data) : {}), ...(0, keygen_1.flattenLocaleData)(l.data) };
610
- return (0, adopted_1.adoptedLocaleFile)(workspace, l.locale, source, values, existing);
648
+ return (0, adopted_1.adoptedLocaleFile)(workspace, l.locale, source, values, existing, others(l.locale));
611
649
  });
612
650
  for (const locale of alsoKeep) {
613
651
  const existing = adopted[locale];
614
652
  if (existing && !out.some((l) => l.locale === locale)) {
615
- out.push((0, adopted_1.adoptedLocaleFile)(workspace, locale, source, (0, keygen_1.flattenLocaleData)(existing.data), existing));
653
+ out.push((0, adopted_1.adoptedLocaleFile)(workspace, locale, source, (0, keygen_1.flattenLocaleData)(existing.data), existing, others(locale)));
616
654
  }
617
655
  }
618
656
  return out;
@@ -620,6 +658,11 @@ function adoptLocales(workspace, adopted, locales, sourceLocale, alsoKeep = [])
620
658
  /** Write each locale file: exact `content` when the engine produced it, else sorted JSON. */
621
659
  async function writeLocales(workspace, locales) {
622
660
  for (const locale of locales) {
661
+ if (locale.files) {
662
+ for (const f of locale.files)
663
+ await fs.outputFile(path.join(workspace.path, f.path), f.content);
664
+ continue;
665
+ }
623
666
  const { file } = (0, file_utils_1.workspaceLocaleFile)(workspace, locale.locale);
624
667
  if (locale.content !== undefined)
625
668
  await fs.outputFile(file, locale.content);
@@ -728,7 +771,7 @@ function mergeChangedFile(list, changed) {
728
771
  existing.hookAdded = existing.hookAdded || changed.hookAdded;
729
772
  }
730
773
  async function finalizePipeline(params) {
731
- const { extraction, keyGeneration, localeHandling, translation, config, startTime, workspace, allTranslatedPerLocale, lockfileStats, tmHits, translationMetadata, formatStrings, frameworkConfig, translatedThisRun, skippedForBudget, keyUsage, gettext, overrideReport, } = params;
774
+ const { extraction, keyGeneration, localeHandling, translation, config, startTime, workspace, allTranslatedPerLocale, lockfileStats, tmHits, translationMetadata, formatStrings, frameworkConfig, translatedThisRun, skippedForBudget, keyUsage, gettext, overrideReport, formalityNotes, } = params;
732
775
  const keyMapping = (0, keygen_1.createKeyMapping)(keyGeneration.keys);
733
776
  // Injection: AST-based i18n hook injection (skipped for frameworks like Django)
734
777
  // An adopted i18n setup is used as it is: no code, config or dependency changes.
@@ -772,6 +815,7 @@ async function finalizePipeline(params) {
772
815
  const finalizationNotes = adoptedSetup
773
816
  ? (0, adopted_1.adoptedSetupNotes)(workspace, config.sourceLocale, config.targetLocales, extraction.notInjected ?? [])
774
817
  : [];
818
+ finalizationNotes.push(...(formalityNotes ?? []));
775
819
  if (gettext) {
776
820
  gettext.refreshReferences(injection);
777
821
  const written = await gettext.write(config.targetLocales, allTranslatedPerLocale, {
@@ -10,8 +10,8 @@ const translator_caller_1 = require("../utils/translator-caller");
10
10
  */
11
11
  function createDefaultTranslationProvider(byokConfig) {
12
12
  return {
13
- async translateBatch({ entries, sourceLang, targetLang, brandVoice, targetLocale, glossary, hints }, options = {}) {
14
- const { translations } = await (0, translator_caller_1.callTranslator)(entries, sourceLang, targetLang, byokConfig, brandVoice, { targetLocale, glossary, hints, signal: options.signal });
13
+ async translateBatch({ entries, sourceLang, targetLang, brandVoice, targetLocale, formality, glossary, hints }, options = {}) {
14
+ const { translations } = await (0, translator_caller_1.callTranslator)(entries, sourceLang, targetLang, byokConfig, brandVoice, { targetLocale, formality, glossary, hints, signal: options.signal });
15
15
  return toKeyResults(entries.map((e) => e.key), translations ?? []);
16
16
  },
17
17
  };
@@ -2,6 +2,7 @@ import type { TranslationEntry } from '../runtime/types';
2
2
  import type { MemoryEntry } from '../modules/translator/memory/types';
3
3
  import type { GlossaryEntryType } from '../modules/glossary/types';
4
4
  import type { TranslationOverride } from '../modules/overrides';
5
+ import type { FormalityLevel, FormalitySetting } from '../modules/translator/formality';
5
6
  /**
6
7
  * Everything the engine needs from the outside world, as interfaces. The
7
8
  * engine never imports a database or cache client: the cloud backend injects
@@ -66,6 +67,8 @@ export interface TranslationBatchRequest {
66
67
  brandVoice?: string;
67
68
  /** Target locale as an ISO code, e.g. "fr" or "pt-BR" (LLM providers only). */
68
69
  targetLocale?: string;
70
+ /** Form of address for the target locale; undefined means auto (LLM providers only). */
71
+ formality?: FormalityLevel;
69
72
  /** Required terminology for this batch: source term → translation (LLM providers only). */
70
73
  glossary?: Array<{
71
74
  term: string;
@@ -129,6 +132,8 @@ export interface GlossaryRule {
129
132
  export interface ProjectRulesStore {
130
133
  getGlossary(projectId: string): Promise<GlossaryRule[]>;
131
134
  getBrandVoice(projectId: string): Promise<string | null>;
135
+ /** Per target locale (or base language) formal/informal/auto address. Optional: absent means auto everywhere. */
136
+ getFormality?(projectId: string): Promise<Record<string, FormalitySetting> | null>;
132
137
  }
133
138
  export interface TranslationOverrideStore {
134
139
  getOverrides(projectId: string): Promise<TranslationOverride[]>;
@@ -1,9 +1,16 @@
1
1
  import { type LocaleGlossary, type LocaleIssue, type LocalePairReport } from './locale-qa';
2
2
  import { type FindLocaleOptions, type LocaleFileSet } from './locale-files';
3
+ import { type FormalitySetting } from '../modules/translator/formality';
4
+ /** Longest brand voice read from `.babelize/config.json` (the cloud setting's limit). */
5
+ export declare const MAX_LOCAL_BRAND_VOICE_CHARS = 300;
3
6
  export interface ProjectLocaleConfig {
4
7
  sourceLocale?: string;
5
8
  targetLocales?: string[];
6
9
  glossary?: LocaleGlossary;
10
+ /** Tone and style for the translator (LLM providers), like a cloud project's brand voice. */
11
+ brandVoice?: string;
12
+ /** Per target locale (or base language): formal, informal or auto address. */
13
+ formality?: Record<string, FormalitySetting>;
7
14
  }
8
15
  /**
9
16
  * The parts of `.babelize/config.json` the local tools use. Missing or
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MAX_LOCAL_BRAND_VOICE_CHARS = void 0;
36
37
  exports.readProjectLocaleConfig = readProjectLocaleConfig;
37
38
  exports.localeIssueFile = localeIssueFile;
38
39
  exports.checkProjectLocales = checkProjectLocales;
@@ -46,6 +47,9 @@ const locale_qa_1 = require("./locale-qa");
46
47
  const locale_files_1 = require("./locale-files");
47
48
  const gettext_files_1 = require("./gettext-files");
48
49
  const locale_names_1 = require("../django/locale-names");
50
+ const formality_1 = require("../modules/translator/formality");
51
+ /** Longest brand voice read from `.babelize/config.json` (the cloud setting's limit). */
52
+ exports.MAX_LOCAL_BRAND_VOICE_CHARS = 300;
49
53
  /**
50
54
  * The parts of `.babelize/config.json` the local tools use. Missing or
51
55
  * malformed config is not an error: everything in it is optional.
@@ -94,6 +98,12 @@ async function readProjectLocaleConfig(projectDir) {
94
98
  }
95
99
  if (neverTranslate.length || alwaysTranslateAs.length)
96
100
  config.glossary = { neverTranslate, alwaysTranslateAs };
101
+ if (typeof raw.brandVoice === 'string' && raw.brandVoice.trim()) {
102
+ config.brandVoice = raw.brandVoice.trim().slice(0, exports.MAX_LOCAL_BRAND_VOICE_CHARS);
103
+ }
104
+ const formality = (0, formality_1.sanitizeFormality)(raw.formality);
105
+ if (formality)
106
+ config.formality = formality;
97
107
  return config;
98
108
  }
99
109
  /** The file a locale issue lives in, relative to the project root. */
@@ -156,7 +166,7 @@ async function checkProjectLocales(projectDir, options = {}) {
156
166
  for (const locale of wanted.filter((l) => set.files[l])) {
157
167
  const target = await (0, locale_files_1.loadLocale)(projectDir, set, locale);
158
168
  fileErrors.push(...target.errors);
159
- locales.push((0, locale_qa_1.checkLocalePair)(source.messages, target.messages, locale, { sourceLocale, glossary, keys: options.keys }));
169
+ locales.push((0, locale_qa_1.checkLocalePair)(source.messages, target.messages, locale, { sourceLocale, glossary, keys: options.keys, formality: config.formality }));
160
170
  }
161
171
  reports.push({
162
172
  dir: set.dir,
@@ -177,7 +187,7 @@ async function checkProjectLocales(projectDir, options = {}) {
177
187
  : [...new Set([...available, ...expected])].filter((l) => l !== sourceLocale).sort();
178
188
  const locales = [];
179
189
  for (const locale of wanted.filter((l) => set.files[l])) {
180
- locales.push((0, locale_qa_1.checkLocalePair)(loaded.source, loaded.byLocale[locale] ?? {}, locale, { sourceLocale, glossary, keys: options.keys }));
190
+ locales.push((0, locale_qa_1.checkLocalePair)(loaded.source, loaded.byLocale[locale] ?? {}, locale, { sourceLocale, glossary, keys: options.keys, formality: config.formality }));
181
191
  }
182
192
  reports.push({
183
193
  dir: set.dir,
@@ -1,7 +1,7 @@
1
1
  export interface LocaleFileSet {
2
2
  /** Directory holding the set, relative to the project root (posix). */
3
3
  dir: string;
4
- layout: 'flat' | 'namespaced';
4
+ layout: 'flat' | 'namespaced' | 'modules';
5
5
  /** locale → files (relative to the project root, posix). */
6
6
  files: Record<string, string[]>;
7
7
  }
@@ -23,21 +23,24 @@ export declare const DEFAULT_LOCALE_IGNORE_DIRS: readonly string[];
23
23
  export interface FindLocaleOptions {
24
24
  /** Directory names to skip at any depth (default DEFAULT_LOCALE_IGNORE_DIRS). */
25
25
  ignoreDirs?: readonly string[];
26
+ /** Also find TypeScript/JS message modules (`<dir>/<locale>/<ns>.ts`). */
27
+ modules?: boolean;
26
28
  }
27
29
  export declare function isLocaleCode(name: string): boolean;
28
30
  /** True when a relative path runs through an ignored directory. */
29
31
  export declare function isIgnoredLocalePath(rel: string, ignoreDirs?: readonly string[]): boolean;
30
32
  /**
31
- * Group relative `.json` paths into locale file sets. Paths that aren't
32
- * `<dir>/<locale>.json` or `<dir>/<locale>/<ns>.json` under a locale folder
33
- * are ignored.
33
+ * Group relative `.json` paths (and, with `modules`, message module paths)
34
+ * into locale file sets. Paths that aren't `<dir>/<locale>.json`,
35
+ * `<dir>/<locale>/<ns>.json` or `<dir>/<locale>/<ns>.ts` under a locale
36
+ * folder are ignored.
34
37
  */
35
38
  export declare function groupLocaleFiles(paths: string[], options?: FindLocaleOptions): LocaleFileSet[];
36
39
  export declare function findLocaleFileSets(projectDir: string, options?: FindLocaleOptions): Promise<LocaleFileSet[]>;
37
40
  /** Reads a project file by relative path; null when it doesn't exist (in that version). */
38
41
  export type ProjectFileReader = (rel: string) => Promise<string | null>;
39
42
  /**
40
- * Read and flatten one locale of a set. Namespaced files are keyed `ns:key`.
43
+ * Read and flatten one locale of a set. Namespaced files and modules are keyed `ns:key`.
41
44
  * `read` reads another version of the files (e.g. from git); by default the
42
45
  * working tree is read.
43
46
  */