@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
@@ -50,11 +50,14 @@ exports.loadLocale = loadLocale;
50
50
  *
51
51
  * locales/en.json, locales/fr.json flat: one file per locale
52
52
  * locales/en/common.json, locales/fr/common.json namespaced (i18next): keys become `common:key`
53
+ * messages/en/auth.ts, messages/fr/auth.ts modules (opt-in): TypeScript/JS message modules,
54
+ * read by AST; `index.*` (the combiner) is not one
53
55
  */
54
56
  const path = __importStar(require("path"));
55
57
  const fs_1 = require("fs");
56
58
  const fast_glob_1 = __importDefault(require("fast-glob"));
57
59
  const locale_qa_1 = require("./locale-qa");
60
+ const message_modules_1 = require("../modules/locale-builder/message-modules");
58
61
  const LOCALE_DIR_NAMES = ['locales', 'locale', 'messages', 'lang', 'langs', 'i18n', 'translations'];
59
62
  /**
60
63
  * Directories never searched for locale files: dependencies, build output,
@@ -77,17 +80,24 @@ function isIgnoredLocalePath(rel, ignoreDirs = exports.DEFAULT_LOCALE_IGNORE_DIR
77
80
  const dirs = rel.split('/').slice(0, -1);
78
81
  return dirs.some((d) => ignoreDirs.includes(d));
79
82
  }
83
+ /** `auth.ts` → `.ts` when it is a message module extension, else null. */
84
+ function moduleExtension(file) {
85
+ if (file.endsWith('.d.ts'))
86
+ return null;
87
+ return message_modules_1.MESSAGE_MODULE_EXTENSIONS.find((ext) => file.endsWith(ext)) ?? null;
88
+ }
80
89
  /**
81
- * Group relative `.json` paths into locale file sets. Paths that aren't
82
- * `<dir>/<locale>.json` or `<dir>/<locale>/<ns>.json` under a locale folder
83
- * are ignored.
90
+ * Group relative `.json` paths (and, with `modules`, message module paths)
91
+ * into locale file sets. Paths that aren't `<dir>/<locale>.json`,
92
+ * `<dir>/<locale>/<ns>.json` or `<dir>/<locale>/<ns>.ts` under a locale
93
+ * folder are ignored.
84
94
  */
