autoglot 0.3.3 → 0.4.0

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
@@ -1,101 +1,65 @@
1
- <!-- HERO BANNER
2
- File: .github/assets/hero.png
3
- Size: 1280x640 (2:1) — also used as GitHub social card (Settings → Social preview)
4
- Prompt: "A minimal, modern banner for an open-source dev tool called 'autoglot'.
5
- Centered wordmark in a clean geometric sans-serif (Inter / Geist), with
6
- a small globe-and-translation glyph to the left. Background: subtle
7
- purple-to-near-black diagonal gradient (#1a0b2e → #4c1d95). White text.
8
- Tagline below the wordmark in a smaller weight: 'AI translation bot for
9
- your i18n JSON. MIT, single-file, your API key.' Flat, no 3D, no AI
10
- glow effects. Looks at home next to Vercel/Resend/Linear branding."
11
- -->
12
- <p align="center">
13
- <img src=".github/assets/hero.svg" alt="autoglot — AI-powered i18n translation bot" width="820">
14
- </p>
15
-
16
1
  <h1 align="center">autoglot</h1>
17
2
 
18
- <p align="center">
19
- <strong>AI-powered i18n translation bot.</strong> Edit <code>en.json</code>, push, and your other locale files appear translated in a bot commit.<br>
20
- MIT alternative to <a href="https://languine.ai">Languine</a>, Lokalise, and Crowdin.
21
- </p>
3
+ <p align="center"><strong>One source catalog. Translations that keep up with your code.</strong></p>
22
4
 
23
5
  <p align="center">
24
- <a href="https://www.npmjs.com/package/autoglot"><img src="https://img.shields.io/npm/v/autoglot.svg?color=8b5cf6&label=npm" alt="npm"></a>
25
- <a href="https://www.npmjs.com/package/autoglot"><img src="https://img.shields.io/npm/dm/autoglot.svg?color=8b5cf6" alt="downloads"></a>
26
- <a href="https://github.com/ffcabbar/autoglot/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/autoglot.svg?color=8b5cf6" alt="license MIT"></a>
27
- <a href="https://github.com/marketplace/actions/autoglot"><img src="https://img.shields.io/badge/marketplace-autoglot-8b5cf6?logo=githubactions&logoColor=white" alt="GitHub Marketplace"></a>
28
- <a href="https://github.com/ffcabbar/autoglot/stargazers"><img src="https://img.shields.io/github/stars/ffcabbar/autoglot?style=flat&color=8b5cf6" alt="stars"></a>
29
- <a href="https://github.com/sponsors/ffcabbar"><img src="https://img.shields.io/badge/sponsor-%E2%9D%A4-ec4899" alt="Sponsor"></a>
6
+ <img src=".github/assets/hero-prism.webp" width="900" alt="A glass prism splits a single violet beam toward three tiles with different writing systems">
30
7
  </p>
31
8
 
32
9
  <p align="center">
33
- <a href="#quickstart-github-action">Quickstart</a> ·
34
- <a href="#how-it-works">How it works</a> ·
35
- <a href="#vs-the-alternatives">vs. Languine / Lokalise</a> ·
36
- <a href="#configuration">Config</a> ·
37
- <a href="#models-and-cost">Cost</a> ·
38
- <a href="#faq">FAQ</a>
10
+ <a href="https://www.npmjs.com/package/autoglot"><img src="https://img.shields.io/npm/v/autoglot?color=8b5cf6" alt="npm version"></a>
11
+ <a href="https://github.com/ffcabbar/autoglot/actions/workflows/ci.yml"><img src="https://github.com/ffcabbar/autoglot/actions/workflows/ci.yml/badge.svg" alt="CI status"></a>
12
+ <a href="https://github.com/ffcabbar/autoglot/tree/v1"><img src="https://img.shields.io/badge/GitHub%20Action-v1-8b5cf6?logo=githubactions&logoColor=white" alt="GitHub Action v1"></a>
13
+ <a href="LICENSE"><img src="https://img.shields.io/npm/l/autoglot?color=8b5cf6" alt="MIT license"></a>
39
14
  </p>
40
15
 
41
- ---
42
-
43
- <!-- DEMO GIF — record after the first real PR run.
44
- File: .github/assets/demo.gif (1280x720, ≤ 8 MB, ≤ 30 s)
45
- Drop the file in and uncomment the <p> tag below.
46
16
  <p align="center">
47
- <img src=".github/assets/demo.gif" alt="autoglot in action: edit en.json, push, watch the bot translate and commit." width="820">
17
+ <a href="#quickstart">Quickstart</a> ·
18
+ <a href="#how-it-works">How it works</a> ·
19
+ <a href="#configuration">Configuration</a> ·
20
+ <a href="#cli-flags">CLI reference</a>
48
21
  </p>
49
- -->
50
22
 
51
- ## What it is (and isn't)
23
+ autoglot translates JSON message catalogs with Claude. Edit your source locale, then run the CLI or let the GitHub Action commit the updated translations to your branch. Your runtime library, such as [next-intl](https://next-intl.dev/), [react-i18next](https://react.i18next.com/), or [Vue I18n](https://vue-i18n.intlify.dev/), reads the resulting files.
52
24
 
53
- autoglot **fills in your missing locale files**. You write `messages/en.json`. autoglot writes `messages/es.json`, `messages/de.json`, etc. by calling Claude on every push.
25
+ - **Incremental.** A committed lock file tracks source strings. autoglot translates new, changed, and missing keys and removes orphaned entries.
26
+ - **Runs where you work.** Use Node.js 20+ locally or in CI. The CLI has zero runtime dependencies and sends translation requests to Anthropic with your API key.
27
+ - **Reviewable.** The GitHub Action commits JSON changes and can post token usage and estimated cost on an open PR.
54
28
 
55
- It is **not** a runtime i18n library. You still need [`next-intl`](https://next-intl.dev/), [`react-i18next`](https://react.i18next.com/), [`vue-i18n`](https://vue-i18n.intlify.dev/), or similar to read those JSON files in your app and resolve `t("...")` calls. autoglot is the translator; your i18n library is the reader.
29
+ ## Quickstart
56
30
 
57
- ## Why
31
+ Run this in your app directory and choose your target locales.
58
32
 
59
- - **Zero npm dependencies.** Single Node 20+ script. Auditable in 30 minutes.
60
- - **Incremental.** A YAML lock file fingerprints every English string; only changed/new keys are sent to the LLM.
61
- - **Free, except for the API key.** No SaaS, no rate limits, no quota. You pay Anthropic directly — typical PR costs **under a cent**.
62
- - **CI-native.** Ships as a GitHub Action. The bot commits the translated JSON back to your branch and posts a cost report on the PR.
63
- - **Framework-agnostic.** Works with `next-intl`, `react-i18next`, `vue-i18n`, `i18next`, anything that reads a flat-or-nested JSON message catalog.
33
+ ```bash
34
+ npx autoglot init
35
+ ```
64
36
 
65
- <!-- PR COMMENT — placeholder mockup. Replace with a real screenshot once you have one.
66
- File: .github/assets/pr-comment.png (1024x600). Until you do, the .svg mockup is fine. -->
67
- <p align="center">
68
- <img src=".github/assets/pr-comment.svg" alt="The bot posts a cost summary as a PR comment" width="720">
69
- </p>
37
+ Review the generated files, install the suggested i18n library, and add `ANTHROPIC_API_KEY` to your GitHub repository secrets. Edit `messages/en.json` and push your branch. For a local preview of the translation plan, run `npx autoglot --dry-run`.
70
38
 
71
- ## Quickstart — `npx autoglot init` (30 seconds)
39
+ ### Non-interactive setup
72
40
 
73
- Inside any project:
41
+ Autoglot 0.4.0 adds unattended setup. From your app directory, pass a comma-separated list of target locales.
74
42
 
75
43
  ```bash
76
- npx autoglot init
44
+ npx --yes autoglot@0.4.0 init --locales=de,pt-BR
45
+ npx --yes autoglot@0.4.0 --dry-run
77
46
  ```
78
47
 
79
- That's it. The CLI:
80
-
81
- - detects your framework (see table below) and picks the right runtime i18n library to recommend
82
- - asks which target locales to support (interactive multi-select)
83
- - scaffolds `messages/en.json`, empty `messages/<locale>.json` per language, `translate.config.json`, the `.github/workflows/translate.yml` workflow, and framework-specific glue
84
- - never overwrites existing files (skips them and prints a clear plan before writing)
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.
85
49
 
86
50
  ### Supported frameworks
87
51
 
88
52
  | Framework | Runtime library | What `init` scaffolds |
89
53
  |---|---|---|
90
- | **Next.js (App Router)** | `next-intl` | `src/i18n/routing.ts`, `src/i18n/request.ts`, `src/middleware.ts`, plus a starter `src/app/[locale]/layout.tsx` + `page.tsx` if no `[locale]` segment exists |
54
+ | **Next.js (App Router)** | `next-intl` | `src/i18n/routing.ts`, `src/i18n/request.ts`, `src/middleware.ts`, plus a starter `src/app/[locale]/layout.tsx` + `page.tsx` if no `[locale]` segment exists. [Repository example](https://github.com/ffcabbar/autoglot/tree/main/examples/nextjs) |
91
55
  | **Next.js (Pages Router)** | `next-i18next` | Messages + workflow only; prints precise wiring steps (next.config.js i18n block, `appWithTranslation` HOC, `serverSideTranslations` in pages) |
92
- | **Expo** | `i18next` + `react-i18next` + `expo-localization` | `src/i18n/index.ts` with device-locale auto-detect on app start |
56
+ | **Expo** | `i18next` + `react-i18next` + `expo-localization` | `src/i18n/index.ts` with device-locale auto-detect on app start. [Android repository example](https://github.com/ffcabbar/autoglot/tree/main/examples/expo-android) |
93
57
  | **React Native (bare)** | `i18next` + `react-i18next` | `src/i18n/index.ts` with all locales registered |
94
58
  | **Vite + React** | `i18next` + `react-i18next` | `src/i18n.ts` |
95
59
  | **Vue / Nuxt** | `vue-i18n` | `src/i18n.ts` (Composition API mode) |
96
60
  | **Generic / unknown** | (your choice) | Messages + workflow only — pair with any i18n library that reads JSON |
97
61
 
98
- After init, three things to finish:
62
+ Install the runtime package and configure the GitHub secret.
99
63
 
100
64
  ```bash
101
65
  # 1. Install the runtime i18n library — or let init do it:
@@ -108,8 +72,6 @@ gh secret set ANTHROPIC_API_KEY
108
72
  # 3. Edit messages/en.json with real strings, then push.
109
73
  ```
110
74
 
111
- Push → GitHub Action runs → bot commits `messages/<locale>.json` translations + cost summary on the PR.
112
-
113
75
  ## Other commands
114
76
 
115
77
  ```bash
@@ -125,11 +87,11 @@ npx autoglot --help # full flag list
125
87
 
126
88
  ### Monorepo
127
89
 
128
- All commands work from any subdirectory. Drop a `translate.config.json` next to the app whose messages you want translated (e.g. `apps/mobile/translate.config.json`) — paths inside the config resolve against the config file's directory, like eslint/vitest/tsconfig. `autoglot doctor` walks up to the repo root to find your workflow regardless of its filename (`translate.yml`, `translate-mobile.yml`, etc.).
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.
129
91
 
130
92
  ## Quickstart — GitHub Action (manual setup)
131
93
 
132
- If you'd rather skip `init` and write the workflow yourself:
94
+ Copy this workflow to `.github/workflows/translate.yml` to set up the Action by hand.
133
95
 
134
96
  ```yaml
135
97
  # .github/workflows/translate.yml
@@ -162,7 +124,7 @@ Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json`, create
162
124
 
163
125
  ### Want it to run on pull requests instead?
164
126
 
165
- Switch the trigger to `pull_request` and tell `actions/checkout` to use the PR's source branch (otherwise the runner checks out a synthetic merge ref that the bot can't push back to):
127
+ Switch the trigger to `pull_request` and tell `actions/checkout` to use the PR's source branch. The job below runs on pull requests from branches in the same repository.
166
128
 
167
129
  ```yaml
168
130
  on:
@@ -173,6 +135,7 @@ on:
173
135
  jobs:
174
136
  translate:
175
137
  runs-on: ubuntu-latest
138
+ if: github.event.pull_request.head.repo.full_name == github.repository
176
139
  permissions:
177
140
  contents: write
178
141
  pull-requests: write
@@ -191,7 +154,8 @@ The action detects pull_request events automatically and pushes translations to
191
154
 
192
155
  ```bash
193
156
  npm install -D autoglot
194
- ANTHROPIC_API_KEY=sk-ant-... npx autoglot
157
+ npx autoglot --dry-run
158
+ npx autoglot # Set ANTHROPIC_API_KEY in your environment first
195
159
  ```
196
160
 
197
161
  Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
@@ -240,13 +204,13 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
240
204
  | `model` | `claude-haiku-4-5` | Anthropic model. Haiku is recommended; quality is excellent. |
241
205
  | `glossary` | `[]` | Product/brand names the model must keep verbatim. |
242
206
  | `namespaceContext` | `{}` | Hint the model about each top-level namespace. Improves quality. |
243
- | `namespaces` | `{}` | Deny-list. Listed namespaces are restricted to listed locales; unlisted namespaces translate to all locales. |
207
+ | `namespaces` | `{}` | Map namespaces to their target locale lists. Other namespaces go to all target locales. |
244
208
 
245
209
  ## CLI flags
246
210
 
247
211
  ```
248
- --check CI gate: exit 1 if lock != source. No AI call.
249
- --dry-run Show plan, no AI call, no writes.
212
+ --check Exit 1 when translation updates are pending. No API call.
213
+ --dry-run Preview the translation plan without updating catalogs.
250
214
  --quiet Suppress per-locale and per-chunk progress. CI keeps verbose logs.
251
215
  --locales=de,fr Restrict run to specific locales.
252
216
  --model=<id> Override the configured model.
@@ -254,7 +218,8 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
254
218
  --messages-dir=<path> Override config.messagesDir.
255
219
  --lock-file=<path> Override config.lockFile.
256
220
  --config=<path> Custom config file path.
257
- --import-languine[=path] Seed our lock file from a `languine.lock`.
221
+ --import-languine[=path] Seed the lock file from languine.lock.
222
+ --summary-path=<path> Write the Markdown translation summary here.
258
223
  -v, --version Print version and exit.
259
224
  -h, --help Print help and exit.
260
225
  ```
@@ -263,31 +228,23 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
263
228
 
264
229
  | Model | Cost (per 1M tokens) | When to use |
265
230
  |---|---|---|
266
- | `claude-haiku-4-5` *(default)* | $1 in / $5 out | Everything. |
267
- | `claude-sonnet-4-6` | $3 in / $15 out | A specific locale where Haiku quality slips. |
268
- | `claude-opus-4-7` | $15 in / $75 out | You almost certainly don't need this. |
231
+ | `claude-haiku-4-5` *(default)* | $1 in / $5 out | General translation |
232
+ | `claude-sonnet-4-6` | $3 in / $15 out | Copy that needs more nuance |
233
+ | `claude-opus-4-7` | $5 in / $25 out | Longer or more complex copy |
269
234
 
270
- Typical PR (1–3 changed keys × 30 locales) costs under a cent on Haiku. A first-run backfill of ~2,000 keys × 30 locales is around $1–$3.
235
+ Cost depends on the catalog, target locales, and token usage. See [Anthropic’s pricing](https://platform.claude.com/docs/en/about-claude/pricing) for current rates.
271
236
 
272
237
  ## Migrating from Languine
273
238
 
274
239
  ```bash
275
240
  npx autoglot --import-languine=languine.lock
276
- rm languine.json languine.lock
241
+ npx autoglot --dry-run
277
242
  ```
278
243
 
279
- Then replace your Languine workflow with the one above. The lock file will be in sync — no re-translation, no re-cost.
244
+ Keep your existing locale files and review the dry-run output before replacing the Languine workflow. Missing translations and strings that changed since the imported hashes will appear in the plan.
280
245
 
281
246
  ## How it works
282
247
 
283
- <!-- ARCHITECTURE DIAGRAM (optional)
284
- File: .github/assets/how-it-works.svg
285
- Prompt: "A simple horizontal flowchart with 5 boxes connected by arrows:
286
- [en.json edit] → [diff vs lock file] → [Anthropic API: only changed keys]
287
- → [merge into <locale>.json files] → [bot commit + PR comment].
288
- Monochrome dark theme, purple accent (#8b5cf6). Looks like a Linear
289
- or Stripe docs diagram. Inter font."
290
- -->
291
248
  <p align="center">
292
249
  <img src=".github/assets/how-it-works.svg" alt="autoglot architecture: diff → translate → merge → commit" width="1100">
293
250
  </p>
@@ -313,7 +270,7 @@ Yes. `npx autoglot init` has explicit support for **Next.js (App Router & Pages
313
270
  <details>
314
271
  <summary><strong>What about ICU plurals, dates, gender?</strong></summary>
315
272
 
316
- ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt to Claude. The placeholder validator covers `{name}` tokens; for ICU we rely on the model — in practice Haiku 4.5 handles it correctly. If you spot a regression, open an issue.
273
+ ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt to Claude. The placeholder validator covers `{name}` tokens; ICU structure is handled by the model and should be reviewed in the resulting JSON.
317
274
 
318
275
  </details>
319
276
 
@@ -327,14 +284,14 @@ JSON covers ~95% of JS app i18n. Adding YAML / `.strings` / Android XML triples
327
284
  <details>
328
285
  <summary><strong>Why not OpenAI / Gemini?</strong></summary>
329
286
 
330
- Coming in v0.2. Anthropic's tool use is the most stable for structured output today, which is why v0.1 ships Anthropic-only. Each provider's tool semantics differ subtly; we'd rather wait until we have tests for all three.
287
+ The current release supports Anthropic. Follow the [roadmap](ROADMAP.md) for provider plans.
331
288
 
332
289
  </details>
333
290
 
334
291
  <details>
335
292
  <summary><strong>Is the bot a "real" GitHub bot with an avatar?</strong></summary>
336
293
 
337
- Not yet. v0.1 commits as `github-actions[bot]` (the default rabbit avatar). A real GitHub App with the autoglot logo is on the roadmap — see `docs/distribution.md` for the four levels of bot identity and why we chose Level 1 to start.
294
+ The Action writes commits as GitHub’s built-in `github-actions[bot]` account.
338
295
 
339
296
  </details>
340
297
 
@@ -359,7 +316,7 @@ Add them to `glossary` in `translate.config.json`. They'll be passed to Claude w
359
316
  - [ ] **v0.3** — YAML / `.strings` / Android XML formats (gated on demand)
360
317
  - [ ] **v0.4** — Hosted GitHub App (real bot avatar, one-click install) — paid tier, OSS still first-class
361
318
 
362
- See [`RELEASE_PLAN.md`](./RELEASE_PLAN.md) for the full plan.
319
+ See the [roadmap](ROADMAP.md) for upcoming work and the [open issues](https://github.com/ffcabbar/autoglot/issues) for current maintenance tasks.
363
320
 
364
321
  ## Contributing
365
322
 
package/bin/cli.mjs CHANGED
@@ -15,7 +15,6 @@
15
15
 
16
16
  import { readFileSync } from "node:fs";
17
17
 
18
- const SUBCOMMANDS = new Set(["init", "add", "doctor", "extract", "help"]);
19
18
  const argv = process.argv.slice(2);
20
19
  const first = argv[0];
21
20
 
@@ -31,6 +30,7 @@ Usage
31
30
  npx autoglot --help | -h Print help
32
31
 
33
32
  init flags
33
+ --locales=de,fr Scaffold these target locales without prompts.
34
34
  --install Install runtime i18n library after scaffolding.
35
35
  --no-install Skip the interactive install prompt.
36
36
  --pm=npm|yarn|pnpm|bun Override the auto-detected package manager.
@@ -38,11 +38,13 @@ init flags
38
38
  extract flags
39
39
  --write Merge candidates into messages/en.json (existing
40
40
  keys are never overwritten).
41
- --source=<path> Override the target file (default: messages/en.json).
41
+ --source=<path> Override the configured source catalog.
42
+ --config=<path> Select an autoglot configuration.
43
+ --root=<path> Override the directory to scan.
42
44
 
43
45
  Translation flags (when no subcommand given)
44
- --check CI gate: exit 1 if lock != source. No AI call.
45
- --dry-run Show plan, no AI call, no writes.
46
+ --check Exit 1 if the lock or selected locales need updates.
47
+ --dry-run Show the plan without calling AI or updating translations.
46
48
  --quiet Suppress per-locale progress (auto-disabled in CI).
47
49
  --locales=de,fr Restrict run to specific locales.
48
50
  --model=<id> Override the configured model (default: claude-haiku-4-5).
@@ -54,7 +56,7 @@ Translation flags (when no subcommand given)
54
56
  --summary-path=<path> Where to write the markdown summary.
55
57
 
56
58
  Environment
57
- ANTHROPIC_API_KEY Required for real runs. Not needed for --check or --dry-run.
59
+ ANTHROPIC_API_KEY Required when sending translation requests.
58
60
 
59
61
  Docs
60
62
  https://github.com/ffcabbar/autoglot
@@ -74,35 +76,22 @@ if (first === "--help" || first === "-h" || first === "help") {
74
76
  if (first === "init") {
75
77
  const m = await import("./init.mjs");
76
78
  await m.run(argv.slice(1));
77
- process.exit(0);
78
- }
79
-
80
- if (first === "add") {
79
+ } else if (first === "add") {
81
80
  const m = await import("./add.mjs");
82
81
  await m.run(argv.slice(1));
83
82
  process.exit(0);
84
- }
85
-
86
- if (first === "doctor") {
83
+ } else if (first === "doctor") {
87
84
  const m = await import("./doctor.mjs");
88
85
  await m.run(argv.slice(1));
89
86
  process.exit(0);
90
- }
91
-
92
- if (first === "extract") {
87
+ } else if (first === "extract") {
93
88
  const m = await import("./extract.mjs");
94
89
  await m.run(argv.slice(1));
95
- process.exit(0);
96
- }
97
-
98
- // Unknown subcommand sanity check: if first arg looks like a subcommand
99
- // (no leading dash, not a known one), warn the user instead of silently
100
- // passing it through to the translator.
101
- if (first && !first.startsWith("-") && !SUBCOMMANDS.has(first)) {
90
+ process.exit(process.exitCode ?? 0);
91
+ } else if (first && !first.startsWith("-")) {
102
92
  process.stderr.write(`autoglot: unknown subcommand '${first}'.\n`);
103
93
  process.stderr.write(`Run \`autoglot --help\` for the list of subcommands.\n`);
104
94
  process.exit(2);
95
+ } else {
96
+ await import("./translate.mjs");
105
97
  }
106
-
107
- // Fall through to the translation engine.
108
- await import("./translate.mjs");
package/bin/doctor.mjs CHANGED
@@ -28,8 +28,10 @@ export async function run(argv = []) {
28
28
  }
29
29
 
30
30
  // 1. translate.config.json
31
- if (paths.configPath) {
31
+ if (paths.config) {
32
32
  ok(`${relative(cwd, paths.configPath) || paths.configPath} found and parses.`);
33
+ } else if (args.config) {
34
+ e(`Configuration file ${args.config} not found.`);
33
35
  } else {
34
36
  w("translate.config.json not found — autoglot will use defaults. Consider `autoglot init`.");
35
37
  }
package/bin/extract.mjs CHANGED
@@ -9,13 +9,13 @@
9
9
  // for "find me the obvious low-hanging strings" the regex approach
10
10
  // catches ~80% of real strings with very few false positives.
11
11
 
12
- import { readFileSync, writeFileSync, readdirSync, statSync, existsSync, mkdirSync } from "node:fs";
13
- import { join, relative, extname, dirname } from "node:path";
12
+ import { readFileSync, writeFileSync, statSync, existsSync, mkdirSync } from "node:fs";
13
+ import { join, relative, resolve, dirname } from "node:path";
14
14
  import { step, info, ok, warn, err, c } from "./prompts.mjs";
15
+ import { resolvePaths } from "./config.mjs";
15
16
  import {
16
17
  walk,
17
18
  extractCandidates,
18
- isLikelyUserFacing,
19
19
  suggestKey,
20
20
  setNested,
21
21
  mergeKeys,
@@ -32,13 +32,26 @@ export const SKIP_DIRS = new Set([
32
32
  * Parse `extract`-specific flags. Unknown flags are ignored (forward-compat).
33
33
  *
34
34
  * --write merge candidates into messages/en.json (skips existing keys)
35
- * --source=<path> override the target file (default: messages/en.json)
35
+ * --source=<path> override the source catalog
36
+ * --config=<path> select an autoglot configuration
37
+ * --root=<path> override the directory to scan
36
38
  */
37
39
  export function parseExtractArgs(argv) {
38
40
  const opts = { write: false, source: null };
39
- for (const arg of argv) {
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const arg = argv[i];
40
43
  if (arg === "--write") opts.write = true;
41
44
  else if (arg.startsWith("--source=")) opts.source = arg.slice("--source=".length);
45
+ else if (arg.startsWith("--config=")) opts.config = arg.slice("--config=".length);
46
+ else if (arg.startsWith("--root=")) opts.root = arg.slice("--root=".length);
47
+ else if (arg === "--root") {
48
+ const next = argv[i + 1];
49
+ opts.root = "";
50
+ if (next && !next.startsWith("-")) {
51
+ opts.root = next;
52
+ i++;
53
+ }
54
+ }
42
55
  }
43
56
  return opts;
44
57
  }
@@ -48,11 +61,33 @@ export async function run(args = []) {
48
61
  const cwd = process.cwd();
49
62
  step("autoglot extract");
50
63
 
51
- // Pick scan roots: prefer SCAN_DIRS that exist; fall back to cwd.
52
- const roots = SCAN_DIRS.map((d) => join(cwd, d)).filter(existsSync);
64
+ let paths;
65
+ try {
66
+ paths = resolvePaths(opts, cwd);
67
+ if (opts.config !== undefined && !paths.config) {
68
+ throw new Error(`Configuration file ${opts.config || "(empty path)"} not found.`);
69
+ }
70
+ } catch (error) {
71
+ err(error.message);
72
+ process.exitCode = 1;
73
+ return;
74
+ }
75
+
76
+ const projectDir = paths.configPath ? dirname(paths.configPath) : cwd;
77
+ const target = relative(cwd, paths.source) || paths.source;
78
+ const isDirectory = (path) => statSync(path, { throwIfNoEntry: false })?.isDirectory();
79
+ const scanDirs = opts.root === undefined
80
+ ? SCAN_DIRS.map((dir) => join(projectDir, dir))
81
+ : opts.root ? [resolve(cwd, opts.root)] : [];
82
+ const roots = scanDirs.filter(isDirectory);
53
83
  if (roots.length === 0) {
54
- warn(`No conventional source directory (${SCAN_DIRS.join(", ")}) found in ${cwd}.`);
55
- info("Pass --root <path> to scan a custom directory. Skipping.");
84
+ if (opts.root !== undefined) {
85
+ err(`Scan directory ${opts.root || "(empty path)"} not found.`);
86
+ process.exitCode = 1;
87
+ return;
88
+ }
89
+ warn(`No conventional source directory (${SCAN_DIRS.join(", ")}) found in ${projectDir}.`);
90
+ info("Pass --root <path> to scan a custom directory.");
56
91
  return;
57
92
  }
58
93
 
@@ -71,7 +106,7 @@ export async function run(args = []) {
71
106
  }
72
107
  const rel = relative(cwd, f);
73
108
  for (const cand of extractCandidates(text)) {
74
- const key = suggestKey(cand.text, rel);
109
+ const key = suggestKey(cand.text, relative(projectDir, f));
75
110
  allCandidates.push({ file: rel, line: cand.line, text: cand.text, key });
76
111
  }
77
112
  }
@@ -106,7 +141,7 @@ export async function run(args = []) {
106
141
  }
107
142
 
108
143
  if (!opts.write) {
109
- step("Suggested additions to messages/en.json");
144
+ step(`Suggested additions to ${target}`);
110
145
  process.stdout.write(JSON.stringify(merged, null, 2) + "\n");
111
146
  }
112
147
 
@@ -114,20 +149,20 @@ export async function run(args = []) {
114
149
  info(`Found ${c.bold}${allCandidates.length}${c.reset} candidate${allCandidates.length === 1 ? "" : "s"} across ${c.bold}${byFile.size}${c.reset} file${byFile.size === 1 ? "" : "s"}.`);
115
150
 
116
151
  if (opts.write) {
117
- const target = opts.source || "messages/en.json";
118
- const full = join(cwd, target);
152
+ const full = paths.source;
119
153
  let existing = {};
120
154
  if (existsSync(full)) {
121
155
  try {
122
156
  existing = JSON.parse(readFileSync(full, "utf8"));
123
157
  } catch (e) {
124
158
  err(`Couldn't parse ${target}: ${e.message}. Aborting --write.`);
159
+ process.exitCode = 1;
125
160
  return;
126
161
  }
127
162
  }
128
163
  const { merged: out, added, skipped, conflicts } = mergeKeys(existing, allCandidates);
129
164
 
130
- step(opts.source ? `Writing ${target}` : "Writing messages/en.json");
165
+ step(`Writing ${target}`);
131
166
  mkdirSync(dirname(full), { recursive: true });
132
167
  writeFileSync(full, JSON.stringify(out, null, 2) + "\n");
133
168
  ok(`${target} now has ${added.length} new key${added.length === 1 ? "" : "s"}.`);
@@ -159,6 +194,6 @@ export async function run(args = []) {
159
194
  }
160
195
 
161
196
  step("Next");
162
- info(`Review the candidates above. Copy the relevant ones into ${c.bold}messages/en.json${c.reset} (or re-run with ${c.bold}--write${c.reset} to do it automatically), then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
197
+ info(`Review the candidates above. Copy the relevant ones into ${c.bold}${target}${c.reset} (or re-run with ${c.bold}--write${c.reset} to do it automatically), then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
163
198
  info("Default mode is read-only. Use --write to merge into messages/en.json (existing keys are never overwritten).");
164
199
  }
package/bin/helpers.mjs CHANGED
@@ -92,7 +92,7 @@ export function parseLockYaml(raw, defaultSource = "") {
92
92
  if (m) { lock.source = m[1]; continue; }
93
93
  if (/^hashes:\s*$/.test(line)) { inHashes = true; continue; }
94
94
  } else {
95
- const m = line.match(/^\s{2}(\S+):\s*(\S+)\s*$/);
95
+ const m = line.match(/^\s{2}(.+):\s*(\S+)\s*$/);
96
96
  if (m) lock.hashes[m[1]] = m[2];
97
97
  else if (!/^\s/.test(line)) inHashes = false;
98
98
  }
@@ -111,7 +111,7 @@ export function dumpLockYaml(lock) {
111
111
  export function allowedTopLevelNamespaces(source, locale, cfg) {
112
112
  const out = new Set();
113
113
  for (const ns of Object.keys(source)) {
114
- const restriction = cfg.namespaces?.[ns];
114
+ const restriction = cfg.namespaces?.[ns] ?? cfg.namespaces?.[ns.split(".")[0]];
115
115
  if (!restriction || restriction.includes(locale)) out.add(ns);
116
116
  }
117
117
  return out;
package/bin/init.mjs CHANGED
@@ -1,13 +1,13 @@
1
- // `autoglot init` — interactive scaffold.
1
+ // `autoglot init` — scaffold a project with prompted or explicit target locales.
2
2
  //
3
- // Detects the framework, asks the user which locales to support, and writes:
3
+ // Detects the framework and writes:
4
4
  // - messages/en.json (with example keys)
5
5
  // - messages/<locale>.json per chosen locale (empty)
6
6
  // - translate.config.json
7
7
  // - .github/workflows/translate.yml
8
8
  // - framework-specific files when supported (e.g. next-intl scaffold)
9
9
  //
10
- // Never overwrites existing files without explicit confirmation.
10
+ // Skips existing files.
11
11
 
12
12
  import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
13
13
  import { join, dirname, resolve } from "node:path";
@@ -31,16 +31,18 @@ const TEMPLATES = {
31
31
  "vite-react": viteReact,
32
32
  "vue": vueI18n,
33
33
  };
34
+ const LOCALE_CODE = /^[a-z]{2,3}(-[A-Z]{2})?$/;
34
35
 
35
36
  /**
36
37
  * Parse `init`-specific flags. Unknown flags are ignored (forward-compat).
37
38
  *
39
+ * --locales=de,fr scaffold for explicit target locales without prompts
38
40
  * --install opt-in: run the package manager to install runtime deps
39
41
  * --pm=npm|yarn|pnpm|bun override the auto-detected package manager
40
42
  * --no-install force off (useful in CI if a default ever flips)
41
43
  */
42
44
  export function parseInitArgs(argv) {
43
- const opts = { install: false, installExplicit: false, pm: null };
45
+ const opts = { install: false, installExplicit: false, pm: null, locales: null };
44
46
  for (const arg of argv) {
45
47
  if (arg === "--install") {
46
48
  opts.install = true;
@@ -51,6 +53,9 @@ export function parseInitArgs(argv) {
51
53
  } else if (arg.startsWith("--pm=")) {
52
54
  const v = arg.slice("--pm=".length);
53
55
  if (PACKAGE_MANAGERS.includes(v)) opts.pm = v;
56
+ } else if (arg === "--locales" || arg.startsWith("--locales=")) {
57
+ const values = arg.slice("--locales=".length).split(",");
58
+ opts.locales = [...new Set(values.map((value) => value.trim()))];
54
59
  }
55
60
  }
56
61
  return opts;
@@ -58,6 +63,14 @@ export function parseInitArgs(argv) {
58
63
 
59
64
  export async function run(argv = []) {
60
65
  const opts = parseInitArgs(argv);
66
+ const defaultLocale = "en";
67
+ 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");
70
+ process.exitCode = 1;
71
+ return;
72
+ }
73
+
61
74
  const cwd = process.cwd();
62
75
  step("autoglot init");
63
76
  info(`cwd: ${c.dim}${cwd}${c.reset}`);
@@ -87,33 +100,31 @@ export async function run(argv = []) {
87
100
 
88
101
  // Pick locales
89
102
  step("Locales");
90
- const localeChoices = LOCALE_CATALOG.map((l) => ({
91
- label: l.label,
92
- value: l.code,
93
- default: ["es", "de", "tr"].includes(l.code),
94
- }));
95
- const targetLocales = await multiselect(
96
- "Which target locales to translate into?",
97
- localeChoices,
98
- );
99
- if (targetLocales.length === 0) {
100
- err("Need at least one target locale. Aborting.");
101
- process.exit(1);
102
- }
103
+ let targetLocales = opts.locales;
104
+ if (!nonInteractive) {
105
+ const localeChoices = LOCALE_CATALOG.map((l) => ({
106
+ label: l.label,
107
+ value: l.code,
108
+ default: ["es", "de", "tr"].includes(l.code),
109
+ }));
110
+ targetLocales = await multiselect("Which target locales to translate into?", localeChoices);
111
+ if (targetLocales.length === 0) {
112
+ err("Need at least one target locale. Aborting.");
113
+ process.exitCode = 1;
114
+ closePrompts();
115
+ return;
116
+ }
103
117
 
104
- const customLocale = await ask(
105
- "Add another locale not in the list? (ISO code, e.g. \"hi\")",
106
- "",
107
- );
108
- if (customLocale) {
109
- if (/^[a-z]{2,3}(-[A-Z]{2})?$/.test(customLocale)) {
110
- targetLocales.push(customLocale);
111
- } else {
112
- warn(`"${customLocale}" doesn't look like an ISO locale code. Skipping.`);
118
+ const customLocale = await ask("Add another locale not in the list? (ISO code, e.g. \"hi\")", "");
119
+ if (customLocale) {
120
+ if (LOCALE_CODE.test(customLocale)) {
121
+ targetLocales.push(customLocale);
122
+ } else {
123
+ warn(`"${customLocale}" doesn't look like an ISO locale code. Skipping.`);
124
+ }
113
125
  }
114
126
  }
115
127
 
116
- const defaultLocale = "en";
117
128
  ok(`Source: ${defaultLocale} → Targets: ${targetLocales.join(", ")}`);
118
129
 
119
130
  // Note: we deliberately do NOT run `npm install` here. Auto-install of a
@@ -185,8 +196,7 @@ export async function run(argv = []) {
185
196
  process.stdout.write(` ${status} ${f.path}\n`);
186
197
  }
187
198
 
188
- const proceed = await confirm("\nProceed?", true);
189
- if (!proceed) {
199
+ if (!nonInteractive && !(await confirm("\nProceed?", true))) {
190
200
  info("Aborted.");
191
201
  closePrompts();
192
202
  return;
@@ -203,7 +213,13 @@ export async function run(argv = []) {
203
213
  continue;
204
214
  }
205
215
  mkdirSync(dirname(full), { recursive: true });
206
- writeFileSync(full, f.content);
216
+ try {
217
+ writeFileSync(full, f.content, { flag: "wx" });
218
+ } catch (error) {
219
+ if (error.code !== "EEXIST") throw error;
220
+ skipped++;
221
+ continue;
222
+ }
207
223
  ok(f.path);
208
224
  written++;
209
225
  }
@@ -219,7 +235,7 @@ export async function run(argv = []) {
219
235
  if (runtimeInstallHint) {
220
236
  const pkgs = runtimeInstallHint.split(" ").filter(Boolean);
221
237
  let shouldInstall = opts.install;
222
- if (!opts.installExplicit) {
238
+ if (!nonInteractive && !opts.installExplicit) {
223
239
  shouldInstall = await confirm(
224
240
  `Install runtime packages now (${pkgs.join(", ")})?`,
225
241
  false,
@@ -237,6 +253,7 @@ export async function run(argv = []) {
237
253
  } else {
238
254
  warn(`${pm} install exited with code ${res.status ?? "?"}. You can re-run manually.`);
239
255
  installFailed = true;
256
+ if (nonInteractive) process.exitCode = 1;
240
257
  }
241
258
  }
242
259
  }
@@ -70,3 +70,7 @@ export function exampleEnJson() {
70
70
  export function emptyLocale() {
71
71
  return "{}\n";
72
72
  }
73
+
74
+ export function localeImportName(locale) {
75
+ return `locale_${locale.replace(/[^a-zA-Z0-9_$]/g, "_")}`;
76
+ }
@@ -5,13 +5,15 @@
5
5
  // We scaffold an i18n init that auto-picks the device locale and falls
6
6
  // back to the configured default.
7
7
 
8
+ import { localeImportName } from "./common.mjs";
9
+
8
10
  /** @param {{ defaultLocale: string, locales: string[] }} ctx */
9
11
  export function indexTs(ctx) {
10
12
  const imports = ctx.locales
11
- .map((l) => `import ${jsId(l)} from "../../messages/${l}.json";`)
13
+ .map((l) => `import ${localeImportName(l)} from "../../messages/${l}.json";`)
12
14
  .join("\n");
13
15
  const resources = ctx.locales
14
- .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${jsId(l)} },`)
16
+ .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${localeImportName(l)} },`)
15
17
  .join("\n");
16
18
  const localesArr = ctx.locales.map((l) => JSON.stringify(l)).join(", ");
17
19
 
@@ -58,9 +60,6 @@ export function followupNotes() {
58
60
  ];
59
61
  }
60
62
 
61
- function jsId(loc) {
62
- return loc.replace(/[^a-zA-Z0-9_$]/g, "_");
63
- }
64
63
  function quoteIfNeeded(loc) {
65
64
  return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loc) ? loc : JSON.stringify(loc);
66
65
  }
@@ -7,13 +7,15 @@
7
7
  // 3. Optionally wire device-locale detection with expo-localization
8
8
  // or react-native-localize — we don't pick one for them.
9
9
 
10
+ import { localeImportName } from "./common.mjs";
11
+
10
12
  /** @param {{ defaultLocale: string, locales: string[] }} ctx */
11
13
  export function indexTs(ctx) {
12
14
  const imports = ctx.locales
13
- .map((l) => `import ${jsId(l)} from "../../messages/${l}.json";`)
15
+ .map((l) => `import ${localeImportName(l)} from "../../messages/${l}.json";`)
14
16
  .join("\n");
15
17
  const resources = ctx.locales
16
- .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${jsId(l)} },`)
18
+ .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${localeImportName(l)} },`)
17
19
  .join("\n");
18
20
 
19
21
  return `import i18n from "i18next";
@@ -51,12 +53,6 @@ export function followupNotes() {
51
53
  ];
52
54
  }
53
55
 
54
- // Locale codes are usually safe ids (en, es, de, zh-CN), but zh-CN contains a
55
- // dash which isn't a valid JS identifier. Use a sanitized name for the import
56
- // binding and quote the property key on the way out.
57
- function jsId(loc) {
58
- return loc.replace(/[^a-zA-Z0-9_$]/g, "_");
59
- }
60
56
  function quoteIfNeeded(loc) {
61
57
  return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loc) ? loc : JSON.stringify(loc);
62
58
  }
@@ -3,13 +3,15 @@
3
3
  // Generates src/i18n.ts with i18next configured. The user imports it
4
4
  // once in src/main.tsx (before <App/> renders).
5
5
 
6
+ import { localeImportName } from "./common.mjs";
7
+
6
8
  /** @param {{ defaultLocale: string, locales: string[] }} ctx */
7
9
  export function i18nTs(ctx) {
8
10
  const imports = ctx.locales
9
- .map((l) => `import ${jsId(l)} from "../messages/${l}.json";`)
11
+ .map((l) => `import ${localeImportName(l)} from "../messages/${l}.json";`)
10
12
  .join("\n");
11
13
  const resources = ctx.locales
12
- .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${jsId(l)} },`)
14
+ .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${localeImportName(l)} },`)
13
15
  .join("\n");
14
16
 
15
17
  return `import i18n from "i18next";
@@ -44,9 +46,6 @@ export function followupNotes() {
44
46
  ];
45
47
  }
46
48
 
47
- function jsId(loc) {
48
- return loc.replace(/[^a-zA-Z0-9_$]/g, "_");
49
- }
50
49
  function quoteIfNeeded(loc) {
51
50
  return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loc) ? loc : JSON.stringify(loc);
52
51
  }
@@ -3,13 +3,15 @@
3
3
  // Generates src/i18n.ts using the vue-i18n composition API. The user
4
4
  // installs the plugin in main.ts: app.use(i18n).
5
5
 
6
+ import { localeImportName } from "./common.mjs";
7
+
6
8
  /** @param {{ defaultLocale: string, locales: string[] }} ctx */
7
9
  export function i18nTs(ctx) {
8
10
  const imports = ctx.locales
9
- .map((l) => `import ${jsId(l)} from "../messages/${l}.json";`)
11
+ .map((l) => `import ${localeImportName(l)} from "../messages/${l}.json";`)
10
12
  .join("\n");
11
13
  const messages = ctx.locales
12
- .map((l) => ` ${quoteIfNeeded(l)}: ${jsId(l)},`)
14
+ .map((l) => ` ${quoteIfNeeded(l)}: ${localeImportName(l)},`)
13
15
  .join("\n");
14
16
 
15
17
  return `import { createI18n } from "vue-i18n";
@@ -43,9 +45,6 @@ export function followupNotes() {
43
45
  ];
44
46
  }
45
47
 
46
- function jsId(loc) {
47
- return loc.replace(/[^a-zA-Z0-9_$]/g, "_");
48
- }
49
48
  function quoteIfNeeded(loc) {
50
49
  return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loc) ? loc : JSON.stringify(loc);
51
50
  }
package/bin/translate.mjs CHANGED
@@ -31,7 +31,7 @@
31
31
  // --import-languine[=<path>] Import a languine.lock to seed our lock file.
32
32
 
33
33
  import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from "node:fs";
34
- import { join, resolve, isAbsolute } from "node:path";
34
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
35
35
  import { tmpdir } from "node:os";
36
36
  import {
37
37
  parseArgs,
@@ -56,8 +56,8 @@ Usage
56
56
  npx autoglot [flags]
57
57
 
58
58
  Flags
59
- --check CI gate: exit 1 if lock != source. No AI call.
60
- --dry-run Show plan, no AI call, no writes.
59
+ --check Exit 1 if the lock or selected locales need updates.
60
+ --dry-run Show the plan without calling AI or updating translations.
61
61
  --quiet Suppress per-locale progress (auto-disabled in CI).
62
62
  --locales=de,fr Restrict run to specific locales.
63
63
  --model=<id> Override the configured model (default: claude-haiku-4-5).
@@ -71,7 +71,7 @@ Flags
71
71
  -h, --help Print this help and exit.
72
72
 
73
73
  Environment
74
- ANTHROPIC_API_KEY Required for real runs. Not needed for --check or --dry-run.
74
+ ANTHROPIC_API_KEY Required when sending translation requests.
75
75
 
76
76
  Docs
77
77
  https://github.com/ffcabbar/autoglot
@@ -85,7 +85,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
85
85
  const PRICING = {
86
86
  "claude-haiku-4-5": { input: 1.0, output: 5.0 },
87
87
  "claude-sonnet-4-6": { input: 3.0, output: 15.0 },
88
- "claude-opus-4-7": { input: 15.0, output: 75.0 },
88
+ "claude-opus-4-7": { input: 5.0, output: 25.0 },
89
89
  };
90
90
 
91
91
  const LOCALE_DISPLAY = new Intl.DisplayNames(["en"], { type: "language" });
@@ -117,6 +117,7 @@ const config = __paths.config || { namespaces: {} };
117
117
  const SOURCE_FILE = __paths.source;
118
118
  const MESSAGES_DIR = __paths.messagesDir;
119
119
  const LOCK_FILE = __paths.lockFile;
120
+ const LOCK_SOURCE = relative(dirname(LOCK_FILE), SOURCE_FILE).split(sep).join("/");
120
121
  const SUMMARY_FILE = args["summary-path"]
121
122
  ? resolvePath(args["summary-path"])
122
123
  : join(tmpdir(), "translate-summary.md");
@@ -154,17 +155,48 @@ async function run() {
154
155
  const source = readJSON(SOURCE_FILE);
155
156
  const sourceFlat = flatten(source);
156
157
  const lock = loadLock();
157
- const targets = args.locales
158
- ? args.locales.split(",").map((s) => s.trim()).filter(Boolean)
159
- : discoverTargetLocales();
158
+ const discovered = discoverTargetLocales();
159
+ const targets = args.locales === undefined
160
+ ? discovered
161
+ : typeof args.locales === "string"
162
+ ? [...new Set(args.locales.split(",").map((s) => s.trim()).filter(Boolean))]
163
+ : [];
164
+ if (args.locales !== undefined && targets.length === 0) {
165
+ console.error("[translate] --locales requires a comma-separated list of target locale codes.");
166
+ process.exit(1);
167
+ }
168
+ for (const locale of targets) {
169
+ try {
170
+ if (join(MESSAGES_DIR, `${locale}.json`).toLowerCase() === SOURCE_FILE.toLowerCase()) {
171
+ throw new Error("matches the source file");
172
+ }
173
+ Intl.getCanonicalLocales(locale);
174
+ } catch {
175
+ console.error(`[translate] Invalid target locale '${locale}'. Use a locale code different from the source locale file.`);
176
+ process.exit(1);
177
+ }
178
+ }
160
179
 
161
180
  const newDelta = [];
162
181
  const changedDelta = [];
163
182
  for (const key of Object.keys(sourceFlat)) {
164
183
  const h = hash(sourceFlat[key]);
165
- if (!lock.hashes[key]) newDelta.push(key);
184
+ if (!Object.hasOwn(lock.hashes, key)) newDelta.push(key);
166
185
  else if (lock.hashes[key] !== h) changedDelta.push(key);
167
186
  }
187
+ const delta = new Set([...newDelta, ...changedDelta]);
188
+ const removed = Object.keys(lock.hashes).filter((key) => !Object.hasOwn(sourceFlat, key));
189
+ const plans = targets.map((locale) => {
190
+ const targetPath = join(MESSAGES_DIR, `${locale}.json`);
191
+ const existing = existsSync(targetPath) ? readJSON(targetPath) : {};
192
+ const existingFlat = flatten(existing);
193
+ const allowed = allowedTopLevelNamespaces(source, locale, config);
194
+ const filteredSource = pickAllowedSource(source, allowed);
195
+ const allowedFlat = flatten(filteredSource);
196
+ const keysToTranslate = Object.keys(allowedFlat).filter((key) => delta.has(key) || !Object.hasOwn(existingFlat, key));
197
+ const hasOrphans = Object.keys(existingFlat).some((key) => !Object.hasOwn(allowedFlat, key));
198
+ return { locale, targetPath, existing, filteredSource, keysToTranslate, hasOrphans };
199
+ });
168
200
 
169
201
  console.log(`[translate] source: ${newDelta.length} new keys, ${changedDelta.length} modified (${newDelta.length + changedDelta.length} total delta)`);
170
202
  if (targets.length === 0) {
@@ -172,20 +204,24 @@ async function run() {
172
204
  }
173
205
 
174
206
  if (args.check) {
175
- if (newDelta.length + changedDelta.length === 0) {
176
- console.log("[translate] All target locales up to date.");
177
- process.exit(0);
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(", "));
209
+ const pending = plans.filter(({ keysToTranslate, hasOrphans }) => keysToTranslate.length || hasOrphans);
210
+ if (pending.length > 0) {
211
+ console.log("[translate] Locales needing updates:", pending.map(({ locale }) => locale).join(", "));
178
212
  }
179
- console.log("[translate] Delta keys:", [...newDelta, ...changedDelta].join(", "));
180
- process.exit(1);
213
+ if (delta.size || removed.length || pending.length) process.exit(1);
214
+ console.log("[translate] All selected locales up to date.");
215
+ return;
181
216
  }
182
217
 
183
- if (!process.env.ANTHROPIC_API_KEY && !args["dry-run"]) {
218
+ const dryRun = Boolean(args["dry-run"]);
219
+ if (!dryRun && plans.some(({ keysToTranslate }) => keysToTranslate.length) && !process.env.ANTHROPIC_API_KEY) {
184
220
  console.error("[translate] ANTHROPIC_API_KEY is not set.");
185
221
  process.exit(1);
186
222
  }
187
223
 
188
- if (!existsSync(MESSAGES_DIR)) mkdirSync(MESSAGES_DIR, { recursive: true });
224
+ if (!dryRun && targets.length) mkdirSync(MESSAGES_DIR, { recursive: true });
189
225
 
190
226
  // Per-locale work runs in parallel up to LOCALE_CONCURRENCY. Each locale
191
227
  // writes its own file, so there's no contention. Aggregation into
@@ -195,28 +231,14 @@ async function run() {
195
231
  let totalIn = 0, totalOut = 0, totalCost = 0, skipped = 0;
196
232
  const limit = pLimit(LOCALE_CONCURRENCY);
197
233
 
198
- async function processLocale(locale) {
199
- const targetPath = join(MESSAGES_DIR, `${locale}.json`);
200
- const existing = existsSync(targetPath) ? readJSON(targetPath) : {};
201
- const existingFlat = flatten(existing);
202
-
203
- const allowedNs = allowedTopLevelNamespaces(source, locale, config);
204
- const isAllowed = (k) => allowedNs.has(k.split(".")[0]);
205
-
206
- const missing = Object.keys(sourceFlat).filter((k) => isAllowed(k) && !(k in existingFlat));
207
- const delta = [...newDelta, ...changedDelta].filter(isAllowed);
208
- const keysToTranslate = Array.from(new Set([...missing, ...delta]));
209
-
210
- const filteredSource = pickAllowedSource(source, allowedNs);
211
- const hasOrphans = Object.keys(existingFlat).some((k) => !(k in sourceFlat) || !isAllowed(k));
212
-
234
+ async function processLocale({ locale, targetPath, existing, filteredSource, keysToTranslate, hasOrphans }) {
213
235
  if (keysToTranslate.length === 0) {
214
236
  if (!hasOrphans) {
215
237
  verbose(`[translate] ${locale.padEnd(6)} → up to date (skipped)`);
216
238
  skipped++;
217
239
  return;
218
240
  }
219
- if (args["dry-run"]) {
241
+ if (dryRun) {
220
242
  verbose(`[translate] ${locale.padEnd(6)} → would remove orphan keys (dry-run)`);
221
243
  perLocale.push({ locale, keys: 0, inTok: 0, outTok: 0, cost: 0 });
222
244
  return;
@@ -228,7 +250,7 @@ async function run() {
228
250
  return;
229
251
  }
230
252
 
231
- if (args["dry-run"]) {
253
+ if (dryRun) {
232
254
  verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys (dry-run)`);
233
255
  perLocale.push({ locale, keys: keysToTranslate.length, inTok: 0, outTok: 0, cost: 0 });
234
256
  return;
@@ -259,14 +281,27 @@ async function run() {
259
281
  verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys | in: ${usageIn} out: ${usageOut} | $${cost.toFixed(5)}`);
260
282
  }
261
283
 
262
- await Promise.all(targets.map((locale) => limit(() => processLocale(locale))));
284
+ await Promise.all(plans.map((plan) => limit(() => processLocale(plan))));
263
285
  // Sort perLocale alphabetically so the summary table is stable across runs
264
286
  // (parallel completion order would otherwise scramble it).
265
287
  perLocale.sort((a, b) => a.locale.localeCompare(b.locale));
266
288
 
267
- if (!args["dry-run"]) {
268
- for (const key of Object.keys(sourceFlat)) lock.hashes[key] = hash(sourceFlat[key]);
269
- for (const key of Object.keys(lock.hashes)) if (!(key in sourceFlat)) delete lock.hashes[key];
289
+ 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]);
300
+ }
301
+ }
302
+ for (const key of removed) delete lock.hashes[key];
303
+ lock.source = LOCK_SOURCE;
304
+ mkdirSync(dirname(LOCK_FILE), { recursive: true });
270
305
  writeFileSync(LOCK_FILE, dumpLockYaml(lock));
271
306
  }
272
307
 
@@ -278,14 +313,14 @@ async function run() {
278
313
  totalOut,
279
314
  totalCost,
280
315
  perLocale,
281
- dryRun: !!args["dry-run"],
316
+ dryRun,
282
317
  newKeys: newDelta.length,
283
318
  modifiedKeys: changedDelta.length,
284
319
  });
285
320
  console.log("[translate] ──────────────────────────────────────");
286
321
  console.log(summary.stdout);
287
- if (STEP_SUMMARY) writeFileSync(STEP_SUMMARY, summary.markdown, { flag: "a" });
288
- writeFileSync(SUMMARY_FILE, summary.markdown);
322
+ if (STEP_SUMMARY && !dryRun) writeFileSync(STEP_SUMMARY, summary.markdown, { flag: "a" });
323
+ if (!dryRun || args["summary-path"]) writeFileSync(SUMMARY_FILE, summary.markdown);
289
324
  }
290
325
 
291
326
  // --- Anthropic call -------------------------------------------------------
@@ -293,8 +328,12 @@ async function run() {
293
328
  // format with unescaped characters — the API returns `input` as a pre-parsed
294
329
  // object, eliminating a whole class of JSON parse failures (e.g. a Lithuanian
295
330
  // translation closing a quoted word with ASCII " instead of U+201D).
296
- async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
331
+ async function translate(locale, payload, attempt = 1, rateAttempt = 0, usage = { input_tokens: 0, output_tokens: 0 }) {
297
332
  const localeName = LOCALE_DISPLAY.of(locale) || locale;
333
+ let sourceLanguage = "the source language";
334
+ try {
335
+ sourceLanguage = LOCALE_DISPLAY.of(basename(SOURCE_FILE, ".json"));
336
+ } catch { /* the source file can have a name other than a locale code */ }
298
337
  const namespaces = new Set(Object.keys(payload).map((k) => k.split(".")[0]));
299
338
  const nsCtx = [...namespaces]
300
339
  .map((n) => `- ${n}: ${(config.namespaceContext && config.namespaceContext[n]) || "application copy"}`)
@@ -304,7 +343,7 @@ async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
304
343
  ? ` Keep these product names verbatim: ${config.glossary.join(", ")}.`
305
344
  : "";
306
345
 
307
- const system = `You are a professional localization engineer. Translate English values into ${localeName}. Preserve all placeholders like {name}, {count} exactly. Preserve ICU plural syntax verbatim ({count, plural, one {...} other {...}} — never translate one/other/few/many/zero or the # symbol).${glossary} Call the emit_translations tool with every input key mapped to its translated string — do not write prose outside the tool call.`;
346
+ const system = `You are a professional localization engineer. Translate values from ${sourceLanguage} into ${localeName}. Preserve all placeholders like {name}, {count} exactly. Preserve ICU plural syntax verbatim ({count, plural, one {...} other {...}} — never translate one/other/few/many/zero or the # symbol). Preserve line breaks as actual newline characters, not literal backslash-n sequences.${glossary} Call the emit_translations tool with every input key mapped to its translated string — do not write prose outside the tool call.`;
308
347
 
309
348
  const user = `Target locale: ${localeName} (${locale}).\nNamespace context:\n${nsCtx}\n\nTranslate:\n${JSON.stringify(payload, null, 2)}`;
310
349
 
@@ -338,36 +377,42 @@ async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
338
377
  const retryAfterSec = Number(res.headers.get("retry-after")) || 60;
339
378
  console.warn(`[translate] ${locale}: rate limited (429), sleeping ${retryAfterSec}s (retry ${rateAttempt + 1}/${RATE_LIMIT_MAX_RETRIES})`);
340
379
  await sleep(retryAfterSec * 1000 + 500);
341
- return translate(locale, payload, attempt, rateAttempt + 1);
380
+ return translate(locale, payload, attempt, rateAttempt + 1, usage);
342
381
  }
343
382
  throw new Error(`Anthropic API ${res.status}: ${await res.text()}`);
344
383
  }
345
384
 
346
385
  const body = await res.json();
347
- const toolUse = body.content?.find((c) => c.type === "tool_use");
386
+ usage.input_tokens += body.usage?.input_tokens ?? 0;
387
+ usage.output_tokens += body.usage?.output_tokens ?? 0;
388
+ const toolUse = body.content?.find((c) => c.type === "tool_use" && c.name === "emit_translations");
348
389
  if (!toolUse || typeof toolUse.input !== "object" || toolUse.input === null) {
349
390
  if (attempt >= 2) throw new Error(`${locale}: no tool_use block in response\nRaw:\n${JSON.stringify(body.content)}`);
350
391
  console.warn(`[translate] ${locale} → missing tool_use block, retrying once`);
351
- return translate(locale, payload, attempt + 1);
392
+ return translate(locale, payload, attempt + 1, rateAttempt, usage);
352
393
  }
353
394
  const translations = toolUse.input;
354
395
 
355
396
  for (const key of Object.keys(payload)) {
356
- if (typeof translations[key] !== "string") {
357
- if (attempt < 2) return translate(locale, payload, attempt + 1);
358
- console.warn(`[translate] ${locale}: '${key}' omitted by model, using source value verbatim`);
359
- translations[key] = payload[key];
360
- continue;
397
+ if (!Object.hasOwn(translations, key) || typeof translations[key] !== "string") {
398
+ if (attempt < 2) return translate(locale, payload, attempt + 1, rateAttempt, usage);
399
+ throw new Error(`${locale}: model omitted a translation for '${key}'`);
361
400
  }
362
401
  const srcP = extractPlaceholders(payload[key]);
363
402
  const outP = extractPlaceholders(translations[key]);
364
403
  if (!setsEqual(srcP, outP)) {
365
404
  if (attempt >= 2) throw new Error(`${locale}: placeholder mismatch on '${key}'. source=[${[...srcP].join(",")}] got=[${[...outP].join(",")}]`);
366
- return translate(locale, payload, attempt + 1);
405
+ return translate(locale, payload, attempt + 1, rateAttempt, usage);
406
+ }
407
+ const sourceBreaks = String(payload[key]).match(/\n/g)?.length ?? 0;
408
+ const translatedBreaks = translations[key].match(/\n/g)?.length ?? 0;
409
+ if (sourceBreaks > 0 && sourceBreaks !== translatedBreaks) {
410
+ if (attempt < 2) return translate(locale, payload, attempt + 1, rateAttempt, usage);
411
+ throw new Error(`${locale}: newline mismatch on '${key}'`);
367
412
  }
368
413
  }
369
414
 
370
- return { translations, usage: body.usage };
415
+ return { translations: Object.fromEntries(Object.keys(payload).map((key) => [key, translations[key]])), usage };
371
416
  }
372
417
 
373
418
  // --- Helpers --------------------------------------------------------------
@@ -380,8 +425,8 @@ function readJSON(p) {
380
425
  }
381
426
 
382
427
  function loadLock() {
383
- if (!existsSync(LOCK_FILE)) return { version: 1, source: SOURCE_FILE, hashes: {} };
384
- return parseLockYaml(readFileSync(LOCK_FILE, "utf8"), SOURCE_FILE);
428
+ if (!existsSync(LOCK_FILE)) return { version: 1, source: LOCK_SOURCE, hashes: {} };
429
+ return parseLockYaml(readFileSync(LOCK_FILE, "utf8"), LOCK_SOURCE);
385
430
  }
386
431
 
387
432
  // loadConfig moved to ./config.mjs (shared with add/doctor; resolves
@@ -389,7 +434,7 @@ function loadLock() {
389
434
 
390
435
  function discoverTargetLocales() {
391
436
  if (!existsSync(MESSAGES_DIR)) return [];
392
- const sourceBasename = SOURCE_FILE.split("/").pop();
437
+ const sourceBasename = basename(SOURCE_FILE);
393
438
  return readdirSync(MESSAGES_DIR)
394
439
  .filter((f) => f.endsWith(".json") && f !== sourceBasename)
395
440
  .map((f) => f.slice(0, -5))
@@ -403,16 +448,29 @@ function importLanguineLock(srcPath) {
403
448
  }
404
449
  const raw = readFileSync(srcPath, "utf8");
405
450
  const hashes = {};
451
+ let inFiles = false;
406
452
  let inFile = false;
453
+ let matchedFile = false;
407
454
  for (const line of raw.split("\n")) {
408
- if (/^files:/.test(line)) continue;
409
- if (/^\s{2}\S.*\.json:/.test(line)) { inFile = true; continue; }
410
- if (/^\s{2}\S/.test(line)) { inFile = false; continue; }
455
+ if (/^files:\s*$/.test(line)) { inFiles = true; continue; }
456
+ if (/^\S/.test(line)) inFiles = false;
457
+ if (!inFiles) continue;
458
+ const file = line.match(/^ {2}(\S.*\.json):\s*$/)?.[1];
459
+ if (/^ {2}\S/.test(line)) {
460
+ inFile = Boolean(file) && [dirname(srcPath), CWD].some((base) => resolve(base, file) === SOURCE_FILE);
461
+ matchedFile ||= inFile;
462
+ continue;
463
+ }
411
464
  if (!inFile) continue;
412
- const m = line.match(/^\s{4}([^:]+):\s*(\S+)\s*$/);
413
- if (m) hashes[m[1].trim()] = m[2].trim();
465
+ const m = line.match(/^ {4}(.+):\s*([0-9a-f]{32})\s*$/i);
466
+ if (m) hashes[m[1].trim().replaceAll("\\.", ".")] = m[2].toLowerCase();
467
+ }
468
+ if (!matchedFile) {
469
+ console.error(`[translate] No entry in ${srcPath} matches ${SOURCE_FILE}. Check --source or --config.`);
470
+ process.exit(1);
414
471
  }
415
- const lock = { version: 1, source: SOURCE_FILE, hashes };
472
+ const lock = { version: 1, source: LOCK_SOURCE, hashes };
473
+ mkdirSync(dirname(LOCK_FILE), { recursive: true });
416
474
  writeFileSync(LOCK_FILE, dumpLockYaml(lock));
417
475
  console.log(`[translate] Imported ${Object.keys(hashes).length} hashes from ${srcPath} → ${LOCK_FILE}`);
418
476
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autoglot",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
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": {
@@ -13,7 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "translate": "node bin/translate.mjs",
16
- "test": "node --test tests/helpers.test.mjs tests/detect.test.mjs tests/templates.test.mjs tests/extract.test.mjs tests/pm.test.mjs tests/init-args.test.mjs tests/expo.test.mjs tests/config.test.mjs"
16
+ "test": "node --test tests/helpers.test.mjs tests/detect.test.mjs tests/templates.test.mjs tests/extract.test.mjs tests/pm.test.mjs tests/init-args.test.mjs tests/expo.test.mjs tests/config.test.mjs tests/translation.test.mjs"
17
17
  },
18
18
  "keywords": [
19
19
  "i18n",