autoglot 0.1.0 → 0.3.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
@@ -68,7 +68,60 @@ It is **not** a runtime i18n library. You still need [`next-intl`](https://next-
68
68
  <img src=".github/assets/pr-comment.svg" alt="The bot posts a cost summary as a PR comment" width="720">
69
69
  </p>
70
70
 
71
- ## Quickstart (GitHub Action)
71
+ ## Quickstart — `npx autoglot init` (30 seconds)
72
+
73
+ Inside any project:
74
+
75
+ ```bash
76
+ npx autoglot init
77
+ ```
78
+
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)
85
+
86
+ ### Supported frameworks
87
+
88
+ | Framework | Runtime library | What `init` scaffolds |
89
+ |---|---|---|
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 |
91
+ | **Next.js (Pages Router)** | `next-i18next` | Messages + workflow only; prints precise wiring steps (next.config.js i18n block, `appWithTranslation` HOC, `serverSideTranslations` in pages) |
92
+ | **React Native** | `i18next` + `react-i18next` | `src/i18n/index.ts` with all locales registered |
93
+ | **Vite + React** | `i18next` + `react-i18next` | `src/i18n.ts` |
94
+ | **Vue / Nuxt** | `vue-i18n` | `src/i18n.ts` (Composition API mode) |
95
+ | **Generic / unknown** | (your choice) | Messages + workflow only — pair with any i18n library that reads JSON |
96
+
97
+ After init, three things to finish:
98
+
99
+ ```bash
100
+ # 1. Install the runtime i18n library it suggested (e.g. next-intl, react-i18next)
101
+ npm install next-intl
102
+
103
+ # 2. Add your Anthropic API key as a repo secret
104
+ gh secret set ANTHROPIC_API_KEY
105
+
106
+ # 3. Edit messages/en.json with real strings, then push.
107
+ ```
108
+
109
+ Push → GitHub Action runs → bot commits `messages/<locale>.json` translations + cost summary on the PR.
110
+
111
+ ## Other commands
112
+
113
+ ```bash
114
+ npx autoglot # run translation (the default; same as before)
115
+ npx autoglot init # interactive scaffold (above)
116
+ npx autoglot add tr ja zh # add new target locales (creates empty JSON files)
117
+ npx autoglot doctor # health check the setup
118
+ npx autoglot extract # scan source for hardcoded strings and suggest keys
119
+ npx autoglot --help # full flag list
120
+ ```
121
+
122
+ ## Quickstart — GitHub Action (manual setup)
123
+
124
+ If you'd rather skip `init` and write the workflow yourself:
72
125
 
73
126
  ```yaml
74
127
  # .github/workflows/translate.yml
@@ -97,25 +150,16 @@ jobs:
97
150
  anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
98
151
  ```
99
152
 
100
- Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json` in your repo, and create one empty `messages/<locale>.json` per language. On the next push, the bot will:
101
-
102
- 1. Diff `en.json` against the lock file (`md5` per key).
103
- 2. Send only changed/new keys to Claude.
104
- 3. Write each locale's JSON file.
105
- 4. Commit `chore(i18n): update translations` and post a cost summary on the PR.
153
+ Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json`, create one empty `messages/<locale>.json` per language. On every push the bot will diff, translate, commit the diff back, and post a cost summary.
106
154
 
107
- ## Quickstart (CLI, no GitHub)
155
+ ## Quickstart — CLI (no GitHub)
108
156
 
109
157
  ```bash
110
158
  npm install -D autoglot
111
- echo '{ "greeting": "Hello, world!" }' > messages/en.json
112
- echo '{}' > messages/es.json
113
- echo '{}' > messages/de.json
114
-
115
159
  ANTHROPIC_API_KEY=sk-ant-... npx autoglot
116
160
  ```
117
161
 
118
- After the first run, `messages/es.json` and `messages/de.json` are populated, and `translate.lock` records what was translated.
162
+ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
119
163
 
120
164
  ## vs. the alternatives
121
165
 
@@ -227,7 +271,7 @@ In CI, the action then commits the diff and posts the cost summary on the PR.
227
271
  <details>
228
272
  <summary><strong>Does it work with my framework?</strong></summary>
229
273
 
