-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
354 lines (326 loc) · 9.74 KB
/
index.ts
File metadata and controls
354 lines (326 loc) · 9.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { Command } from "commander";
import * as babelParser from "@babel/parser";
import * as t from "@babel/types";
import traverseModule from "@babel/traverse";
// Handle ESM import for @babel/traverse
const traverse = (traverseModule as any).default || traverseModule;
const program = new Command();
program
.name("extract-i18n")
.description("Extract raw text from JSX for i18n")
.argument("[directory]", "Directory to scan", ".")
.option(
"-e, --ext <extensions>",
"Comma-separated list of file extensions",
".tsx,.jsx"
)
.option(
"-a, --attributes <names>",
"Comma-separated list of attribute names",
"title,alt,placeholder"
)
.option(
"-t, --truncate <limit>",
"Truncate text to this length, 0 to disable",
"30"
)
.option(
"-f, --filter-non-alpha",
"Filter out text containing only non-alphabetic characters",
false
)
.option(
"-l, --include-literals",
"Include string literals from objects, function calls, and schemas",
false
)
.option("-d, --deps", "Include dependency directories (node_modules)")
.parse();
const dir = path.resolve(program.args?.at(0) ?? ".");
const options = program.opts();
const extensions = options.ext.split(",").map((ext: string) => ext.trim());
const attributes = options.attributes
.split(",")
.map((attr: string) => attr.trim());
const truncate = options.truncate ? parseInt(options.truncate) : 0;
const filterNonAlpha = options.filterNonAlpha || false;
const includeLiterals = options.includeLiterals || false;
// Keys that typically contain user-facing text
const USER_FACING_KEYS = new Set([
"message",
"error",
"label",
"title",
"description",
"text",
"placeholder",
"tooltip",
"hint",
"content",
"name",
"displayName",
]);
// Function/method names that typically contain user-facing text
const USER_FACING_FUNCTIONS = new Set([
"toast",
"error",
"warn",
"message",
"alert",
"notify",
"success",
"info",
]);
// Keys to always skip (technical/code values)
const SKIP_KEYS = new Set([
"className",
"class",
"id",
"key",
"ref",
"style",
"type",
"href",
"src",
"path",
"url",
"api",
"endpoint",
"method",
"mode",
"variant",
]);
function hasAlphabeticChar(text: string): boolean {
return /[a-zA-Z]/.test(text);
}
function isUserFacingText(text: string): boolean {
// Skip empty or very short strings
if (!text || text.length < 2) return false;
// Skip strings that look like code patterns
if (/^[a-z][a-zA-Z]*$/.test(text)) return false; // camelCase
if (/^[A-Z_]+$/.test(text)) return false; // CONSTANTS
if (text.startsWith("/") || text.startsWith("./")) return false; // paths
if (text.includes("://")) return false; // URLs
if (!hasAlphabeticChar(text)) {
return filterNonAlpha ? false : true;
}
return true;
}
function extractTextWithLocation(filePath: string, code: string) {
const ast = babelParser.parse(code, {
sourceType: "module",
plugins: ["jsx", "typescript"],
});
const results: { line: number; text: string }[] = [];
traverse(ast, {
JSXText(path: any) {
const text = path.node.value.trim();
if (text) {
// Skip text with only non-alphabetic characters if filter is enabled
if (filterNonAlpha && !hasAlphabeticChar(text)) {
return;
}
results.push({
line: path.node.loc?.start.line || 0,
text,
});
}
},
JSXAttribute(path: any) {
const name = path.node.name.name;
const value = path.node.value;
if (
typeof name === "string" &&
attributes.includes(name) &&
value &&
t.isStringLiteral(value)
) {
const text = value.value.trim();
// Skip text with only non-alphabetic characters if filter is enabled
if (filterNonAlpha && !hasAlphabeticChar(text)) {
return;
}
results.push({
line: value.loc?.start.line || 0,
text,
});
}
},
});
// Extended extraction for literals (objects, function calls, schemas)
if (includeLiterals) {
traverse(ast, {
// Extract from object properties with user-facing keys
ObjectProperty(path: any) {
const key = path.node.key;
const value = path.node.value;
// Get the key name
let keyName = "";
if (t.isIdentifier(key)) {
keyName = key.name;
} else if (t.isStringLiteral(key)) {
keyName = key.value;
}
if (SKIP_KEYS.has(keyName)) return;
// Check if it's a user-facing key or extract all strings
if (USER_FACING_KEYS.has(keyName) || true) {
if (t.isStringLiteral(value)) {
const text = value.value.trim();
if (isUserFacingText(text)) {
results.push({
line: value.loc?.start.line || 0,
text,
});
}
}
}
},
NewExpression(path: any) {
const callee = path.node.callee;
if (t.isIdentifier(callee, { name: "Error" })) {
const arg = path.node.arguments[0];
if (t.isStringLiteral(arg)) {
const text = arg.value.trim();
if (isUserFacingText(text)) {
results.push({
line: arg.loc?.start.line || 0,
text,
});
}
}
}
},
// Extract from function calls (toast, error, etc.)
CallExpression(path: any) {
const callee = path.node.callee;
let functionName = "";
if (t.isIdentifier(callee)) {
functionName = callee.name;
} else if (t.isMemberExpression(callee)) {
// Handle toast.error(), console.warn(), etc.
if (
t.isIdentifier(callee.object) &&
t.isIdentifier(callee.property)
) {
const obj = callee.object.name;
const prop = callee.property.name;
functionName = prop;
// Common patterns
if (
(obj === "toast" || obj === "console") &&
USER_FACING_FUNCTIONS.has(prop)
) {
const arg = path.node.arguments[0];
if (t.isStringLiteral(arg)) {
const text = arg.value.trim();
if (isUserFacingText(text)) {
results.push({
line: arg.loc?.start.line || 0,
text,
});
}
}
}
}
// Handle Zod: .message(), .min(), .max(), etc.
if (t.isIdentifier(callee.property)) {
const methodName = callee.property.name;
if (methodName === "message" || methodName === "describe") {
const arg = path.node.arguments[0];
if (t.isStringLiteral(arg)) {
const text = arg.value.trim();
if (isUserFacingText(text)) {
results.push({
line: arg.loc?.start.line || 0,
text,
});
}
}
}
// Zod validation with error message as second arg
if (
["min", "max", "length", "email", "url", "regex"].includes(
methodName
)
) {
const arg = path.node.arguments[1];
if (t.isStringLiteral(arg)) {
const text = arg.value.trim();
if (isUserFacingText(text)) {
results.push({
line: arg.loc?.start.line || 0,
text,
});
}
} else if (t.isObjectExpression(arg)) {
// .min(5, { message: "..." })
const messageProp = arg.properties.find(
(prop: any) =>
t.isObjectProperty(prop) &&
t.isIdentifier(prop.key, { name: "message" })
);
if (
messageProp &&
t.isStringLiteral((messageProp as any).value)
) {
const text = ((messageProp as any).value as any).value.trim();
if (isUserFacingText(text)) {
results.push({
line:
((messageProp as any).value as any).loc?.start.line ||
0,
text,
});
}
}
}
}
}
} else if (USER_FACING_FUNCTIONS.has(functionName)) {
const arg = path.node.arguments[0];
if (t.isStringLiteral(arg)) {
const text = arg.value.trim();
if (isUserFacingText(text)) {
results.push({
line: arg.loc?.start.line || 0,
text,
});
}
}
}
},
});
}
results.forEach(({ line, text }) => {
const truncatedText = truncate
? text.length > truncate
? text.substring(0, truncate) + "..."
: text
: text;
console.log(
`[${path.relative(process.cwd(), filePath)}:${line}] ${truncatedText}`
);
});
}
function scanDir(dirPath: string) {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
if (!options.deps && entry.name === "node_modules") {
continue;
}
scanDir(fullPath);
} else if (
entry.isFile() &&
extensions.includes(path.extname(entry.name))
) {
const code = fs.readFileSync(fullPath, "utf8");
extractTextWithLocation(fullPath, code);
}
}
}
scanDir(dir);