autoglot 0.4.0 → 0.4.2

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
@@ -41,8 +41,8 @@ Review the generated files, install the suggested i18n library, and add `ANTHROP
41
41
  Autoglot 0.4.0 adds unattended setup. From your app directory, pass a comma-separated list of target locales.
42
42
 
43
43
  ```bash
44
- npx --yes autoglot@0.4.0 init --locales=de,pt-BR
45
- npx --yes autoglot@0.4.0 --dry-run
44
+ npx --yes autoglot@0.4.2 init --locales=de,pt-BR
45
+ npx --yes autoglot@0.4.2 --dry-run
46
46
  ```
47
47
 
48
48
  Setup creates the missing files and skips paths that already exist. The dry run lists the keys to translate for `de` and `pt-BR` without an API key. Add `--install` to opt into installing the runtime libraries. If that install fails, unattended setup exits with an error after printing the retry command.
@@ -87,7 +87,11 @@ npx autoglot --help # full flag list
87
87
 
88
88
  ### Monorepo
89
89
 
90
- Keep `translate.config.json` next to each app’s catalog. Translation, `add`, and `doctor` look for the config in the current directory and its parents. To select an app from the repository root, pass `--config=apps/mobile/translate.config.json`. Paths inside the config are relative to the config file. Keep GitHub workflows in the repository root’s `.github/workflows/` directory.
90
+ Run `autoglot init` in each app directory within your Git checkout. For example, run `npx autoglot init --locales=de` from `apps/web`.
91
+
92
+ Init creates an app-specific `translate-<id>.yml` in the repository root’s `.github/workflows/` directory. The workflow passes the app’s config to the Action and watches the config, source catalog, and target locale JSON files. Init uses the catalog paths from an existing app config and creates missing requested locale files at the configured destination. Use relative paths inside the checkout for generated workflows. If an existing app config omits `source`, `messagesDir`, or `lockFile`, init uses app-local defaults for scaffolding and prints the missing entries. Add those entries and rerun init to generate the workflow. If init reports that it cannot generate a scoped workflow, set it up manually. Each app gets its own workflow, and init skips existing files. If you already have a workflow for this app, keep only the one you want to run. If an earlier init put a workflow in the app’s own `.github/workflows/` directory, review the new root workflow before removing the old copy.
93
+
94
+ Translation, `add`, and `doctor` look for the config in the current directory and its parents. To select an app from the repository root, pass `--config=apps/web/translate.config.json`. Paths inside the config are relative to the config file. See the [monorepo example](https://github.com/ffcabbar/autoglot/tree/main/examples/monorepo) for an offline dry run.
91
95
 
92
96
  ## Quickstart — GitHub Action (manual setup)
93
97
 
@@ -209,7 +213,7 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
209
213
  ## CLI flags
210
214
 
211
215
  ```
212
- --check Exit 1 when translation updates are pending. No API call.
216
+ --check Exit 1 when translations or the shared lock need updates.
213
217
  --dry-run Preview the translation plan without updating catalogs.
214
218
  --quiet Suppress per-locale and per-chunk progress. CI keeps verbose logs.
215
219
  --locales=de,fr Restrict run to specific locales.
@@ -224,6 +228,14 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
224
228
  -h, --help Print help and exit.
