@oxog/i18n-cli 0.0.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/LICENSE +21 -0
- package/dist/cli.js +1010 -0
- package/package.json +48 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Ersin Koç
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1010 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { promises } from 'fs';
|
|
3
|
+
import path, { join, relative, sep } from 'path';
|
|
4
|
+
import { readdir, stat } from 'fs/promises';
|
|
5
|
+
import { createInterface } from 'readline';
|
|
6
|
+
|
|
7
|
+
// src/utils/colors.ts
|
|
8
|
+
var getIsColorSupported = () => !process.env.NO_COLOR && process.env.FORCE_COLOR !== "0" && (process.env.FORCE_COLOR === "1" || process.stdout.isTTY);
|
|
9
|
+
var colorize = (code) => (text) => getIsColorSupported() ? `\x1B[${code}m${text}\x1B[0m` : text;
|
|
10
|
+
var colors = {
|
|
11
|
+
reset: colorize(0),
|
|
12
|
+
bold: colorize(1),
|
|
13
|
+
dim: colorize(2),
|
|
14
|
+
red: colorize(31),
|
|
15
|
+
green: colorize(32),
|
|
16
|
+
yellow: colorize(33),
|
|
17
|
+
blue: colorize(34),
|
|
18
|
+
magenta: colorize(35),
|
|
19
|
+
cyan: colorize(36),
|
|
20
|
+
white: colorize(37),
|
|
21
|
+
gray: colorize(90),
|
|
22
|
+
// Background colors
|
|
23
|
+
bgRed: colorize(41),
|
|
24
|
+
bgGreen: colorize(42),
|
|
25
|
+
bgYellow: colorize(43),
|
|
26
|
+
bgBlue: colorize(44),
|
|
27
|
+
// Combinations
|
|
28
|
+
error: (text) => colorize(31)(colorize(1)(text)),
|
|
29
|
+
success: (text) => colorize(32)(colorize(1)(text)),
|
|
30
|
+
warning: (text) => colorize(33)(colorize(1)(text)),
|
|
31
|
+
info: (text) => colorize(34)(colorize(1)(text)),
|
|
32
|
+
// Semantic colors
|
|
33
|
+
primary: colorize(36),
|
|
34
|
+
secondary: colorize(90)
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/utils/commander.ts
|
|
38
|
+
var Commander = class {
|
|
39
|
+
commands = /* @__PURE__ */ new Map();
|
|
40
|
+
globalOptions = [];
|
|
41
|
+
programName = "cli";
|
|
42
|
+
programDescription = "";
|
|
43
|
+
programVersion = "1.0.0";
|
|
44
|
+
name(name) {
|
|
45
|
+
this.programName = name;
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
description(desc) {
|
|
49
|
+
this.programDescription = desc;
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
version(version) {
|
|
53
|
+
this.programVersion = version;
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
option(flags, description, defaultValue) {
|
|
57
|
+
this.globalOptions.push({ flags, description, defaultValue });
|
|
58
|
+
return this;
|
|
59
|
+
}
|
|
60
|
+
command(name) {
|
|
61
|
+
const command = {
|
|
62
|
+
name,
|
|
63
|
+
description: "",
|
|
64
|
+
options: []
|
|
65
|
+
};
|
|
66
|
+
this.commands.set(name, command);
|
|
67
|
+
return new CommandBuilder(command);
|
|
68
|
+
}
|
|
69
|
+
async parse(argv = process.argv) {
|
|
70
|
+
const args = argv.slice(2);
|
|
71
|
+
if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
|
|
72
|
+
this.showHelp();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (args.includes("--version") || args.includes("-V")) {
|
|
76
|
+
console.log(this.programVersion);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const commandName = args[0];
|
|
80
|
+
const command = this.commands.get(commandName);
|
|
81
|
+
if (!command) {
|
|
82
|
+
console.error(colors.red(`Unknown command: ${commandName}`));
|
|
83
|
+
this.showHelp();
|
|
84
|
+
process.exit(1);
|
|
85
|
+
}
|
|
86
|
+
const options = this.parseOptions(args.slice(1), [...this.globalOptions, ...command.options]);
|
|
87
|
+
if (command.action) {
|
|
88
|
+
try {
|
|
89
|
+
await command.action(options);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.error(colors.red("Error:"), error instanceof Error ? error.message : String(error));
|
|
92
|
+
process.exit(1);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
parseOptions(args, optionDefinitions) {
|
|
97
|
+
const options = {};
|
|
98
|
+
const optionMap = /* @__PURE__ */ new Map();
|
|
99
|
+
for (const option of optionDefinitions) {
|
|
100
|
+
const [shortFlag, longFlag] = this.parseFlags(option.flags);
|
|
101
|
+
if (shortFlag) optionMap.set(shortFlag, option);
|
|
102
|
+
if (longFlag) optionMap.set(longFlag, option);
|
|
103
|
+
if (option.defaultValue !== void 0) {
|
|
104
|
+
const key = this.getOptionKey(option.flags);
|
|
105
|
+
options[key] = option.defaultValue;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (let i = 0; i < args.length; i++) {
|
|
109
|
+
const arg = args[i];
|
|
110
|
+
if (arg.startsWith("-")) {
|
|
111
|
+
const option = optionMap.get(arg);
|
|
112
|
+
if (!option) {
|
|
113
|
+
console.error(colors.red(`Unknown option: ${arg}`));
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
const key = this.getOptionKey(option.flags);
|
|
117
|
+
if (this.isBooleanOption(option)) {
|
|
118
|
+
options[key] = true;
|
|
119
|
+
} else {
|
|
120
|
+
i++;
|
|
121
|
+
if (i >= args.length) {
|
|
122
|
+
console.error(colors.red(`Option ${arg} requires a value`));
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
options[key] = args[i];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const option of optionDefinitions) {
|
|
130
|
+
if (option.required) {
|
|
131
|
+
const key = this.getOptionKey(option.flags);
|
|
132
|
+
if (options[key] === void 0) {
|
|
133
|
+
console.error(colors.red(`Required option missing: ${option.flags}`));
|
|
134
|
+
process.exit(1);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return options;
|
|
139
|
+
}
|
|
140
|
+
parseFlags(flags) {
|
|
141
|
+
const parts = flags.split(/,\s*/);
|
|
142
|
+
let shortFlag;
|
|
143
|
+
let longFlag;
|
|
144
|
+
for (const part of parts) {
|
|
145
|
+
const trimmed = part.trim();
|
|
146
|
+
if (trimmed.startsWith("--")) {
|
|
147
|
+
longFlag = trimmed;
|
|
148
|
+
} else if (trimmed.startsWith("-")) {
|
|
149
|
+
shortFlag = trimmed;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return [shortFlag, longFlag];
|
|
153
|
+
}
|
|
154
|
+
getOptionKey(flags) {
|
|
155
|
+
const [, longFlag] = this.parseFlags(flags);
|
|
156
|
+
if (longFlag) {
|
|
157
|
+
return longFlag.replace(/^--/, "").replace(/\s*[<\[].*$/, "").replace(/-/g, "_");
|
|
158
|
+
}
|
|
159
|
+
const [shortFlag] = this.parseFlags(flags);
|
|
160
|
+
return shortFlag.replace(/^-/, "").replace(/\s*[<\[].*$/, "");
|
|
161
|
+
}
|
|
162
|
+
isBooleanOption(option) {
|
|
163
|
+
return !option.flags.includes("<") && !option.flags.includes("[");
|
|
164
|
+
}
|
|
165
|
+
showHelp() {
|
|
166
|
+
console.log(colors.bold(this.programName));
|
|
167
|
+
if (this.programDescription) {
|
|
168
|
+
console.log(this.programDescription);
|
|
169
|
+
}
|
|
170
|
+
console.log();
|
|
171
|
+
console.log(colors.bold("Usage:"));
|
|
172
|
+
console.log(` ${this.programName} [command] [options]`);
|
|
173
|
+
console.log();
|
|
174
|
+
if (this.commands.size > 0) {
|
|
175
|
+
console.log(colors.bold("Commands:"));
|
|
176
|
+
for (const [name, command] of this.commands) {
|
|
177
|
+
console.log(` ${name.padEnd(15)} ${command.description}`);
|
|
178
|
+
}
|
|
179
|
+
console.log();
|
|
180
|
+
}
|
|
181
|
+
if (this.globalOptions.length > 0) {
|
|
182
|
+
console.log(colors.bold("Options:"));
|
|
183
|
+
for (const option of this.globalOptions) {
|
|
184
|
+
console.log(` ${option.flags.padEnd(20)} ${option.description}`);
|
|
185
|
+
}
|
|
186
|
+
console.log();
|
|
187
|
+
}
|
|
188
|
+
console.log(colors.bold("Global Options:"));
|
|
189
|
+
console.log(" -h, --help Show help");
|
|
190
|
+
console.log(" -V, --version Show version");
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
var CommandBuilder = class {
|
|
194
|
+
constructor(command) {
|
|
195
|
+
this.command = command;
|
|
196
|
+
}
|
|
197
|
+
description(desc) {
|
|
198
|
+
this.command.description = desc;
|
|
199
|
+
return this;
|
|
200
|
+
}
|
|
201
|
+
option(flags, description, defaultValue) {
|
|
202
|
+
this.command.options.push({ flags, description, defaultValue });
|
|
203
|
+
return this;
|
|
204
|
+
}
|
|
205
|
+
action(fn) {
|
|
206
|
+
this.command.action = fn;
|
|
207
|
+
return this;
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
function createCommander() {
|
|
211
|
+
return new Commander();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// src/utils/spinner.ts
|
|
215
|
+
var spinnerFrames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
216
|
+
var Spinner = class {
|
|
217
|
+
intervalId;
|
|
218
|
+
currentFrame = 0;
|
|
219
|
+
text;
|
|
220
|
+
isSpinning = false;
|
|
221
|
+
constructor(text = "") {
|
|
222
|
+
this.text = text;
|
|
223
|
+
}
|
|
224
|
+
start(text) {
|
|
225
|
+
if (text) this.text = text;
|
|
226
|
+
if (this.isSpinning) return this;
|
|
227
|
+
this.isSpinning = true;
|
|
228
|
+
process.stdout.write("\x1B[?25l");
|
|
229
|
+
this.intervalId = setInterval(() => {
|
|
230
|
+
this.render();
|
|
231
|
+
this.currentFrame = (this.currentFrame + 1) % spinnerFrames.length;
|
|
232
|
+
}, 80);
|
|
233
|
+
return this;
|
|
234
|
+
}
|
|
235
|
+
stop() {
|
|
236
|
+
if (!this.isSpinning) return this;
|
|
237
|
+
if (this.intervalId) {
|
|
238
|
+
clearInterval(this.intervalId);
|
|
239
|
+
this.intervalId = void 0;
|
|
240
|
+
}
|
|
241
|
+
this.isSpinning = false;
|
|
242
|
+
this.clearLine();
|
|
243
|
+
process.stdout.write("\x1B[?25h");
|
|
244
|
+
return this;
|
|
245
|
+
}
|
|
246
|
+
succeed(text) {
|
|
247
|
+
this.stop();
|
|
248
|
+
const message = text || this.text;
|
|
249
|
+
console.log(colors.green("\u2713") + " " + message);
|
|
250
|
+
return this;
|
|
251
|
+
}
|
|
252
|
+
fail(text) {
|
|
253
|
+
this.stop();
|
|
254
|
+
const message = text || this.text;
|
|
255
|
+
console.log(colors.red("\u2717") + " " + message);
|
|
256
|
+
return this;
|
|
257
|
+
}
|
|
258
|
+
warn(text) {
|
|
259
|
+
this.stop();
|
|
260
|
+
const message = text || this.text;
|
|
261
|
+
console.log(colors.yellow("\u26A0") + " " + message);
|
|
262
|
+
return this;
|
|
263
|
+
}
|
|
264
|
+
info(text) {
|
|
265
|
+
this.stop();
|
|
266
|
+
const message = text || this.text;
|
|
267
|
+
console.log(colors.blue("\u2139") + " " + message);
|
|
268
|
+
return this;
|
|
269
|
+
}
|
|
270
|
+
set(text) {
|
|
271
|
+
this.text = text;
|
|
272
|
+
return this;
|
|
273
|
+
}
|
|
274
|
+
render() {
|
|
275
|
+
const frame = spinnerFrames[this.currentFrame];
|
|
276
|
+
const line = colors.cyan(frame) + " " + this.text;
|
|
277
|
+
this.clearLine();
|
|
278
|
+
process.stdout.write(line);
|
|
279
|
+
}
|
|
280
|
+
clearLine() {
|
|
281
|
+
process.stdout.write("\r\x1B[K");
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
function createSpinner(text = "") {
|
|
285
|
+
return new Spinner(text);
|
|
286
|
+
}
|
|
287
|
+
async function glob(pattern, cwd = process.cwd()) {
|
|
288
|
+
const results = [];
|
|
289
|
+
const regex = globToRegex(pattern);
|
|
290
|
+
async function walk(dir) {
|
|
291
|
+
try {
|
|
292
|
+
const entries = await readdir(dir);
|
|
293
|
+
for (const entry of entries) {
|
|
294
|
+
const fullPath = join(dir, entry);
|
|
295
|
+
const stats2 = await stat(fullPath);
|
|
296
|
+
if (stats2.isDirectory()) {
|
|
297
|
+
if (shouldDescend(pattern, relative(cwd, fullPath))) {
|
|
298
|
+
await walk(fullPath);
|
|
299
|
+
}
|
|
300
|
+
} else if (stats2.isFile()) {
|
|
301
|
+
const relativePath = relative(cwd, fullPath).replace(/\\/g, "/");
|
|
302
|
+
if (regex.test(relativePath)) {
|
|
303
|
+
results.push(fullPath);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
} catch (error) {
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
await walk(cwd);
|
|
311
|
+
return results.sort();
|
|
312
|
+
}
|
|
313
|
+
function globToRegex(pattern) {
|
|
314
|
+
pattern = pattern.replace(/\\/g, "/");
|
|
315
|
+
let regex = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "___DOUBLESTAR___").replace(/\*/g, "___STAR___").replace(/___DOUBLESTAR___/g, ".*").replace(/\?/g, "___QUESTION___");
|
|
316
|
+
regex = regex.replace(/\\\{([^}]+)\\\}/g, (_, group) => {
|
|
317
|
+
const options = group.split(",").join("|");
|
|
318
|
+
return `(${options})`;
|
|
319
|
+
});
|
|
320
|
+
regex = regex.replace(/\//g, "[\\/\\\\]");
|
|
321
|
+
regex = regex.replace(/___STAR___/g, "[^\\/\\\\]*").replace(/___QUESTION___/g, "[^\\/\\\\]");
|
|
322
|
+
return new RegExp(`^${regex}$`);
|
|
323
|
+
}
|
|
324
|
+
function shouldDescend(pattern, currentPath) {
|
|
325
|
+
if (pattern.includes("**")) return true;
|
|
326
|
+
const patternParts = pattern.split("/");
|
|
327
|
+
const currentParts = currentPath.split(sep);
|
|
328
|
+
if (currentParts.length >= patternParts.length) return false;
|
|
329
|
+
for (let i = 0; i < currentParts.length; i++) {
|
|
330
|
+
const patternPart = patternParts[i];
|
|
331
|
+
const currentPart = currentParts[i];
|
|
332
|
+
if (patternPart === "**") return true;
|
|
333
|
+
if (patternPart !== currentPart && !isGlobMatch(patternPart, currentPart)) {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
function isGlobMatch(pattern, text) {
|
|
340
|
+
const regex = globToRegex(pattern);
|
|
341
|
+
return regex.test(text);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/commands/compile.ts
|
|
345
|
+
async function compile(options) {
|
|
346
|
+
const spinner = createSpinner("Compiling translations").start();
|
|
347
|
+
try {
|
|
348
|
+
const pattern = path.join(options.input, "*.json");
|
|
349
|
+
const files = await glob(pattern);
|
|
350
|
+
await promises.mkdir(options.output, { recursive: true });
|
|
351
|
+
let compiledCount = 0;
|
|
352
|
+
for (const file of files) {
|
|
353
|
+
const locale = path.basename(file, ".json");
|
|
354
|
+
const content = await promises.readFile(file, "utf-8");
|
|
355
|
+
const translations = JSON.parse(content);
|
|
356
|
+
const optimized = optimizeTranslations(translations);
|
|
357
|
+
const outputFile = path.join(options.output, `${locale}.${options.format}`);
|
|
358
|
+
switch (options.format) {
|
|
359
|
+
case "json":
|
|
360
|
+
await promises.writeFile(outputFile, JSON.stringify(optimized));
|
|
361
|
+
break;
|
|
362
|
+
case "js":
|
|
363
|
+
await promises.writeFile(
|
|
364
|
+
outputFile,
|
|
365
|
+
`exports.default = ${JSON.stringify(optimized)};`
|
|
366
|
+
);
|
|
367
|
+
break;
|
|
368
|
+
case "mjs":
|
|
369
|
+
await promises.writeFile(
|
|
370
|
+
outputFile,
|
|
371
|
+
`export default ${JSON.stringify(optimized)};`
|
|
372
|
+
);
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
compiledCount++;
|
|
376
|
+
}
|
|
377
|
+
const indexContent = generateIndex(files, options.format);
|
|
378
|
+
const indexFile = path.join(
|
|
379
|
+
options.output,
|
|
380
|
+
`index.${options.format === "mjs" ? "mjs" : "js"}`
|
|
381
|
+
);
|
|
382
|
+
await promises.writeFile(indexFile, indexContent);
|
|
383
|
+
spinner.succeed(`Compiled ${compiledCount} locale files`);
|
|
384
|
+
const originalSize = await calculateDirSize(options.input);
|
|
385
|
+
const compiledSize = await calculateDirSize(options.output);
|
|
386
|
+
const reduction = ((originalSize - compiledSize) / originalSize * 100).toFixed(1);
|
|
387
|
+
console.log("\n" + colors.green("\u2728 Compilation complete!"));
|
|
388
|
+
console.log(colors.gray(`Files compiled: ${compiledCount}`));
|
|
389
|
+
console.log(colors.gray(`Size reduction: ${reduction}%`));
|
|
390
|
+
console.log(colors.gray(`Output: ${options.output}`));
|
|
391
|
+
} catch (error) {
|
|
392
|
+
spinner.fail("Compilation failed");
|
|
393
|
+
console.error(error);
|
|
394
|
+
process.exit(1);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function optimizeTranslations(obj) {
|
|
398
|
+
if (typeof obj !== "object" || obj === null) {
|
|
399
|
+
return obj;
|
|
400
|
+
}
|
|
401
|
+
if (Array.isArray(obj)) {
|
|
402
|
+
return obj.map(optimizeTranslations).filter((v) => v !== null && v !== "");
|
|
403
|
+
}
|
|
404
|
+
const result = {};
|
|
405
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
406
|
+
const optimized = optimizeTranslations(value);
|
|
407
|
+
if (optimized !== null && optimized !== "" && !(typeof optimized === "object" && Object.keys(optimized).length === 0)) {
|
|
408
|
+
result[key] = optimized;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return result;
|
|
412
|
+
}
|
|
413
|
+
function generateIndex(files, format) {
|
|
414
|
+
const locales = files.map((f) => path.basename(f, ".json"));
|
|
415
|
+
if (format === "mjs") {
|
|
416
|
+
return `${locales.map((l) => `import ${l} from './${l}.mjs';`).join("\n")}
|
|
417
|
+
|
|
418
|
+
export default {
|
|
419
|
+
${locales.join(",\n ")}
|
|
420
|
+
};
|
|
421
|
+
`;
|
|
422
|
+
}
|
|
423
|
+
return `${locales.map((l) => `const ${l} = require('./${l}.js').default;`).join("\n")}
|
|
424
|
+
|
|
425
|
+
module.exports = {
|
|
426
|
+
${locales.join(",\n ")}
|
|
427
|
+
};
|
|
428
|
+
`;
|
|
429
|
+
}
|
|
430
|
+
async function calculateDirSize(dir) {
|
|
431
|
+
const files = await glob(path.join(dir, "**/*"));
|
|
432
|
+
let totalSize = 0;
|
|
433
|
+
for (const file of files) {
|
|
434
|
+
try {
|
|
435
|
+
const stats2 = await promises.stat(file);
|
|
436
|
+
if (stats2.isFile()) {
|
|
437
|
+
totalSize += stats2.size;
|
|
438
|
+
}
|
|
439
|
+
} catch (error) {
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return totalSize;
|
|
443
|
+
}
|
|
444
|
+
async function extract(options) {
|
|
445
|
+
const spinner = createSpinner("Extracting translation keys").start();
|
|
446
|
+
try {
|
|
447
|
+
const files = await glob(options.pattern);
|
|
448
|
+
const keys = /* @__PURE__ */ new Set();
|
|
449
|
+
const patterns = [
|
|
450
|
+
/\.t\(['"`]([^'"`]+)['"`]/g,
|
|
451
|
+
/t\(['"`]([^'"`]+)['"`]/g,
|
|
452
|
+
/<T\s+id=['"`]([^'"`]+)['"`]/g,
|
|
453
|
+
/<Trans\s+id=['"`]([^'"`]+)['"`]/g
|
|
454
|
+
];
|
|
455
|
+
for (const file of files) {
|
|
456
|
+
const content = await promises.readFile(file, "utf-8");
|
|
457
|
+
for (const pattern of patterns) {
|
|
458
|
+
let match;
|
|
459
|
+
while ((match = pattern.exec(content)) !== null) {
|
|
460
|
+
keys.add(match[1]);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
spinner.text = `Found ${keys.size} translation keys`;
|
|
465
|
+
await promises.mkdir(options.output, { recursive: true });
|
|
466
|
+
const locales = options.locales.split(",").map((l) => l.trim());
|
|
467
|
+
for (const locale of locales) {
|
|
468
|
+
const filePath = path.join(options.output, `${locale}.json`);
|
|
469
|
+
let existingTranslations = {};
|
|
470
|
+
try {
|
|
471
|
+
const content = await promises.readFile(filePath, "utf-8");
|
|
472
|
+
existingTranslations = JSON.parse(content);
|
|
473
|
+
} catch {
|
|
474
|
+
}
|
|
475
|
+
const translations = {};
|
|
476
|
+
for (const key of Array.from(keys).sort()) {
|
|
477
|
+
const parts = key.split(".");
|
|
478
|
+
let current = translations;
|
|
479
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
480
|
+
if (!current[parts[i]]) {
|
|
481
|
+
current[parts[i]] = {};
|
|
482
|
+
}
|
|
483
|
+
current = current[parts[i]];
|
|
484
|
+
}
|
|
485
|
+
const finalKey = parts[parts.length - 1];
|
|
486
|
+
current[finalKey] = getNestedValue(existingTranslations, key) || `[${key}]`;
|
|
487
|
+
}
|
|
488
|
+
await promises.writeFile(filePath, JSON.stringify(translations, null, 2));
|
|
489
|
+
}
|
|
490
|
+
spinner.succeed(`Extracted ${keys.size} keys to ${locales.length} locale files`);
|
|
491
|
+
console.log("\n" + colors.green("\u2728 Extraction complete!"));
|
|
492
|
+
console.log(colors.gray(`Keys extracted: ${keys.size}`));
|
|
493
|
+
console.log(colors.gray(`Files scanned: ${files.length}`));
|
|
494
|
+
console.log(colors.gray(`Output: ${options.output}`));
|
|
495
|
+
} catch (error) {
|
|
496
|
+
spinner.fail("Extraction failed");
|
|
497
|
+
console.error(error);
|
|
498
|
+
process.exit(1);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
function getNestedValue(obj, path7) {
|
|
502
|
+
const parts = path7.split(".");
|
|
503
|
+
let current = obj;
|
|
504
|
+
for (const part of parts) {
|
|
505
|
+
if (current && typeof current === "object" && part in current) {
|
|
506
|
+
current = current[part];
|
|
507
|
+
} else {
|
|
508
|
+
return void 0;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return current;
|
|
512
|
+
}
|
|
513
|
+
var Prompts = class {
|
|
514
|
+
readline = createInterface({
|
|
515
|
+
input: process.stdin,
|
|
516
|
+
output: process.stdout
|
|
517
|
+
});
|
|
518
|
+
async text(options) {
|
|
519
|
+
return new Promise((resolve) => {
|
|
520
|
+
const prompt = `${colors.cyan("?")} ${options.message}${options.initial ? colors.gray(` (${options.initial})`) : ""}: `;
|
|
521
|
+
this.readline.question(prompt, (answer) => {
|
|
522
|
+
const value = answer.trim() || String(options.initial || "");
|
|
523
|
+
if (options.validate) {
|
|
524
|
+
const validation = options.validate(value);
|
|
525
|
+
if (validation !== true) {
|
|
526
|
+
console.log(colors.red(typeof validation === "string" ? validation : "Invalid input"));
|
|
527
|
+
resolve(this.text(options));
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
resolve(options.format ? options.format(value) : value);
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
async confirm(options) {
|
|
536
|
+
const initial = options.initial;
|
|
537
|
+
const defaultText = initial ? "Y/n" : "y/N";
|
|
538
|
+
return new Promise((resolve) => {
|
|
539
|
+
const prompt = `${colors.cyan("?")} ${options.message} ${colors.gray(`(${defaultText})`)}: `;
|
|
540
|
+
this.readline.question(prompt, (answer) => {
|
|
541
|
+
const trimmed = answer.trim().toLowerCase();
|
|
542
|
+
if (trimmed === "") {
|
|
543
|
+
resolve(initial);
|
|
544
|
+
} else if (trimmed === "y" || trimmed === "yes") {
|
|
545
|
+
resolve(true);
|
|
546
|
+
} else if (trimmed === "n" || trimmed === "no") {
|
|
547
|
+
resolve(false);
|
|
548
|
+
} else {
|
|
549
|
+
console.log(colors.red("Please answer yes or no"));
|
|
550
|
+
resolve(this.confirm(options));
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
async select(options) {
|
|
556
|
+
const choices = options.choices || [];
|
|
557
|
+
const initial = typeof options.initial === "number" ? options.initial : 0;
|
|
558
|
+
console.log(`${colors.cyan("?")} ${options.message}`);
|
|
559
|
+
choices.forEach((choice, index) => {
|
|
560
|
+
const marker = index === initial ? colors.cyan("\u276F") : " ";
|
|
561
|
+
const title = index === initial ? colors.cyan(choice.title) : choice.title;
|
|
562
|
+
const desc = choice.description ? colors.gray(` - ${choice.description}`) : "";
|
|
563
|
+
console.log(`${marker} ${title}${desc}`);
|
|
564
|
+
});
|
|
565
|
+
return new Promise((resolve) => {
|
|
566
|
+
let selectedIndex = initial;
|
|
567
|
+
const onKeypress = (str, key) => {
|
|
568
|
+
if (key.name === "up" && selectedIndex > 0) {
|
|
569
|
+
selectedIndex--;
|
|
570
|
+
this.redrawChoices(options.message, choices, selectedIndex);
|
|
571
|
+
} else if (key.name === "down" && selectedIndex < choices.length - 1) {
|
|
572
|
+
selectedIndex++;
|
|
573
|
+
this.redrawChoices(options.message, choices, selectedIndex);
|
|
574
|
+
} else if (key.name === "return") {
|
|
575
|
+
process.stdin.removeListener("keypress", onKeypress);
|
|
576
|
+
process.stdin.setRawMode(false);
|
|
577
|
+
resolve(choices[selectedIndex].value);
|
|
578
|
+
} else if (key.ctrl && key.name === "c") {
|
|
579
|
+
process.exit(0);
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
process.stdin.setRawMode(true);
|
|
583
|
+
process.stdin.on("keypress", onKeypress);
|
|
584
|
+
process.stdin.resume();
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
async list(options) {
|
|
588
|
+
const result = await this.text({
|
|
589
|
+
...options,
|
|
590
|
+
message: `${options.message} (comma-separated)`
|
|
591
|
+
});
|
|
592
|
+
return result.split(",").map((item) => item.trim()).filter(Boolean);
|
|
593
|
+
}
|
|
594
|
+
redrawChoices(message, choices, selectedIndex) {
|
|
595
|
+
process.stdout.write(`\x1B[${choices.length + 1}A`);
|
|
596
|
+
console.log(`${colors.cyan("?")} ${message}`);
|
|
597
|
+
choices.forEach((choice, index) => {
|
|
598
|
+
const marker = index === selectedIndex ? colors.cyan("\u276F") : " ";
|
|
599
|
+
const title = index === selectedIndex ? colors.cyan(choice.title) : choice.title;
|
|
600
|
+
const desc = choice.description ? colors.gray(` - ${choice.description}`) : "";
|
|
601
|
+
console.log(`${marker} ${title}${desc}`);
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
close() {
|
|
605
|
+
this.readline.close();
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
function createPrompts() {
|
|
609
|
+
return new Prompts();
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// src/commands/init.ts
|
|
613
|
+
async function init(options) {
|
|
614
|
+
console.log(colors.blue("\n\u{1F30D} Initializing @oxog/i18n\n"));
|
|
615
|
+
const prompts = createPrompts();
|
|
616
|
+
let framework = options.framework;
|
|
617
|
+
if (!framework) {
|
|
618
|
+
framework = await prompts.select({
|
|
619
|
+
message: "Which framework are you using?",
|
|
620
|
+
choices: [
|
|
621
|
+
{ title: "React", value: "react" },
|
|
622
|
+
{ title: "Vue", value: "vue" },
|
|
623
|
+
{ title: "Svelte", value: "svelte" },
|
|
624
|
+
{ title: "None (Vanilla)", value: "vanilla" }
|
|
625
|
+
],
|
|
626
|
+
initial: 0
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
let typescript = options.typescript;
|
|
630
|
+
if (typescript === void 0) {
|
|
631
|
+
typescript = await prompts.confirm({
|
|
632
|
+
message: "Are you using TypeScript?",
|
|
633
|
+
initial: true
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
const localesPath = await prompts.text({
|
|
637
|
+
message: "Where should translation files be stored?",
|
|
638
|
+
initial: "./src/locales"
|
|
639
|
+
});
|
|
640
|
+
const defaultLocale = await prompts.text({
|
|
641
|
+
message: "What is your default locale?",
|
|
642
|
+
initial: "en"
|
|
643
|
+
});
|
|
644
|
+
const additionalLocales = await prompts.list({
|
|
645
|
+
message: "Additional locales"
|
|
646
|
+
});
|
|
647
|
+
prompts.close();
|
|
648
|
+
const config = {
|
|
649
|
+
framework,
|
|
650
|
+
typescript,
|
|
651
|
+
localesPath,
|
|
652
|
+
defaultLocale,
|
|
653
|
+
additionalLocales: additionalLocales.filter(Boolean)
|
|
654
|
+
};
|
|
655
|
+
const spinner = createSpinner("Setting up @oxog/i18n").start();
|
|
656
|
+
try {
|
|
657
|
+
await promises.mkdir(config.localesPath, { recursive: true });
|
|
658
|
+
const defaultMessages = {
|
|
659
|
+
welcome: "Welcome to {{appName}}!",
|
|
660
|
+
"common.yes": "Yes",
|
|
661
|
+
"common.no": "No",
|
|
662
|
+
"common.cancel": "Cancel",
|
|
663
|
+
"common.save": "Save"
|
|
664
|
+
};
|
|
665
|
+
await promises.writeFile(
|
|
666
|
+
path.join(config.localesPath, `${config.defaultLocale}.json`),
|
|
667
|
+
JSON.stringify(defaultMessages, null, 2)
|
|
668
|
+
);
|
|
669
|
+
for (const locale of config.additionalLocales) {
|
|
670
|
+
await promises.writeFile(
|
|
671
|
+
path.join(config.localesPath, `${locale}.json`),
|
|
672
|
+
JSON.stringify(defaultMessages, null, 2)
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
const configContent = config.typescript ? generateTypeScriptConfig(config) : generateJavaScriptConfig(config);
|
|
676
|
+
const configFileName = config.typescript ? "i18n.config.ts" : "i18n.config.js";
|
|
677
|
+
await promises.writeFile(path.join("./src", configFileName), configContent);
|
|
678
|
+
if (config.typescript) {
|
|
679
|
+
await promises.mkdir(path.join("./src/types"), { recursive: true });
|
|
680
|
+
const typesContent = generateTypes();
|
|
681
|
+
await promises.writeFile(path.join("./src/types", "i18n.d.ts"), typesContent);
|
|
682
|
+
}
|
|
683
|
+
spinner.succeed("Setup complete!");
|
|
684
|
+
console.log("\n" + colors.green("\u2728 Next steps:"));
|
|
685
|
+
console.log(colors.gray("1. Install the required packages:"));
|
|
686
|
+
console.log(colors.cyan(` npm install @oxog/i18n${config.framework !== "vanilla" ? ` @oxog/i18n-${config.framework}` : ""}`));
|
|
687
|
+
console.log(colors.gray("2. Import and use the i18n configuration:"));
|
|
688
|
+
console.log(colors.cyan(` import { i18n } from './src/${configFileName}'`));
|
|
689
|
+
if (config.framework === "react") {
|
|
690
|
+
console.log(colors.gray("3. Wrap your app with I18nProvider:"));
|
|
691
|
+
console.log(colors.cyan(" <I18nProvider i18n={i18n}><App /></I18nProvider>"));
|
|
692
|
+
}
|
|
693
|
+
} catch (error) {
|
|
694
|
+
spinner.fail("Setup failed");
|
|
695
|
+
console.error(error);
|
|
696
|
+
process.exit(1);
|
|
697
|
+
}
|
|
698
|
+
function generateTypeScriptConfig(config2) {
|
|
699
|
+
const framework2 = config2.framework;
|
|
700
|
+
const imports = [`import { createI18n } from '@oxog/i18n';`];
|
|
701
|
+
if (framework2 !== "vanilla") {
|
|
702
|
+
imports.push(`// import { I18nProvider } from '@oxog/i18n-${framework2}';`);
|
|
703
|
+
}
|
|
704
|
+
return `${imports.join("\n")}
|
|
705
|
+
import type { Messages } from './types/i18n';
|
|
706
|
+
import en from '${config2.localesPath}/en.json';
|
|
707
|
+
${config2.additionalLocales.map((locale) => `import ${locale} from '${config2.localesPath}/${locale}.json';`).join("\n")}
|
|
708
|
+
|
|
709
|
+
export const i18n = createI18n<Messages>({
|
|
710
|
+
locale: '${config2.defaultLocale}',
|
|
711
|
+
fallbackLocale: '${config2.defaultLocale}',
|
|
712
|
+
messages: {
|
|
713
|
+
en,
|
|
714
|
+
${config2.additionalLocales.join(",\n ")}
|
|
715
|
+
},
|
|
716
|
+
warnOnMissingTranslations: process.env.NODE_ENV !== 'production',
|
|
717
|
+
});
|
|
718
|
+
`;
|
|
719
|
+
}
|
|
720
|
+
function generateJavaScriptConfig(config2) {
|
|
721
|
+
const framework2 = config2.framework;
|
|
722
|
+
const imports = [`import { createI18n } from '@oxog/i18n';`];
|
|
723
|
+
if (framework2 !== "vanilla") {
|
|
724
|
+
imports.push(`// import { I18nProvider } from '@oxog/i18n-${framework2}';`);
|
|
725
|
+
}
|
|
726
|
+
return `${imports.join("\n")}
|
|
727
|
+
import en from '${config2.localesPath}/en.json';
|
|
728
|
+
${config2.additionalLocales.map((locale) => `import ${locale} from '${config2.localesPath}/${locale}.json';`).join("\n")}
|
|
729
|
+
|
|
730
|
+
export const i18n = createI18n({
|
|
731
|
+
locale: '${config2.defaultLocale}',
|
|
732
|
+
fallbackLocale: '${config2.defaultLocale}',
|
|
733
|
+
messages: {
|
|
734
|
+
en,
|
|
735
|
+
${config2.additionalLocales.join(",\n ")}
|
|
736
|
+
},
|
|
737
|
+
warnOnMissingTranslations: process.env.NODE_ENV !== 'production',
|
|
738
|
+
});
|
|
739
|
+
`;
|
|
740
|
+
}
|
|
741
|
+
function generateTypes() {
|
|
742
|
+
return `import type enMessages from '../locales/en.json';
|
|
743
|
+
|
|
744
|
+
export type Messages = typeof enMessages;
|
|
745
|
+
|
|
746
|
+
declare module '@oxog/i18n' {
|
|
747
|
+
interface CustomMessages extends Messages {}
|
|
748
|
+
}
|
|
749
|
+
`;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
async function stats(options) {
|
|
753
|
+
const spinner = createSpinner("Calculating statistics").start();
|
|
754
|
+
try {
|
|
755
|
+
const pattern = path.join(options.path, "*.json");
|
|
756
|
+
const files = await glob(pattern);
|
|
757
|
+
if (files.length === 0) {
|
|
758
|
+
throw new Error("No translation files found");
|
|
759
|
+
}
|
|
760
|
+
const localeStats = [];
|
|
761
|
+
let maxKeys = 0;
|
|
762
|
+
for (const file of files) {
|
|
763
|
+
const locale = path.basename(file, ".json");
|
|
764
|
+
const content = await promises.readFile(file, "utf-8");
|
|
765
|
+
const translations = JSON.parse(content);
|
|
766
|
+
const stats2 = calculateStats(translations);
|
|
767
|
+
maxKeys = Math.max(maxKeys, stats2.keys);
|
|
768
|
+
localeStats.push({
|
|
769
|
+
locale,
|
|
770
|
+
...stats2,
|
|
771
|
+
coverage: 0
|
|
772
|
+
// Will calculate after we know maxKeys
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
localeStats.forEach((stat2) => {
|
|
776
|
+
stat2.coverage = maxKeys > 0 ? stat2.keys / maxKeys * 100 : 100;
|
|
777
|
+
});
|
|
778
|
+
spinner.stop();
|
|
779
|
+
if (options.format === "json") {
|
|
780
|
+
console.log(JSON.stringify(localeStats, null, 2));
|
|
781
|
+
} else {
|
|
782
|
+
displayTable(localeStats);
|
|
783
|
+
}
|
|
784
|
+
} catch (error) {
|
|
785
|
+
spinner.fail("Statistics calculation failed");
|
|
786
|
+
console.error(error);
|
|
787
|
+
process.exit(1);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
function calculateStats(obj) {
|
|
791
|
+
let keys = 0;
|
|
792
|
+
let words = 0;
|
|
793
|
+
let characters = 0;
|
|
794
|
+
function traverse(node) {
|
|
795
|
+
if (typeof node === "string") {
|
|
796
|
+
keys++;
|
|
797
|
+
characters += node.length;
|
|
798
|
+
words += node.split(/\s+/).filter(Boolean).length;
|
|
799
|
+
} else if (typeof node === "object" && node !== null) {
|
|
800
|
+
Object.values(node).forEach(traverse);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
traverse(obj);
|
|
804
|
+
return { keys, words, characters };
|
|
805
|
+
}
|
|
806
|
+
function displayTable(stats2) {
|
|
807
|
+
console.log("\n" + colors.bold("Translation Statistics"));
|
|
808
|
+
console.log(colors.gray("\u2500".repeat(60)));
|
|
809
|
+
console.log(
|
|
810
|
+
colors.gray(
|
|
811
|
+
"Locale".padEnd(10) + "Keys".padEnd(10) + "Words".padEnd(10) + "Characters".padEnd(15) + "Coverage"
|
|
812
|
+
)
|
|
813
|
+
);
|
|
814
|
+
console.log(colors.gray("\u2500".repeat(60)));
|
|
815
|
+
stats2.sort((a, b) => b.coverage - a.coverage);
|
|
816
|
+
for (const stat2 of stats2) {
|
|
817
|
+
const coverageColor = stat2.coverage === 100 ? colors.green : stat2.coverage >= 80 ? colors.yellow : colors.red;
|
|
818
|
+
console.log(
|
|
819
|
+
stat2.locale.padEnd(10) + stat2.keys.toString().padEnd(10) + stat2.words.toString().padEnd(10) + stat2.characters.toString().padEnd(15) + coverageColor(`${stat2.coverage.toFixed(1)}%`)
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
console.log(colors.gray("\u2500".repeat(60)));
|
|
823
|
+
const totalKeys = Math.max(...stats2.map((s) => s.keys));
|
|
824
|
+
const avgCoverage = stats2.reduce((sum, s) => sum + s.coverage, 0) / stats2.length;
|
|
825
|
+
console.log("\n" + colors.bold("Summary:"));
|
|
826
|
+
console.log(colors.gray(`Total locales: ${stats2.length}`));
|
|
827
|
+
console.log(colors.gray(`Total keys: ${totalKeys}`));
|
|
828
|
+
console.log(colors.gray(`Average coverage: ${avgCoverage.toFixed(1)}%`));
|
|
829
|
+
}
|
|
830
|
+
async function sync(options) {
|
|
831
|
+
const spinner = createSpinner("Loading translations").start();
|
|
832
|
+
try {
|
|
833
|
+
const sourceFile = path.join(options.path, `${options.source}.json`);
|
|
834
|
+
const sourceContent = await promises.readFile(sourceFile, "utf-8");
|
|
835
|
+
const sourceTranslations = JSON.parse(sourceContent);
|
|
836
|
+
let targetLocales = [];
|
|
837
|
+
if (options.target) {
|
|
838
|
+
targetLocales = options.target.split(",").map((l) => l.trim());
|
|
839
|
+
} else {
|
|
840
|
+
const files = await promises.readdir(options.path);
|
|
841
|
+
const localeFiles = files.filter((f) => f.endsWith(".json") && f !== `${options.source}.json`);
|
|
842
|
+
targetLocales = localeFiles.map((f) => path.basename(f, ".json"));
|
|
843
|
+
}
|
|
844
|
+
spinner.text = `Syncing to ${targetLocales.length} locales`;
|
|
845
|
+
const syncResults = {};
|
|
846
|
+
for (const locale of targetLocales) {
|
|
847
|
+
const targetFile = path.join(options.path, `${locale}.json`);
|
|
848
|
+
let targetTranslations = {};
|
|
849
|
+
try {
|
|
850
|
+
const content = await promises.readFile(targetFile, "utf-8");
|
|
851
|
+
targetTranslations = JSON.parse(content);
|
|
852
|
+
} catch {
|
|
853
|
+
}
|
|
854
|
+
const result = syncTranslations(sourceTranslations, targetTranslations);
|
|
855
|
+
syncResults[locale] = result.stats;
|
|
856
|
+
if (result.stats.added > 0 || result.stats.updated > 0) {
|
|
857
|
+
spinner.stop();
|
|
858
|
+
console.log(`
|
|
859
|
+
${colors.yellow(locale)}:`);
|
|
860
|
+
console.log(colors.gray(` Added: ${result.stats.added}`));
|
|
861
|
+
console.log(colors.gray(` Updated: ${result.stats.updated}`));
|
|
862
|
+
const prompts = createPrompts();
|
|
863
|
+
const confirm = await prompts.confirm({
|
|
864
|
+
message: `Apply changes to ${locale}?`,
|
|
865
|
+
initial: true
|
|
866
|
+
});
|
|
867
|
+
prompts.close();
|
|
868
|
+
if (confirm) {
|
|
869
|
+
await promises.writeFile(targetFile, JSON.stringify(result.merged, null, 2));
|
|
870
|
+
}
|
|
871
|
+
spinner.start();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
spinner.succeed("Sync complete");
|
|
875
|
+
console.log("\n" + colors.green("\u2728 Sync summary:"));
|
|
876
|
+
for (const [locale, stats2] of Object.entries(syncResults)) {
|
|
877
|
+
if (stats2.added > 0 || stats2.updated > 0) {
|
|
878
|
+
console.log(colors.gray(`${locale}: +${stats2.added} added, ~${stats2.updated} updated`));
|
|
879
|
+
} else {
|
|
880
|
+
console.log(colors.gray(`${locale}: up to date`));
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
} catch (error) {
|
|
884
|
+
spinner.fail("Sync failed");
|
|
885
|
+
console.error(error);
|
|
886
|
+
process.exit(1);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
function syncTranslations(source, target) {
|
|
890
|
+
const stats2 = { added: 0, updated: 0 };
|
|
891
|
+
function merge(src, tgt) {
|
|
892
|
+
if (typeof src !== "object" || src === null) {
|
|
893
|
+
return src;
|
|
894
|
+
}
|
|
895
|
+
const result = { ...tgt };
|
|
896
|
+
for (const [key, value] of Object.entries(src)) {
|
|
897
|
+
if (!(key in result)) {
|
|
898
|
+
result[key] = value;
|
|
899
|
+
if (typeof value === "string") {
|
|
900
|
+
stats2.added++;
|
|
901
|
+
}
|
|
902
|
+
} else if (typeof value === "object" && value !== null) {
|
|
903
|
+
result[key] = merge(value, result[key] || {});
|
|
904
|
+
} else if (typeof value === "string" && result[key] !== value) {
|
|
905
|
+
stats2.updated++;
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
return result;
|
|
909
|
+
}
|
|
910
|
+
return {
|
|
911
|
+
merged: merge(source, target),
|
|
912
|
+
stats: stats2
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
async function validate(options) {
|
|
916
|
+
const spinner = createSpinner("Validating translations").start();
|
|
917
|
+
try {
|
|
918
|
+
const files = await glob(options.pattern);
|
|
919
|
+
const results = {};
|
|
920
|
+
const sourceFile = files.find((f) => path.basename(f, ".json") === options.source);
|
|
921
|
+
if (!sourceFile) {
|
|
922
|
+
throw new Error(`Source locale file not found: ${options.source}`);
|
|
923
|
+
}
|
|
924
|
+
const sourceContent = await promises.readFile(sourceFile, "utf-8");
|
|
925
|
+
const sourceTranslations = JSON.parse(sourceContent);
|
|
926
|
+
const sourceKeys = extractKeys(sourceTranslations);
|
|
927
|
+
for (const file of files) {
|
|
928
|
+
if (file === sourceFile) continue;
|
|
929
|
+
const locale = path.basename(file, ".json");
|
|
930
|
+
const content = await promises.readFile(file, "utf-8");
|
|
931
|
+
const translations = JSON.parse(content);
|
|
932
|
+
const keys = extractKeys(translations);
|
|
933
|
+
const missing = sourceKeys.filter((key) => !keys.includes(key));
|
|
934
|
+
const extra = keys.filter((key) => !sourceKeys.includes(key));
|
|
935
|
+
if (missing.length > 0 || extra.length > 0) {
|
|
936
|
+
results[locale] = { missing, extra };
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
spinner.stop();
|
|
940
|
+
if (Object.keys(results).length === 0) {
|
|
941
|
+
console.log(colors.green("\u2713 All translations are in sync!"));
|
|
942
|
+
} else {
|
|
943
|
+
console.log(colors.red("\n\u2717 Translation issues found:\n"));
|
|
944
|
+
for (const [locale, issues] of Object.entries(results)) {
|
|
945
|
+
console.log(colors.yellow(`${locale}:`));
|
|
946
|
+
if (issues.missing.length > 0) {
|
|
947
|
+
console.log(colors.red(` Missing keys (${issues.missing.length}):`));
|
|
948
|
+
issues.missing.forEach((key) => {
|
|
949
|
+
console.log(colors.gray(` - ${key}`));
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
if (issues.extra.length > 0) {
|
|
953
|
+
console.log(colors.blue(` Extra keys (${issues.extra.length}):`));
|
|
954
|
+
issues.extra.forEach((key) => {
|
|
955
|
+
console.log(colors.gray(` - ${key}`));
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
console.log();
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
} catch (error) {
|
|
962
|
+
spinner.fail("Validation failed");
|
|
963
|
+
console.error(error);
|
|
964
|
+
process.exit(1);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
function extractKeys(obj, prefix = "") {
|
|
968
|
+
const keys = [];
|
|
969
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
970
|
+
const fullKey = prefix ? `${prefix}.${key}` : key;
|
|
971
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
972
|
+
keys.push(...extractKeys(value, fullKey));
|
|
973
|
+
} else {
|
|
974
|
+
keys.push(fullKey);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
return keys;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
// src/cli.ts
|
|
981
|
+
process.on("uncaughtException", (error) => {
|
|
982
|
+
console.error("[CLI] Uncaught exception:", error.message);
|
|
983
|
+
if (process.env.NODE_ENV !== "production") {
|
|
984
|
+
console.error(error.stack);
|
|
985
|
+
}
|
|
986
|
+
process.exit(1);
|
|
987
|
+
});
|
|
988
|
+
process.on("unhandledRejection", (reason, promise) => {
|
|
989
|
+
console.error("[CLI] Unhandled rejection at:", promise, "reason:", reason);
|
|
990
|
+
if (process.env.NODE_ENV !== "production") {
|
|
991
|
+
console.error(reason?.stack);
|
|
992
|
+
}
|
|
993
|
+
process.exit(1);
|
|
994
|
+
});
|
|
995
|
+
try {
|
|
996
|
+
const program = createCommander().name("oxog-i18n").description("CLI tool for @oxog/i18n").version("0.0.0");
|
|
997
|
+
program.command("init").description("Initialize i18n in your project").option("-f, --framework <framework>", "Framework to use (react, vue, svelte)").option("-t, --typescript", "Use TypeScript").action(init);
|
|
998
|
+
program.command("extract").description("Extract translation keys from source code").option("-p, --pattern <pattern>", "Glob pattern for files", "src/**/*.{ts,tsx,js,jsx}").option("-o, --output <path>", "Output directory for translations", "./src/locales").option("-l, --locales <locales>", "Comma-separated list of locales", "en").action(extract);
|
|
999
|
+
program.command("validate").description("Validate translations for missing keys").option("-p, --pattern <pattern>", "Glob pattern for translation files", "./src/locales/**/*.json").option("-s, --source <locale>", "Source locale to compare against", "en").action(validate);
|
|
1000
|
+
program.command("compile").description("Pre-compile translations for production").option("-i, --input <path>", "Input directory", "./src/locales").option("-o, --output <path>", "Output directory", "./dist/locales").option("-f, --format <format>", "Output format (json, js, mjs)", "json").action(compile);
|
|
1001
|
+
program.command("sync").description("Sync translations across locales").option("-s, --source <locale>", "Source locale", "en").option("-t, --target <locales>", "Target locales (comma-separated)").option("-p, --path <path>", "Translation files path", "./src/locales").action(sync);
|
|
1002
|
+
program.command("stats").description("Show translation coverage statistics").option("-p, --path <path>", "Translation files path", "./src/locales").option("-f, --format <format>", "Output format (table, json)", "table").action(stats);
|
|
1003
|
+
program.parse();
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
console.error("[CLI] Fatal error during initialization:", error.message);
|
|
1006
|
+
if (process.env.NODE_ENV !== "production") {
|
|
1007
|
+
console.error(error.stack);
|
|
1008
|
+
}
|
|
1009
|
+
process.exit(1);
|
|
1010
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@oxog/i18n-cli",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "CLI tools for @oxog/i18n",
|
|
5
|
+
"author": "Ersin Koç",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/ersinkoc/i18n",
|
|
10
|
+
"directory": "packages/cli"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"bin": {
|
|
14
|
+
"oxog-i18n": "./dist/cli.js"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@oxog/i18n": "0.0.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^20.11.5",
|
|
24
|
+
"@types/prompts": "^2.4.9",
|
|
25
|
+
"@vitest/coverage-v8": "^1.2.1",
|
|
26
|
+
"tsup": "^8.0.1",
|
|
27
|
+
"typescript": "^5.3.3",
|
|
28
|
+
"vitest": "^1.2.1"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18.0.0"
|
|
32
|
+
},
|
|
33
|
+
"keywords": [
|
|
34
|
+
"i18n",
|
|
35
|
+
"cli",
|
|
36
|
+
"internationalization",
|
|
37
|
+
"localization",
|
|
38
|
+
"translation"
|
|
39
|
+
],
|
|
40
|
+
"scripts": {
|
|
41
|
+
"dev": "tsup --watch",
|
|
42
|
+
"build": "tsup",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"test:watch": "vitest",
|
|
45
|
+
"test:coverage": "vitest run --coverage",
|
|
46
|
+
"typecheck": "tsc --noEmit"
|
|
47
|
+
}
|
|
48
|
+
}
|