@babelize/engine 0.3.1 → 0.3.3

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.
@@ -45,6 +45,8 @@ export interface TranslateReportLocale {
45
45
  failed: number;
46
46
  qaWarnings: number;
47
47
  sameAsSource: number;
48
+ /** Keys re-translated only because their glossary rules changed. */
49
+ glossaryChanged: number;
48
50
  }
49
51
  export interface TranslateReport {
50
52
  $schema: string;
@@ -129,6 +131,14 @@ export interface TranslateReport {
129
131
  value: string;
130
132
  }>;
131
133
  };
134
+ /** Keys re-translated although their source didn't change, because their glossary rules did. */
135
+ glossaryChanged: {
136
+ total: number;
137
+ items: Array<{
138
+ locale: string;
139
+ key: string;
140
+ }>;
141
+ };
132
142
  notInjected: {
133
143
  total: number;
134
144
  items: Array<{
@@ -68,6 +68,7 @@ function buildTranslateReport(r) {
68
68
  const missing = r.locales.flatMap((l) => l.missing.filter((k) => !failedBy.has(`${l.locale}\0${k}`)).map((key) => ({ locale: l.locale, key })));
69
69
  const unchanged = r.locales.flatMap((l) => l.sameAsSource.map((key) => ({ locale: l.locale, key, value: r.results.targets[l.locale]?.[key] ?? '' })));
70
70
  const unchangedBy = new Set(unchanged.map((u) => `${u.locale}\0${u.key}`));
71
+ const glossaryChanged = r.locales.flatMap((l) => (l.glossaryChanged ?? []).map((key) => ({ locale: l.locale, key })));
71
72
  const keys = Object.entries(r.results.source).map(([key, source]) => {
72
73
  const locales = {};
73
74
  for (const l of r.locales) {
@@ -141,12 +142,14 @@ function buildTranslateReport(r) {
141
142
  failed,
142
143
  qaWarnings: l.qa.length,
143
144
  sameAsSource: l.sameAsSource.length,
145
+ glossaryChanged: l.glossaryChanged?.length ?? 0,
144
146
  };
145
147
  }),
146
148
  failures: { total: failures.length, items: failures },
147
149
  qaWarnings: { total: qaItems.length, items: qaItems },
148
150
  missing: { total: missing.length, items: missing },
149
151
  unchanged: { total: unchanged.length, items: unchanged },
152
+ glossaryChanged: { total: glossaryChanged.length, items: glossaryChanged },
150
153
  notInjected: { total: r.notInjected.length, items: r.notInjected },
151
154
  unusedKeys: { total: r.unusedKeys.length, items: r.unusedKeys },
152
155
  dynamicKeyFiles: r.dynamicKeyFiles,
@@ -109,6 +109,12 @@ export interface LocaleReport {
109
109
  * "OK", or a cached value from before that check existed).
110
110
  */
111
111
  sameAsSource: string[];
112
+ /**
113
+ * Keys re-translated although their source text didn't change, because the
114
+ * glossary rules that apply to them did. Explains a locale diff with no
115
+ * matching change in the source locale. Failed keys are listed in `failed`.
116
+ */
117
+ glossaryChanged?: string[];
112
118
  }
113
119
  /**
114
120
  * Everything a run produced. Structured so a per-key QA report (#237) can be
@@ -210,7 +216,7 @@ export declare function validateLocales(sourceLocale: string, targetLocales: str
210
216
  /** `msg` as one sentence: trailing dots/spaces trimmed, exactly one period added. */
211
217
  export declare function sentence(msg: string): string;
212
218
  export declare function isEngineLogNoise(message: string): boolean;
213
- export declare function buildLocaleReports(targetLocales: string[], source: Record<string, string>, targets: Record<string, Record<string, string>>, failures?: TranslationFailure[], metadata?: Record<string, Record<string, unknown>>): LocaleReport[];
219
+ export declare function buildLocaleReports(targetLocales: string[], source: Record<string, string>, targets: Record<string, Record<string, string>>, failures?: TranslationFailure[], metadata?: Record<string, Record<string, unknown>>, glossaryRetranslated?: Record<string, string[]>): LocaleReport[];
214
220
  /**
215
221
  * Run the Babelize engine on a temp copy of `projectDir` and, unless
216
222
  * `dryRun`, apply the result back to the working tree. The project is never
@@ -206,7 +206,7 @@ function stripMeta(flat) {
206
206
  function hasLetters(text) {
207
207
  return /\p{L}/u.test(text);
208
208
  }
209
- function buildLocaleReports(targetLocales, source, targets, failures = [], metadata = {}) {
209
+ function buildLocaleReports(targetLocales, source, targets, failures = [], metadata = {}, glossaryRetranslated = {}) {
210
210
  const src = stripMeta(source);
211
211
  const keys = Object.keys(src);
212
212
  return targetLocales.map((locale) => {
@@ -233,7 +233,12 @@ function buildLocaleReports(targetLocales, source, targets, failures = [], metad
233
233
  if (Array.isArray(warnings) && warnings.length > 0)
234
234
  qa.push({ key, warnings: warnings.map(String) });
235
235
  }
236
- return { locale, total: keys.length, translated, missing, failed, qa, sameAsSource };
236
+ const failedKeys = new Set(failed.map((f) => f.key));
237
+ const glossaryChanged = (glossaryRetranslated[locale] ?? []).filter((k) => k in src && !failedKeys.has(k));
238
+ return {
239
+ locale, total: keys.length, translated, missing, failed, qa, sameAsSource,
240
+ ...(glossaryChanged.length > 0 ? { glossaryChanged } : {}),
241
+ };
237
242
  });
238
243
  }
239
244
  function describeEngineFailure(error, byok) {
@@ -362,7 +367,7 @@ async function runScoped(opts, deps, engineLog, state) {
362
367
  const targets = result.results?.targets ?? {};
363
368
  const translationFailures = result.translationFailures ?? [];
364
369
  const metadata = (result.results?.metadata ?? {});
365
- const locales = buildLocaleReports(targetLocales, source, targets, translationFailures, metadata);
370
+ const locales = buildLocaleReports(targetLocales, source, targets, translationFailures, metadata, result.stats.glossaryRetranslated);
366
371
  // A locale with source keys but zero translations (nothing, or only copies
367
372
  // of the source text) is a failed run, not a partial one: refuse to write
368
373
  // it rather than ship an untranslated language as if it were done.
@@ -373,15 +373,25 @@ function partitionKeys(lockfile, keys, targetLocales, options = {}) {
373
373
  continue;
374
374
  }
375
375
  // Hash matches — check if all target locales are present
376
- const missing = targetLocales.filter((locale) => !(locale in entry.languages) || isStalePseudoEntry(entry, locale, options) ||
377
- glossaryChanged(entry, value, locale, options));
376
+ const glossaryLocales = [];
377
+ const missing = targetLocales.filter((locale) => {
378
+ if (!(locale in entry.languages) || isStalePseudoEntry(entry, locale, options))
379
+ return true;
380
+ if (!glossaryChanged(entry, value, locale, options))
381
+ return false;
382
+ glossaryLocales.push(locale);
383
+ return true;
384
+ });
378
385
  if (missing.length === 0) {
379
386
  // Fully translated and unchanged
380
387
  result.unchanged.push({ key, value });
381
388
  }
382
389
  else {
383
- // Some locales missing
384
- result.missingLocales.push({ key, value, missingLocales: missing });
390
+ // Some locales missing (or due again because the glossary changed)
391
+ result.missingLocales.push({
392
+ key, value, missingLocales: missing,
393
+ ...(glossaryLocales.length > 0 ? { glossaryLocales } : {}),
394
+ });
385
395
  }
386
396
  }
387
397
  return result;
@@ -529,11 +539,17 @@ function collectCachedTranslations(lockfile, unchangedKeys, targetLocales, optio
529
539
  * Compute stats for the UI: X translated, Y reused, Z changed.
530
540
  */
531
541
  function computeLockfileStats(partition) {
542
+ const glossaryRetranslated = {};
543
+ for (const { key, glossaryLocales } of partition.missingLocales) {
544
+ for (const locale of glossaryLocales ?? [])
545
+ (glossaryRetranslated[locale] ?? (glossaryRetranslated[locale] = [])).push(key);
546
+ }
532
547
  return {
533
548
  reused: partition.unchanged.length,
534
549
  translated: partition.newKeys.length +
535
550
  partition.changed.length +
536
551
  partition.missingLocales.length,
537
552
  changed: partition.changed.length,
553
+ ...(Object.keys(glossaryRetranslated).length > 0 ? { glossaryRetranslated } : {}),
538
554
  };
539
555
  }
@@ -197,14 +197,21 @@ export interface LockfilePartition {
197
197
  newKeys: PartitionedKey[];
198
198
  /** Keys whose source hash has changed */
199
199
  changed: PartitionedKey[];
200
- /** Keys whose hash matches but are missing some target locales */
200
+ /**
201
+ * Keys whose hash matches but are missing some target locales. A locale is
202
+ * also "missing" when the glossary rules for the key changed since its
203
+ * translation was stored; those locales are listed in `glossaryLocales` too.
204
+ */
201
205
  missingLocales: Array<PartitionedKey & {
202
206
  missingLocales: string[];
207
+ glossaryLocales?: string[];
203
208
  }>;
204
209
  }
205
210
  export interface LockfileStats {
206
211
  reused: number;
207
212
  translated: number;
208
213
  changed: number;
214
+ /** locale → keys re-translated only because their glossary rules changed. */
215
+ glossaryRetranslated?: Record<string, string[]>;
209
216
  }
210
217
  export declare function createEmptyLockfile(projectId: string): LockfileData;
@@ -19,6 +19,7 @@ function generateSummary(extraction, keyGeneration, localeHandling, translation,
19
19
  lockfileUsed: lockfileStats != null,
20
20
  lockfileKeysTranslated: lockfileStats?.translated,
21
21
  lockfileKeysChanged: lockfileStats?.changed,
22
+ ...(lockfileStats?.glossaryRetranslated ? { glossaryRetranslated: lockfileStats.glossaryRetranslated } : {}),
22
23
  };
23
24
  const warnings = [
24
25
  ...collectExtractionWarnings(extraction),
@@ -134,6 +134,29 @@ declare function restoreNumbers(translated: string, slots: NumberSlot[]): {
134
134
  } | {
135
135
  problem: string;
136
136
  };
137
+ /**
138
+ * Branches of one message sent as a single sentence ("You have 1 item in your
139
+ * cart; you have 25 items in your cart."), so a plain-text translator words
140
+ * them alike: translated one by one, NLLB picked "carrito" for one branch and
141
+ * "carro" for the other, or "Du" and "Sie". Null when the branches don't fit
142
+ * in one sentence: fewer than two, more than four, too long, or already
143
+ * containing several sentences or a semicolon.
144
+ */
145
+ export interface JointBranches {
146
+ text: string;
147
+ units: BranchUnit[];
148
+ /** Per unit: the source ended with "." (the translation gets the target's full stop back). */
149
+ endsWithStop: boolean[];
150
+ /** Per unit: its first letter was lowered to join the sentence (raised again after). */
151
+ lowered: boolean[];
152
+ }
153
+ export declare function joinBranchUnits(units: BranchUnit[], targetLocale?: string): JointBranches | null;
154
+ /**
155
+ * The joint translation split back per unit, or null when it doesn't come
156
+ * apart cleanly (the caller then sends the branches one by one): a different
157
+ * number of parts, an empty one, or one that came back untranslated.
158
+ */
159
+ export declare function splitJointTranslation(translated: string, joint: JointBranches): string[] | null;
137
160
  /** ICU-escape literal text: apostrophes before syntax, and `{`, `}` (and `#` in a plural) quoted. */
138
161
  export declare function escapeIcuText(text: string, inPlural: boolean): string;
139
162
  /** Exposed for tests. */
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.__test = exports.MAX_BRANCH_UNITS = void 0;
4
4
  exports.targetCategories = targetCategories;
5
5
  exports.planIcuBranches = planIcuBranches;
6
+ exports.joinBranchUnits = joinBranchUnits;
7
+ exports.splitJointTranslation = splitJointTranslation;
6
8
  exports.escapeIcuText = escapeIcuText;
7
9
  /**
8
10
  * ICU plural/select messages for plain-text machine translation (NLLB).
@@ -327,6 +329,74 @@ function restoreNumbers(translated, slots) {
327
329
  }
328
330
  return { text };
329
331
  }
332
+ const JOINT_MAX_UNITS = 4;
333
+ /** The translator keeps up to 40 words in one model pass; stay under it. */
334
+ const JOINT_MAX_WORDS = 36;
335
+ const JOINT_SEPARATOR = /\s*[;;؛]\s*/;
336
+ /**
337
+ * Whether ordinary counts take more forms than singular and plural in this
338
+ * language (Polish, Russian, Czech, Arabic…). Joined into one sentence, NLLB
339
+ * copies the noun form across the counts ("22 plików" for "22 pliki"), while
340
+ * one sentence per count inflects right, so count branches go one by one there.
341
+ */
342
+ function inflectsCountsBeyondOneOther(locale) {
343
+ return targetCategories(locale, 'cardinal').some((c) => c !== 'one' && c !== 'other' && numbersFor(locale, 'plural', c).length > 0);
344
+ }
345
+ function joinBranchUnits(units, targetLocale) {
346
+ if (units.length < 2 || units.length > JOINT_MAX_UNITS)
347
+ return null;
348
+ if (targetLocale && units.some((u) => u.slots.length > 0) && inflectsCountsBeyondOneOther(targetLocale))
349
+ return null;
350
+ const words = units.reduce((n, u) => n + u.sendText.trim().split(/\s+/).length, 0);
351
+ if (words > JOINT_MAX_WORDS)
352
+ return null;
353
+ const parts = [];
354
+ const endsWithStop = [];
355
+ const lowered = [];
356
+ for (const [i, u] of units.entries()) {
357
+ const text = u.sendText.trim();
358
+ // One sentence each, ending in a full stop or nothing.
359
+ if (!text || /[;;؛]/.test(text) || /[.!?](?=\s+\S)/.test(text) || /[!?]$/.test(text))
360
+ return null;
361
+ const stop = text.endsWith('.');
362
+ let part = stop ? text.slice(0, -1) : text;
363
+ // "You have…" → "you have…" after the semicolon; acronyms ("API") stay.
364
+ const lower = i > 0 && /^\p{Lu}\p{Ll}/u.test(part);
365
+ if (lower)
366
+ part = part[0].toLowerCase() + part.slice(1);
367
+ parts.push(part);
368
+ endsWithStop.push(stop);
369
+ lowered.push(lower);
370
+ }
371
+ const last = endsWithStop[endsWithStop.length - 1];
372
+ return { text: parts.join('; ') + (last ? '.' : ''), units, endsWithStop, lowered };
373
+ }
374
+ /**
375
+ * The joint translation split back per unit, or null when it doesn't come
376
+ * apart cleanly (the caller then sends the branches one by one): a different
377
+ * number of parts, an empty one, or one that came back untranslated.
378
+ */
379
+ function splitJointTranslation(translated, joint) {
380
+ const trimmed = translated.trim();
381
+ const stop = /[.。.।۔]$/u.exec(trimmed)?.[0];
382
+ const body = stop ? trimmed.slice(0, -stop.length) : trimmed;
383
+ const parts = body.split(JOINT_SEPARATOR);
384
+ if (parts.length !== joint.units.length || parts.some((p) => !p.trim()))
385
+ return null;
386
+ const bare = (t) => t.trim().replace(/[.。]$/, '').toLowerCase();
387
+ if (parts.some((p, i) => bare(p) === bare(joint.units[i].sendText)))
388
+ return null;
389
+ // Later sentences start with a capital when the first one does ("Se cargó…; se cargaron…").
390
+ const capitalized = /^\p{Lu}/u.test(parts[0].trim());
391
+ return parts.map((p, i) => {
392
+ let out = p.trim();
393
+ if ((joint.lowered[i] || (i > 0 && capitalized)) && /^\p{Ll}/u.test(out))
394
+ out = out[0].toUpperCase() + out.slice(1);
395
+ if (joint.endsWithStop[i])
396
+ out += stop ?? '.';
397
+ return out;
398
+ });
399
+ }
330
400
  /** ICU-escape literal text: apostrophes before syntax, and `{`, `}` (and `#` in a plural) quoted. */
331
401
  function escapeIcuText(text, inPlural) {
332
402
  const special = inPlural ? /[{}#]/ : /[{}]/;
@@ -777,6 +777,12 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
777
777
  const plans = new Map();
778
778
  const requests = [];
779
779
  const unitKey = (key, id) => `${key}#branch${id}`;
780
+ const jointKey = (key) => `${key}#joint`;
781
+ // Branches that fit in one sentence go together, so they are worded alike.
782
+ const joints = new Map();
783
+ const unitRequests = (b, plan) => plan.units
784
+ .filter((u) => !u.passthrough)
785
+ .map((u) => ({ key: unitKey(b.key, u.id), value: u.sendText, parentContext: contextMap?.[b.key], extractionContext: extractionContextMap?.[b.key] }));
780
786
  for (const b of entries) {
781
787
  const plan = (0, icu_branches_1.planIcuBranches)(b.value, targetLocale, {
782
788
  neverTranslateTerms,
@@ -790,10 +796,13 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
790
796
  continue;
791
797
  }
792
798
  plans.set(b.key, { entry: b, plan });
793
- for (const u of plan.units) {
794
- if (u.passthrough)
795
- continue;
796
- requests.push({ key: unitKey(b.key, u.id), value: u.sendText, parentContext: contextMap?.[b.key], extractionContext: extractionContextMap?.[b.key] });
799
+ const joint = (0, icu_branches_1.joinBranchUnits)(plan.units.filter((u) => !u.passthrough), targetLocale);
800
+ if (joint) {
801
+ joints.set(b.key, joint);
802
+ requests.push({ key: jointKey(b.key), value: joint.text, parentContext: contextMap?.[b.key], extractionContext: extractionContextMap?.[b.key] });
803
+ }
804
+ else {
805
+ requests.push(...unitRequests(b, plan));
797
806
  }
798
807
  }
799
808
  const results = new Map();
@@ -822,17 +831,38 @@ async function translateEntries(entries, sourceLang, targetLang, projectId, onPr
822
831
  });
823
832
  if (skipped.length > 0)
824
833
  await sendAll(skipped);
834
+ // A joint translation is split back into its branches.
835
+ for (const [key, joint] of joints) {
836
+ const r = results.get(jointKey(key));
837
+ const parts = r?.status === 'ok' ? (0, icu_branches_1.splitJointTranslation)(r.value, joint) : null;
838
+ if (!parts)
839
+ continue;
840
+ joint.units.forEach((u, i) => results.set(unitKey(key, u.id), { key: unitKey(key, u.id), status: 'ok', value: parts[i] }));
841
+ }
825
842
  const checkUnit = (unit, translated) => isUnchangedSentence(unit.sendText, translated) || (0, untranslated_1.isUntranslatedInto)(unit.sendText, translated, targetLocale)
826
843
  ? { ok: false, reason: 'untranslated', retryable: true, message: `returned unchanged instead of translated into ${targetLocale}` }
827
844
  : null;
828
- for (const [key, { entry, plan }] of plans) {
829
- const composed = plan.compose(new Map(plan.units.map((u) => [u.id, results.get(unitKey(key, u.id))])), checkUnit);
830
- if (!composed.ok) {
831
- out.set(key, { ok: false, reason: composed.reason, retryable: composed.retryable, message: composed.message });
832
- continue;
845
+ const composeAll = (keys) => {
846
+ for (const key of keys) {
847
+ const { entry, plan } = plans.get(key);
848
+ const composed = plan.compose(new Map(plan.units.map((u) => [u.id, results.get(unitKey(key, u.id))])), checkUnit);
849
+ if (!composed.ok) {
850
+ out.set(key, { ok: false, reason: composed.reason, retryable: composed.retryable, message: composed.message });
851
+ continue;
852
+ }
853
+ // Each branch was cleaned up on its own; the message is checked as a whole.
854
+ out.set(key, judge(entry, { key, status: 'ok', value: composed.value }, false));
833
855
  }
834
- // Each branch was cleaned up on its own; the message is checked as a whole.
835
- out.set(key, judge(entry, { key, status: 'ok', value: composed.value }, false));
856
+ };
857
+ composeAll(plans.keys());
858
+ // A joint translation that didn't split or compose cleanly: its branches one by one.
859
+ const retry = [...joints.keys()].filter((key) => out.get(key)?.ok === false);
860
+ if (retry.length > 0) {
861
+ for (const key of retry)
862
+ for (const u of plans.get(key).plan.units)
863
+ results.delete(unitKey(key, u.id));
864
+ await sendAll(retry.flatMap((key) => unitRequests(plans.get(key).entry, plans.get(key).plan)));
865
+ composeAll(retry);
836
866
  }
837
867
  return out;
838
868
  };
@@ -347,6 +347,8 @@ export interface ProcessingStats {
347
347
  lockfileKeysTranslated?: number;
348
348
  /** Keys whose source text changed vs the lockfile */
349
349
  lockfileKeysChanged?: number;
350
+ /** locale → keys re-translated only because their glossary rules changed */
351
+ glossaryRetranslated?: Record<string, string[]>;
350
352
  /**
351
353
  * (key, locale) translations the translator actually produced this run —
352
354
  * the billable work. Excludes lockfile, translation-memory and cache reuse,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelize/engine",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Babelize translation pipeline (extract, keygen, translate, inject). Infrastructure is injected through provider/store interfaces.",
5
5
  "keywords": [
6
6
  "babelize",
@@ -111,7 +111,8 @@
111
111
  "missing": { "$ref": "#/$defs/count" },
112
112
  "failed": { "$ref": "#/$defs/count" },
113
113
  "qaWarnings": { "$ref": "#/$defs/count" },
114
- "sameAsSource": { "$ref": "#/$defs/count" }
114
+ "sameAsSource": { "$ref": "#/$defs/count" },
115
+ "glossaryChanged": { "$ref": "#/$defs/count", "description": "Keys re-translated only because their glossary rules changed." }
115
116
  }
116
117
  }
117
118
  },
@@ -171,6 +172,22 @@
171
172
  }
172
173
  }
173
174
  },
175
+ "glossaryChanged": {
176
+ "$ref": "#/$defs/list",
177
+ "type": "object",
178
+ "description": "Keys re-translated although their source text didn't change, because the glossary rules that apply to them did.",
179
+ "properties": {
180
+ "items": {
181
+ "type": "array",
182
+ "items": {
183
+ "type": "object",
184
+ "additionalProperties": false,
185
+ "required": ["locale", "key"],
186
+ "properties": { "locale": { "type": "string" }, "key": { "type": "string" } }
187
+ }
188
+ }
189
+ }
190
+ },
174
191
  "unchanged": {
175
192
  "$ref": "#/$defs/list",
176
193
  "type": "object",