230
- If your i18n library reads JSON files (`next-intl`, `react-i18next`, `vue-i18n`, `i18next`, `formatjs`, `lingui`, `react-intl`, ...), yes. autoglot is format-agnostic about how the JSON is structured.
274
+ Yes. `npx autoglot init` has explicit support for **Next.js (App Router & Pages Router)**, **React Native**, **Vite + React**, and **Vue / Nuxt** — it scaffolds the right runtime setup for each. For anything else (Astro, SvelteKit, Solid, plain HTML, native mobile, server-side, ...) `init` runs in generic mode and just creates the messages + workflow; pair with whichever i18n library you already use that reads JSON.
231
275
 
232
276
  </details>
233
277
 
package/bin/add.mjs ADDED
@@ -0,0 +1,63 @@
1
+ // `autoglot add <locale> [<locale>...]` — add new target locales.
2
+ //
3
+ // Creates an empty messages/<locale>.json. The next push to en.json will
4
+ // populate it. Idempotent: if the file already exists, we leave it alone.
5
+
6
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { info, ok, warn, err, step, c } from "./prompts.mjs";
9
+
10
+ export async function run(args) {
11
+ const positional = args.filter((a) => !a.startsWith("-"));
12
+ if (positional.length === 0) {
13
+ err("Usage: autoglot add <locale> [<locale>...]");
14
+ err('Example: autoglot add tr ja zh');
15
+ process.exit(1);
16
+ }
17
+
18
+ const cwd = process.cwd();
19
+ step("autoglot add");
20
+
21
+ // Try to read messagesDir from translate.config.json
22
+ let messagesDir = "messages";
23
+ const cfgPath = join(cwd, "translate.config.json");
24
+ if (existsSync(cfgPath)) {
25
+ try {
26
+ const cfg = JSON.parse(readFileSync(cfgPath, "utf8"));
27
+ if (cfg.messagesDir) messagesDir = cfg.messagesDir;
28
+ } catch {/* ignore */}
29
+ } else {
30
+ warn("translate.config.json not found — using default messages/ dir. Run `autoglot init` first if this is a new project.");
31
+ }
32
+
33
+ const sourcePath = join(cwd, messagesDir, "en.json");
34
+ if (!existsSync(sourcePath)) {
35
+ err(`Source file ${messagesDir}/en.json not found. Run \`autoglot init\` first.`);
36
+ process.exit(1);
37
+ }
38
+
39
+ let added = 0;
40
+ let already = 0;
41
+ for (const code of positional) {
42
+ if (!/^[a-z]{2,3}(-[A-Z]{2})?$/.test(code)) {
43
+ warn(`"${code}" doesn't look like an ISO locale code. Skipping.`);
44
+ continue;
45
+ }
46
+ const localePath = join(cwd, messagesDir, `${code}.json`);
47
+ if (existsSync(localePath)) {
48
+ info(`${messagesDir}/${code}.json already exists — leaving it alone.`);
49
+ already++;
50
+ continue;
51
+ }
52
+ writeFileSync(localePath, "{}\n");
53
+ ok(`${messagesDir}/${code}.json`);
54
+ added++;
55
+ }
56
+
57
+ step("Next");
58
+ if (added > 0) {
59
+ info(`Push to a branch — autoglot will populate ${added} new file${added === 1 ? "" : "s"} on the next run.`);
60
+ } else if (already > 0) {
61
+ info("Nothing to do. All requested locales already exist.");
62
+ }
63
+ }
package/bin/cli.mjs ADDED
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ // autoglot CLI dispatcher.
3
+ //
4
+ // Subcommands:
5
+ // autoglot → run translation (default; reads translate.config.json)
6
+ // autoglot init → interactive scaffold for a new project
7
+ // autoglot add <locale> → add a new target locale
8
+ // autoglot doctor → health check of the current setup
9
+ // autoglot --version | -v → print version
10
+ // autoglot --help | -h → print help
11
+ //
12
+ // Anything that doesn't match a subcommand falls through to the
13
+ // translation engine, so action.yml's `npx -y autoglot --source=... --check`
14
+ // continues to work without changes.
15
+
16
+ import { readFileSync } from "node:fs";
17
+
18
+ const SUBCOMMANDS = new Set(["init", "add", "doctor", "extract", "help"]);
19
+ const argv = process.argv.slice(2);
20
+ const first = argv[0];
21
+
22
+ const HELP = `autoglot — AI-powered i18n translation bot
23
+
24
+ Usage
25
+ npx autoglot Run translation (uses translate.config.json)
26
+ npx autoglot init Interactive setup for a new project
27
+ npx autoglot add <locale> Add an empty target locale file
28
+ npx autoglot doctor Health check of your autoglot setup
29
+ npx autoglot extract Scan source files for hardcoded strings
30
+ npx autoglot --version | -v Print version
31
+ npx autoglot --help | -h Print help
32
+
33
+ init flags
34
+ --install Install runtime i18n library after scaffolding.
35
+ --no-install Skip the interactive install prompt.
36
+ --pm=npm|yarn|pnpm|bun Override the auto-detected package manager.
37
+
38
+ extract flags
39
+ --write Merge candidates into messages/en.json (existing
40
+ keys are never overwritten).
41
+ --source=<path> Override the target file (default: messages/en.json).
42
+
43
+ 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
+ --quiet Suppress per-locale progress (auto-disabled in CI).
47
+ --locales=de,fr Restrict run to specific locales.
48
+ --model=<id> Override the configured model (default: claude-haiku-4-5).
49
+ --source=<path> Override config.source (default: messages/en.json).
50
+ --messages-dir=<path> Override config.messagesDir (default: messages).
51
+ --lock-file=<path> Override config.lockFile (default: translate.lock).
52
+ --config=<path> Custom config file path (default: translate.config.json).
53
+ --import-languine[=<path>] Seed our lock file from a languine.lock and exit.
54
+ --summary-path=<path> Where to write the markdown summary.
55
+
56
+ Environment
57
+ ANTHROPIC_API_KEY Required for real runs. Not needed for --check or --dry-run.
58
+
59
+ Docs
60
+ https://github.com/ffcabbar/autoglot
61
+ `;
62
+
63
+ if (first === "--version" || first === "-v") {
64
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
65
+ process.stdout.write(`${pkg.version}\n`);
66
+ process.exit(0);
67
+ }
68
+
69
+ if (first === "--help" || first === "-h" || first === "help") {
70
+ process.stdout.write(HELP);
71
+ process.exit(0);
72
+ }
73
+
74
+ if (first === "init") {
75
+ const m = await import("./init.mjs");
76
+ await m.run(argv.slice(1));
77
+ process.exit(0);
78
+ }
79
+
80
+ if (first === "add") {
81
+ const m = await import("./add.mjs");
82
+ await m.run(argv.slice(1));
83
+ process.exit(0);
84
+ }
85
+
86
+ if (first === "doctor") {
87
+ const m = await import("./doctor.mjs");
88
+ await m.run(argv.slice(1));
89
+ process.exit(0);
90
+ }
91
+
92
+ if (first === "extract") {
93
+ const m = await import("./extract.mjs");
94
+ 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)) {
102
+ process.stderr.write(`autoglot: unknown subcommand '${first}'.\n`);
103
+ process.stderr.write(`Run \`autoglot --help\` for the list of subcommands.\n`);
104
+ process.exit(2);
105
+ }
106
+
107
+ // Fall through to the translation engine.
108
+ await import("./translate.mjs");
package/bin/detect.mjs ADDED
@@ -0,0 +1,106 @@
1
+ // Detect the framework in the current working directory.
2
+ //
3
+ // Pure helper for ease of testing: takes a `pkg` (parsed package.json) and a
4
+ // list of paths that exist on disk, returns a framework descriptor.
5
+
6
+ /**
7
+ * @typedef {{
8
+ * key: "nextjs-app" | "nextjs-pages" | "expo" | "react-native" | "vite-react" | "vue" | "generic",
9
+ * label: string,
10
+ * runtime: "next-intl" | "next-i18next" | "react-i18next" | "vue-i18n" | null,
11
+ * note?: string
12
+ * }} Framework
13
+ */
14
+
15
+ /**
16
+ * @param {object} pkg parsed package.json (or {} if none)
17
+ * @param {Set<string>} present set of relative paths that exist (e.g. "src/app", "pages")
18
+ * @returns {Framework}
19
+ */
20
+ export function detect(pkg, present) {
21
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
22
+
23
+ // Expo before react-native: an Expo app has BOTH `expo` and `react-native` as
24
+ // deps, but Expo has a cleaner device-locale API (expo-localization) so we
25
+ // give it the dedicated template.
26
+ if (deps["expo"]) {
27
+ return {
28
+ key: "expo",
29
+ label: "Expo",
30
+ runtime: "react-i18next",
31
+ note: "Will scaffold src/i18n/index.ts with react-i18next + expo-localization for device-locale auto-detect.",
32
+ };
33
+ }
34
+
35
+ if (deps["react-native"]) {
36
+ return {
37
+ key: "react-native",
38
+ label: "React Native",
39
+ runtime: "react-i18next",
40
+ note: "Will scaffold src/i18n/index.ts with react-i18next. Pair with react-native-localize for device locale.",
41
+ };
42
+ }
43
+
44
+ if (deps["next"]) {
45
+ const hasApp = present.has("src/app") || present.has("app");
46
+ const hasPages = present.has("src/pages") || present.has("pages");
47
+ if (hasApp || (!hasApp && !hasPages)) {
48
+ return {
49
+ key: "nextjs-app",
50
+ label: "Next.js (App Router)",
51
+ runtime: "next-intl",
52
+ };
53
+ }
54
+ return {
55
+ key: "nextjs-pages",
56
+ label: "Next.js (Pages Router)",
57
+ runtime: "next-i18next",
58
+ note: "We'll scaffold messages + workflow and print the next-i18next wiring steps. We don't auto-modify next.config.js or _app.tsx.",
59
+ };
60
+ }
61
+
62
+ if (deps["nuxt"] || deps["vue"]) {
63
+ return {
64
+ key: "vue",
65
+ label: "Vue / Nuxt",
66
+ runtime: "vue-i18n",
67
+ };
68
+ }
69
+
70
+ if (deps["vite"] && deps["react"]) {
71
+ return {
72
+ key: "vite-react",
73
+ label: "Vite + React",
74
+ runtime: "react-i18next",
75
+ };
76
+ }
77
+
78
+ return {
79
+ key: "generic",
80
+ label: "Generic / no framework detected",
81
+ runtime: null,
82
+ note: "We'll scaffold messages + workflow only. Pair with any i18n library that reads JSON.",
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Built-in catalog of common locales for the multi-select.
88
+ * Display name + ISO code.
89
+ */
90
+ export const LOCALE_CATALOG = [
91
+ { code: "es", label: "Spanish (es)" },
92
+ { code: "fr", label: "French (fr)" },
93
+ { code: "de", label: "German (de)" },
94
+ { code: "tr", label: "Turkish (tr)" },
95
+ { code: "pt", label: "Portuguese (pt)" },
96
+ { code: "it", label: "Italian (it)" },
97
+ { code: "ja", label: "Japanese (ja)" },
98
+ { code: "ko", label: "Korean (ko)" },
99
+ { code: "zh", label: "Chinese (zh)" },
100
+ { code: "ru", label: "Russian (ru)" },
101
+ { code: "ar", label: "Arabic (ar)" },
102
+ { code: "nl", label: "Dutch (nl)" },
103
+ { code: "pl", label: "Polish (pl)" },
104
+ { code: "sv", label: "Swedish (sv)" },
105
+ { code: "id", label: "Indonesian (id)" },
106
+ ];
package/bin/doctor.mjs ADDED
@@ -0,0 +1,119 @@
1
+ // `autoglot doctor` — health check.
2
+ //
3
+ // Verifies the setup is correct so launching CI for the first time doesn't
4
+ // fail at 2am. Read-only — never writes or modifies anything.
5
+
6
+ import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { ok, warn, err, info, step, c } from "./prompts.mjs";
9
+
10
+ export async function run() {
11
+ const cwd = process.cwd();
12
+ step("autoglot doctor");
13
+
14
+ let warnings = 0;
15
+ let errors = 0;
16
+
17
+ function pass(msg) { ok(msg); }
18
+ function w(msg) { warn(msg); warnings++; }
19
+ function e(msg) { err(msg); errors++; }
20
+
21
+ // 1. translate.config.json
22
+ let cfg = null;
23
+ const cfgPath = join(cwd, "translate.config.json");
24
+ if (existsSync(cfgPath)) {
25
+ try {
26
+ cfg = JSON.parse(readFileSync(cfgPath, "utf8"));
27
+ pass("translate.config.json found and parses.");
28
+ } catch (err) {
29
+ e(`translate.config.json failed to parse: ${err.message}`);
30
+ }
31
+ } else {
32
+ w("translate.config.json not found — autoglot will use defaults. Consider \`autoglot init\`.");
33
+ }
34
+
35
+ // 2. Source file
36
+ const messagesDir = cfg?.messagesDir || "messages";
37
+ const sourcePath = cfg?.source || join(messagesDir, "en.json");
38
+ if (existsSync(join(cwd, sourcePath))) {
39
+ let sourceObj;
40
+ try {
41
+ sourceObj = JSON.parse(readFileSync(join(cwd, sourcePath), "utf8"));
42
+ const keys = countLeafKeys(sourceObj);
43
+ if (keys === 0) w(`${sourcePath} has no keys yet. Add your strings before running autoglot.`);
44
+ else pass(`${sourcePath} parses with ${keys} key${keys === 1 ? "" : "s"}.`);
45
+ } catch (err) {
46
+ e(`${sourcePath} failed to parse: ${err.message}`);
47
+ }
48
+ } else {
49
+ e(`Source file ${sourcePath} not found.`);
50
+ }
51
+
52
+ // 3. Target locales
53
+ const messagesFull = join(cwd, messagesDir);
54
+ if (existsSync(messagesFull) && statSync(messagesFull).isDirectory()) {
55
+ const sourceBase = sourcePath.replace(`${messagesDir}/`, "").replace(".json", "");
56
+ const targets = readdirSync(messagesFull)
57
+ .filter((f) => f.endsWith(".json") && f !== `${sourceBase}.json`);
58
+ if (targets.length === 0) {
59
+ w(`No target locale files in ${messagesDir}/. Add some with \`autoglot add <locale>\`.`);
60
+ } else {
61
+ pass(`${targets.length} target locale${targets.length === 1 ? "" : "s"}: ${targets.map((f) => f.replace(".json", "")).join(", ")}`);
62
+ }
63
+ }
64
+
65
+ // 4. Workflow
66
+ const workflowPath = join(cwd, ".github/workflows/translate.yml");
67
+ if (existsSync(workflowPath)) {
68
+ const workflow = readFileSync(workflowPath, "utf8");
69
+ if (workflow.includes("ffcabbar/autoglot")) {
70
+ pass(".github/workflows/translate.yml uses ffcabbar/autoglot.");
71
+ } else {
72
+ w(".github/workflows/translate.yml exists but doesn't reference ffcabbar/autoglot.");
73
+ }
74
+ if (workflow.includes("ANTHROPIC_API_KEY")) {
75
+ pass("Workflow references ANTHROPIC_API_KEY secret.");
76
+ } else {
77
+ w("Workflow doesn't reference ANTHROPIC_API_KEY. autoglot will fail without it.");
78
+ }
79
+ } else {
80
+ w(".github/workflows/translate.yml not found. Run \`autoglot init\` to create one, or add the workflow manually.");
81
+ }
82
+
83
+ // 5. lock file format (if exists)
84
+ const lockPath = join(cwd, cfg?.lockFile || "translate.lock");
85
+ if (existsSync(lockPath)) {
86
+ const txt = readFileSync(lockPath, "utf8");
87
+ if (/^version:\s*1\b/m.test(txt)) {
88
+ pass("translate.lock has version 1 header.");
89
+ } else {
90
+ w("translate.lock exists but doesn't look like an autoglot lock file.");
91
+ }
92
+ }
93
+
94
+ // 6. ANTHROPIC_API_KEY in env (only relevant for local runs)
95
+ if (process.env.ANTHROPIC_API_KEY) {
96
+ pass("ANTHROPIC_API_KEY set in current shell.");
97
+ } else {
98
+ info("ANTHROPIC_API_KEY not set in this shell — fine for CI; only needed for local runs.");
99
+ }
100
+
101
+ // Summary
102
+ step("Summary");
103
+ if (errors > 0) {
104
+ err(`${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}.`);
105
+ process.exit(1);
106
+ } else if (warnings > 0) {
107
+ warn(`${warnings} warning${warnings === 1 ? "" : "s"}, no errors. autoglot will run but you might want to address these.`);
108
+ } else {
109
+ ok("All clear. autoglot is healthy.");
110
+ }
111
+ }
112
+
113
+ function countLeafKeys(obj) {
114
+ if (typeof obj !== "object" || obj === null) return 1;
115
+ if (Array.isArray(obj)) return 0;
116
+ let n = 0;
117
+ for (const k of Object.keys(obj)) n += countLeafKeys(obj[k]);
118
+ return n;
119
+ }