autoglot 0.2.2 → 0.3.1

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/bin/add.mjs CHANGED
@@ -3,36 +3,35 @@
3
3
  // Creates an empty messages/<locale>.json. The next push to en.json will
4
4
  // populate it. Idempotent: if the file already exists, we leave it alone.
5
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";
6
+ import { writeFileSync, existsSync } from "node:fs";
7
+ import { join, relative, basename } from "node:path";
8
+ import { info, ok, warn, err, step } from "./prompts.mjs";
9
+ import { resolvePaths, parseSharedFlags } from "./config.mjs";
9
10
 
10
- export async function run(args) {
11
- const positional = args.filter((a) => !a.startsWith("-"));
11
+ export async function run(argv = []) {
12
+ const { args, positional } = parseSharedFlags(argv);
12
13
  if (positional.length === 0) {
13
14
  err("Usage: autoglot add <locale> [<locale>...]");
14
- err('Example: autoglot add tr ja zh');
15
+ err("Example: autoglot add tr ja zh");
15
16
  process.exit(1);
16
17
  }
17
18
 
18
19
  const cwd = process.cwd();
19
20
  step("autoglot add");
20
21
 
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 {
22
+ let paths;
23
+ try {
24
+ paths = resolvePaths(args, cwd);
25
+ } catch (e) {
26
+ err(e.message);
27
+ process.exit(1);
28
+ }
29
+ if (!paths.config) {
30
30
  warn("translate.config.json not found — using default messages/ dir. Run `autoglot init` first if this is a new project.");
31
31
  }
32
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.`);
33
+ if (!existsSync(paths.source)) {
34
+ err(`Source file ${relative(cwd, paths.source) || paths.source} not found. Run \`autoglot init\` first.`);
36
35
  process.exit(1);
37
36
  }
38
37
 
@@ -43,14 +42,15 @@ export async function run(args) {
43
42
  warn(`"${code}" doesn't look like an ISO locale code. Skipping.`);
44
43
  continue;
45
44
  }
46
- const localePath = join(cwd, messagesDir, `${code}.json`);
45
+ const localePath = join(paths.messagesDir, `${code}.json`);
46
+ const displayPath = relative(cwd, localePath) || localePath;
47
47
  if (existsSync(localePath)) {
48
- info(`${messagesDir}/${code}.json already exists — leaving it alone.`);
48
+ info(`${displayPath} already exists — leaving it alone.`);
49
49
  already++;
50
50
  continue;
51
51
  }
52
52
  writeFileSync(localePath, "{}\n");
53
- ok(`${messagesDir}/${code}.json`);
53
+ ok(displayPath);
54
54
  added++;
55
55
  }
56
56
 
package/bin/cli.mjs CHANGED
@@ -30,6 +30,16 @@ Usage
30
30
  npx autoglot --version | -v Print version
31
31
  npx autoglot --help | -h Print help
32
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
+
33
43
  Translation flags (when no subcommand given)
34
44
  --check CI gate: exit 1 if lock != source. No AI call.
35
45
  --dry-run Show plan, no AI call, no writes.
