@babelize/engine 0.3.7 → 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 (36) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +11 -1
  3. package/dist/local/hosted-provider.js +1 -0
  4. package/dist/local/translate-core.d.ts +13 -2
  5. package/dist/local/translate-core.js +27 -9
  6. package/dist/local/translate-messages.d.ts +5 -0
  7. package/dist/local/translate-messages.js +1 -1
  8. package/dist/modules/finalization/nextjs-finalize.d.ts +19 -2
  9. package/dist/modules/finalization/nextjs-finalize.js +46 -4
  10. package/dist/modules/locale-builder/adopted.d.ts +29 -2
  11. package/dist/modules/locale-builder/adopted.js +185 -16
  12. package/dist/modules/locale-builder/locales.js +11 -2
  13. package/dist/modules/locale-builder/message-modules.d.ts +40 -0
  14. package/dist/modules/locale-builder/message-modules.js +263 -0
  15. package/dist/modules/translator/client/byok.provider.js +8 -2
  16. package/dist/modules/translator/formality.d.ts +40 -0
  17. package/dist/modules/translator/formality.js +313 -0
  18. package/dist/modules/translator/translate.d.ts +18 -0
  19. package/dist/modules/translator/translate.js +78 -11
  20. package/dist/modules/workspace/existing-setup.d.ts +3 -1
  21. package/dist/modules/workspace/existing-setup.js +32 -15
  22. package/dist/orchestrator.js +51 -7
  23. package/dist/providers/default-translation-provider.js +2 -2
  24. package/dist/providers/types.d.ts +5 -0
  25. package/dist/qa/check-project.d.ts +7 -0
  26. package/dist/qa/check-project.js +12 -2
  27. package/dist/qa/locale-files.d.ts +8 -5
  28. package/dist/qa/locale-files.js +37 -9
  29. package/dist/qa/locale-qa.d.ts +10 -1
  30. package/dist/qa/locale-qa.js +9 -0
  31. package/dist/qa/review.js +1 -1
  32. package/dist/runtime/types.d.ts +21 -1
  33. package/dist/types.d.ts +2 -0
  34. package/dist/utils/translator-caller.d.ts +19 -0
  35. package/dist/utils/translator-caller.js +55 -21
  36. package/package.json +2 -2