225
229
  ```
226
230
 
231
+ Use `--locales=es` to translate only Spanish. Later runs reuse that work if the source string is still the same and the translation is present. After an English edit in a project with Spanish and German catalogs, running `--locales=es` and then running without the flag sends the changed string once for Spanish and once for German. Existing v1 lock files work as-is. Keep the updated lock file with the catalogs so later runs can reuse the recorded progress.
232
+
233
+ On case-insensitive filesystems, `pt-br` refers to an existing `pt-BR.json` in both `--locales` and `namespaces` locale lists. A case-only rename carries the catalog's recorded progress to the new filename. If your filesystem has distinct catalogs that differ only in case, use the exact locale spelling from the filename.
234
+
235
+ With `--check --locales=es`, only the Spanish catalog is checked. Without `--locales`, `--check` also checks the shared lock and all discovered catalogs. Checks make no API calls.
236
+
237
+ After a fatal locale error, Autoglot stops starting queued locales and lets active locales finish. It saves successful work before exiting with the first error, so a rerun can pick up the remaining translations.
238
+
227
239
  ## Models and cost
228
240
 
229
241
  | Model | Cost (per 1M tokens) | When to use |
@@ -250,7 +262,7 @@ Keep your existing locale files and review the dry-run output before replacing t
250
262
  </p>
251
263
 
252
264
  1. **Flatten** your source JSON to dotted keys: `{ "checkout.cta": "Pay now" }`.
253
- 2. **Diff** each value's md5 against the lock file → `new`, `changed`, `orphan` (deleted) keys.
265
+ 2. **Diff** each value's md5 against the lock file. The shared hashes track progress across all applicable locales, and optional per-locale hashes record progress when locales differ.
254
266
  3. **For each locale**: collect missing + changed keys, chunk into batches of 200, call Anthropic with forced [tool use](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) so the response is structured JSON (not freeform).
255
267
  4. **Validate** placeholders (`{name}`) match between source and translation; retry on mismatch.
256
268
  5. **Merge** translations back into the locale's JSON, preserving source key order, dropping orphan keys.
package/bin/cli.mjs CHANGED
@@ -43,10 +43,12 @@ extract flags
43
43
  --root=<path> Override the directory to scan.
44
44
 
45
45
  Translation flags (when no subcommand given)
46
- --check Exit 1 if the lock or selected locales need updates.
46
+ --check Exit 1 if translations or the shared lock need updates.
47
+ With --locales, check only the selected catalogs.
47
48
  --dry-run Show the plan without calling AI or updating translations.
48
49
  --quiet Suppress per-locale progress (auto-disabled in CI).
49
50
  --locales=de,fr Restrict run to specific locales.
51
+ Match filename casing to distinguish case variants.
50
52
  --model=<id> Override the configured model (default: claude-haiku-4-5).
51
53
  --source=<path> Override config.source (default: messages/en.json).
52
54
  --messages-dir=<path> Override config.messagesDir (default: messages).
package/bin/helpers.mjs CHANGED
@@ -81,20 +81,31 @@ export function chunk(arr, size) {
81
81
 
82
82
  export function parseLockYaml(raw, defaultSource = "") {
83
83
  const lock = { version: 1, source: defaultSource, hashes: {} };
84
- let inHashes = false;
84
+ let section;
85
+ let locale;
85
86
  for (const rawLine of raw.split("\n")) {
86
87
  const line = rawLine.replace(/\r$/, "");
87
88
  if (!line || /^\s*#/.test(line)) continue;
88
- if (!inHashes) {
89
+ if (/^\S/.test(line)) {
90
+ section = undefined;
91
+ locale = undefined;
89
92
  let m = line.match(/^version:\s*(\d+)\s*$/);
90
93
  if (m) { lock.version = Number(m[1]); continue; }
91
94
  m = line.match(/^source:\s*(.+?)\s*$/);
92
95
  if (m) { lock.source = m[1]; continue; }
93
- if (/^hashes:\s*$/.test(line)) { inHashes = true; continue; }
94
- } else {
96
+ section = line.match(/^(hashes|localeHashes):\s*$/)?.[1];
97
+ } else if (section === "hashes") {
95
98
  const m = line.match(/^\s{2}(.+):\s*(\S+)\s*$/);
96
99
  if (m) lock.hashes[m[1]] = m[2];
97
- else if (!/^\s/.test(line)) inHashes = false;
100
+ } else if (section === "localeHashes") {
101
+ const header = line.match(/^ {2}([a-z0-9-]+):\s*$/i);
102
+ if (header) {
103
+ lock.localeHashes ??= {};
104
+ locale = lock.localeHashes[header[1]] = {};
105
+ continue;
106
+ }
107
+ const entry = line.match(/^ {4}(.+):\s*(\S+)\s*$/);
108
+ if (locale && entry) locale[entry[1]] = entry[2] === "null" ? null : entry[2];
98
109
  }
99
110
  }
100
111
  return lock;
@@ -105,6 +116,13 @@ export function dumpLockYaml(lock) {
105
116
  for (const key of Object.keys(lock.hashes)) {
106
117
  out += ` ${key}: ${lock.hashes[key]}\n`;
107
118
  }
119
+ if (Object.keys(lock.localeHashes ?? {}).length) {
120
+ out += "localeHashes:\n";
121
+ for (const [locale, hashes] of Object.entries(lock.localeHashes)) {
122
+ out += ` ${locale}:\n`;
123
+ for (const [key, value] of Object.entries(hashes)) out += ` ${key}: ${value}\n`;
124
+ }
125
+ }
108
126
  return out;
109
127
  }
110
128
 
package/bin/init.mjs CHANGED
@@ -9,8 +9,10 @@
9
9
  //
10
10
  // Skips existing files.
11
11
 
12
- import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
13
- import { join, dirname, resolve } from "node:path";
12
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, lstatSync, realpathSync } from "node:fs";
13
+ import { basename, join, dirname, relative, sep, isAbsolute } from "node:path";
14
+ import { createHash } from "node:crypto";
15
+ import { findRepoRoot, resolvePaths } from "./config.mjs";
14
16
  import { spawnSync } from "node:child_process";
15
17
  import { ask, select, multiselect, confirm, info, ok, warn, err, step, c, closePrompts } from "./prompts.mjs";
16
18
  import { detect, LOCALE_CATALOG } from "./detect.mjs";
@@ -61,17 +63,92 @@ export function parseInitArgs(argv) {
61
63
  return opts;
62
64
  }
63
65
 
66
+ const CONFIG_NAME = "translate.config.json";
67
+
68
+ function checkoutPath(root, full) {
69
+ const path = relative(root, full);
70
+ if (path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path)) return null;
71
+ const segments = path.split(sep);
72
+ if (segments.some((segment) => {
73
+ const name = segment.toLowerCase();
74
+ if (process.platform === "win32") {
75
+ // Win32 ignores trailing dots and spaces and can expose a DOS short name.
76
+ return /^(?:\.git|git~1)[. ]*$/.test(name);
77
+ }
78
+ return name === ".git";
79
+ })) return null;
80
+ return segments.join("/");
81
+ }
82
+
83
+ function workflowFor(root, appDir, catalogs) {
84
+ const workflowName = appDir
85
+ ? `translate-${createHash("sha256").update(appDir).digest("hex").slice(0, 12)}`
86
+ : "translate";
87
+ return {
88
+ baseDir: root,
89
+ path: `.github/workflows/${workflowName}.yml`,
90
+ content: common.workflow({ appDir, workflowName, ...catalogs }),
91
+ protectParents: Boolean(appDir),
92
+ };
93
+ }
94
+
95
+ function symlinkInPath(baseDir, path) {
96
+ let full = baseDir;
97
+ for (const segment of path.split("/")) {
98
+ full = join(full, segment);
99
+ const entry = lstatSync(full, { throwIfNoEntry: false });
100
+ if (!entry) return null;
101
+ if (entry.isSymbolicLink()) return full;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ function scaffoldExists(file, cwd) {
107
+ const baseDir = file.baseDir || cwd;
108
+ if (file.protectParents) {
109
+ const symlink = symlinkInPath(baseDir, dirname(file.path).split(sep).join("/"));
110
+ if (symlink) throw new Error(`refusing to follow symbolic link: ${symlink}`);
111
+ }
112
+ // Preserve the entry itself, including a symbolic link with a missing target.
113
+ return lstatSync(join(baseDir, file.path), { throwIfNoEntry: false }) !== undefined;
114
+ }
115
+
64
116
  export async function run(argv = []) {
65
117
  const opts = parseInitArgs(argv);
66
118
  const defaultLocale = "en";
67
119
  const nonInteractive = opts.locales !== null;
68
- if (nonInteractive && opts.locales.some((locale) => !LOCALE_CODE.test(locale) || locale === defaultLocale)) {
69
- process.stderr.write("autoglot init: expected target locale codes other than en, e.g. --locales=de,pt-BR.\n");
120
+ const cwd = process.cwd();
121
+ const root = findRepoRoot(cwd) || cwd;
122
+ const appDir = checkoutPath(root, cwd);
123
+ if (appDir === null) {
124
+ err("Run init from a working tree directory.");
125
+ process.exitCode = 1;
126
+ closePrompts();
127
+ return;
128
+ }
129
+ const configPath = join(cwd, CONFIG_NAME);
130
+ const defaultSource = join(cwd, "messages/en.json");
131
+ const defaultMessagesDir = join(cwd, "messages");
132
+ let resolved;
133
+ const existingConfig = existsSync(configPath);
134
+ let rawConfig = {};
135
+ try {
136
+ resolved = resolvePaths({ config: configPath }, cwd);
137
+ if (existingConfig) rawConfig = JSON.parse(readFileSync(configPath, "utf8"));
138
+ } catch (error) {
139
+ err(error.message);
140
+ process.exitCode = 1;
141
+ closePrompts();
142
+ return;
143
+ }
144
+ const { source, messagesDir, lockFile } = resolved;
145
+ const sourceLocale = basename(source, ".json");
146
+ if (nonInteractive && opts.locales.some((locale) => !LOCALE_CODE.test(locale) || locale === sourceLocale)) {
147
+ process.stderr.write(`autoglot init: expected target locale codes other than ${sourceLocale}, e.g. --locales=de,pt-BR.\n`);
70
148
  process.exitCode = 1;
71
149
  return;
72
150
  }
73
151
 
74
- const cwd = process.cwd();
75
152
  step("autoglot init");
76
153
  info(`cwd: ${c.dim}${cwd}${c.reset}`);
77
154
 
@@ -102,7 +179,10 @@ export async function run(argv = []) {
102
179
  step("Locales");
103
180
  let targetLocales = opts.locales;
104
181
  if (!nonInteractive) {
105
- const localeChoices = LOCALE_CATALOG.map((l) => ({
182
+ const localeCatalog = sourceLocale === defaultLocale
183
+ ? LOCALE_CATALOG
184
+ : [{ code: "en", label: "English (en)" }, ...LOCALE_CATALOG];
185
+ const localeChoices = localeCatalog.filter((l) => l.code !== sourceLocale).map((l) => ({
106
186
  label: l.label,
107
187
  value: l.code,
108
188
  default: ["es", "de", "tr"].includes(l.code),
@@ -125,7 +205,35 @@ export async function run(argv = []) {
125
205
  }
126
206
  }
127
207
 
128
- ok(`Source: ${defaultLocale} → Targets: ${targetLocales.join(", ")}`);
208
+ const customCatalogs = source !== defaultSource || messagesDir !== defaultMessagesDir;
209
+ const sourcePath = checkoutPath(root, source);
210
+ const targetDir = checkoutPath(root, messagesDir);
211
+ const appConfig = checkoutPath(root, configPath);
212
+ const catalogPaths = [sourcePath, targetDir];
213
+ const localCatalogs = !catalogPaths.includes(null) &&
214
+ ![rawConfig.source, rawConfig.messagesDir].some((path) => path && isAbsolute(path));
215
+ const symlinkedCatalogs = (customCatalogs || appDir) && localCatalogs &&
216
+ catalogPaths.some((path) => path && symlinkInPath(root, path));
217
+ const externalDefaultMessagesDir = appDir && !customCatalogs && existsSync(defaultMessagesDir) &&
218
+ checkoutPath(realpathSync(root), realpathSync(defaultMessagesDir)) === null;
219
+ const scaffoldCatalogs = localCatalogs && !(customCatalogs && symlinkedCatalogs) &&
220
+ !externalDefaultMessagesDir;
221
+ const lockPath = checkoutPath(root, lockFile);
222
+ const localLock = lockPath !== null && !(rawConfig.lockFile && isAbsolute(rawConfig.lockFile)) &&
223
+ !(lockPath && symlinkInPath(root, lockPath));
224
+
225
+ if (targetLocales.includes(sourceLocale)) {
226
+ warn(`Skipping ${sourceLocale} because it is the configured source locale.`);
227
+ targetLocales = targetLocales.filter((locale) => locale !== sourceLocale);
228
+ }
229
+ if (!targetLocales.length) {
230
+ err("Need at least one target locale different from the source.");
231
+ process.exitCode = 1;
232
+ closePrompts();
233
+ return;
234
+ }
235
+
236
+ ok(`Source: ${customCatalogs ? relative(cwd, source) : defaultLocale} → Targets: ${targetLocales.join(", ")}`);
129
237
 
130
238
  // Note: we deliberately do NOT run `npm install` here. Auto-install of a
131
239
  // runtime i18n library is fragile (peer-dep mismatches across React 18/19,
@@ -135,7 +243,7 @@ export async function run(argv = []) {
135
243
  // Use the template's full runtimePackages list (e.g. RN needs both i18next
136
244
  // AND react-i18next, not just one) instead of the single fw.runtime label.
137
245
  let runtimeInstallHint = null;
138
- if (fw.runtime) {
246
+ if (fw.runtime && !customCatalogs) {
139
247
  const templateForHint = TEMPLATES[fw.key];
140
248
  const pkgs = templateForHint?.runtimePackages || [fw.runtime];
141
249
  const installed = hasPkg
@@ -152,48 +260,66 @@ export async function run(argv = []) {
152
260
  step("Plan");
153
261
  const filesToWrite = [];
154
262
 
155
- // Common files
156
- filesToWrite.push({
157
- path: "messages/en.json",
158
- content: common.exampleEnJson(),
159
- skipIfExists: true,
160
- });
161
- for (const loc of targetLocales) {
162
- filesToWrite.push({
163
- path: `messages/${loc}.json`,
164
- content: common.emptyLocale(),
165
- skipIfExists: true,
166
- });
263
+ if (scaffoldCatalogs) {
264
+ filesToWrite.push({ baseDir: root, path: sourcePath, content: common.exampleEnJson() });
265
+ for (const loc of targetLocales) {
266
+ filesToWrite.push({
267
+ baseDir: root,
268
+ path: checkoutPath(root, join(messagesDir, `${loc}.json`)),
269
+ content: common.emptyLocale(),
270
+ });
271
+ }
272
+ } else {
273
+ warn("Configured catalog paths require manual setup. Add any missing locale files in the configured messages directory.");
167
274
  }
168
275
  filesToWrite.push({
169
- path: "translate.config.json",
170
- content: common.translateConfig({ source: "messages/en.json", messagesDir: "messages" }),
171
- skipIfExists: true,
172
- });
173
- filesToWrite.push({
174
- path: ".github/workflows/translate.yml",
175
- content: common.workflow({ messagesDir: "messages" }),
176
- skipIfExists: true,
276
+ path: CONFIG_NAME,
277
+ content: common.translateConfig(),
177
278
  });
178
279
 
179
- // Framework-specific files
280
+ const symlinkedWorkflowPaths = appDir && (symlinkedCatalogs || symlinkInPath(root, appConfig));
281
+ const workflowPathsSupported = scaffoldCatalogs && localLock && !symlinkedWorkflowPaths &&
282
+ ![...catalogPaths, appConfig].some((path) => path.includes("${{"));
283
+ const missingPaths = appDir && existingConfig && workflowPathsSupported
284
+ ? Object.entries({ source, messagesDir, lockFile })
285
+ .filter(([key]) => !rawConfig[key])
286
+ : [];
287
+ let workflow;
288
+ if (missingPaths.length) {
289
+ const fields = missingPaths.map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(checkoutPath(cwd, value))}`).join(", ");
290
+ warn(`Add the missing app-relative paths to ${CONFIG_NAME} and rerun init to generate the workflow: ${fields}`);
291
+ } else if (workflowPathsSupported) {
292
+ workflow = workflowFor(root, appDir, { sourcePath, targetDir, customCatalogs });
293
+ filesToWrite.push(workflow);
294
+ } else {
295
+ warn("Autoglot could not generate scoped checkout paths. Review the configured paths and configure the workflow manually.");
296
+ }
297
+
298
+ // Framework templates import the default catalog paths.
180
299
  let followupNotes = [];
