autoglot 0.3.0 → 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/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/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,10 @@ 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;
180
240
  }
181
241
 
182
242
  /**
@@ -195,19 +255,32 @@ export function getNested(obj, dottedPath) {
195
255
 
196
256
  /**
197
257
  * Merge new candidate keys into an existing messages object.
198
- * Returns { merged, added, skipped }:
258
+ * Returns { merged, added, skipped, conflicts }:
199
259
  * - merged: the new object (does not mutate the input)
200
260
  * - added: [{key, text}] entries that were newly written
201
261
  * - skipped: [{key, existing, text}] entries that already had a value
262
+ * - conflicts: [{key, kind, text}] entries blocked by namespace/leaf shape
202
263
  *
203
264
  * Existing keys are NEVER overwritten — extract --write is meant to be
204
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.*`.
205
272
  */
206
273
  export function mergeKeys(existing, candidates) {
207
274
  const merged = structuredClone(existing ?? {});
208
275
  const added = [];
209
276
  const skipped = [];
277
+ const conflicts = [];
210
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
+ }
211
284
  const current = getNested(merged, cand.key);
212
285
  if (typeof current === "string") {
213
286
  skipped.push({ key: cand.key, existing: current, text: cand.text });
@@ -216,7 +289,35 @@ export function mergeKeys(existing, candidates) {
216
289
  setNested(merged, cand.key, cand.text);
217
290
  added.push({ key: cand.key, text: cand.text });
218
291
  }
219
- return { merged, added, skipped };
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";
220
321
  }
221
322
 
222
323
  /** Set a value at a dotted path on an object. Mutates `obj`. */
package/bin/extract.mjs CHANGED
@@ -125,14 +125,14 @@ export async function run(args = []) {
125
125
  return;
126
126
  }
127
127
  }
128
- const { merged: out, added, skipped } = mergeKeys(existing, allCandidates);
128
+ const { merged: out, added, skipped, conflicts } = mergeKeys(existing, allCandidates);
129
129
 
130
130
  step(opts.source ? `Writing ${target}` : "Writing messages/en.json");
131
131
  mkdirSync(dirname(full), { recursive: true });
132
132
  writeFileSync(full, JSON.stringify(out, null, 2) + "\n");
133
133
  ok(`${target} now has ${added.length} new key${added.length === 1 ? "" : "s"}.`);
134
134
  if (skipped.length > 0) {
135
- info(`${skipped.length} key${skipped.length === 1 ? "" : "s"} already existed and were left untouched:`);
135
+ info(`${skipped.length} key${skipped.length === 1 ? "" : "s"} already existed (same path) and were left untouched:`);
136
136
  for (const s of skipped.slice(0, 5)) {
137
137
  process.stdout.write(` ${c.dim}${s.key} (kept: ${JSON.stringify(s.existing)})${c.reset}\n`);
138
138
  }
@@ -140,6 +140,19 @@ export async function run(args = []) {
140
140
  process.stdout.write(` ${c.dim}…and ${skipped.length - 5} more${c.reset}\n`);
141
141
  }
142
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
+ }
143
156
  step("Next");
144
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.`);
145
158
  return;
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.3.0",
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 tests/pm.test.mjs tests/init-args.test.mjs tests/expo.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",