@@ -0,0 +1,313 @@
1
+ "use strict";
2
+ /**
3
+ * Formal vs informal address per target language (#371): the forms the
4
+ * translator is told to use, and the marker words that tell which form a
5
+ * translated string uses (detection from an existing catalog, QA for mixed
6
+ * forms). Languages without a T–V distinction have no entry and get no
7
+ * instruction.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.hasFormalitySplit = hasFormalitySplit;
11
+ exports.formalityFor = formalityFor;
12
+ exports.formalityInstruction = formalityInstruction;
13
+ exports.formalityOf = formalityOf;
14
+ exports.detectFormality = detectFormality;
15
+ exports.formalityIssues = formalityIssues;
16
+ exports.parseFormalityList = parseFormalityList;
17
+ exports.sanitizeFormality = sanitizeFormality;
18
+ /** Whole words: \b is ASCII-only, so letters are matched with \p{L}. */
19
+ const words = (list, flags = 'iu') => new RegExp(`(?<!\\p{L})(?:${list})(?!\\p{L})`, flags);
20
+ const SPECS = {
21
+ de: {
22
+ formal: '"Sie" (Ihr, Ihnen; imperatives like "Klicken Sie")',
23
+ informal: '"du" (dein, dich, dir; imperatives like "Klicke")',
24
+ // "Sie" at the very start may be "she/they"; capitalized mid-sentence it is the polite "you".
25
+ formalMarkers: /(?<=\p{L}[,;:]?\s)Sie(?!\p{L})|(?<!\p{L})(?:Ihnen|Ihr|Ihre|Ihrem|Ihren|Ihrer|Ihres)(?!\p{L})/u,
26
+ informalMarkers: words('du|dich|dir|dein|deine|deinem|deinen|deiner|deines'),
27
+ },
28
+ fr: {
29
+ formal: '"vous" (votre, vos; imperatives in -ez)',
30
+ informal: '"tu" (te, toi, ton, ta, tes; imperatives without -ez)',
31
+ formalMarkers: words('vous|votre|vos'),
32
+ informalMarkers: words("tu|toi|ton|ta|tes|te|t(?=['’]\\p{L})"),
33
+ },
34
+ es: {
35
+ formal: '"usted" (su, le; verbs in the third person, e.g. "Introduzca")',
36
+ informal: '"tú" (tu, te, ti; verbs in the second person, e.g. "Introduce")',
37
+ formalMarkers: words('usted|ustedes'),
38
+ informalMarkers: words('tú|tu|tus|te|ti|contigo'),
39
+ },
40
+ it: {
41
+ formal: '"Lei" (Suo, Sua, La; verbs in the third person, e.g. "Inserisca")',
42
+ informal: '"tu" (tuo, tua, ti; verbs in the second person, e.g. "Inserisci")',
43
+ formalMarkers: words('Lei|Suo|Sua|Suoi|Sue', 'u'),
44
+ informalMarkers: words('tu|tuo|tua|tuoi|tue|ti'),
45
+ },
46
+ pt: {
47
+ formal: '"o senhor" / "a senhora" (verbs in the third person)',
48
+ informal: '"você" in Brazilian Portuguese, "tu" in European Portuguese',
49
+ formalMarkers: words('o senhor|a senhora|os senhores|as senhoras'),
50
+ informalMarkers: words('você|vocês|tu|teu|tua|teus|tuas|contigo'),
51
+ },
52
+ nl: {
53
+ formal: '"u" (uw)',
54
+ informal: '"je" / "jij" (jouw, jou)',
55
+ formalMarkers: words('u|uw'),
56
+ informalMarkers: words('je|jij|jou|jouw'),
57
+ },
58
+ pl: {
59
+ formal: '"Pan" / "Pani" / "Państwo" (verbs in the third person)',
60
+ informal: '"ty" (twój; verbs in the second person singular)',
61
+ formalMarkers: words('Pan|Pani|Państwo|Pana|Panu|Panią|Państwa|Państwu', 'u'),
62
+ informalMarkers: words('ty|twój|twoja|twoje|twoich|twoim|ciebie|cię|tobie'),
63
+ },
64
+ tr: {
65
+ formal: '"siz" (sizin; imperatives like "Giriş yapın")',
66
+ informal: '"sen" (senin; imperatives like "Giriş yap")',
67
+ formalMarkers: words('siz|sizin|size|sizi|sizinle'),
68
+ informalMarkers: words('sen|senin|sana|seni|seninle'),
69
+ },
70
+ ru: {
71
+ formal: '"вы" (ваш, вам, вас)',
72
+ informal: '"ты" (твой, тебе, тебя)',
73
+ formalMarkers: words('вы|вас|вам|вами|ваш|ваша|ваше|ваши|вашего|вашей|вашим|ваших|вашу'),
74
+ informalMarkers: words('ты|тебя|тебе|тобой|твой|твоя|твоё|твое|твои|твоего|твоей|твоим|твоих|твою'),
75
+ },
76
+ uk: {
77
+ formal: '"ви" (ваш, вам, вас)',
78
+ informal: '"ти" (твій, тобі, тебе)',
79
+ formalMarkers: words('ви|вас|вам|вами|ваш|ваша|ваше|ваші|вашого|вашої|вашим|ваших|вашу'),
80
+ informalMarkers: words('ти|тебе|тобі|тобою|твій|твоя|твоє|твої|твого|твоєї|твоїм|твоїх|твою'),
81
+ },
82
+ bg: {
83
+ formal: '"Вие" (Ваш)',
84
+ informal: '"ти" (твой)',
85
+ formalMarkers: words('вие|вас|вам|ваш|ваша|ваше|ваши'),
86
+ informalMarkers: words('ти|теб|тебе|твой|твоя|твое|твои'),
87
+ },
88
+ cs: {
89
+ formal: '"vy" (váš; verbs in the second person plural)',
90
+ informal: '"ty" (tvůj; verbs in the second person singular)',
91
+ formalMarkers: words('vy|vás|vám|vámi|váš|vaše|vašeho|vaší|vašich|vašim'),
92
+ informalMarkers: words('ty|tebe|tě|tobě|ti|tvůj|tvoje|tvá|tvého|tvých|tvým'),
93
+ },
94
+ sk: {
95
+ formal: '"vy" (váš; verbs in the second person plural)',
96
+ informal: '"ty" (tvoj; verbs in the second person singular)',
97
+ formalMarkers: words('vy|vás|vám|vami|váš|vaša|vaše|vášho|vašej|vašich'),
98
+ informalMarkers: words('ty|teba|ťa|tebe|ti|tvoj|tvoja|tvoje|tvojho|tvojej|tvojich'),
99
+ },
100
+ hu: {
101
+ formal: '"Ön" / "Önök" (verbs in the third person)',
102
+ informal: '"te" (verbs in the second person)',
103
+ formalMarkers: words('Ön|Önök|Önt|Önnek|Önnel|Öntől|Önök', 'u'),
104
+ informalMarkers: words('te|téged|neked|veled|tőled'),
105
+ },
106
+ ro: {
107
+ formal: '"dumneavoastră" (verbs in the second person plural)',
108
+ informal: '"tu" (verbs in the second person singular)',
109
+ formalMarkers: words('dumneavoastră|dvs'),
110
+ informalMarkers: words('tu|tău|ta|tale|tine|ție|ţie'),
111
+ },
112
+ ca: {
113
+ formal: '"vostè" (verbs in the third person)',
114
+ informal: '"tu" (verbs in the second person)',
115
+ formalMarkers: words('vostè|vostès'),
116
+ informalMarkers: words('tu|teu|teva|teus|teves'),
117
+ },
118
+ el: {
119
+ formal: '"εσείς" (σας; verbs in the second person plural)',
120
+ informal: '"εσύ" (σου; verbs in the second person singular)',
121
+ formalMarkers: words('εσείς|σας'),
122
+ informalMarkers: words('εσύ|σου'),
123
+ },
124
+ sv: {
125
+ formal: '"ni" (er, ert) — rare in modern Swedish software, which uses "du"',
126
+ informal: '"du" (din, dig)',
127
+ informalMarkers: words('du|dig|din|ditt|dina'),
128
+ },
129
+ da: {
130
+ formal: '"De" (Dem, Deres) — rare in modern Danish software, which uses "du"',
131
+ informal: '"du" (din, dig)',
132
+ formalMarkers: words('Dem|Deres', 'u'),
133
+ informalMarkers: words('du|dig|din|dit|dine'),
134
+ },
135
+ nb: {
136
+ formal: '"De" (Dem, Deres) — rare in modern Norwegian software, which uses "du"',
137
+ informal: '"du" (din, deg)',
138
+ formalMarkers: words('Dem|Deres', 'u'),
139
+ informalMarkers: words('du|deg|din|ditt|dine'),
140
+ },
141
+ fi: {
142
+ formal: '"te" (Teidän; verbs in the second person plural) — rare in modern Finnish software, which uses "sinä"',
143
+ informal: '"sinä" (sinun; verbs in the second person singular)',
144
+ },
145
+ hi: {
146
+ formal: '"आप" (आपका, आपके)',
147
+ informal: '"तुम" (तुम्हारा, तुम्हें)',
148
+ formalMarkers: /आप/u,
149
+ informalMarkers: /तुम|तू(?!\p{M})/u,
150
+ },
151
+ id: {
152
+ formal: '"Anda"',
153
+ informal: '"kamu" / "kau"',
154
+ formalMarkers: words('Anda', 'u'),
155
+ informalMarkers: words('kamu|kau|mu'),
156
+ },
157
+ ms: {
158
+ formal: '"Anda"',
159
+ informal: '"kamu" / "awak"',
160
+ formalMarkers: words('Anda', 'u'),
161
+ informalMarkers: words('kamu|awak'),
162
+ },
163
+ zh: {
164
+ formal: '"您"',
165
+ informal: '"你"',
166
+ formalMarkers: /您/u,
167
+ informalMarkers: /你/u,
168
+ },
169
+ ja: {
170
+ formal: 'polite keigo (です/ます forms, ください)',
171
+ informal: 'plain casual forms (だ/る endings, no です/ます)',
172
+ },
173
+ ko: {
174
+ formal: 'formal polite speech (합니다/습니다 or 해요 endings)',
175
+ informal: 'casual speech (반말, 해/야 endings)',
176
+ },
177
+ };
178
+ function baseLanguage(locale) {
179
+ const base = locale.toLowerCase().split(/[-_]/)[0];
180
+ return base === 'no' || base === 'nn' ? 'nb' : base;
181
+ }
182
+ function specFor(locale) {
183
+ return SPECS[baseLanguage(locale)];
184
+ }
185
+ /** True when the language distinguishes formal and informal address. */
186
+ function hasFormalitySplit(locale) {
187
+ return !!specFor(locale);
188
+ }
189
+ /**
190
+ * The formality configured for `locale`: the exact locale, else its base
191
+ * language (`de` covers `de-AT`). `auto` and unlisted locales: undefined.
192
+ */
193
+ function formalityFor(settings, locale) {
194
+ if (!settings)
195
+ return undefined;
196
+ const lower = Object.fromEntries(Object.entries(settings).map(([k, v]) => [k.toLowerCase().replace(/_/g, '-'), v]));
197
+ const exact = lower[locale.toLowerCase().replace(/_/g, '-')];
198
+ const value = exact ?? lower[locale.toLowerCase().split(/[-_]/)[0]];
199
+ return value === 'formal' || value === 'informal' ? value : undefined;
200
+ }
201
+ /**
202
+ * The prompt rule for the form of address. With a level set, it names the
203
+ * concrete forms to use and to avoid; on `auto` it still forbids mixing them.
204
+ * Undefined for languages without the distinction (and `auto`): the generic
205
+ * consistency rule applies.
206
+ */
207
+ function formalityInstruction(locale, level, languageName) {
208
+ const spec = specFor(locale);
209
+ if (!spec)
210
+ return undefined;
211
+ if (!level) {
212
+ return `Address the user in one form throughout: either the formal ${spec.formal} or the informal ${spec.informal}, whichever is conventional for modern software in ${languageName} — never mix them.`;
213
+ }
214
+ const [use, avoid] = level === 'formal' ? [spec.formal, spec.informal] : [spec.informal, spec.formal];
215
+ return `Address the user ${level === 'formal' ? 'formally' : 'informally'} in every entry: use ${use}. Never use ${avoid}, even where a context or a previous translation does.`;
216
+ }
217
+ /** Which form a single string uses: undefined when it addresses no one (or both forms appear). */
218
+ function formalityOf(text, locale) {
219
+ const spec = specFor(locale);
220
+ if (!spec?.formalMarkers && !spec?.informalMarkers)
221
+ return undefined;
222
+ // Placeholders ({name}, {{name}}, tokens) and tags aren't words of the message.
223
+ const prose = text.replace(/\{\{?\s*[\w.-]+\s*\}?\}|<[^<>]*>|\[#[^\]]*#\]/g, ' ');
224
+ const formal = !!spec.formalMarkers?.test(prose);
225
+ const informal = !!spec.informalMarkers?.test(prose);
226
+ if (formal === informal)
227
+ return undefined;
228
+ return formal ? 'formal' : 'informal';
229
+ }
230
+ /**
231
+ * The form an existing catalog uses, when it clearly uses one: at least
232
+ * three strings address the user and 80% of them use the same form.
233
+ */
234
+ function detectFormality(values, locale) {
235
+ let formal = 0;
236
+ let informal = 0;
237
+ for (const v of values) {
238
+ const form = formalityOf(v, locale);
239
+ if (form === 'formal')
240
+ formal++;
241
+ else if (form === 'informal')
242
+ informal++;
243
+ }
244
+ const total = formal + informal;
245
+ if (total < 3)
246
+ return undefined;
247
+ if (formal / total >= 0.8)
248
+ return 'formal';
249
+ if (informal / total >= 0.8)
250
+ return 'informal';
251
+ return undefined;
252
+ }
253
+ /**
254
+ * Strings of one locale that break its form of address: with `expected`, the
255
+ * ones using the other form; without it, the minority form when both appear
256
+ * (all of them on a tie). Key → message.
257
+ */
258
+ function formalityIssues(values, locale, expected) {
259
+ const formOf = {};
260
+ let formal = 0;
261
+ let informal = 0;
262
+ for (const [key, value] of Object.entries(values)) {
263
+ const form = formalityOf(value, locale);
264
+ if (!form)
265
+ continue;
266
+ formOf[key] = form;
267
+ if (form === 'formal')
268
+ formal++;
269
+ else
270
+ informal++;
271
+ }
272
+ const out = {};
273
+ if (expected) {
274
+ for (const [key, form] of Object.entries(formOf)) {
275
+ if (form !== expected)
276
+ out[key] = `Uses ${form} address, but ${locale} is set to ${expected}`;
277
+ }
278
+ return out;
279
+ }
280
+ if (formal === 0 || informal === 0)
281
+ return out;
282
+ const flag = formal === informal ? ['formal', 'informal'] : [formal < informal ? 'formal' : 'informal'];
283
+ for (const [key, form] of Object.entries(formOf)) {
284
+ if (!flag.includes(form))
285
+ continue;
286
+ out[key] = `Mixes forms of address: uses ${form} address while ${formal === informal ? 'as many' : 'most'} strings in ${locale} use ${form === 'formal' ? 'informal' : 'formal'} (${formal} formal, ${informal} informal)`;
287
+ }
288
+ return out;
289
+ }
290
+ /** Parse `de=formal,it=informal` (CLI flag values); throws on a malformed item. */
291
+ function parseFormalityList(items) {
292
+ const out = {};
293
+ for (const item of items.flatMap((i) => i.split(',')).map((i) => i.trim()).filter(Boolean)) {
294
+ const m = /^([A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*)\s*[=:]\s*(formal|informal|auto)$/i.exec(item);
295
+ if (!m)
296
+ throw new Error(`Invalid formality "${item}": use <locale>=formal|informal|auto, e.g. de=formal`);
297
+ out[m[1]] = m[2].toLowerCase();
298
+ }
299
+ return out;
300
+ }
301
+ /** Keep valid `locale → formal|informal|auto` entries of untrusted input (config files, DB rows). */
302
+ function sanitizeFormality(raw) {
303
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
304
+ return undefined;
305
+ const out = {};
306
+ for (const [k, v] of Object.entries(raw)) {
307
+ if (!/^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{2,8})*$/.test(k))
308
+ continue;
309
+ if (v === 'formal' || v === 'informal' || v === 'auto')
310
+ out[k] = v;
311
+ }
312
+ return Object.keys(out).length > 0 ? out : undefined;
313
+ }
@@ -2,6 +2,7 @@ import type { LocaleFile, WorkspaceInfo } from '../../runtime/types';
2
2
  import type { ByokProvider } from '@babelize/types';
3
3
  import { type GlossaryRules } from '../glossary';
4
4
  import type { EngineProviders, ProjectRulesStore, TranslationFailure, TranslationCache } from '../../providers/types';
5
+ import { type FormalityLevel, type FormalitySetting } from './formality';
5
6
  /** QA note on keys the backup (NLLB) translator produced. */
6
7
  export declare const FALLBACK_QA_WARNING = "translated with the backup translator; will be retried with the AI translator next run";
7
8
  export interface TranslateOptions {
@@ -43,9 +44,26 @@ export interface TranslateOptions {
43
44
  export interface LoadedTranslationRules {
44
45
  glossary: GlossaryRules;
45
46
  brandVoice: string | null;
47
+ /** Configured form of address per locale (or base language); unlisted is auto. */
48
+ formality?: Record<string, FormalitySetting> | null;
49
+ /**
50
+ * Form of address found in a locale's existing translations (an adopted
51
+ * setup), used where the configured one is auto. Guides new translations
52
+ * only: unlike a configured one it doesn't re-translate stored keys.
53
+ */
54
+ detectedFormality?: Record<string, FormalityLevel>;
46
55
  /** False if the glossary or brand voice failed to load. */
47
56
  complete: boolean;
48
57
  }
58
+ /** The form of address translations into `locale` use: configured, else detected, else auto (undefined). */
59
+ export declare function effectiveFormality(rules: Pick<LoadedTranslationRules, 'formality' | 'detectedFormality'>, locale: string): FormalityLevel | undefined;
60
+ /**
61
+ * The lockfile fingerprint of the project rules a translation was made
62
+ * under: the glossary's, plus the configured form of address. A key is
63
+ * re-translated when it changes. Auto adds nothing, so projects without a
64
+ * formality setting keep their fingerprints.
65
+ */
66
+ export declare function rulesFingerprint(source: string, locale: string, rules: Pick<LoadedTranslationRules, 'glossary' | 'formality'>): string;
49
67
  /**
50
68
  * Load a project's glossary and brand voice. Never throws: a failure means
51
69
  * translating without that rule, as before. The two lookups are independent,
@@ -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;