locale-ai 0.6.5 → 0.6.6

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.
package/README.md CHANGED
@@ -32,7 +32,7 @@ Download 577 MB? (Y/n)
32
32
  - **Placeholders are never translated or lost**: `{name}`, `{{count}}`, `%s`, `%1$s`, `%(name)s`, `%{name}`, `${name}`, `:attribute`, `$t(key)`, `@:key`, `<b>…</b>`, `<0>…</0>`, `&nbsp;`, URLs, e-mails.
33
33
  - **ICU MessageFormat**: `{count, plural, one {# file} other {# files}}`, `select`, nesting. Only the text is translated.
34
34
  - **i18next plurals**: adds the forms the target language needs (`_few`, `_many` for Arabic, Russian, Polish...), so the app doesn't fall back to the English string — each added form copies the `_other` translation verbatim rather than inflecting it, so review and adjust the wording of `_zero`/`_two`/`_few`/`_many` by hand for languages where those forms use a different noun/adjective form. The `_one` form is translated with its `{{count}}` temporarily replaced by a literal "1", since the model otherwise sometimes picks the target's plural noun form despite the English source being grammatically singular.
35
- - **Incremental**: only missing keys are translated, existing translations are kept, re-runs are no-ops. `--overwrite` re-translates everything.
35
+ - **Incremental, and edit-aware**: only missing or changed keys are translated; untouched translations are kept, so re-runs are no-ops. A small `locale-ai.lock.json` (commit it, like a package lock) remembers a hash of each source string and of the output last written for it per target locale — so editing a source string gets it re-translated automatically (it isn't enough for the target to already hold *some* text), while editing a target string by hand is detected and reported for review instead of being silently overwritten on the next run. `--overwrite` bypasses the lock and re-translates everything.
36
36
  - **Structure**: key order, numbers, booleans, arrays, indentation and trailing newline are preserved.
37
37
 
38
38
  **Format notes**: for `.po`, `msgid` is the stable key (never changed) and `msgstr` is the translated value, as gettext expects — the English `.po` file's `msgstr` must hold the source text (most generators already fill it; an empty `msgstr` is treated as empty, not inherited from `msgid`). `msgid_plural`/`msgstr[n]` plural entries are translated too (the singular and plural source forms), then expanded to however many `msgstr[n]` the target language's plural rules need (6 for Arabic, 1 for Japanese, ...) — not full grammatical inflection for in-between categories (`few`/`many`/...), which get the plural-sourced translation verbatim, the same simplification `addPluralForms` makes for i18next. `Plural-Forms` in the header is computed for the target language, not copied from the source; an existing target file's header is otherwise left as you last edited it (a hand-fixed `Plural-Forms`, `Last-Translator`, ...) instead of being regenerated on every rerun. For `.arb`, `@key` metadata and `@@locale` are never translated; `@@locale` is set to the target locale on output.
@@ -41,7 +41,7 @@ Download 577 MB? (Y/n)
41
41
 
42
42
  - **No API keys, no cloud bill.** Google/DeepL/OpenAI-based translation tools work well but mean an account, a key, a per-character cost, and your strings leaving your machine. locale-ai runs the model on your own CPU.
43
43
  - **Built for i18n files, not plain text.** General MT tools translate strings; they don't know that `{count}`, `<0>bold</0>`, or `$t(common.footer.tagline)` must survive untouched. locale-ai is built around i18next/ICU conventions specifically, so placeholders, plurals, and nested references come out intact instead of mangled or dropped.
44
- - **Incremental by default.** Add one new key to `en.json` and only that key gets translated — existing translations in `fr.json`/`es.json`/etc. are left alone, so re-runs are cheap and safe to automate in CI.
44
+ - **Incremental by default.** Add one new key to `en.json` and only that key gets translated; edit an existing one and the lockfile catches it and re-translates just that key — existing, unrelated translations are left alone, so re-runs are cheap and safe to automate in CI.
45
45
  - **Honest about quality.** The [Languages](#languages) section tells you which pairs are review-light vs. which need a human pass, instead of presenting every language as equally production-ready.
46
46
 
47
47
  **When *not* to use it**: if you need professional/legal-grade translation, or languages outside the [supported list](#languages), use a human translator or a larger cloud model instead — locale-ai is built for keeping UI strings in sync across languages during development, with a review pass before shipping.
package/dist/cli.js CHANGED
@@ -9,6 +9,7 @@ import { CATALOG, customEntries, findById, reachableTargets, resolveRoute, } fro
9
9
  import { translateStrings } from "./engine.js";
10
10
  import { CONFIG_FILE, glossaryLookup, loadConfig, protectRegex } from "./glossary.js";
11
11
  import { intlCode, parseLocale } from "./lang.js";
12
+ import { editedPaths, isSourceStale, LOCK_FILENAME, loadLock, recordEntries, saveLock } from "./lock.js";
12
13
  import { addPluralForms, buildTarget, detectLayout, existingTargets, flattenStrings, keyPathProtect, pendingStrings, pluralOneStrings, readLocaleDoc, sourceFiles, targetFile, } from "./locales.js";
13
14
  import { cacheRoot, install, isInstalled, loadTranslator, localModelProblem, planInstall, readManifest, uninstall, } from "./models.js";
14
15
  import { mask } from "./placeholders.js";
@@ -54,6 +55,8 @@ const endStatus = () => {
54
55
  };
55
56
  const mb = (bytes) => `${Math.round(bytes / 1e6)} MB`;
56
57
  const rel = (p) => path.relative(process.cwd(), p) || ".";
58
+ /** Portable lock-file key: forward slashes regardless of platform. */
59
+ const fileKey = (p) => rel(p).split(path.sep).join("/");
57
60
  /**
58
61
  * `Number("abc")` is NaN, and NaN silently poisons everything downstream (an
59
62
  * all-garbage translation batch, or a raw ONNX crash deep in the model) instead of
@@ -160,6 +163,8 @@ async function cmdTranslate(argv) {
160
163
  const protect = protectRegex(config);
161
164
  const isProtectedKey = keyPathProtect(config.doNotTranslateKeys);
162
165
  const layout = detectLayout(process.cwd(), from.tag, values.input);
166
+ const lockPath = path.resolve(process.cwd(), LOCK_FILENAME);
167
+ const lock = loadLock(lockPath);
163
168
  const sources = sourceFiles(layout, from.tag).map((f) => ({ file: f, doc: readLocaleDoc(f, from.tag) }));
164
169
  const singularHints = new Set(sources.flatMap(({ doc }) => [...pluralOneStrings(doc.data)]));
165
170
  log(`locale-ai ${VERSION}`);
@@ -179,12 +184,13 @@ async function cmdTranslate(argv) {
179
184
  const files = sources.map(({ file, doc }) => {
180
185
  const target = targetFile(layout, from.tag, locale.tag, file);
181
186
  const existing = fs.existsSync(target) ? readLocaleDoc(target, locale.tag).data : undefined;
187
+ const isStale = (p, s) => isSourceStale(lock, fileKey(file), p, s);
182
188
  return {
183
189
  source: file,
184
190
  target,
185
191
  doc,
186
192
  existing,
187
- pending: pendingStrings(doc.data, existing, values.overwrite, isProtectedKey),
193
+ pending: pendingStrings(doc.data, existing, values.overwrite, isProtectedKey, isStale),
188
194
  };
189
195
  });
190
196
  const unique = new Set(files.flatMap((f) => f.pending)).size;
@@ -244,7 +250,14 @@ async function cmdTranslate(argv) {
244
250
  let written = 0;
245
251
  let pluralsAdded = 0;
246
252
  for (const f of job.files) {
247
- const built = buildTarget(f.doc.data, f.existing, (s) => translations.get(s) ?? s, values.overwrite, isProtectedKey);
253
+ const lockKey = fileKey(f.source);
254
+ const isStale = (p, s) => isSourceStale(lock, lockKey, p, s);
255
+ if (f.existing !== undefined) {
256
+ for (const editedPath of editedPaths(lock, lockKey, job.locale.tag, flattenStrings(f.existing))) {
257
+ allIssues.push({ source: editedPath, kind: "edited", locale: job.locale.tag });
258
+ }
259
+ }
260
+ const built = buildTarget(f.doc.data, f.existing, (s) => translations.get(s) ?? s, values.overwrite, isProtectedKey, isStale);
248
261
  const { doc, added } = addPluralForms(built, intlCode(job.locale));
249
262
  pluralsAdded += added;
250
263
  const before = fs.existsSync(f.target) ? fs.readFileSync(f.target, "utf8") : undefined;
@@ -254,6 +267,8 @@ async function cmdTranslate(argv) {
254
267
  fs.writeFileSync(f.target, text);
255
268
  written++;
256
269
  }
270
+ const outFlat = new Map(flattenStrings(doc).map((e) => [e.path, e.value]));
271
+ recordEntries(lock, lockKey, job.locale.tag, flattenStrings(f.doc.data).map(({ path: p, value }) => ({ path: p, source: value, written: outFlat.get(p) ?? "" })));
257
272
  }
258
273
  const secs = ((Date.now() - started) / 1000).toFixed(1);
259
274
  const issues = allIssues.filter((i) => i.locale === job.locale.tag).length;
@@ -264,6 +279,8 @@ async function cmdTranslate(argv) {
264
279
  }
265
280
  for (const t of loaded.values())
266
281
  await t.dispose();
282
+ if (jobs.length)
283
+ saveLock(lockPath, lock);
267
284
  if (allIssues.length) {
268
285
  log();
269
286
  log(`${allIssues.length} string${allIssues.length === 1 ? "" : "s"} worth a quick review:`);
package/dist/locales.js CHANGED
@@ -461,11 +461,11 @@ export function keyPathProtect(doNotTranslateKeys) {
461
461
  return undefined;
462
462
  return (path) => keys.some((k) => path === k || path.startsWith(`${k}.`) || path.startsWith(`${k}[`));
463
463
  }
464
- export function pendingStrings(source, existing, overwrite, isProtected) {
464
+ export function pendingStrings(source, existing, overwrite, isProtected, isStale) {
465
465
  const out = [];
466
466
  const visit = (s, e, path) => {
467
467
  if (typeof s === "string") {
468
- if (!isProtected?.(path) && needsTranslation(e, overwrite))
468
+ if (!isProtected?.(path) && (needsTranslation(e, overwrite) || !!isStale?.(path, s)))
469
469
  out.push(s);
470
470
  }
471
471
  else if (Array.isArray(s)) {
@@ -481,16 +481,19 @@ export function pendingStrings(source, existing, overwrite, isProtected) {
481
481
  }
482
482
  /**
483
483
  * Builds the target document: source structure and key order, existing
484
- * translations kept (unless overwrite), new strings from `translate`, and keys
485
- * that only exist in the target preserved at the end. A string at a protected
486
- * path (see keyPathProtect) is always copied from the source verbatim.
484
+ * translations kept (unless overwrite or stale), new strings from `translate`,
485
+ * and keys that only exist in the target preserved at the end. A string at a
486
+ * protected path (see keyPathProtect) is always copied from the source
487
+ * verbatim. `isStale` (see the lock module) forces re-translation of a
488
+ * non-empty target when its source string has changed since it was last
489
+ * translated.
487
490
  */
488
- export function buildTarget(source, existing, translate, overwrite, isProtected) {
491
+ export function buildTarget(source, existing, translate, overwrite, isProtected, isStale) {
489
492
  const visit = (s, e, path) => {
490
493
  if (typeof s === "string") {
491
494
  if (isProtected?.(path))
492
495
  return s;
493
- return needsTranslation(e, overwrite) ? translate(s) : e;
496
+ return needsTranslation(e, overwrite) || isStale?.(path, s) ? translate(s) : e;
494
497
  }
495
498
  if (Array.isArray(s))
496
499
  return s.map((v, i) => visit(v, Array.isArray(e) ? e[i] : undefined, `${path}[${i}]`));
package/dist/lock.js ADDED
@@ -0,0 +1,56 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ export const LOCK_FILENAME = "locale-ai.lock.json";
4
+ export function hashOf(s) {
5
+ return crypto.createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16);
6
+ }
7
+ export function loadLock(file) {
8
+ try {
9
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
10
+ if (parsed && typeof parsed === "object" && parsed.files)
11
+ return { version: 1, files: parsed.files };
12
+ }
13
+ catch {
14
+ // Missing or invalid: start fresh rather than fail the run.
15
+ }
16
+ return { version: 1, files: {} };
17
+ }
18
+ export function saveLock(file, lock) {
19
+ fs.writeFileSync(file, `${JSON.stringify(lock, null, 2)}\n`);
20
+ }
21
+ /**
22
+ * True when `path`'s source string in `fileKey` has changed since it was last
23
+ * translated — meaning the existing target text is stale and needs redoing
24
+ * even though it's non-empty. False for a path the lock has never seen (new
25
+ * adoption, or a brand-new key, both already handled by the empty-target check).
26
+ */
27
+ export function isSourceStale(lock, fileKey, path, source) {
28
+ const entry = lock.files[fileKey]?.[path];
29
+ return entry !== undefined && entry.source !== hashOf(source);
30
+ }
31
+ /**
32
+ * Key paths whose existing target text no longer matches the output this tool
33
+ * last wrote there for `targetTag` — i.e. a translator edited it since. Only
34
+ * reported; the edit is never overwritten.
35
+ */
36
+ export function editedPaths(lock, fileKey, targetTag, entries) {
37
+ const file = lock.files[fileKey];
38
+ if (!file)
39
+ return [];
40
+ const out = [];
41
+ for (const { path, value } of entries) {
42
+ const mt = file[path]?.mt[targetTag];
43
+ if (mt !== undefined && mt !== hashOf(value))
44
+ out.push(path);
45
+ }
46
+ return out;
47
+ }
48
+ /** Records, for every path translated this run, the current source hash and the hash of what ended up on disk. */
49
+ export function recordEntries(lock, fileKey, targetTag, entries) {
50
+ const file = (lock.files[fileKey] ??= {});
51
+ for (const { path, source, written } of entries) {
52
+ const entry = (file[path] ??= { source: hashOf(source), mt: {} });
53
+ entry.source = hashOf(source);
54
+ entry.mt[targetTag] = hashOf(written);
55
+ }
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "locale-ai",
3
- "version": "0.6.5",
3
+ "version": "0.6.6",
4
4
  "description": "Translate your i18n locale files locally on CPU. Free, offline, no API keys.",
5
5
  "author": "Taha KHABOUSS",
6
6
  "repository": {