181
300
  const tpl = TEMPLATES[fw.key];
182
- if (tpl) {
301
+ if (tpl && !customCatalogs) {
183
302
  const hasExistingApp = present.has("src/app") || present.has("app");
184
303
  const ctx = { defaultLocale, locales: [defaultLocale, ...targetLocales], hasExistingApp };
185
304
  for (const f of tpl.files(ctx)) {
186
- filesToWrite.push({ path: f.path, content: f.content, skipIfExists: true });
305
+ filesToWrite.push({ path: f.path, content: f.content });
187
306
  }
188
307
  followupNotes = tpl.followupNotes(ctx);
189
308
  }
190
309
 
191
310
  // Show plan
192
311
  for (const f of filesToWrite) {
193
- const full = join(cwd, f.path);
194
- const exists = existsSync(full);
195
- const status = exists ? `${c.yellow}EXISTS (will skip)${c.reset}` : `${c.green}CREATE${c.reset}`;
196
- process.stdout.write(` ${status} ${f.path}\n`);
312
+ const baseDir = f.baseDir || cwd;
313
+ try {
314
+ const exists = scaffoldExists(f, cwd);
315
+ const status = exists ? `${c.yellow}EXISTS (will skip)${c.reset}` : `${c.green}CREATE${c.reset}`;
316
+ process.stdout.write(` ${status} ${relative(cwd, join(baseDir, f.path))}\n`);
317
+ } catch (error) {
318
+ err(error.message);
319
+ process.exitCode = 1;
320
+ closePrompts();
321
+ return;
322
+ }
197
323
  }
198
324
 
199
325
  if (!nonInteractive && !(await confirm("\nProceed?", true))) {
@@ -207,8 +333,9 @@ export async function run(argv = []) {
207
333
  let written = 0;
208
334
  let skipped = 0;
209
335
  for (const f of filesToWrite) {
210
- const full = join(cwd, f.path);
211
- if (existsSync(full)) {
336
+ const baseDir = f.baseDir || cwd;
337
+ const full = join(baseDir, f.path);
338
+ if (scaffoldExists(f, cwd)) {
212
339
  skipped++;
213
340
  continue;
214
341
  }
@@ -220,7 +347,7 @@ export async function run(argv = []) {
220
347
  skipped++;
221
348
  continue;
222
349
  }
223
- ok(f.path);
350
+ ok(relative(cwd, full));
224
351
  written++;
225
352
  }
226
353
 
@@ -270,9 +397,13 @@ export async function run(argv = []) {
270
397
  }
271
398
  numbered.push(
272
399
  `Add ${c.bold}ANTHROPIC_API_KEY${c.reset} to your repo secrets:\n ${c.dim}gh secret set ANTHROPIC_API_KEY${c.reset}`,
273
- `Edit ${c.bold}messages/en.json${c.reset} with real strings.`,
274
- `Push to a branch — autoglot will translate and commit \`messages/<locale>.json\` files.`,
275
400
  );
401
+ if (scaffoldCatalogs) numbered.push(`Edit ${c.bold}${relative(cwd, source)}${c.reset} with real strings.`);
402
+ if (workflow) {
403
+ numbered.push(appDir
404
+ ? `Review ${relative(cwd, join(root, workflow.path))}, then push to a branch.`
405
+ : "Push to a branch — autoglot will translate and commit `messages/<locale>.json` files.");
406
+ }
276
407
  for (const note of followupNotes) numbered.push(note);
277
408
  numbered.forEach((note, i) => {
278
409
  process.stdout.write(` ${c.dim}${i + 1}.${c.reset} ${note}\n`);
@@ -3,20 +3,32 @@
3
3
 
4
4
  /**
5
5
  * Generate the GitHub Actions workflow.
6
- * @param {{ messagesDir?: string }} [opts]
7
6
  */
8
7
  export function workflow(opts = {}) {
9
- const messagesDir = opts.messagesDir || "messages";
10
- return `name: translate
8
+ const { messagesDir = "messages", appDir = "", workflowName = "translate",
9
+ customCatalogs = false, sourcePath = `${appDir}/${messagesDir}/en.json`, targetDir = `${appDir}/${messagesDir}` } = opts;
10
+ const config = appDir ? `${appDir}/translate.config.json` : "translate.config.json";
11
+ // Escape GitHub's glob operators in the literal part of each path filter.
12
+ const pattern = (path) => path.replace(/[\\*?+![\]]/g, "\\$&");
13
+ const targetPrefix = targetDir ? `${targetDir}/` : "";
14
+ const paths = appDir || customCatalogs
15
+ ? [
16
+ `${pattern(targetPrefix)}*.json`,
17
+ ...(sourcePath.startsWith(targetPrefix) && /^[^/]+\.json$/.test(sourcePath.slice(targetPrefix.length))
18
+ ? [] : [pattern(sourcePath)]),
19
+ pattern(config),
20
+ ].map((path) => JSON.stringify(path))
21
+ : [`${messagesDir}/en.json`, config];
22
+ const configInput = /^\s/.test(config) ? `./${config}` : config;
23
+ return `name: ${workflowName}
11
24
  on:
12
25
  push:
13
26
  branches: ["**"]
14
27
  paths:
15
- - ${messagesDir}/en.json
16
- - translate.config.json
28
+ ${paths.map((path) => ` - ${path}`).join("\n")}
17
29
 
18
30
  concurrency:
19
- group: translate-\${{ github.ref }}
31
+ group: ${workflowName}-\${{ github.ref }}
20
32
  cancel-in-progress: true
21
33
 
22
34
  jobs:
@@ -30,7 +42,7 @@ jobs:
30
42
  - uses: ffcabbar/autoglot@v1
31
43
  with:
32
44
  anthropic-api-key: \${{ secrets.ANTHROPIC_API_KEY }}
33
- `;
45
+ ${appDir ? ` config: ${JSON.stringify(configInput)}\n` : ""}`;
34
46
  }
35
47
 
36
48
  /**
package/bin/translate.mjs CHANGED
@@ -20,7 +20,7 @@
20
20
  // 3. Run: npx <this-package>
21
21
  //
22
22
  // Flags
23
- // --check CI gate: exit 1 if lock != source.
23
+ // --check Exit 1 if translations or the shared lock need updates.
24
24
  // --dry-run Show plan, no AI call, no writes.
25
25
  // --locales=de,fr Restrict run to specific locales.
26
26
  // --model=<id> Override the Anthropic model.
@@ -30,7 +30,7 @@
30
30
  // --lock-file=<path> Override config.lockFile.
31
31
  // --import-languine[=<path>] Import a languine.lock to seed our lock file.
32
32
 
33
- import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from "node:fs";
33
+ import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync, statSync, lstatSync } from "node:fs";
34
34
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
35
35
  import { tmpdir } from "node:os";
36
36
  import {
@@ -56,10 +56,12 @@ Usage
56
56
  npx autoglot [flags]
57
57
 
58
58
  Flags
59
- --check Exit 1 if the lock or selected locales need updates.
59
+ --check Exit 1 if translations or the shared lock need updates.
60
+ With --locales, check only the selected catalogs.
60
61
  --dry-run Show the plan without calling AI or updating translations.
61
62
  --quiet Suppress per-locale progress (auto-disabled in CI).
62
63
  --locales=de,fr Restrict run to specific locales.
64
+ Match filename casing to distinguish case variants.
63
65
  --model=<id> Override the configured model (default: claude-haiku-4-5).
64
66
  --source=<path> Override config.source (default: messages/en.json).
65
67
  --messages-dir=<path> Override config.messagesDir (default: messages).
@@ -155,47 +157,98 @@ async function run() {
155
157
  const source = readJSON(SOURCE_FILE);
156
158
  const sourceFlat = flatten(source);
157
159
  const lock = loadLock();
158
- const discovered = discoverTargetLocales();
159
- const targets = args.locales === undefined
160
+ const sourceFile = statSync(SOURCE_FILE, { bigint: true });
161
+ const catalogPath = (locale) => join(MESSAGES_DIR, `${locale}.json`);
162
+ const isSourceAlias = (path) => {
163
+ const candidate = statSync(path, { bigint: true, throwIfNoEntry: false });
164
+ return candidate?.dev === sourceFile.dev && candidate.ino === sourceFile.ino;
165
+ };
166
+ const catalogs = discoverCatalogLocales();
167
+ const discovered = catalogs.filter((locale) => {
168
+ if (`${locale}.json` === basename(SOURCE_FILE)) return false;
169
+ try {
170
+ return !isSourceAlias(catalogPath(locale));
171
+ } catch (error) {
172
+ if (!error.code) throw error;
173
+ // Keep unavailable catalogs pending. Validate their paths if selected.
174
+ return true;
175
+ }
176
+ });
177
+ const requested = args.locales === undefined
160
178
  ? discovered
161
179
  : typeof args.locales === "string"
162
- ? [...new Set(args.locales.split(",").map((s) => s.trim()).filter(Boolean))]
180
+ ? args.locales.split(",").map((s) => s.trim()).filter(Boolean)
163
181
  : [];
164
- if (args.locales !== undefined && targets.length === 0) {
182
+ if (args.locales !== undefined && requested.length === 0) {
165
183
  console.error("[translate] --locales requires a comma-separated list of target locale codes.");
166
184
  process.exit(1);
167
185
  }
168
- for (const locale of targets) {
186
+ const selected = new Set();
187
+ for (const locale of requested) {
188
+ let validLocale = true;
169
189
  try {
170
- if (join(MESSAGES_DIR, `${locale}.json`).toLowerCase() === SOURCE_FILE.toLowerCase()) {
171
- throw new Error("matches the source file");
172
- }
173
190
  Intl.getCanonicalLocales(locale);
174
191
  } catch {
192
+ validLocale = false;
193
+ }
194
+ const path = catalogPath(locale);
195
+ if (!validLocale || path.toLowerCase() === SOURCE_FILE.toLowerCase() || isSourceAlias(path)) {
175
196
  console.error(`[translate] Invalid target locale '${locale}'. Use a locale code different from the source locale file.`);
176
197
  process.exit(1);
177
198
  }
199
+ selected.add(resolveCatalogLocale(locale, true));
178
200
  }
201
+ const targets = [...selected];
179
202
 
203
+ function resolveCatalogLocale(locale, explicit = false) {
204
+ if (typeof locale !== "string" || catalogs.includes(locale)) return locale;
205
+ const matches = catalogs.filter((name) => name.toLowerCase() === locale.toLowerCase());
206
+ if (explicit && matches.length > 1) {
207
+ console.error(`[translate] Ambiguous target locale '${locale}'. Use an exact catalog name: ${matches.join(", ")}.`);
208
+ process.exit(1);
209
+ }
210
+ if (matches.length === 1) {
211
+ // Match the directory entry even when its symlink target is unavailable.
212
+ try {
213
+ if (lstatSync(catalogPath(locale), { throwIfNoEntry: false })) return matches[0];
214
+ } catch (error) {
215
+ if (explicit || !error.code) throw error;
216
+ }
217
+ }
218
+ return locale;
219
+ }
220
+
221
+ if (lock.localeHashes) {
222
+ lock.localeHashes = normalizeLocaleHashes(lock, resolveCatalogLocale);
223
+ }
224
+ const namespaceConfig = {
225
+ namespaces: Object.fromEntries(Object.entries(config.namespaces).map(([name, locales]) => [
226
+ name, Array.isArray(locales) ? locales.map((locale) => resolveCatalogLocale(locale)) : locales,
227
+ ])),
228
+ };
229
+ const sourceForLocale = (locale) =>
230
+ pickAllowedSource(source, allowedTopLevelNamespaces(source, locale, namespaceConfig));
231
+
232
+ const sourceHashes = new Map(Object.entries(sourceFlat).map(([key, value]) => [key, hash(value)]));
180
233
  const newDelta = [];
181
234
  const changedDelta = [];
182
- for (const key of Object.keys(sourceFlat)) {
183
- const h = hash(sourceFlat[key]);
235
+ for (const [key, h] of sourceHashes) {
184
236
  if (!Object.hasOwn(lock.hashes, key)) newDelta.push(key);
185
237
  else if (lock.hashes[key] !== h) changedDelta.push(key);
186
238
  }
187
- const delta = new Set([...newDelta, ...changedDelta]);
188
- const removed = Object.keys(lock.hashes).filter((key) => !Object.hasOwn(sourceFlat, key));
239
+ const removed = Object.keys(lock.hashes).filter((key) => !sourceHashes.has(key));
189
240
  const plans = targets.map((locale) => {
190
- const targetPath = join(MESSAGES_DIR, `${locale}.json`);
241
+ const targetPath = catalogPath(locale);
191
242
  const existing = existsSync(targetPath) ? readJSON(targetPath) : {};
192
243
  const existingFlat = flatten(existing);
193
- const allowed = allowedTopLevelNamespaces(source, locale, config);
194
- const filteredSource = pickAllowedSource(source, allowed);
244
+ const filteredSource = sourceForLocale(locale);
195
245
  const allowedFlat = flatten(filteredSource);
196
- const keysToTranslate = Object.keys(allowedFlat).filter((key) => delta.has(key) || !Object.hasOwn(existingFlat, key));
246
+ const allowedKeys = Object.keys(allowedFlat);
247
+ const keysToTranslate = allowedKeys.filter((key) =>
248
+ !Object.hasOwn(existingFlat, key) || recordedHash(lock, locale, key) !== sourceHashes.get(key)
249
+ );
197
250
  const hasOrphans = Object.keys(existingFlat).some((key) => !Object.hasOwn(allowedFlat, key));
198
- return { locale, targetPath, existing, filteredSource, keysToTranslate, hasOrphans };
251
+ return { locale, targetPath, existing, filteredSource, allowedKeys, keysToTranslate, hasOrphans };
199
252
  });
200
253
 
201
254
  console.log(`[translate] source: ${newDelta.length} new keys, ${changedDelta.length} modified (${newDelta.length + changedDelta.length} total delta)`);
@@ -204,13 +257,15 @@ async function run() {
204
257
  }
205
258
 
206
259
  if (args.check) {
207
- if (delta.size > 0) console.log("[translate] Delta keys:", [...delta].join(", "));
208
- if (removed.length > 0) console.log("[translate] Removed source keys:", removed.join(", "));
260
+ const delta = [...newDelta, ...changedDelta];
261
+ const checkSharedLock = args.locales === undefined;
262
+ if (checkSharedLock && delta.length) console.log("[translate] Delta keys:", delta.join(", "));
263
+ if (checkSharedLock && removed.length) console.log("[translate] Removed source keys:", removed.join(", "));
209
264
  const pending = plans.filter(({ keysToTranslate, hasOrphans }) => keysToTranslate.length || hasOrphans);
210
265
  if (pending.length > 0) {
211
266
  console.log("[translate] Locales needing updates:", pending.map(({ locale }) => locale).join(", "));
212
267
  }
213
- if (delta.size || removed.length || pending.length) process.exit(1);
268
+ if (pending.length || (checkSharedLock && (delta.length || removed.length))) process.exit(1);
214
269
  console.log("[translate] All selected locales up to date.");
215
270
  return;
216
271
  }
@@ -281,29 +336,34 @@ async function run() {
281
336
  verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys | in: ${usageIn} out: ${usageOut} | $${cost.toFixed(5)}`);
282
337
  }
283
338
 
284
- await Promise.all(plans.map((plan) => limit(() => processLocale(plan))));
339
+ let failure;
340
+ const results = await Promise.all(plans.map((plan) => limit(async () => {
341
+ if (failure) return;
342
+ try {
343
+ await processLocale(plan);
344
+ return [plan.locale, plan.allowedKeys];
345
+ } catch (reason) {
346
+ // Set this before the limiter frees the slot for the next locale.
347
+ failure ??= { reason };
348
+ }
349
+ })));
285
350
  // Sort perLocale alphabetically so the summary table is stable across runs
286
351
  // (parallel completion order would otherwise scramble it).
287
352
  perLocale.sort((a, b) => a.locale.localeCompare(b.locale));
288
353
 
289
354
  if (!dryRun) {
290
- // A shared hash can only advance after every applicable existing locale has caught up.
291
- const selected = new Set(targets);
292
- const pending = new Set();
293
- for (const locale of discovered.filter((locale) => !selected.has(locale))) {
294
- const allowed = allowedTopLevelNamespaces(source, locale, config);
295
- for (const key of Object.keys(flatten(pickAllowedSource(source, allowed)))) pending.add(key);
296
- }
297
- if (targets.length > 0) {
298
- for (const key of Object.keys(sourceFlat)) {
299
- if (!pending.has(key)) lock.hashes[key] = hash(sourceFlat[key]);
355
+ const completed = new Map(results.filter(Boolean));
356
+ if (!failure || completed.size) {
357
+ const unprocessed = new Set([...discovered, ...targets].filter((locale) => !completed.has(locale)));
358
+ try {
359
+ saveLock(lock, sourceForLocale, sourceHashes, removed, completed, unprocessed);
360
+ } catch (error) {
361
+ if (!failure) throw error;
362
+ console.error(`[translate] Could not save translation progress: ${error.message}`);
300
363
  }
301
364
  }
302
- for (const key of removed) delete lock.hashes[key];
303
- lock.source = LOCK_SOURCE;
304
- mkdirSync(dirname(LOCK_FILE), { recursive: true });
305
- writeFileSync(LOCK_FILE, dumpLockYaml(lock));
306
365
  }
366
+ if (failure) throw failure.reason;
307
367
 
308
368
  const summary = renderSummary({
309
369
  model: MODEL,
@@ -429,14 +489,88 @@ function loadLock() {
429
489
  return parseLockYaml(readFileSync(LOCK_FILE, "utf8"), LOCK_SOURCE);
430
490
  }
431
491
 
492
+ function recordedHash(lock, locale, key) {
493
+ const overrides = lock.localeHashes?.[locale];
494
+ if (overrides && Object.hasOwn(overrides, key)) return overrides[key];
495
+ return Object.hasOwn(lock.hashes, key) ? lock.hashes[key] : null;
496
+ }
497
+
498
+ function normalizeLocaleHashes(lock, resolveCatalogLocale) {
499
+ const groups = new Map();
500
+ for (const locale of Object.keys(lock.localeHashes)) {
501
+ const catalog = resolveCatalogLocale(locale);
502
+ if (!groups.has(catalog)) groups.set(catalog, []);
503
+ groups.get(catalog).push(locale);
504
+ }
505
+ return Object.fromEntries([...groups].map(([catalog, aliases]) => {
506
+ if (aliases.length === 1 && aliases[0] === catalog) return [catalog, lock.localeHashes[catalog]];
507
+ const keys = new Set(aliases.flatMap((locale) => Object.keys(lock.localeHashes[locale])));
508
+ // The on-disk spelling may have its own implicit shared history.
509
+ if (!aliases.includes(catalog)) aliases.push(catalog);
510
+ const hashes = Object.fromEntries([...keys].map((key) => {
511
+ // Each saved spelling implicitly inherits shared hashes for its other keys.
512
+ const candidates = new Set(aliases.map((locale) => recordedHash(lock, locale, key)));
513
+ return [key, candidates.size === 1 ? candidates.values().next().value : null];
514
+ }));
515
+ return [catalog, hashes];
516
+ }));
517
+ }
518
+
519
+ function saveLock(lock, sourceForLocale, sourceHashes, removed, completed, unprocessed) {
520
+ // Keep the v1 shared hash until every applicable locale has caught up.
521
+ const pending = new Set();
522
+ for (const locale of unprocessed) {
523
+ for (const key of Object.keys(flatten(sourceForLocale(locale)))) {
524
+ if (recordedHash(lock, locale, key) !== sourceHashes.get(key)) pending.add(key);
525
+ }
526
+ }
527
+ const hashes = { ...lock.hashes };
528
+ const changedShared = new Set(removed);
529
+ for (const key of removed) delete hashes[key];
530
+ if (completed.size) {
531
+ for (const [key, h] of sourceHashes) {
532
+ if (pending.has(key) || (Object.hasOwn(hashes, key) && hashes[key] === h)) continue;
533
+ hashes[key] = h;
534
+ changedShared.add(key);
535
+ }
536
+ }
537
+
538
+ const localeHashes = {};
539
+ for (const [locale, keys] of completed) {
540
+ const overrides = keys.filter((key) => changedFromShared(key, sourceHashes.get(key)))
541
+ .map((key) => [key, sourceHashes.get(key)]);
542
+ if (overrides.length) localeHashes[locale] = Object.fromEntries(overrides);
543
+ }
544
+ for (const locale of new Set([...unprocessed, ...Object.keys(lock.localeHashes ?? {})])) {
545
+ if (completed.has(locale)) continue;
546
+ // A removed key or an out-of-scope namespace can leave an untouched
547
+ // translation on disk, so retain its history when the shared hash moves.
548
+ const previous = lock.localeHashes?.[locale] ?? {};
549
+ const keys = new Set([...Object.keys(previous), ...changedShared]);
550
+ const overrides = [...keys].map((key) => [key, recordedHash(lock, locale, key)])
551
+ .filter(([key, h]) => changedFromShared(key, h));
552
+ if (!overrides.length && !unprocessed.has(locale)) {
553
+ // An absent catalog needs one entry to stay tracked through convergence.
554
+ overrides.push(...Object.entries(previous).slice(0, 1));
555
+ }
556
+ if (overrides.length) localeHashes[locale] = Object.fromEntries(overrides);
557
+ }
558
+
559
+ function changedFromShared(key, h) {
560
+ return h !== (Object.hasOwn(hashes, key) ? hashes[key] : null);
561
+ }
562
+
563
+ mkdirSync(dirname(LOCK_FILE), { recursive: true });
564
+ writeFileSync(LOCK_FILE, dumpLockYaml({ ...lock, source: LOCK_SOURCE, hashes, localeHashes }));
565
+ }
566
+
432
567
  // loadConfig moved to ./config.mjs (shared with add/doctor; resolves
433
568
  // config-relative paths so monorepo invocations work from any subdir).
434
569
 
435
- function discoverTargetLocales() {
570
+ function discoverCatalogLocales() {
436
571
  if (!existsSync(MESSAGES_DIR)) return [];
437
- const sourceBasename = basename(SOURCE_FILE);
438
572
  return readdirSync(MESSAGES_DIR)
439
- .filter((f) => f.endsWith(".json") && f !== sourceBasename)
573
+ .filter((f) => f.endsWith(".json"))
440
574
  .map((f) => f.slice(0, -5))
441
575
  .sort();
442
576
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autoglot",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "AI-powered i18n translation bot. Diff your en.json on every push, translate only what changed, commit the JSON files back. MIT alternative to Languine, Lokalise, and Crowdin.",
5
5
  "type": "module",
6
6
  "bin": {