@tolkit/cli 0.0.0-stage → 0.2.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/dist/scan.js ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * The pure core of `tolkit scan`: find literal occurrences of key names in
3
+ * source text and turn them into bounded `{ file, line, snippet }` usages.
4
+ * No filesystem or network here (see commands/scan.ts), so it's fully tested.
5
+ *
6
+ * Matching rule: a hit counts only when the characters immediately before and
7
+ * after it cannot continue a key — not a letter, digit, `.`, `_` or `-`. So
8
+ * `nav.settings` does not match inside `nav.settings.label` or `my_nav.settings`.
9
+ * Configured `prefixes` are the exception: with `m.`, `m.nav_settings()` is a
10
+ * usage of `nav_settings` (Paraglide's message functions). Scoped
11
+ * (`t("settings")` under a namespace) and dynamic (`` t(`nav.${x}`) ``) keys
12
+ * are deliberately not guessed at: no usage is better than a wrong file:line.
13
+ *
14
+ * Each usage also records the element it sits in (`elementAt`), from which the
15
+ * server infers what the string is on screen: a button, a status badge…
16
+ */
17
+ /** Bounds mirrored by the server (lib/queries.ts). */
18
+ export const SNIPPET_MAX = 200;
19
+ export const USAGES_PER_KEY_MAX = 20;
20
+ // Characters that can continue a key; a hit must not touch one on either side.
21
+ const KEY_CHAR = /[\p{L}\p{N}._-]/u;
22
+ // Maximal runs of key characters — candidate key names in a line.
23
+ const KEY_RUN = /[\p{L}\p{N}._-]+/gu;
24
+ /** Trim + truncate a source line to at most SNIPPET_MAX characters. */
25
+ export function clampSnippet(line) {
26
+ const t = line.trim();
27
+ return t.length > SNIPPET_MAX ? `${t.slice(0, SNIPPET_MAX - 1)}…` : t;
28
+ }
29
+ /**
30
+ * A matcher over a fixed key set. Keys made only of key characters (the vast
31
+ * majority: `nav.settings`, `billing_seats`) are found by splitting each line
32
+ * into maximal runs and looking each up in a Set — O(line length) regardless
33
+ * of how many keys there are. Keys with other characters (`common:save`,
34
+ * `Hello world`) fall back to an indexOf scan with the same boundary check.
35
+ */
36
+ export function createMatcher(keys, prefixes = []) {
37
+ const simple = new Set();
38
+ const complex = [];
39
+ for (const k of keys) {
40
+ if (!k)
41
+ continue;
42
+ if (/^[\p{L}\p{N}._-]+$/u.test(k))
43
+ simple.add(k);
44
+ else
45
+ complex.push(k);
46
+ }
47
+ /** Distinct keys found in one line, in order of first appearance. */
48
+ function match(line) {
49
+ const found = [];
50
+ const seen = new Set();
51
+ if (simple.size > 0) {
52
+ for (const m of line.matchAll(KEY_RUN)) {
53
+ const run = m[0];
54
+ const p = prefixes.find((p) => run.startsWith(p) && simple.has(run.slice(p.length)));
55
+ const key = simple.has(run) ? run : p ? run.slice(p.length) : null;
56
+ if (key && !seen.has(key)) {
57
+ seen.add(key);
58
+ found.push(key);
59
+ }
60
+ }
61
+ }
62
+ for (const k of complex) {
63
+ if (!seen.has(k) && hasBoundedHit(line, k)) {
64
+ seen.add(k);
65
+ found.push(k);
66
+ }
67
+ }
68
+ return found;
69
+ }
70
+ return { match };
71
+ }
72
+ function hasBoundedHit(line, key) {
73
+ for (let i = line.indexOf(key); i !== -1; i = line.indexOf(key, i + 1)) {
74
+ const before = i > 0 ? line[i - 1] : "";
75
+ const after = line[i + key.length] ?? "";
76
+ // a key starting/ending in a non-key character can't be "continued" there
77
+ const okBefore = !before || !KEY_CHAR.test(key[0]) || !KEY_CHAR.test(before);
78
+ const okAfter = !after || !KEY_CHAR.test(key[key.length - 1]) || !KEY_CHAR.test(after);
79
+ if (okBefore && okAfter)
80
+ return true;
81
+ }
82
+ return false;
83
+ }
84
+ /**
85
+ * Accumulates usages across files. Each key keeps at most USAGES_PER_KEY_MAX
86
+ * usages (first found, in walk order) while `totals` counts every hit, so the
87
+ * caller can report what the cap dropped instead of silently applying it.
88
+ */
89
+ export function createCollector(keys, prefixes = []) {
90
+ const keyList = [...keys];
91
+ const matcher = createMatcher(keyList, prefixes);
92
+ const usages = new Map(keyList.map((k) => [k, []]));
93
+ const totals = new Map();
94
+ function addFile(file, text) {
95
+ const lines = text.split(/\r\n|\r|\n/);
96
+ for (let i = 0; i < lines.length; i++) {
97
+ const line = lines[i];
98
+ const hits = matcher.match(line);
99
+ if (hits.length === 0)
100
+ continue;
101
+ for (const key of hits) {
102
+ totals.set(key, (totals.get(key) ?? 0) + 1);
103
+ const list = usages.get(key);
104
+ if (list.length < USAGES_PER_KEY_MAX) {
105
+ list.push({ file, line: i + 1, snippet: clampSnippet(line), element: elementAt(lines, i, line.indexOf(key)) });
106
+ }
107
+ }
108
+ }
109
+ }
110
+ /** Every key (found or not — `[]` clears stale rows server-side). */
111
+ function result() {
112
+ const capped = [...totals]
113
+ .filter(([, n]) => n > USAGES_PER_KEY_MAX)
114
+ .map(([key, total]) => ({ key, total }))
115
+ .sort((a, b) => b.total - a.total || a.key.localeCompare(b.key));
116
+ let found = 0;
117
+ let hits = 0;
118
+ for (const list of usages.values()) {
119
+ if (list.length > 0)
120
+ found++;
121
+ hits += list.length;
122
+ }
123
+ return { usages: Object.fromEntries(usages), found, hits, capped };
124
+ }
125
+ return { addFile, result };
126
+ }
127
+ // How far back an enclosing element is looked for.
128
+ const LOOKBACK_LINES = 15;
129
+ /**
130
+ * The element a key at `lines[lineIndex][column]` sits in, as the server's
131
+ * role inference reads it: `<Button>` (its text), `<Input placeholder>` (an
132
+ * attribute), `title` (an object property), `toast()` (a call), or null when
133
+ * none is recognisable. A heuristic over source text, not a parser: an answer
134
+ * it is unsure of is null, never a guess.
135
+ */
136
+ export function elementAt(lines, lineIndex, column) {
137
+ if (column < 0)
138
+ return null;
139
+ let text = [...lines.slice(Math.max(0, lineIndex - LOOKBACK_LINES), lineIndex), lines[lineIndex].slice(0, column)]
140
+ .join("\n")
141
+ // What calls the key: `m.`, `t("`, `i18n.t(`.
142
+ .replace(/["'`]$/, "")
143
+ .replace(/[\w$.]+\(\s*$/, "")
144
+ .replace(/[\w$.]+$/, "");
145
+ if (/\btoast(?:\.\w+)?\(\s*$/.test(text))
146
+ return "toast()";
147
+ text = collapseBraces(text);
148
+ const attribute = text.match(/\s([A-Za-z][\w-]*)=\{[^{}]*$/);
149
+ if (attribute) {
150
+ const tag = text.slice(0, attribute.index).match(/<([A-Za-z][\w.]*)(?:[^<>{}]|\{\})*$/);
151
+ return tag ? `<${tag[1]} ${attribute[1]}>` : attribute[1];
152
+ }
153
+ // `label: m.x()` or `label: () => m.x()`
154
+ const property = text.match(/(?:^|[{,\s])([A-Za-z][\w-]*)\s*:\s*(?:\(\)\s*=~\s*)?$/);
155
+ if (property)
156
+ return property[1];
157
+ // JSX content: `{` after a tag or text, not after JS punctuation.
158
+ const child = text.match(/([^\s])\s*\{[^{}]*$/);
159
+ if (!child || "(=,:[?&|{".includes(child[1]))
160
+ return null;
161
+ const tag = innermostOpenTag(text.slice(0, (child.index ?? 0) + 1));
162
+ return tag ? `<${tag}>` : null;
163
+ }
164
+ /**
165
+ * Empty every closed `{…}`, innermost first, so attribute values such as
166
+ * `onPress={() => { a > b }}` can't be mistaken for tags. An arrow's `>`
167
+ * would also read as the end of a tag, so it goes first.
168
+ */
169
+ function collapseBraces(text) {
170
+ let out = text.replace(/=>/g, "=~");
171
+ for (let prev = ""; prev !== out;) {
172
+ prev = out;
173
+ out = out.replace(/\{[^{}]*\}/g, "{}");
174
+ }
175
+ return out;
176
+ }
177
+ function innermostOpenTag(text) {
178
+ const stack = [];
179
+ for (const m of text.matchAll(/<(\/?)([A-Za-z][\w.]*)[^<>]*?(\/?)>/g)) {
180
+ const [, closing, name, selfClosing] = m;
181
+ if (selfClosing)
182
+ continue;
183
+ if (!closing)
184
+ stack.push(name);
185
+ else {
186
+ const at = stack.lastIndexOf(name);
187
+ if (at !== -1)
188
+ stack.length = at;
189
+ }
190
+ }
191
+ return stack.at(-1) ?? null;
192
+ }
193
+ /** Heuristic binary check: a NUL byte in the first 8 KB. */
194
+ export function looksBinary(buf) {
195
+ const n = Math.min(buf.length, 8192);
196
+ for (let i = 0; i < n; i++)
197
+ if (buf[i] === 0)
198
+ return true;
199
+ return false;
200
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@tolkit/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "CLI and MCP server for Tolkit translation management",
5
+ "license": "MIT",
6
+ "homepage": "https://tolkit.app",
7
+ "type": "module",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "bin": {
12
+ "tolkit": "dist/index.js"
13
+ },
14
+ "exports": {
15
+ "./bin": "./dist/index.js"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.json",
26
+ "prepublishOnly": "pnpm build",
27
+ "test": "vitest run"
28
+ },
29
+ "dependencies": {
30
+ "@modelcontextprotocol/sdk": "^1.32.2",
31
+ "zod": "^4.6.7"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^26.6.6",
35
+ "typescript": "^7.0.2",
36
+ "vitest": "^5.1.1"
37
+ }
38
+ }