package/bin/config.mjs ADDED
@@ -0,0 +1,146 @@
1
+ // Shared config loading + path resolution used by add / doctor / translate.
2
+ //
3
+ // Two-axis path resolution:
4
+ // - CLI flags resolve against CWD (POSIX convention).
5
+ // - Config file values resolve against `path.dirname(configPath)` (so a
6
+ // config at apps/mobile/translate.config.json saying "messages/en.json"
7
+ // means apps/mobile/messages/en.json regardless of where you invoke from).
8
+ //
9
+ // `findConfig(cwd)` walks up from CWD looking for translate.config.json so
10
+ // `autoglot doctor` works from any subdirectory of a monorepo.
11
+
12
+ import { readFileSync, existsSync, statSync } from "node:fs";
13
+ import { resolve, isAbsolute, dirname, join } from "node:path";
14
+
15
+ /**
16
+ * Walk up from `cwd` looking for `translate.config.json`. Returns the
17
+ * absolute path of the first one found, or null if none up to the
18
+ * filesystem root (or a `.git` directory — that's the repo boundary).
19
+ */
20
+ export function findConfig(cwd, name = "translate.config.json") {
21
+ let dir = resolve(cwd);
22
+ const seen = new Set();
23
+ while (!seen.has(dir)) {
24
+ seen.add(dir);
25
+ const candidate = join(dir, name);
26
+ if (existsSync(candidate)) return candidate;
27
+ if (existsSync(join(dir, ".git"))) return null;
28
+ const parent = dirname(dir);
29
+ if (parent === dir) return null;
30
+ dir = parent;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /**
36
+ * Walk up from `cwd` looking for a `.git` directory. Returns the
37
+ * absolute path of the repo root, or null if not in a git repo.
38
+ */
39
+ export function findRepoRoot(cwd) {
40
+ let dir = resolve(cwd);
41
+ const seen = new Set();
42
+ while (!seen.has(dir)) {
43
+ seen.add(dir);
44
+ if (existsSync(join(dir, ".git"))) return dir;
45
+ const parent = dirname(dir);
46
+ if (parent === dir) return null;
47
+ dir = parent;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /**
53
+ * Resolve a path:
54
+ * - absolute → as-is
55
+ * - relative → against baseDir
56
+ */
57
+ export function resolveAgainst(baseDir, p) {
58
+ if (!p) return p;
59
+ return isAbsolute(p) ? p : resolve(baseDir, p);
60
+ }
61
+
62
+ /**
63
+ * Load the config file (if present) and resolve all path fields against
64
+ * its directory. Returns null if the file doesn't exist; caller decides
65
+ * whether to fall back to defaults.
66
+ */
67
+ export function loadConfig(configPath) {
68
+ if (!existsSync(configPath)) return null;
69
+ let parsed;
70
+ try {
71
+ parsed = JSON.parse(readFileSync(configPath, "utf8"));
72
+ } catch (err) {
73
+ throw new Error(`Failed to parse ${configPath}: ${err.message}`);
74
+ }
75
+ const baseDir = dirname(resolve(configPath));
76
+ const out = { ...parsed, namespaces: parsed.namespaces || {} };
77
+ if (parsed.source) out.source = resolveAgainst(baseDir, parsed.source);
78
+ if (parsed.messagesDir) out.messagesDir = resolveAgainst(baseDir, parsed.messagesDir);
79
+ if (parsed.lockFile) out.lockFile = resolveAgainst(baseDir, parsed.lockFile);
80
+ out.__configDir = baseDir;
81
+ out.__configPath = configPath;
82
+ return out;
83
+ }
84
+
85
+ /**
86
+ * Resolve the canonical "where do I look for stuff?" tuple from CLI args
87
+ * and (optionally) a config file. Precedence: CLI flag > config value >
88
+ * built-in default. CLI flags resolve vs. CWD; config values resolve vs.
89
+ * the config file's directory (handled by loadConfig).
90
+ *
91
+ * @param {object} args parsed CLI flags ({ source, "messages-dir", "lock-file", config })
92
+ * @param {string} cwd current working directory (defaults: process.cwd())
93
+ * @returns {{
94
+ * cwd: string, configPath: string|null, config: object|null,
95
+ * source: string, messagesDir: string, lockFile: string
96
+ * }}
97
+ */
98
+ export function resolvePaths(args, cwd = process.cwd()) {
99
+ let configPath = null;
100
+ if (args.config) {
101
+ configPath = resolveAgainst(cwd, args.config);
102
+ } else {
103
+ configPath = findConfig(cwd);
104
+ }
105
+
106
+ const config = configPath ? loadConfig(configPath) : null;
107
+
108
+ const source = args.source
109
+ ? resolveAgainst(cwd, args.source)
110
+ : config?.source
111
+ ? config.source
112
+ : resolve(cwd, "messages/en.json");
113
+
114
+ const messagesDir = args["messages-dir"]
115
+ ? resolveAgainst(cwd, args["messages-dir"])
116
+ : config?.messagesDir
117
+ ? config.messagesDir
118
+ : resolve(cwd, "messages");
119
+
120
+ const lockFile = args["lock-file"]
121
+ ? resolveAgainst(cwd, args["lock-file"])
122
+ : config?.lockFile
123
+ ? config.lockFile
124
+ : resolve(cwd, "translate.lock");
125
+
126
+ return { cwd, configPath, config, source, messagesDir, lockFile };
127
+ }
128
+
129
+ /**
130
+ * Minimal flag parser for add/doctor: extracts --source, --messages-dir,
131
+ * --lock-file, --config. Positional args (non-flag) are returned separately.
132
+ */
133
+ export function parseSharedFlags(argv) {
134
+ const args = {};
135
+ const positional = [];
136
+ for (const a of argv) {
137
+ if (!a.startsWith("--")) { positional.push(a); continue; }
138
+ const eq = a.indexOf("=");
139
+ if (eq > 0) {
140
+ args[a.slice(2, eq)] = a.slice(eq + 1);
141
+ } else {
142
+ args[a.slice(2)] = true;
143
+ }
144
+ }
145
+ return { args, positional };
146
+ }
package/bin/detect.mjs CHANGED
@@ -5,9 +5,9 @@
5
5
 
6
6
  /**
7
7
  * @typedef {{
8
- * key: "nextjs-app" | "nextjs-pages" | "react-native" | "vite-react" | "vue" | "generic",
8
+ * key: "nextjs-app" | "nextjs-pages" | "expo" | "react-native" | "vite-react" | "vue" | "generic",
9
9
  * label: string,
10
- * runtime: "next-intl" | "react-i18next" | "vue-i18n" | null,
10
+ * runtime: "next-intl" | "next-i18next" | "react-i18next" | "vue-i18n" | null,
11
11
  * note?: string
12
12
  * }} Framework
13
13
  */
@@ -20,12 +20,24 @@
20
20
  export function detect(pkg, present) {
21
21
  const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
22
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
+
23
35
  if (deps["react-native"]) {
24
36
  return {
25
37
  key: "react-native",
26
38
  label: "React Native",
27
39
  runtime: "react-i18next",
28
- note: "Will scaffold src/i18n/index.ts with react-i18next + AsyncStorage-aware locale init.",
40
+ note: "Will scaffold src/i18n/index.ts with react-i18next. Pair with react-native-localize for device locale.",
29
41
  };
30
42
  }
31
43
 
package/bin/doctor.mjs CHANGED
@@ -4,88 +4,100 @@
4
4
  // fail at 2am. Read-only — never writes or modifies anything.
5
5
 
6
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";
7
+ import { join, relative, basename } from "node:path";
8
+ import { ok, warn, err, info, step } from "./prompts.mjs";
9
+ import { resolvePaths, parseSharedFlags, findRepoRoot } from "./config.mjs";
9
10
 
10
- export async function run() {
11
+ export async function run(argv = []) {
12
+ const { args } = parseSharedFlags(argv);
11
13
  const cwd = process.cwd();
12
14
  step("autoglot doctor");
13
15
 
14
16
  let warnings = 0;
15
17
  let errors = 0;
16
18
 
17
- function pass(msg) { ok(msg); }
18
19
  function w(msg) { warn(msg); warnings++; }
19
20
  function e(msg) { err(msg); errors++; }
20
21
 
22
+ let paths;
23
+ try {
24
+ paths = resolvePaths(args, cwd);
25
+ } catch (errObj) {
26
+ e(errObj.message);
27
+ process.exit(1);
28
+ }
29
+
21
30
  // 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
+ if (paths.configPath) {
32
+ ok(`${relative(cwd, paths.configPath) || paths.configPath} found and parses.`);
31
33
  } else {
32
- w("translate.config.json not found — autoglot will use defaults. Consider \`autoglot init\`.");
34
+ w("translate.config.json not found — autoglot will use defaults. Consider `autoglot init`.");
33
35
  }
34
36
 
35
37
  // 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;
38
+ const sourceDisplay = relative(cwd, paths.source) || paths.source;
39
+ if (existsSync(paths.source)) {
40
40
  try {
41
- sourceObj = JSON.parse(readFileSync(join(cwd, sourcePath), "utf8"));
41
+ const sourceObj = JSON.parse(readFileSync(paths.source, "utf8"));
42
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}`);
43
+ if (keys === 0) w(`${sourceDisplay} has no keys yet. Add your strings before running autoglot.`);
44
+ else ok(`${sourceDisplay} parses with ${keys} key${keys === 1 ? "" : "s"}.`);
45
+ } catch (errObj) {
46
+ e(`${sourceDisplay} failed to parse: ${errObj.message}`);
47
47
  }
48
48
  } else {
49
- e(`Source file ${sourcePath} not found.`);
49
+ e(`Source file ${sourceDisplay} not found.`);
50
50
  }
51
51
 
52
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`);
53
+ if (existsSync(paths.messagesDir) && statSync(paths.messagesDir).isDirectory()) {
54
+ const sourceBase = basename(paths.source);
55
+ const targets = readdirSync(paths.messagesDir)
56
+ .filter((f) => f.endsWith(".json") && f !== sourceBase);
58
57
  if (targets.length === 0) {
59
- w(`No target locale files in ${messagesDir}/. Add some with \`autoglot add <locale>\`.`);
58
+ w(`No target locale files in ${relative(cwd, paths.messagesDir) || paths.messagesDir}/. Add some with \`autoglot add <locale>\`.`);
60
59
  } else {
61
- pass(`${targets.length} target locale${targets.length === 1 ? "" : "s"}: ${targets.map((f) => f.replace(".json", "")).join(", ")}`);
60
+ ok(`${targets.length} target locale${targets.length === 1 ? "" : "s"}: ${targets.map((f) => f.replace(".json", "")).join(", ")}`);
62
61
  }
63
62
  }
64
63
 
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.");
64
+ // 4. Workflow — walk up to repo root, scan all .github/workflows/*.{yml,yaml}
65
+ // for one that uses the action. Falls back to local .github/workflows/ if
66
+ // not in a git repo.
67
+ const workflowSearchRoot = findRepoRoot(cwd) || cwd;
68
+ const workflowsDir = join(workflowSearchRoot, ".github/workflows");
69
+ let foundWorkflow = null;
70
+ if (existsSync(workflowsDir) && statSync(workflowsDir).isDirectory()) {
71
+ const files = readdirSync(workflowsDir).filter((f) => /\.ya?ml$/.test(f));
72
+ for (const f of files) {
73
+ try {
74
+ const txt = readFileSync(join(workflowsDir, f), "utf8");
75
+ if (/\bffcabbar\/autoglot\b/.test(txt)) {
76
+ foundWorkflow = { path: join(workflowsDir, f), content: txt };
77
+ break;
78
+ }
79
+ } catch {/* skip unreadable */}
73
80
  }
74
- if (workflow.includes("ANTHROPIC_API_KEY")) {
75
- pass("Workflow references ANTHROPIC_API_KEY secret.");
81
+ }
82
+
83
+ if (foundWorkflow) {
84
+ ok(`Workflow ${relative(cwd, foundWorkflow.path) || foundWorkflow.path} uses ffcabbar/autoglot.`);
85
+ if (foundWorkflow.content.includes("ANTHROPIC_API_KEY")) {
86
+ ok("Workflow references ANTHROPIC_API_KEY secret.");
76
87
  } else {
77
88
  w("Workflow doesn't reference ANTHROPIC_API_KEY. autoglot will fail without it.");
78
89
  }
90
+ } else if (existsSync(workflowsDir)) {
91
+ w(`No workflow in ${relative(cwd, workflowsDir) || workflowsDir}/ references ffcabbar/autoglot. Run \`autoglot init\` or add one manually.`);
79
92
  } else {
80
- w(".github/workflows/translate.yml not found. Run \`autoglot init\` to create one, or add the workflow manually.");
93
+ w(`.github/workflows/ not found at ${relative(cwd, workflowSearchRoot) || workflowSearchRoot}. Run \`autoglot init\` to create one.`);
81
94
  }
82
95
 
83
96
  // 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");
97
+ if (existsSync(paths.lockFile)) {
98
+ const txt = readFileSync(paths.lockFile, "utf8");
87
99
  if (/^version:\s*1\b/m.test(txt)) {
88
- pass("translate.lock has version 1 header.");
100
+ ok("translate.lock has version 1 header.");
89
101
  } else {
90
102
  w("translate.lock exists but doesn't look like an autoglot lock file.");
91
103
  }
@@ -93,7 +105,7 @@ export async function run() {
93
105
 
94
106
  // 6. ANTHROPIC_API_KEY in env (only relevant for local runs)
95
107
  if (process.env.ANTHROPIC_API_KEY) {
96
- pass("ANTHROPIC_API_KEY set in current shell.");
108
+ ok("ANTHROPIC_API_KEY set in current shell.");
97
109
  } else {
98
110
  info("ANTHROPIC_API_KEY not set in this shell — fine for CI; only needed for local runs.");
99
111
  }
@@ -96,20 +96,48 @@ export function lineFromOffset(code, offset) {
96
96
  return line;
97
97
  }
98
98
 
99
+ // Code-shaped tokens that don't appear in real UI copy. The pattern that
100
+ // false-positives the most: regex catches text between `<...>` brackets,
101
+ // but TS generics (useRef<T>(null)) and intersection types look the same.
102
+ // If ANY of these substrings appear, reject.
103
+ const CODE_TOKEN_DENYLIST = [
104
+ "=>", ";", "===", "!==", "&&", "||", "??",
105
+ "const ", "let ", "var ", "function ", "return ", " as ",
106
+ "useRef", "useState", "useEffect", "useMemo", "useCallback",
107
+ "useSharedValue", "useDerivedValue", "useAnimatedRef", "useAnimatedStyle",
108
+ "Math.", "JSON.", "Object.", "Array.",
109
+ "props.", "this.", "<= ", ">= ", "== ", "!= ",
110
+ "console.", "process.", "Promise.",
111
+ ];
112
+
113
+ // Type names that show up bare between generic brackets. These aren't
114
+ // user-facing strings even when they pass other heuristics.
115
+ const BARE_TYPE_DENYLIST = new Set([
116
+ "Promise", "void", "null", "undefined", "any", "never", "unknown",
117
+ "Required", "Partial", "Record", "Pick", "Omit", "Readonly", "Exclude",
118
+ "Map", "Set", "Array", "ReadonlyArray", "Iterable", "AsyncIterable",
119
+ "ReactNode", "ReactElement", "ReactChild", "FunctionComponent",
120
+ "StyleProp", "SharedValue", "DerivedValue", "AnimatedRef",
121
+ "React.ReactNode", "React.ReactElement", "React.FunctionComponent",
122
+ "React.FC", "React.ComponentType",
123
+ ]);
124
+
99
125
  /**
100
126
  * Heuristic: is this string something a user actually sees?
101
127
  * Conservative — better to miss a real one than flag 100 false positives.
102
128
  *
103
129
  * Keep:
104
- * - Anything with a space ("Get started", "Click to continue")
105
- * - Strings starting with a capital letter that look like a sentence/word
130
+ * - Anything with a space that doesn't look like code ("Get started")
131
+ * - Single words starting with a capital letter ("Submit", "Cancel")
106
132
  *
107
133
  * Skip:
108
134
  * - Empty / very short / pure punctuation
109
135
  * - All-digit / pure numeric formatting
110
136
  * - URLs, paths, file extensions
111
- * - Identifier-like (lowercase with dashes/underscores, no spaces) — likely CSS classes / tokens
112
- * - Pure symbol strings ("→", "&copy;")
137
+ * - Identifier-like (lowercase with dashes/underscores, no spaces)
138
+ * - Code-shaped tokens (TS generics, comparison expressions, hook calls)
139
+ * - Bare type names (Promise, void, ReactNode, etc.)
140
+ * - Strings starting with `(`, `[`, `=`, `&`, `|`, `;`, `,`, `.`, `:`, `>` or a digit
113
141
  */
114
142
  export function isLikelyUserFacing(text) {
115
143
  if (!text || text.length < 2) return false;
@@ -121,21 +149,33 @@ export function isLikelyUserFacing(text) {
121
149
  if (/^\//.test(text) || /^\.\.?\//.test(text)) return false; // paths
122
150
  if (/^[a-zA-Z][\w-]*\.(json|tsx?|jsx?|css|svg|png|jpg|gif|md|yml|yaml)$/i.test(text)) return false; // filenames
123
151
 
124
- // Has whitespace = almost certainly user-facing copy.
125
- if (/\s/.test(text)) return true;
126
-
127
- // Single word: must start with a letter (kicks out "&copy;", "→", "©2026", etc.)
152
+ // Doesn't start with a letter → likely a code fragment leaked from `<...>`.
153
+ // (Real UI copy starts with a letter or with whitespace stripped to one.)
128
154
  if (!/^[A-Za-z]/.test(text)) return false;
129
155
 
130
- // Identifier-pattern (lowercase + dashes/underscores/digits, no caps,
131
- // no whitespace) → likely a CSS class, token, or variable name.
156
+ // Bare type names from TS generics.
157
+ if (BARE_TYPE_DENYLIST.has(text)) return false;
158
+
159
+ // Code-shaped tokens anywhere in the candidate.
160
+ for (const tok of CODE_TOKEN_DENYLIST) {
161
+ if (text.includes(tok)) return false;
162
+ }
163
+
164
+ // Has whitespace AND survived the code-token check → user copy.
165
+ if (/\s/.test(text)) return true;
166
+
167
+ // Single word: identifier pattern → reject.
132
168
  if (/^[a-z][\w-]*$/.test(text)) return false;
133
169
 
134
- // ALL_CAPS or SCREAMING_SNAKE_CASE → constants, not copy.
170
+ // ALL_CAPS or SCREAMING_SNAKE_CASE → constants.
135
171
  if (/^[A-Z_]+$/.test(text)) return false;
136
172
 
137
- // Anything else starting with a letter (e.g. "Submit", "Welcome!", "Hi-five")
138
- // is likely user-facing single-word copy.
173
+ // camelCase / PascalCase with junk like "eStatusCompleted", "sCompleteonboardingConst"
174
+ // → reject if last 1-3 chars look like a leaked TS suffix.
175
+ // Conservative: only allow single-word candidates with no caps inside.
176
+ // (i.e. "Submit" yes, "submitBtn" no.)
177
+ if (/[A-Z]/.test(text.slice(1))) return false;
178
+
139
179
  return true;
140
180
  }
141
181
 
@@ -157,17 +197,34 @@ function pathToNamespace(relPath) {
157
197
  // Strip extension
158
198
  let p = relPath.replace(/\.(tsx?|jsx?|vue|svelte)$/, "");
159
199
  // Strip conventional prefixes
160
- p = p.replace(/^(?:src\/)?(?:app\/|components\/|pages\/|screens\/)?/, "");
161
- // Bracketed Next.js segments: drop them (e.g. [locale])
200
+ p = p.replace(/^(?:src\/)?(?:app\/|components\/|pages\/|screens\/|hooks\/|services\/|lib\/|utils\/)?/, "");
201
+ // Bracketed Next.js segments: drop them (e.g. [locale], [...slug])
162
202
  p = p.replace(/\[[^\]]+\]\/?/g, "");
163
- // Drop trailing or whole-path "page" / "index" / "layout".
164
- // Matches "page", "/page", "foo/page" — leaves "foo".
165
- p = p.replace(/(^|\/)(page|index|layout)$/, "");
166
- // Slashes → dots
167
- p = p.replace(/\/+/g, ".").replace(/^\.+|\.+$/g, "");
203
+ // Parenthesized Expo Router groups: strip the parens, keep the name
204
+ // ("(onboarding)/age" → "onboarding/age")
205
+ p = p.replace(/\(([^)]+)\)/g, "$1");
206
+ // Drop trailing or whole-path "page" / "index" / "layout" / "_layout".
207
+ p = p.replace(/(^|\/)(page|index|_?layout)$/, "");
208
+ // Normalize each segment: dashes/underscores → camelCase, strip non-identifier
209
+ p = p.split("/").filter(Boolean).map(sanitizeSegment).filter(Boolean).join(".");
168
210
  return p;
169
211
  }
170
212
 
213
+ function sanitizeSegment(seg) {
214
+ // "journal-upload" → "journalUpload", "apple_intel" → "appleIntel"
215
+ const parts = seg.split(/[-_]+/).filter(Boolean);
216
+ if (parts.length === 0) return "";
217
+ const head = parts[0].replace(/[^a-zA-Z0-9]/g, "");
218
+ const tail = parts.slice(1).map((w) => {
219
+ const clean = w.replace(/[^a-zA-Z0-9]/g, "");
220
+ return clean ? clean[0].toUpperCase() + clean.slice(1) : "";
221
+ }).join("");
222
+ let out = head + tail;
223
+ // Prefix `_` if digit-leading so it's a valid JS identifier.
224
+ if (/^\d/.test(out)) out = "_" + out;
225
+ return out;
226
+ }
227
+
171
228
  function textToCamelKey(text) {
172
229
  const words = text
173
230
  .toLowerCase()
@@ -176,7 +233,91 @@ function textToCamelKey(text) {
176
233
  .filter(Boolean)
177
234
  .slice(0, 3);
178
235
  if (words.length === 0) return "key";
179
- return words[0] + words.slice(1).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
236
+ let key = words[0] + words.slice(1).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
237
+ // Prefix `_` if digit-leading so it's a valid JS identifier.
238
+ if (/^\d/.test(key)) key = "_" + key;
239
+ return key;
240
+ }
241
+
242
+ /**
243
+ * Look up a value at a dotted path. Returns `undefined` if the path
244
+ * doesn't fully exist or hits a non-object midway.
245
+ */
246
+ export function getNested(obj, dottedPath) {
247
+ const parts = dottedPath.split(".");
248
+ let cur = obj;
249
+ for (const k of parts) {
250
+ if (cur === null || typeof cur !== "object" || Array.isArray(cur)) return undefined;
251
+ cur = cur[k];
252
+ }
253
+ return cur;
254
+ }
255
+
256
+ /**
257
+ * Merge new candidate keys into an existing messages object.
258
+ * Returns { merged, added, skipped, conflicts }:
259
+ * - merged: the new object (does not mutate the input)
260
+ * - added: [{key, text}] entries that were newly written
261
+ * - skipped: [{key, existing, text}] entries that already had a value
262
+ * - conflicts: [{key, kind, text}] entries blocked by namespace/leaf shape
263
+ *
264
+ * Existing keys are NEVER overwritten — extract --write is meant to be
265
+ * safe to run repeatedly without clobbering hand-curated translations.
266
+ *
267
+ * Shape conflicts (the #7 silent-corruption class) are detected and refused:
268
+ * - kind="leaf-vs-namespace": existing path `a.b` is a string but candidate
269
+ * wants to write `a.b.c` — would replace string with object.
270
+ * - kind="namespace-vs-leaf": existing path `a.b` is an object but candidate
271
+ * wants to write `a.b` as a string — would silently delete `a.b.*`.
272
+ */
273
+ export function mergeKeys(existing, candidates) {
274
+ const merged = structuredClone(existing ?? {});
275
+ const added = [];
276
+ const skipped = [];
277
+ const conflicts = [];
278
+ for (const cand of candidates) {
279
+ const conflict = detectShapeConflict(merged, cand.key);
280
+ if (conflict) {
281
+ conflicts.push({ key: cand.key, kind: conflict, text: cand.text });
282
+ continue;
283
+ }
284
+ const current = getNested(merged, cand.key);
285
+ if (typeof current === "string") {
286
+ skipped.push({ key: cand.key, existing: current, text: cand.text });
287
+ continue;
288
+ }
289
+ setNested(merged, cand.key, cand.text);
290
+ added.push({ key: cand.key, text: cand.text });
291
+ }
292
+ return { merged, added, skipped, conflicts };
293
+ }
294
+
295
+ /**
296
+ * Check whether writing `dottedPath = <string>` into `obj` would clobber
297
+ * a non-string node, in either direction.
298
+ *
299
+ * Returns null (safe), "leaf-vs-namespace" (an ancestor is already a
300
+ * string), or "namespace-vs-leaf" (the target is already an object).
301
+ */
302
+ export function detectShapeConflict(obj, dottedPath) {
303
+ const parts = dottedPath.split(".");
304
+ let cur = obj;
305
+ // Walk ancestors. If we hit a non-object before reaching the leaf,
306
+ // it's a leaf-vs-namespace conflict (existing string blocks a deeper key).
307
+ for (let i = 0; i < parts.length - 1; i++) {
308
+ const k = parts[i];
309
+ const next = cur?.[k];
310
+ if (next === undefined) return null; // free space, fine
311
+ if (typeof next !== "object" || next === null || Array.isArray(next)) {
312
+ return "leaf-vs-namespace";
313
+ }
314
+ cur = next;
315
+ }
316
+ const leaf = cur?.[parts[parts.length - 1]];
317
+ if (leaf === undefined) return null;
318
+ if (typeof leaf === "string") return null; // mergeKeys handles this as "skipped"
319
+ // It's an object/array — writing a string here would delete its contents.
320
+ return "namespace-vs-leaf";
180
321
  }
181
322
 
182
323
  /** Set a value at a dotted path on an object. Mutates `obj`. */
package/bin/extract.mjs CHANGED
@@ -9,7 +9,7 @@
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, readdirSync, statSync, existsSync } from "node:fs";
12
+ import { readFileSync, writeFileSync, readdirSync, statSync, existsSync, mkdirSync } from "node:fs";
13
13
  import { join, relative, extname, dirname } from "node:path";
14
14
  import { step, info, ok, warn, err, c } from "./prompts.mjs";
15
15
  import {
@@ -18,6 +18,7 @@ import {
18
18
  isLikelyUserFacing,
19
19
  suggestKey,
20
20
  setNested,
21
+ mergeKeys,
21
22
  } from "./extract-helpers.mjs";
22
23
 
23
24
  export const SCAN_EXTS = new Set([".tsx", ".jsx", ".ts", ".js", ".vue", ".svelte"]);
@@ -27,7 +28,23 @@ export const SKIP_DIRS = new Set([
27
28
  "coverage", ".vercel", ".cache", ".parcel-cache", "out", "public",
28
29
  ]);
29
30
 
30
- export async function run(args) {
31
+ /**
32
+ * Parse `extract`-specific flags. Unknown flags are ignored (forward-compat).
33
+ *
34
+ * --write merge candidates into messages/en.json (skips existing keys)
35
+ * --source=<path> override the target file (default: messages/en.json)
36
+ */
37
+ export function parseExtractArgs(argv) {
38
+ const opts = { write: false, source: null };
39
+ for (const arg of argv) {
40
+ if (arg === "--write") opts.write = true;
41
+ else if (arg.startsWith("--source=")) opts.source = arg.slice("--source=".length);
42
+ }
43
+ return opts;
44
+ }
45
+
46
+ export async function run(args = []) {
47
+ const opts = parseExtractArgs(args);
31
48
  const cwd = process.cwd();
32
49
  step("autoglot extract");
33
50
 
@@ -88,13 +105,60 @@ export async function run(args) {
88
105
  setNested(merged, cand.key, cand.text);
89
106
  }
90
107
 
91
- step("Suggested additions to messages/en.json");
92
- process.stdout.write(JSON.stringify(merged, null, 2) + "\n");
108
+ if (!opts.write) {
109
+ step("Suggested additions to messages/en.json");
110
+ process.stdout.write(JSON.stringify(merged, null, 2) + "\n");
111
+ }
93
112
 
94
113
  step("Summary");
95
114
  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"}.`);
96
115
 
116
+ if (opts.write) {
117
+ const target = opts.source || "messages/en.json";
118
+ const full = join(cwd, target);
119
+ let existing = {};
120
+ if (existsSync(full)) {
121
+ try {
122
+ existing = JSON.parse(readFileSync(full, "utf8"));
123
+ } catch (e) {
124
+ err(`Couldn't parse ${target}: ${e.message}. Aborting --write.`);
125
+ return;
126
+ }
127
+ }
128
+ const { merged: out, added, skipped, conflicts } = mergeKeys(existing, allCandidates);
129
+
130
+ step(opts.source ? `Writing ${target}` : "Writing messages/en.json");
131
+ mkdirSync(dirname(full), { recursive: true });
132
+ writeFileSync(full, JSON.stringify(out, null, 2) + "\n");
133
+ ok(`${target} now has ${added.length} new key${added.length === 1 ? "" : "s"}.`);
134
+ if (skipped.length > 0) {
135
+ info(`${skipped.length} key${skipped.length === 1 ? "" : "s"} already existed (same path) and were left untouched:`);
136
+ for (const s of skipped.slice(0, 5)) {
137
+ process.stdout.write(` ${c.dim}${s.key} (kept: ${JSON.stringify(s.existing)})${c.reset}\n`);
138
+ }
139
+ if (skipped.length > 5) {
140
+ process.stdout.write(` ${c.dim}…and ${skipped.length - 5} more${c.reset}\n`);
141
+ }
142
+ }
143
+ if (conflicts.length > 0) {
144
+ warn(`${conflicts.length} candidate${conflicts.length === 1 ? "" : "s"} skipped due to namespace/leaf shape conflicts:`);
145
+ for (const cn of conflicts.slice(0, 5)) {
146
+ const note = cn.kind === "leaf-vs-namespace"
147
+ ? "an ancestor is already a string"
148
+ : "the target is already a namespace (writing would delete children)";
149
+ process.stdout.write(` ${c.dim}${cn.key} — ${note}${c.reset}\n`);
150
+ }
151
+ if (conflicts.length > 5) {
152
+ process.stdout.write(` ${c.dim}…and ${conflicts.length - 5} more${c.reset}\n`);
153
+ }
154
+ info("Rename the candidate keys (or the existing entry) to resolve.");
155
+ }
156
+ step("Next");
157
+ info(`Review the new keys in ${c.bold}${target}${c.reset}, then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
158
+ return;
159
+ }
160
+
97
161
  step("Next");
98
- info(`Review the candidates above. Copy the relevant ones into ${c.bold}messages/en.json${c.reset}, then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
99
- info("autoglot extract is read-only by design — it never modifies your source.");
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.`);
163
+ info("Default mode is read-only. Use --write to merge into messages/en.json (existing keys are never overwritten).");
100
164
  }
package/bin/init.mjs CHANGED
@@ -11,24 +11,53 @@
11
11
 
12
12
  import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
13
13
  import { join, dirname, resolve } from "node:path";
14
+ import { spawnSync } from "node:child_process";
14
15
  import { ask, select, multiselect, confirm, info, ok, warn, err, step, c, closePrompts } from "./prompts.mjs";
15
16
  import { detect, LOCALE_CATALOG } from "./detect.mjs";
17
+ import { detectPackageManager, installCommand, PACKAGE_MANAGERS } from "./pm.mjs";
16
18
  import * as common from "./templates/common.mjs";
17
19
  import * as nextAppRouter from "./templates/nextjs-app-router.mjs";
18
20
  import * as nextPagesRouter from "./templates/nextjs-pages-router.mjs";
19
21
  import * as reactNative from "./templates/react-native.mjs";
22
+ import * as expo from "./templates/expo.mjs";
20
23
  import * as viteReact from "./templates/vite-react.mjs";
21
24
  import * as vueI18n from "./templates/vue-i18n.mjs";
22
25
 
23
26
  const TEMPLATES = {
24
27
  "nextjs-app": nextAppRouter,
25
28
  "nextjs-pages": nextPagesRouter,
29
+ "expo": expo,
26
30
  "react-native": reactNative,
27
31
  "vite-react": viteReact,
28
32
  "vue": vueI18n,
29
33
  };
30
34
 
31
- export async function run() {
35
+ /**
36
+ * Parse `init`-specific flags. Unknown flags are ignored (forward-compat).
37
+ *
38
+ * --install opt-in: run the package manager to install runtime deps
39
+ * --pm=npm|yarn|pnpm|bun override the auto-detected package manager
40
+ * --no-install force off (useful in CI if a default ever flips)
41
+ */
42
+ export function parseInitArgs(argv) {
43
+ const opts = { install: false, installExplicit: false, pm: null };
44
+ for (const arg of argv) {
45
+ if (arg === "--install") {
46
+ opts.install = true;
47
+ opts.installExplicit = true;
48
+ } else if (arg === "--no-install") {
49
+ opts.install = false;
50
+ opts.installExplicit = true;
51
+ } else if (arg.startsWith("--pm=")) {
52
+ const v = arg.slice("--pm=".length);
53
+ if (PACKAGE_MANAGERS.includes(v)) opts.pm = v;
54
+ }
55
+ }
56
+ return opts;
57
+ }
58
+
59
+ export async function run(argv = []) {
60
+ const opts = parseInitArgs(argv);
32
61
  const cwd = process.cwd();
33
62
  step("autoglot init");
34
63
  info(`cwd: ${c.dim}${cwd}${c.reset}`);
@@ -179,14 +208,48 @@ export async function run() {
179
208
  written++;
180
209
  }
181
210
 
182
- // Final report + next steps
211
+ // Final report
183
212
  step("Done");
184
213
  info(`Wrote ${written} file${written === 1 ? "" : "s"}, skipped ${skipped} existing file${skipped === 1 ? "" : "s"}.`);
185
214
 
215
+ // Optionally install runtime deps. Default is OFF — auto-install across
216
+ // monorepos / mixed React versions is fragile. Opt in with --install.
217
+ let installSucceeded = false;
218
+ let installFailed = false;
219
+ if (runtimeInstallHint) {
220
+ const pkgs = runtimeInstallHint.split(" ").filter(Boolean);
221
+ let shouldInstall = opts.install;
222
+ if (!opts.installExplicit) {
223
+ shouldInstall = await confirm(
224
+ `Install runtime packages now (${pkgs.join(", ")})?`,
225
+ false,
226
+ );
227
+ }
228
+ if (shouldInstall) {
229
+ const pm = opts.pm || detectPackageManager(cwd);
230
+ const [bin, ...args] = installCommand(pm, pkgs);
231
+ step(`Installing with ${pm}`);
232
+ info(`${c.dim}${bin} ${args.join(" ")}${c.reset}`);
233
+ const res = spawnSync(bin, args, { stdio: "inherit", cwd });
234
+ if (res.status === 0) {
235
+ ok(`Installed ${pkgs.join(", ")} via ${pm}.`);
236
+ installSucceeded = true;
237
+ } else {
238
+ warn(`${pm} install exited with code ${res.status ?? "?"}. You can re-run manually.`);
239
+ installFailed = true;
240
+ }
241
+ }
242
+ }
243
+
186
244
  step("Next steps");
187
245
  const numbered = [];
188
- if (runtimeInstallHint) {
189
- numbered.push(`Install the runtime i18n library:\n ${c.dim}npm install ${runtimeInstallHint}${c.reset}`);
246
+ if (runtimeInstallHint && !installSucceeded) {
247
+ const hintPm = opts.pm || detectPackageManager(cwd);
248
+ const [bin, ...args] = installCommand(hintPm, runtimeInstallHint.split(" ").filter(Boolean));
249
+ const label = installFailed
250
+ ? `Retry installing the runtime i18n library:`
251
+ : `Install the runtime i18n library:`;
252
+ numbered.push(`${label}\n ${c.dim}${bin} ${args.join(" ")}${c.reset}`);
190
253
  }
191
254
  numbered.push(
192
255
  `Add ${c.bold}ANTHROPIC_API_KEY${c.reset} to your repo secrets:\n ${c.dim}gh secret set ANTHROPIC_API_KEY${c.reset}`,
package/bin/pm.mjs ADDED
@@ -0,0 +1,57 @@
1
+ // Package manager detection + install command construction.
2
+ // Pure helpers (no I/O) plus one thin filesystem wrapper for the CLI.
3
+
4
+ import { existsSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ export const PACKAGE_MANAGERS = ["npm", "yarn", "pnpm", "bun"];
8
+
9
+ /**
10
+ * Decide which package manager a project uses from its lockfile presence.
11
+ * Precedence: bun > pnpm > yarn > npm (most distinctive first).
12
+ *
13
+ * Pure function — takes the set of lockfile names that exist, returns a name.
14
+ * Use `detectPackageManager(cwd)` for the filesystem wrapper.
15
+ *
16
+ * @param {Set<string>} lockfiles e.g. new Set(["pnpm-lock.yaml"])
17
+ * @returns {"npm" | "yarn" | "pnpm" | "bun"}
18
+ */
19
+ export function detectFromLockfiles(lockfiles) {
20
+ if (lockfiles.has("bun.lockb") || lockfiles.has("bun.lock")) return "bun";
21
+ if (lockfiles.has("pnpm-lock.yaml")) return "pnpm";
22
+ if (lockfiles.has("yarn.lock")) return "yarn";
23
+ // package-lock.json or nothing → npm (safe default; ships with Node).
24
+ return "npm";
25
+ }
26
+
27
+ /** Filesystem wrapper around detectFromLockfiles. */
28
+ export function detectPackageManager(cwd) {
29
+ const candidates = ["bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock", "package-lock.json"];
30
+ const present = new Set();
31
+ for (const f of candidates) {
32
+ if (existsSync(join(cwd, f))) present.add(f);
33
+ }
34
+ return detectFromLockfiles(present);
35
+ }
36
+
37
+ /**
38
+ * Build the install command tokens for a package manager.
39
+ * Returns [bin, ...args] suitable for spawn().
40
+ *
41
+ * @param {"npm" | "yarn" | "pnpm" | "bun"} pm
42
+ * @param {string[]} packages e.g. ["i18next", "react-i18next"]
43
+ * @returns {string[]}
44
+ */
45
+ export function installCommand(pm, packages) {
46
+ switch (pm) {
47
+ case "yarn":
48
+ return ["yarn", "add", ...packages];
49
+ case "pnpm":
50
+ return ["pnpm", "add", ...packages];
51
+ case "bun":
52
+ return ["bun", "add", ...packages];
53
+ case "npm":
54
+ default:
55
+ return ["npm", "install", ...packages];
56
+ }
57
+ }
@@ -0,0 +1,66 @@
1
+ // Expo + react-i18next scaffold.
2
+ //
3
+ // Expo apps have `react-native` in deps too, but Expo offers a cleaner
4
+ // device-locale API via `expo-localization` (no native linking required).
5
+ // We scaffold an i18n init that auto-picks the device locale and falls
6
+ // back to the configured default.
7
+
8
+ /** @param {{ defaultLocale: string, locales: string[] }} ctx */
9
+ export function indexTs(ctx) {
10
+ const imports = ctx.locales
11
+ .map((l) => `import ${jsId(l)} from "../../messages/${l}.json";`)
12
+ .join("\n");
13
+ const resources = ctx.locales
14
+ .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${jsId(l)} },`)
15
+ .join("\n");
16
+ const localesArr = ctx.locales.map((l) => JSON.stringify(l)).join(", ");
17
+
18
+ return `import i18n from "i18next";
19
+ import { initReactI18next } from "react-i18next";
20
+ import { getLocales } from "expo-localization";
21
+
22
+ ${imports}
23
+
24
+ // Pick the first device locale that we have a translation for; otherwise
25
+ // fall back to the configured default.
26
+ const supported = new Set([${localesArr}]);
27
+ const deviceLocale = getLocales().find((l) => supported.has(l.languageTag) || supported.has(l.languageCode));
28
+ const initialLocale = deviceLocale?.languageTag ?? deviceLocale?.languageCode ?? "${ctx.defaultLocale}";
29
+
30
+ i18n.use(initReactI18next).init({
31
+ // i18next requires this on RN/Expo to avoid Intl polyfill differences.
32
+ compatibilityJSON: "v4",
33
+ resources: {
34
+ ${resources}
35
+ },
36
+ lng: supported.has(initialLocale) ? initialLocale : "${ctx.defaultLocale}",
37
+ fallbackLng: "${ctx.defaultLocale}",
38
+ interpolation: { escapeValue: false },
39
+ });
40
+
41
+ export default i18n;
42
+ `;
43
+ }
44
+
45
+ /** @param {{ defaultLocale: string, locales: string[] }} ctx */
46
+ export function files(ctx) {
47
+ return [{ path: "src/i18n/index.ts", content: indexTs(ctx) }];
48
+ }
49
+
50
+ export const runtimePackages = ["i18next", "react-i18next", "expo-localization"];
51
+
52
+ export function followupNotes() {
53
+ return [
54
+ "Import the i18n init early in App.tsx — before any t() calls:\n import \"./src/i18n\";",
55
+ "Use the useTranslation() hook in components: const { t } = useTranslation();",
56
+ "expo-localization is included — device locale is auto-detected on app start.",
57
+ "For Expo Router: place the import in app/_layout.tsx instead of App.tsx.",
58
+ ];
59
+ }
60
+
61
+ function jsId(loc) {
62
+ return loc.replace(/[^a-zA-Z0-9_$]/g, "_");
63
+ }
64
+ function quoteIfNeeded(loc) {
65
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loc) ? loc : JSON.stringify(loc);
66
+ }
package/bin/translate.mjs CHANGED
@@ -47,6 +47,7 @@ import {
47
47
  pickAllowedSource,
48
48
  pLimit,
49
49
  } from "./helpers.mjs";
50
+ import { resolvePaths } from "./config.mjs";
50
51
 
51
52
  // --- Constants ------------------------------------------------------------
52
53
  const HELP_TEXT = `autoglot — AI-powered i18n translation bot
@@ -104,13 +105,18 @@ if (args.help || args.h) {
104
105
  process.exit(0);
105
106
  }
106
107
 
107
- const CONFIG_PATH = resolvePath(args.config || "translate.config.json");
108
-
109
- const config = loadConfig(CONFIG_PATH);
110
-
111
- const SOURCE_FILE = resolvePath(args.source || config.source || "messages/en.json");
112
- const MESSAGES_DIR = resolvePath(args["messages-dir"] || config.messagesDir || "messages");
113
- const LOCK_FILE = resolvePath(args["lock-file"] || config.lockFile || "translate.lock");
108
+ let __paths;
109
+ try {
110
+ __paths = resolvePaths(args, CWD);
111
+ } catch (err) {
112
+ console.error(`[translate] ${err.message}`);
113
+ process.exit(1);
114
+ }
115
+ const CONFIG_PATH = __paths.configPath || resolvePath(args.config || "translate.config.json");
116
+ const config = __paths.config || { namespaces: {} };
117
+ const SOURCE_FILE = __paths.source;
118
+ const MESSAGES_DIR = __paths.messagesDir;
119
+ const LOCK_FILE = __paths.lockFile;
114
120
  const SUMMARY_FILE = args["summary-path"]
115
121
  ? resolvePath(args["summary-path"])
116
122
  : join(tmpdir(), "translate-summary.md");
@@ -378,19 +384,8 @@ function loadLock() {
378
384
  return parseLockYaml(readFileSync(LOCK_FILE, "utf8"), SOURCE_FILE);
379
385
  }
380
386
 
381
- function loadConfig(p) {
382
- if (!existsSync(p)) return { namespaces: {} };
383
- try {
384
- const parsed = JSON.parse(readFileSync(p, "utf8"));
385
- return {
386
- ...parsed,
387
- namespaces: parsed.namespaces || {},
388
- };
389
- } catch (err) {
390
- console.error(`[translate] Failed to parse ${p}: ${err.message}`);
391
- process.exit(1);
392
- }
393
- }
387
+ // loadConfig moved to ./config.mjs (shared with add/doctor; resolves
388
+ // config-relative paths so monorepo invocations work from any subdir).
394
389
 
395
390
  function discoverTargetLocales() {
396
391
  if (!existsSync(MESSAGES_DIR)) return [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autoglot",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
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"
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"
17
17
  },
18
18
  "keywords": [
19
19
  "i18n",