85
95
  function groupLocaleFiles(paths, options = {}) {
86
96
  var _a;
87
97
  const ignoreDirs = options.ignoreDirs ?? exports.DEFAULT_LOCALE_IGNORE_DIRS;
88
98
  const sets = new Map();
89
99
  for (const rel of [...new Set(paths.map(toPosix))].sort()) {
90
- if (!rel.endsWith('.json') || isIgnoredLocalePath(rel, ignoreDirs))
100
+ if (isIgnoredLocalePath(rel, ignoreDirs))
91
101
  continue;
92
102
  const parts = rel.split('/');
93
103
  const file = parts[parts.length - 1];
@@ -95,7 +105,21 @@ function groupLocaleFiles(paths, options = {}) {
95
105
  let dir;
96
106
  let locale;
97
107
  let layout;
98
- if (parent !== undefined && LOCALE_DIR_NAMES.includes(parent) && isLocaleCode(file.slice(0, -5))) {
108
+ const moduleExt = options.modules ? moduleExtension(file) : null;
109
+ if (moduleExt) {
110
+ // The combining index module isn't a catalog of its own.
111
+ if (parts.length < 3 || !LOCALE_DIR_NAMES.includes(parts[parts.length - 3]) || !isLocaleCode(parent))
112
+ continue;
113
+ if (file.slice(0, -moduleExt.length) === 'index')
114
+ continue;
115
+ dir = parts.slice(0, -2).join('/');
116
+ locale = parent;
117
+ layout = 'modules';
118
+ }
119
+ else if (!rel.endsWith('.json')) {
120
+ continue;
121
+ }
122
+ else if (parent !== undefined && LOCALE_DIR_NAMES.includes(parent) && isLocaleCode(file.slice(0, -5))) {
99
123
  dir = parts.slice(0, -1).join('/');
100
124
  locale = file.slice(0, -5);
101
125
  layout = 'flat';
@@ -118,7 +142,10 @@ function groupLocaleFiles(paths, options = {}) {
118
142
  async function findLocaleFileSets(projectDir, options = {}) {
119
143
  const names = `{${LOCALE_DIR_NAMES.join(',')}}`;
120
144
  const ignoreDirs = options.ignoreDirs ?? exports.DEFAULT_LOCALE_IGNORE_DIRS;
121
- const found = await (0, fast_glob_1.default)([`**/${names}/*.json`, `**/${names}/*/*.json`], {
145
+ const patterns = [`**/${names}/*.json`, `**/${names}/*/*.json`];
146
+ if (options.modules)
147
+ patterns.push(`**/${names}/*/*.{${message_modules_1.MESSAGE_MODULE_EXTENSIONS.map((e) => e.slice(1)).join(',')}}`);
148
+ const found = await (0, fast_glob_1.default)(patterns, {
122
149
  cwd: projectDir,
123
150
  ignore: ignoreDirs.map((d) => `**/${d}/**`),
124
151
  onlyFiles: true,
@@ -128,7 +155,7 @@ async function findLocaleFileSets(projectDir, options = {}) {
128
155
  return groupLocaleFiles(found, options);
129
156
  }
130
157
  /**
131
- * Read and flatten one locale of a set. Namespaced files are keyed `ns:key`.
158
+ * Read and flatten one locale of a set. Namespaced files and modules are keyed `ns:key`.
132
159
  * `read` reads another version of the files (e.g. from git); by default the
133
160
  * working tree is read.
134
161
  */
@@ -145,9 +172,10 @@ async function loadLocale(projectDir, set, locale, read = (rel) => fs_1.promises
145
172
  const content = await read(rel);
146
173
  if (content === null)
147
174
  continue;
148
- const data = JSON.parse(content);
175
+ const ext = set.layout === 'modules' ? path.extname(rel) : '.json';
176
+ const data = set.layout === 'modules' ? ((0, message_modules_1.parseMessageModule)(content, toPosix(rel))?.data ?? {}) : JSON.parse(content);
149
177
  const flat = (0, locale_qa_1.flattenLocaleMessages)(data);
150
- const ns = set.layout === 'namespaced' ? path.basename(rel, '.json') : null;
178
+ const ns = set.layout === 'flat' ? null : path.basename(rel, ext);
151
179
  for (const [k, v] of Object.entries(flat))
152
180
  messages[ns ? `${ns}:${k}` : k] = v;
153
181
  }
@@ -1,10 +1,13 @@
1
+ import { type FormalitySetting } from '../modules/translator/formality';
1
2
  export type LocaleIssueCode = 'missing_key' | 'extra_key' | 'empty_value' | 'untranslated' | 'placeholder_mismatch' | 'icu_invalid' | 'icu_mismatch' | 'plural_category_invalid' | 'plural_category_missing' | 'glossary_violation'
2
3
  /** The source text changed but the translation didn't (review of a diff). */
3
4
  | 'stale_translation'
4
5
  /** A translation present at the base of a diff was deleted while the source still has it. */
5
6
  | 'translation_removed'
6
7
  /** Pseudo-localized test output (`--provider pseudo`, ⟦…⟧), not a translation. */
7
- | 'pseudo_translation';
8
+ | 'pseudo_translation'
9
+ /** Formal and informal address mixed within one locale, or the form other than the one set. */
10
+ | 'mixed_formality';
8
11
  export type LocaleIssueSeverity = 'error' | 'warning' | 'info';
9
12
  export interface LocaleIssue {
10
13
  locale: string;
@@ -32,6 +35,12 @@ export interface LocalePairOptions {
32
35
  * detection is limited to them too.
33
36
  */
34
37
  keys?: string[];
38
+ /**
39
+ * Configured form of address per locale (or base language). Set: strings
40
+ * using the other form are flagged. Auto: the minority form is flagged when
41
+ * a locale mixes both.
42
+ */
43
+ formality?: Record<string, FormalitySetting>;
35
44
  }
36
45
  export interface LocalePairReport {
37
46
  locale: string;
@@ -20,6 +20,7 @@ const rules_1 = require("../modules/glossary/rules");
20
20
  const placeholder_protection_1 = require("../utils/placeholder-protection");
21
21
  const pseudo_markers_1 = require("../utils/pseudo-markers");
22
22
  const icu_spans_1 = require("../utils/icu-spans");
23
+ const formality_1 = require("../modules/translator/formality");
23
24
  const PLURAL_CATEGORIES = ['zero', 'one', 'two', 'few', 'many', 'other'];
24
25
  const PLURAL_SUFFIX = /^(.+)_(zero|one|two|few|many|other)$/;
25
26
  /**
@@ -324,6 +325,14 @@ function checkLocalePair(source, target, locale, options = {}) {
324
325
  continue;
325
326
  push({ key, code: 'extra_key', severity: 'info', message: 'Not in the source locale (stale or renamed key).' });
326
327
  }
328
+ // Form of address is judged over the whole locale (a diff's few keys can't
329
+ // tell which form is the norm); only keys in scope are reported.
330
+ const translations = Object.fromEntries(Object.entries(target).filter(([k, v]) => k in source && v !== source[k]));
331
+ const address = (0, formality_1.formalityIssues)(translations, locale, (0, formality_1.formalityFor)(options.formality, locale));
332
+ for (const [key, message] of Object.entries(address)) {
333
+ if (inScope(key))
334
+ push({ key, code: 'mixed_formality', severity: 'warning', message: `${message}.` });
335
+ }
327
336
  return tallyLocaleIssues({ locale, total, translated, counts: {}, errors: 0, warnings: 0, issues });
328
337
  }
329
338
  /** Recompute `counts`/`errors`/`warnings` from `issues` (after adding issues to a report). */
package/dist/qa/review.js CHANGED
@@ -129,7 +129,7 @@ async function reviewLocaleChanges(projectDir, options = {}) {
129
129
  : new Set([...changedTarget, ...source.added, ...source.changed, ...source.removed.filter((k) => k in tgtNow)].filter((k) => !removed.has(k)));
130
130
  if (keys.size === 0 && removedTarget.length === 0)
131
131
  continue;
132
- const report = (0, locale_qa_1.checkLocalePair)(srcNow, tgtNow, locale, { sourceLocale, glossary, keys: [...keys] });
132
+ const report = (0, locale_qa_1.checkLocalePair)(srcNow, tgtNow, locale, { sourceLocale, glossary, keys: [...keys], formality: config.formality });
133
133
  if (fileDeleted) {
134
134
  report.issues.unshift({
135
135
  locale,
@@ -92,8 +92,19 @@ export interface EngineConfigV2 {
92
92
  }
93
93
  export interface ExistingI18nSetup {
94
94
  library: I18nLibraryId;
95
- /** Directory of the flat `<locale>.json` files, relative to the workspace (posix). */
95
+ /**
96
+ * Directory of the locale files, relative to the workspace (posix):
97
+ * `<localeDir>/<locale>.json` (flat), or one folder per locale holding a
98
+ * file per namespace, `<localeDir>/<locale>/<ns>.json` (namespaced) or
99
+ * TypeScript/JS message modules `<localeDir>/<locale>/<ns>.ts` (modules).
100
+ */
96
101
  localeDir: string;
102
+ /** Unset: flat. */
103
+ layout?: 'flat' | 'namespaced' | 'modules';
104
+ /** Namespaced and modules: the source language's files (`auth.json`, `auth.ts`), in order. */
105
+ namespaces?: string[];
106
+ /** Modules: the source language's combining module (`index.ts`), copied for a new language. */
107
+ indexFile?: string;
97
108
  /**
98
109
  * Code files that list the app's languages by code (a locale registry, a
99
110
  * `supportedLocales` array): a new language may need adding there too.
@@ -251,6 +262,15 @@ export interface LocaleFile {
251
262
  * is the source file of an adopted i18n setup, which a run never rewrites.
252
263
  */
253
264
  noFile?: boolean;
265
+ /**
266
+ * The locale is several files (an adopted setup with a folder per locale,
267
+ * `path` being that folder): hosts write each one's exact content and
268
+ * ignore `content`/`data` for writing.
269
+ */
270
+ files?: Array<{
271
+ path: string;
272
+ content: string;
273
+ }>;
254
274
  /** Further files generated for this locale (e.g. a compiled .mo next to the .po). */
255
275
  extraFiles?: Array<{
256
276
  path: string;
package/dist/types.d.ts CHANGED
@@ -114,6 +114,8 @@ export interface HFTranslateRequest {
114
114
  brandVoice?: string;
115
115
  /** Target locale as ISO code (keeps regional variants such as pt-BR). */
116
116
  targetLocale?: string;
117
+ /** Form of address in the target language; undefined means auto. */
118
+ formality?: 'formal' | 'informal';
117
119
  /** Required terminology: source term → translation. */
118
120
  glossary?: Array<{
119
121
  term: string;
@@ -3,6 +3,7 @@ import type { ByokProvider } from '@babelize/types';
3
3
  /** Options only LLM (BYOK) providers use; the NLLB service ignores them. */
4
4
  export interface LlmRequestOptions {
5
5
  targetLocale?: string;
6
+ formality?: 'formal' | 'informal';
6
7
  glossary?: Array<{
7
8
  term: string;
8
9
  translation: string;
@@ -24,6 +25,24 @@ export declare function callTranslator(entries: TranslationEntry[], sourceLang:
24
25
  translations: TranslationEntry[];
25
26
  metadata?: any;
26
27
  }>;
28
+ /** Pauses before asking the translator again for entries it left out. */
29
+ export declare const MISSING_RETRY_DELAYS_MS: number[];
30
+ /**
31
+ * When its model call fails, the translator service still answers, with only
32
+ * the entries it resolved from its dictionary ("Features", "Log in"). That
33
+ * failure comes and goes, so ask again — twice, after a pause — for just the
34
+ * entries that are missing. A retry that fails keeps what we already have.
35
+ */
36
+ export declare function retryMissingEntries(entries: TranslationEntry[], first: {
37
+ translations: TranslationEntry[];
38
+ metadata?: any;
39
+ }, request: (batch: TranslationEntry[]) => Promise<{
40
+ translations: TranslationEntry[];
41
+ metadata?: any;
42
+ }>, signal?: AbortSignal, delaysMs?: number[]): Promise<{
43
+ translations: TranslationEntry[];
44
+ metadata?: any;
45
+ }>;
27
46
  export declare function checkTranslatorHealth(byokConfig?: {
28
47
  provider: ByokProvider;
29
48
  apiKey: string;
@@ -33,7 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MISSING_RETRY_DELAYS_MS = void 0;
36
37
  exports.callTranslator = callTranslator;
38
+ exports.retryMissingEntries = retryMissingEntries;
37
39
  exports.checkTranslatorHealth = checkTranslatorHealth;
38
40
  exports.warmupTranslator = warmupTranslator;
39
41
  const logger_1 = require("./logger");
@@ -51,28 +53,30 @@ async function callTranslator(entries, sourceLang, targetLang, byokConfig, brand
51
53
  const outerSignal = llmOptions.signal;
52
54
  const { translatorLoadBalancer } = await Promise.resolve().then(() => __importStar(require('./translator-load-balancer')));
53
55
  let rustResult = null;
54
- try {
55
- rustResult = await translatorLoadBalancer.executeWithFailover(async (translatorUrl) => {
56
- const response = await fetch(`${translatorUrl}/translate`, {
57
- method: 'POST',
58
- headers: { 'Content-Type': 'application/json' },
59
- body: JSON.stringify({ sourceLang, targetLang, entries }),
60
- signal: outerSignal ? AbortSignal.any([AbortSignal.timeout(300000), outerSignal]) : AbortSignal.timeout(300000),
61
- });
62
- if (!response.ok) {
63
- throw new Error(`Translation API error: ${response.status} ${response.statusText}`);
64
- }
65
- const data = await response.json();
66
- if (data.metadata) {
67
- logger_1.engineLogger.info('Translation metadata', {
68
- dictVersion: data.metadata.dictVersion,
69
- processingTimeMs: data.metadata.processingTimeMs,
70
- dictionaryHits: data.metadata.dictionaryHits,
71
- modelTranslations: data.metadata.modelTranslations,
72
- });
73
- }
74
- return { translations: data.translations || [], metadata: data.metadata };
56
+ const requestRust = (batch) => translatorLoadBalancer.executeWithFailover(async (translatorUrl) => {
57
+ const response = await fetch(`${translatorUrl}/translate`, {
58
+ method: 'POST',
59
+ headers: { 'Content-Type': 'application/json' },
60
+ body: JSON.stringify({ sourceLang, targetLang, entries: batch }),
61
+ signal: outerSignal ? AbortSignal.any([AbortSignal.timeout(300000), outerSignal]) : AbortSignal.timeout(300000),
75
62
  });
63
+ if (!response.ok) {
64
+ throw new Error(`Translation API error: ${response.status} ${response.statusText}`);
65
+ }
66
+ const data = await response.json();
67
+ if (data.metadata) {
68
+ logger_1.engineLogger.info('Translation metadata', {
69
+ dictVersion: data.metadata.dictVersion,
70
+ processingTimeMs: data.metadata.processingTimeMs,
71
+ dictionaryHits: data.metadata.dictionaryHits,
72
+ modelTranslations: data.metadata.modelTranslations,
73
+ });
74
+ }
75
+ return { translations: (data.translations || []), metadata: data.metadata };
76
+ });
77
+ try {
78
+ rustResult = await requestRust(entries);
79
+ rustResult = await retryMissingEntries(entries, rustResult, requestRust, outerSignal);
76
80
  }
77
81
  catch (err) {
78
82
  logger_1.engineLogger.warn('Rust translator unavailable, will try HF Inference API fallback', {
@@ -109,6 +113,36 @@ async function callTranslator(entries, sourceLang, targetLang, byokConfig, brand
109
113
  logger_1.engineLogger.error(`Translator unavailable for ${sourceLang} → ${targetLang}; no translations produced`);
110
114
  return { translations: [], metadata: { translatorUnavailable: true } };
111
115
  }
116
+ /** Pauses before asking the translator again for entries it left out. */
117
+ exports.MISSING_RETRY_DELAYS_MS = [1000, 3000];
118
+ /**
119
+ * When its model call fails, the translator service still answers, with only
120
+ * the entries it resolved from its dictionary ("Features", "Log in"). That
121
+ * failure comes and goes, so ask again — twice, after a pause — for just the
122
+ * entries that are missing. A retry that fails keeps what we already have.
123
+ */
124
+ async function retryMissingEntries(entries, first, request, signal, delaysMs = exports.MISSING_RETRY_DELAYS_MS) {
125
+ let result = first;
126
+ for (const delayMs of delaysMs) {
127
+ const have = new Set(result.translations.map((t) => t.key));
128
+ const missing = entries.filter((e) => !have.has(e.key));
129
+ if (missing.length === 0 || signal?.aborted)
130
+ break;
131
+ logger_1.engineLogger.warn('Translator left entries out of its response; asking again for them', { missing: missing.length, of: entries.length, delayMs });
132
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
133
+ let retry;
134
+ try {
135
+ retry = await request(missing);
136
+ }
137
+ catch (err) {
138
+ logger_1.engineLogger.warn('Retry for missing entries failed', { error: err instanceof Error ? err.message : String(err) });
139
+ break;
140
+ }
141
+ const wanted = new Set(missing.map((e) => e.key));
142
+ result = { ...result, translations: [...result.translations, ...retry.translations.filter((t) => wanted.has(t.key))] };
143
+ }
144
+ return result;
145
+ }
112
146
  async function callByokTranslator(entries, sourceLang, targetLang, byokConfig, brandVoice, llmOptions = {}) {
113
147
  const client = new byok_provider_1.BYOKTranslatorClient(byokConfig);
114
148
  const { signal, ...promptOptions } = llmOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.5",
3
+ "version": "0.3.8",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",
@@ -32,7 +32,7 @@
32
32
  "@babel/parser": "^7.28.5",
33
33
  "@babel/traverse": "^7.28.5",
34
34
  "@babel/types": "^7.29.8",
35
- "@babelize/types": "^0.1.3",
35
+ "@babelize/types": "^0.1.5",
36
36
  "@vue/compiler-dom": "^3.5",
37
37
  "@vue/compiler-sfc": "^3.5",
38
38
  "diff": "^8.0.4",
@@ -42,7 +42,7 @@
42
42
  "magic-string": "^0.30",
43
43
  "node-html-parser": "^8.0.4",
44
44
  "recast": "^0.23",
45
- "zod": "^3.22.4"
45
+ "zod": "^4.6.6"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@eslint/js": "^9.39.2",