@kopynator/cli 1.5.0 → 1.6.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/README.md +187 -13
- package/dist/index.js +392 -91
- package/package.json +1 -2
- package/src/commands/check.ts +118 -10
- package/src/commands/index.ts +1 -0
- package/src/commands/limits.ts +110 -0
- package/src/commands/sync.ts +1 -48
- package/src/index.ts +12 -4
- package/src/lib/i18n-guardian.ts +190 -0
- package/src/lib/project.ts +60 -0
package/dist/index.js
CHANGED
|
@@ -25,7 +25,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
25
25
|
|
|
26
26
|
// src/index.ts
|
|
27
27
|
var import_commander = require("commander");
|
|
28
|
-
var
|
|
28
|
+
var import_chalk6 = __toESM(require("chalk"));
|
|
29
29
|
|
|
30
30
|
// src/commands/init.ts
|
|
31
31
|
var import_inquirer = __toESM(require("inquirer"));
|
|
@@ -270,81 +270,302 @@ async function initCommand() {
|
|
|
270
270
|
|
|
271
271
|
// src/commands/check.ts
|
|
272
272
|
var import_chalk2 = __toESM(require("chalk"));
|
|
273
|
+
var import_fs4 = __toESM(require("fs"));
|
|
274
|
+
var import_path4 = __toESM(require("path"));
|
|
275
|
+
|
|
276
|
+
// src/lib/project.ts
|
|
273
277
|
var import_fs2 = __toESM(require("fs"));
|
|
274
278
|
var import_path2 = __toESM(require("path"));
|
|
275
|
-
|
|
279
|
+
function detectFramework() {
|
|
280
|
+
const angularJson = import_path2.default.join(process.cwd(), "angular.json");
|
|
281
|
+
const packageJson = import_path2.default.join(process.cwd(), "package.json");
|
|
282
|
+
if (import_fs2.default.existsSync(angularJson)) {
|
|
283
|
+
return "Angular";
|
|
284
|
+
}
|
|
285
|
+
if (import_fs2.default.existsSync(packageJson)) {
|
|
286
|
+
try {
|
|
287
|
+
const pkg = JSON.parse(import_fs2.default.readFileSync(packageJson, "utf-8"));
|
|
288
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
289
|
+
if (deps["@angular/core"]) return "Angular";
|
|
290
|
+
if (deps["react"]) return "React";
|
|
291
|
+
if (deps["vue"]) return "Vue";
|
|
292
|
+
} catch (e) {
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return "Other";
|
|
296
|
+
}
|
|
297
|
+
function getTranslationDir(framework) {
|
|
298
|
+
switch (framework) {
|
|
299
|
+
case "Angular":
|
|
300
|
+
return import_path2.default.join(process.cwd(), "src/assets/i18n");
|
|
301
|
+
case "React":
|
|
302
|
+
case "Vue":
|
|
303
|
+
return import_path2.default.join(process.cwd(), "public/locales");
|
|
304
|
+
default:
|
|
305
|
+
return import_path2.default.join(process.cwd(), "locales");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function getSourceRoot(framework) {
|
|
309
|
+
switch (framework) {
|
|
310
|
+
case "Angular":
|
|
311
|
+
case "React":
|
|
312
|
+
case "Vue":
|
|
313
|
+
return import_path2.default.join(process.cwd(), "src");
|
|
314
|
+
default:
|
|
315
|
+
return process.cwd();
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/lib/i18n-guardian.ts
|
|
320
|
+
var import_fs3 = __toESM(require("fs"));
|
|
321
|
+
var import_path3 = __toESM(require("path"));
|
|
322
|
+
var import_child_process = require("child_process");
|
|
323
|
+
var SAFELIST_FILE = "kopynator.i18n-safelist.json";
|
|
324
|
+
var BASELINE_FILE = "kopynator.i18n-baseline.json";
|
|
325
|
+
var SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".html", ".vue"];
|
|
326
|
+
var EXCLUDED_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".angular", "coverage", ".next", ".nuxt", "out"]);
|
|
327
|
+
var KEY = `[\\w.:-]+`;
|
|
328
|
+
var USE_PATTERNS = [
|
|
329
|
+
// {{ 'key' | kopy }} — Angular pipe
|
|
330
|
+
{ re: new RegExp(`(['"\`])(${KEY})\\1\\s*\\|\\s*kopy`, "g"), group: 2 },
|
|
331
|
+
// [kopy]="'key'" — Angular directive with a string literal binding
|
|
332
|
+
{ re: new RegExp(`\\[kopy\\]\\s*=\\s*"'(${KEY})'"`, "g"), group: 1 },
|
|
333
|
+
// .translate('key') / .t('key') — @kopynator/core & @kopynator/react API
|
|
334
|
+
{ re: new RegExp(`\\.(?:translate|t)\\(\\s*(['"\`])(${KEY})\\1`, "g"), group: 2 }
|
|
335
|
+
];
|
|
336
|
+
var MAGIC_RE = /kopynator-keys\s*:\s*([^\n]+)/g;
|
|
337
|
+
function flatten(obj, prefix = "") {
|
|
338
|
+
const out = {};
|
|
339
|
+
for (const [k, v] of Object.entries(obj || {})) {
|
|
340
|
+
const key = prefix ? `${prefix}.${k}` : k;
|
|
341
|
+
if (v && typeof v === "object" && !Array.isArray(v)) {
|
|
342
|
+
Object.assign(out, flatten(v, key));
|
|
343
|
+
} else {
|
|
344
|
+
out[key] = String(v);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
function walkSourceFiles(rootDir) {
|
|
350
|
+
if (!import_fs3.default.existsSync(rootDir)) return [];
|
|
351
|
+
const results = [];
|
|
352
|
+
function walk(dir) {
|
|
353
|
+
for (const entry of import_fs3.default.readdirSync(dir, { withFileTypes: true })) {
|
|
354
|
+
if (entry.isDirectory()) {
|
|
355
|
+
if (EXCLUDED_DIRS.has(entry.name)) continue;
|
|
356
|
+
walk(import_path3.default.join(dir, entry.name));
|
|
357
|
+
} else if (SOURCE_EXTENSIONS.includes(import_path3.default.extname(entry.name))) {
|
|
358
|
+
results.push(import_path3.default.join(dir, entry.name));
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
walk(rootDir);
|
|
363
|
+
return results;
|
|
364
|
+
}
|
|
365
|
+
function scanUsedKeys(files) {
|
|
366
|
+
const used = /* @__PURE__ */ new Map();
|
|
367
|
+
const dynamicPrefixes = /* @__PURE__ */ new Set();
|
|
368
|
+
for (const file of files) {
|
|
369
|
+
const content = import_fs3.default.readFileSync(file, "utf-8");
|
|
370
|
+
for (const { re, group } of USE_PATTERNS) {
|
|
371
|
+
re.lastIndex = 0;
|
|
372
|
+
let match;
|
|
373
|
+
while (match = re.exec(content)) {
|
|
374
|
+
const key = match[group];
|
|
375
|
+
used.set(key, (used.get(key) || 0) + 1);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
MAGIC_RE.lastIndex = 0;
|
|
379
|
+
let magicMatch;
|
|
380
|
+
while (magicMatch = MAGIC_RE.exec(content)) {
|
|
381
|
+
for (const raw of magicMatch[1].split(",")) {
|
|
382
|
+
const prefix = raw.trim().replace(/\*$/, "");
|
|
383
|
+
if (prefix) dynamicPrefixes.add(prefix);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return { used, dynamicPrefixes };
|
|
388
|
+
}
|
|
389
|
+
function loadSafelist(cwd) {
|
|
390
|
+
const p = import_path3.default.join(cwd, SAFELIST_FILE);
|
|
391
|
+
if (!import_fs3.default.existsSync(p)) return { dynamicPrefixes: [] };
|
|
392
|
+
try {
|
|
393
|
+
return JSON.parse(import_fs3.default.readFileSync(p, "utf-8"));
|
|
394
|
+
} catch {
|
|
395
|
+
return { dynamicPrefixes: [] };
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function loadBaseline(cwd) {
|
|
399
|
+
const p = import_path3.default.join(cwd, BASELINE_FILE);
|
|
400
|
+
if (!import_fs3.default.existsSync(p)) return { keys: [] };
|
|
401
|
+
try {
|
|
402
|
+
const parsed = JSON.parse(import_fs3.default.readFileSync(p, "utf-8"));
|
|
403
|
+
return { keys: Array.isArray(parsed.keys) ? parsed.keys : [] };
|
|
404
|
+
} catch {
|
|
405
|
+
return { keys: [] };
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
function saveBaseline(cwd, keys) {
|
|
409
|
+
const p = import_path3.default.join(cwd, BASELINE_FILE);
|
|
410
|
+
import_fs3.default.writeFileSync(p, JSON.stringify({ keys: keys.sort() }, null, 2) + "\n");
|
|
411
|
+
}
|
|
412
|
+
function isProtectedByPrefix(key, prefixes) {
|
|
413
|
+
for (const prefix of prefixes) {
|
|
414
|
+
if (key.startsWith(prefix)) return true;
|
|
415
|
+
}
|
|
416
|
+
return false;
|
|
417
|
+
}
|
|
418
|
+
function gitShowFile(cwd, ref, relPath) {
|
|
419
|
+
try {
|
|
420
|
+
return (0, import_child_process.execFileSync)("git", ["show", `${ref}:${relPath}`], { cwd, stdio: ["pipe", "pipe", "ignore"] }).toString("utf-8");
|
|
421
|
+
} catch {
|
|
422
|
+
return null;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function slugify(value, maxLen = 40) {
|
|
426
|
+
return String(value).replace(/<[^>]+>/g, "").replace(/\{\{[^}]+\}\}/g, "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, maxLen) || "value";
|
|
427
|
+
}
|
|
428
|
+
function pickGlobal(keys) {
|
|
429
|
+
const globals = keys.filter((k) => k.startsWith("global."));
|
|
430
|
+
if (!globals.length) return null;
|
|
431
|
+
const segmented = globals.filter((k) => /^global\.(status|error|action)\./.test(k));
|
|
432
|
+
const pool = segmented.length ? segmented : globals;
|
|
433
|
+
return pool.reduce((shortest, k) => k.length < shortest.length ? k : shortest, pool[0]);
|
|
434
|
+
}
|
|
435
|
+
function findGlobalDuplicates(values, usedKeys) {
|
|
436
|
+
const byValue = /* @__PURE__ */ new Map();
|
|
437
|
+
for (const [key, value] of Object.entries(values)) {
|
|
438
|
+
const trimmed = value.trim();
|
|
439
|
+
if (!trimmed) continue;
|
|
440
|
+
const group = byValue.get(trimmed) || [];
|
|
441
|
+
group.push(key);
|
|
442
|
+
byValue.set(trimmed, group);
|
|
443
|
+
}
|
|
444
|
+
const findings = [];
|
|
445
|
+
for (const [value, keys] of byValue) {
|
|
446
|
+
if (keys.length < 2) continue;
|
|
447
|
+
const canonical = pickGlobal(keys) || `global.${slugify(value)}`;
|
|
448
|
+
for (const key of keys) {
|
|
449
|
+
if (key === canonical) continue;
|
|
450
|
+
if (!usedKeys.has(key)) continue;
|
|
451
|
+
findings.push({ key, value, canonical, canonicalIsNew: !keys.includes(canonical) });
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return findings;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/commands/check.ts
|
|
458
|
+
async function checkCommand(opts = {}) {
|
|
459
|
+
if (process.env.KOPYNATOR_I18N_SKIP === "1") {
|
|
460
|
+
console.log(import_chalk2.default.yellow("\u26A0\uFE0F KOPYNATOR_I18N_SKIP=1 \u2014 skipping i18n check."));
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
276
463
|
console.log(import_chalk2.default.bold.blue("\n\u{1F50D} Validating JSON translation files...\n"));
|
|
277
|
-
const
|
|
278
|
-
|
|
464
|
+
const cwd = process.cwd();
|
|
465
|
+
const framework = detectFramework();
|
|
466
|
+
const assetsDir = getTranslationDir(framework);
|
|
467
|
+
if (!import_fs4.default.existsSync(assetsDir)) {
|
|
279
468
|
console.log(import_chalk2.default.red(`\u274C Could not find directory: ${assetsDir}`));
|
|
280
469
|
console.log(import_chalk2.default.yellow("Make sure you are running this from your project root."));
|
|
281
|
-
|
|
470
|
+
process.exit(1);
|
|
282
471
|
}
|
|
283
|
-
const files =
|
|
472
|
+
const files = import_fs4.default.readdirSync(assetsDir).filter((f) => f.endsWith(".json"));
|
|
284
473
|
if (files.length === 0) {
|
|
285
|
-
console.log(import_chalk2.default.yellow("\u26A0\uFE0F No JSON files found in
|
|
474
|
+
console.log(import_chalk2.default.yellow("\u26A0\uFE0F No JSON files found in " + assetsDir + "."));
|
|
286
475
|
return;
|
|
287
476
|
}
|
|
288
|
-
let
|
|
477
|
+
let hasJsonErrors = false;
|
|
478
|
+
const parsed = {};
|
|
289
479
|
files.forEach((file) => {
|
|
290
480
|
try {
|
|
291
|
-
const content =
|
|
292
|
-
JSON.parse(content);
|
|
481
|
+
const content = import_fs4.default.readFileSync(import_path4.default.join(assetsDir, file), "utf-8");
|
|
482
|
+
parsed[file] = JSON.parse(content);
|
|
293
483
|
console.log(import_chalk2.default.green(`\u2713 ${file} is valid JSON.`));
|
|
294
484
|
} catch (e) {
|
|
295
|
-
|
|
485
|
+
hasJsonErrors = true;
|
|
296
486
|
console.log(import_chalk2.default.red(`\u274C ${file} has syntax errors:`));
|
|
297
487
|
console.log(import_chalk2.default.red(` ${e.message}`));
|
|
298
488
|
}
|
|
299
489
|
});
|
|
300
|
-
if (
|
|
490
|
+
if (hasJsonErrors) {
|
|
301
491
|
console.log(import_chalk2.default.red("\n\u{1F4A5} Validation failed. Please fix the errors above."));
|
|
302
492
|
process.exit(1);
|
|
303
|
-
} else {
|
|
304
|
-
console.log(import_chalk2.default.bold.green("\n\u2728 All files are valid! You are ready to go."));
|
|
305
493
|
}
|
|
494
|
+
console.log(import_chalk2.default.bold.blue("\n\u{1F6E1}\uFE0F Guarding against broken references and duplicate keys...\n"));
|
|
495
|
+
const definedKeys = /* @__PURE__ */ new Set();
|
|
496
|
+
for (const file of files) {
|
|
497
|
+
Object.keys(flatten(parsed[file])).forEach((k) => definedKeys.add(k));
|
|
498
|
+
}
|
|
499
|
+
const refFile = files.includes("en.json") ? "en.json" : files.sort()[0];
|
|
500
|
+
const refValues = flatten(parsed[refFile]);
|
|
501
|
+
const sourceRoot = getSourceRoot(framework);
|
|
502
|
+
const sourceFiles = walkSourceFiles(sourceRoot);
|
|
503
|
+
const { used, dynamicPrefixes: magicPrefixes } = scanUsedKeys(sourceFiles);
|
|
504
|
+
const safelist = loadSafelist(cwd);
|
|
505
|
+
const protectedPrefixes = /* @__PURE__ */ new Set([...safelist.dynamicPrefixes || [], ...magicPrefixes]);
|
|
506
|
+
const missing = [...used.keys()].filter((k) => !definedKeys.has(k)).filter((k) => !isProtectedByPrefix(k, protectedPrefixes));
|
|
507
|
+
const baseline = loadBaseline(cwd);
|
|
508
|
+
const baselineSet = new Set(baseline.keys);
|
|
509
|
+
const freshMissing = missing.filter((k) => !baselineSet.has(k));
|
|
510
|
+
const staleBaseline = baseline.keys.filter((k) => !missing.includes(k));
|
|
511
|
+
if (opts.updateBaseline) {
|
|
512
|
+
saveBaseline(cwd, missing);
|
|
513
|
+
console.log(import_chalk2.default.green(`\u2705 Baseline updated: ${missing.length} accepted missing key(s) written to kopynator.i18n-baseline.json`));
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (opts.all) {
|
|
517
|
+
console.log(import_chalk2.default.bold(`
|
|
518
|
+
All missing keys (${missing.length}):`));
|
|
519
|
+
missing.slice().sort().forEach((k) => {
|
|
520
|
+
const tag = baselineSet.has(k) ? import_chalk2.default.gray("[baseline]") : import_chalk2.default.red("[NEW]");
|
|
521
|
+
console.log(` ${tag} ${k} ${import_chalk2.default.gray(`(used ${used.get(k)}x)`)}`);
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
const baseRef = opts.baseRef || "master";
|
|
525
|
+
const oldRefContent = gitShowFile(cwd, baseRef, import_path4.default.relative(cwd, import_path4.default.join(assetsDir, refFile)));
|
|
526
|
+
const oldRefValues = oldRefContent ? flatten(JSON.parse(oldRefContent)) : {};
|
|
527
|
+
const duplicates = findGlobalDuplicates(refValues, new Set(used.keys())).filter(
|
|
528
|
+
(d) => oldRefValues[d.key] === void 0 || oldRefValues[d.key] !== refValues[d.key]
|
|
529
|
+
);
|
|
530
|
+
let hasFailures = false;
|
|
531
|
+
if (freshMissing.length) {
|
|
532
|
+
hasFailures = true;
|
|
533
|
+
console.log(import_chalk2.default.red(`
|
|
534
|
+
\u274C ${freshMissing.length} translation key(s) used in code but missing from ${assetsDir}:`));
|
|
535
|
+
freshMissing.sort().forEach((k) => console.log(import_chalk2.default.red(` - ${k} ${import_chalk2.default.gray(`(used ${used.get(k)}x)`)}`)));
|
|
536
|
+
}
|
|
537
|
+
if (duplicates.length) {
|
|
538
|
+
hasFailures = true;
|
|
539
|
+
console.log(import_chalk2.default.red(`
|
|
540
|
+
\u274C ${duplicates.length} key(s) duplicate an existing global value:`));
|
|
541
|
+
duplicates.forEach(
|
|
542
|
+
(d) => console.log(import_chalk2.default.red(` - "${d.key}" duplicates "${d.canonical}"${d.canonicalIsNew ? import_chalk2.default.gray(" (not created yet \u2014 proposed)") : ""} \u2192 "${d.value}"`))
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
if (staleBaseline.length) {
|
|
546
|
+
console.log(
|
|
547
|
+
import_chalk2.default.blue(`
|
|
548
|
+
\u2139\uFE0F i18n: ${staleBaseline.length} baseline key(s) no longer missing; regenerate: kopynator check --update-baseline`)
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
if (hasFailures) {
|
|
552
|
+
console.log(import_chalk2.default.red("\n\u{1F4A5} i18n check failed. Fix the issues above, or run with --update-baseline to accept current debt."));
|
|
553
|
+
process.exit(1);
|
|
554
|
+
}
|
|
555
|
+
console.log(import_chalk2.default.bold.green(`
|
|
556
|
+
\u2728 i18n check passed (${files.length} locale file(s); baseline=${baselineSet.size}; scanned ${sourceFiles.length} source file(s)).`));
|
|
306
557
|
}
|
|
307
558
|
|
|
308
559
|
// src/commands/sync.ts
|
|
309
560
|
var import_chalk3 = __toESM(require("chalk"));
|
|
310
|
-
var
|
|
311
|
-
var
|
|
561
|
+
var import_fs5 = __toESM(require("fs"));
|
|
562
|
+
var import_path5 = __toESM(require("path"));
|
|
312
563
|
var import_inquirer2 = __toESM(require("inquirer"));
|
|
313
564
|
var import_ora = __toESM(require("ora"));
|
|
314
|
-
function detectFramework() {
|
|
315
|
-
const angularJson = import_path3.default.join(process.cwd(), "angular.json");
|
|
316
|
-
const packageJson = import_path3.default.join(process.cwd(), "package.json");
|
|
317
|
-
if (import_fs3.default.existsSync(angularJson)) {
|
|
318
|
-
return "Angular";
|
|
319
|
-
}
|
|
320
|
-
if (import_fs3.default.existsSync(packageJson)) {
|
|
321
|
-
try {
|
|
322
|
-
const pkg = JSON.parse(import_fs3.default.readFileSync(packageJson, "utf-8"));
|
|
323
|
-
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
324
|
-
if (deps["@angular/core"]) return "Angular";
|
|
325
|
-
if (deps["react"]) return "React";
|
|
326
|
-
if (deps["vue"]) return "Vue";
|
|
327
|
-
} catch (e) {
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
return "Other";
|
|
331
|
-
}
|
|
332
|
-
function getTranslationDir(framework) {
|
|
333
|
-
switch (framework) {
|
|
334
|
-
case "Angular":
|
|
335
|
-
return import_path3.default.join(process.cwd(), "src/assets/i18n");
|
|
336
|
-
case "React":
|
|
337
|
-
return import_path3.default.join(process.cwd(), "public/locales");
|
|
338
|
-
case "Vue":
|
|
339
|
-
return import_path3.default.join(process.cwd(), "public/locales");
|
|
340
|
-
default:
|
|
341
|
-
return import_path3.default.join(process.cwd(), "locales");
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
565
|
function loadJsonConfig(jsonPath) {
|
|
345
|
-
if (!
|
|
566
|
+
if (!import_fs5.default.existsSync(jsonPath)) return null;
|
|
346
567
|
try {
|
|
347
|
-
const config = JSON.parse(
|
|
568
|
+
const config = JSON.parse(import_fs5.default.readFileSync(jsonPath, "utf-8"));
|
|
348
569
|
if (config.apiKey) return { apiKey: config.apiKey, baseUrl: config.baseUrl };
|
|
349
570
|
} catch (e) {
|
|
350
571
|
if (jsonPath.includes("kopynator.config.json")) {
|
|
@@ -355,28 +576,28 @@ function loadJsonConfig(jsonPath) {
|
|
|
355
576
|
}
|
|
356
577
|
function extractApiKey() {
|
|
357
578
|
const cwd = process.cwd();
|
|
358
|
-
const configFromRoot = loadJsonConfig(
|
|
579
|
+
const configFromRoot = loadJsonConfig(import_path5.default.join(cwd, "kopynator.config.json"));
|
|
359
580
|
if (configFromRoot) {
|
|
360
581
|
console.log(import_chalk3.default.blue("\u2139\uFE0F Found API key in kopynator.config.json"));
|
|
361
582
|
return configFromRoot;
|
|
362
583
|
}
|
|
363
|
-
const configFromSrc = loadJsonConfig(
|
|
584
|
+
const configFromSrc = loadJsonConfig(import_path5.default.join(cwd, "src/kopynator.config.json"));
|
|
364
585
|
if (configFromSrc) {
|
|
365
586
|
console.log(import_chalk3.default.blue("\u2139\uFE0F Found API key in src/kopynator.config.json"));
|
|
366
587
|
return configFromSrc;
|
|
367
588
|
}
|
|
368
|
-
const appConfigPath =
|
|
369
|
-
const appModulePath =
|
|
370
|
-
if (
|
|
371
|
-
const content =
|
|
589
|
+
const appConfigPath = import_path5.default.join(cwd, "src/app/app.config.ts");
|
|
590
|
+
const appModulePath = import_path5.default.join(cwd, "src/app/app.module.ts");
|
|
591
|
+
if (import_fs5.default.existsSync(appConfigPath)) {
|
|
592
|
+
const content = import_fs5.default.readFileSync(appConfigPath, "utf-8");
|
|
372
593
|
const apiKeyMatch = content.match(/apiKey:\s*['"]([^'"]+)['"]/);
|
|
373
594
|
if (apiKeyMatch) {
|
|
374
595
|
console.log(import_chalk3.default.blue("\u2139\uFE0F Found API key in app.config.ts"));
|
|
375
596
|
return { apiKey: apiKeyMatch[1] };
|
|
376
597
|
}
|
|
377
598
|
}
|
|
378
|
-
if (
|
|
379
|
-
const content =
|
|
599
|
+
if (import_fs5.default.existsSync(appModulePath)) {
|
|
600
|
+
const content = import_fs5.default.readFileSync(appModulePath, "utf-8");
|
|
380
601
|
const apiKeyMatch = content.match(/apiKey:\s*['"]([^'"]+)['"]/);
|
|
381
602
|
if (apiKeyMatch) {
|
|
382
603
|
console.log(import_chalk3.default.blue("\u2139\uFE0F Found API key in app.module.ts"));
|
|
@@ -394,10 +615,10 @@ function extractApiKey() {
|
|
|
394
615
|
return null;
|
|
395
616
|
}
|
|
396
617
|
async function getSyncConfig() {
|
|
397
|
-
const configPath =
|
|
398
|
-
if (
|
|
618
|
+
const configPath = import_path5.default.join(process.cwd(), "kopynator.sync.config.json");
|
|
619
|
+
if (import_fs5.default.existsSync(configPath)) {
|
|
399
620
|
try {
|
|
400
|
-
const config2 = JSON.parse(
|
|
621
|
+
const config2 = JSON.parse(import_fs5.default.readFileSync(configPath, "utf-8"));
|
|
401
622
|
console.log(import_chalk3.default.blue("\u2139\uFE0F Using existing sync configuration"));
|
|
402
623
|
return config2;
|
|
403
624
|
} catch (e) {
|
|
@@ -442,7 +663,7 @@ async function getSyncConfig() {
|
|
|
442
663
|
pretty: answers.pretty,
|
|
443
664
|
indent: answers.indent
|
|
444
665
|
};
|
|
445
|
-
|
|
666
|
+
import_fs5.default.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
446
667
|
console.log(import_chalk3.default.green("\u2705 Configuration saved to kopynator.sync.config.json\n"));
|
|
447
668
|
return config;
|
|
448
669
|
}
|
|
@@ -475,8 +696,8 @@ async function syncCommand() {
|
|
|
475
696
|
const languages = await languagesResponse.json();
|
|
476
697
|
spinner.succeed(`Found ${languages.length} language(s): ${languages.join(", ")}`);
|
|
477
698
|
const i18nDir = getTranslationDir(framework);
|
|
478
|
-
if (!
|
|
479
|
-
|
|
699
|
+
if (!import_fs5.default.existsSync(i18nDir)) {
|
|
700
|
+
import_fs5.default.mkdirSync(i18nDir, { recursive: true });
|
|
480
701
|
console.log(import_chalk3.default.blue(`\u{1F4C1} Created directory: ${i18nDir}`));
|
|
481
702
|
}
|
|
482
703
|
for (const locale of languages) {
|
|
@@ -493,7 +714,7 @@ async function syncCommand() {
|
|
|
493
714
|
continue;
|
|
494
715
|
}
|
|
495
716
|
const translationData = await translationResponse.json();
|
|
496
|
-
const outputPath =
|
|
717
|
+
const outputPath = import_path5.default.join(i18nDir, `${locale}.json`);
|
|
497
718
|
let jsonString;
|
|
498
719
|
if (syncConfig.pretty) {
|
|
499
720
|
const indentValue = syncConfig.indent === "tab" ? " " : Number(syncConfig.indent);
|
|
@@ -501,7 +722,7 @@ async function syncCommand() {
|
|
|
501
722
|
} else {
|
|
502
723
|
jsonString = JSON.stringify(translationData);
|
|
503
724
|
}
|
|
504
|
-
|
|
725
|
+
import_fs5.default.writeFileSync(outputPath, jsonString);
|
|
505
726
|
downloadSpinner.succeed(`Saved ${locale}.json`);
|
|
506
727
|
} catch (err) {
|
|
507
728
|
downloadSpinner.fail(`Error downloading ${locale}: ${err instanceof Error ? err.message : "Unknown error"}`);
|
|
@@ -515,17 +736,17 @@ async function syncCommand() {
|
|
|
515
736
|
|
|
516
737
|
// src/commands/upload.ts
|
|
517
738
|
var import_chalk4 = __toESM(require("chalk"));
|
|
518
|
-
var
|
|
519
|
-
var
|
|
739
|
+
var import_fs6 = __toESM(require("fs"));
|
|
740
|
+
var import_path6 = __toESM(require("path"));
|
|
520
741
|
var import_ora2 = __toESM(require("ora"));
|
|
521
742
|
var BATCH_SIZE = 500;
|
|
522
|
-
function
|
|
743
|
+
function flatten2(data, prefix = "") {
|
|
523
744
|
const result = {};
|
|
524
745
|
for (const key in data) {
|
|
525
746
|
const fullKey = prefix ? `${prefix}.${key}` : key;
|
|
526
747
|
const value = data[key];
|
|
527
748
|
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
528
|
-
Object.assign(result,
|
|
749
|
+
Object.assign(result, flatten2(value, fullKey));
|
|
529
750
|
} else {
|
|
530
751
|
result[fullKey] = String(value);
|
|
531
752
|
}
|
|
@@ -533,9 +754,9 @@ function flatten(data, prefix = "") {
|
|
|
533
754
|
return result;
|
|
534
755
|
}
|
|
535
756
|
function loadJsonConfig2(jsonPath) {
|
|
536
|
-
if (!
|
|
757
|
+
if (!import_fs6.default.existsSync(jsonPath)) return null;
|
|
537
758
|
try {
|
|
538
|
-
const config = JSON.parse(
|
|
759
|
+
const config = JSON.parse(import_fs6.default.readFileSync(jsonPath, "utf-8"));
|
|
539
760
|
const key = config.apiKey ?? config.api_key;
|
|
540
761
|
if (key && typeof key === "string") return { apiKey: key, baseUrl: config.baseUrl };
|
|
541
762
|
} catch {
|
|
@@ -544,19 +765,19 @@ function loadJsonConfig2(jsonPath) {
|
|
|
544
765
|
}
|
|
545
766
|
function extractApiKey2() {
|
|
546
767
|
const cwd = process.cwd();
|
|
547
|
-
const appConfigPath =
|
|
548
|
-
const appModulePath =
|
|
549
|
-
const configFromRoot = loadJsonConfig2(
|
|
768
|
+
const appConfigPath = import_path6.default.join(cwd, "src/app/app.config.ts");
|
|
769
|
+
const appModulePath = import_path6.default.join(cwd, "src/app/app.module.ts");
|
|
770
|
+
const configFromRoot = loadJsonConfig2(import_path6.default.join(cwd, "kopynator.config.json"));
|
|
550
771
|
if (configFromRoot) return configFromRoot;
|
|
551
|
-
const configFromSrc = loadJsonConfig2(
|
|
772
|
+
const configFromSrc = loadJsonConfig2(import_path6.default.join(cwd, "src/kopynator.config.json"));
|
|
552
773
|
if (configFromSrc) return configFromSrc;
|
|
553
|
-
if (
|
|
554
|
-
const content =
|
|
774
|
+
if (import_fs6.default.existsSync(appConfigPath)) {
|
|
775
|
+
const content = import_fs6.default.readFileSync(appConfigPath, "utf-8");
|
|
555
776
|
const apiKeyMatch = content.match(/apiKey:\s*['"]([^'"]+)['"]/);
|
|
556
777
|
if (apiKeyMatch) return { apiKey: apiKeyMatch[1] };
|
|
557
778
|
}
|
|
558
|
-
if (
|
|
559
|
-
const content =
|
|
779
|
+
if (import_fs6.default.existsSync(appModulePath)) {
|
|
780
|
+
const content = import_fs6.default.readFileSync(appModulePath, "utf-8");
|
|
560
781
|
const apiKeyMatch = content.match(/apiKey:\s*['"]([^'"]+)['"]/);
|
|
561
782
|
if (apiKeyMatch) return { apiKey: apiKeyMatch[1] };
|
|
562
783
|
}
|
|
@@ -570,7 +791,7 @@ function extractApiKey2() {
|
|
|
570
791
|
return null;
|
|
571
792
|
}
|
|
572
793
|
function inferLangFromFile(filePath) {
|
|
573
|
-
const base =
|
|
794
|
+
const base = import_path6.default.basename(filePath, import_path6.default.extname(filePath));
|
|
574
795
|
return base;
|
|
575
796
|
}
|
|
576
797
|
async function uploadCommand(options) {
|
|
@@ -578,13 +799,13 @@ async function uploadCommand(options) {
|
|
|
578
799
|
const config = extractApiKey2();
|
|
579
800
|
if (!config) {
|
|
580
801
|
const cwd = process.cwd();
|
|
581
|
-
const rootConfig =
|
|
582
|
-
const srcConfig =
|
|
802
|
+
const rootConfig = import_path6.default.join(cwd, "kopynator.config.json");
|
|
803
|
+
const srcConfig = import_path6.default.join(cwd, "src/kopynator.config.json");
|
|
583
804
|
console.log(import_chalk4.default.red("\u274C Could not find API key. Set it in kopynator.config.json, app.config.ts, or KOPYNATOR_API_KEY. Run `npx kopynator init` to create config."));
|
|
584
805
|
console.log(import_chalk4.default.gray(` Directorio actual: ${cwd}`));
|
|
585
|
-
console.log(import_chalk4.default.gray(` Comprobado: ${rootConfig} (${
|
|
586
|
-
console.log(import_chalk4.default.gray(` Comprobado: ${srcConfig} (${
|
|
587
|
-
if (
|
|
806
|
+
console.log(import_chalk4.default.gray(` Comprobado: ${rootConfig} (${import_fs6.default.existsSync(rootConfig) ? "existe" : "no existe"})`));
|
|
807
|
+
console.log(import_chalk4.default.gray(` Comprobado: ${srcConfig} (${import_fs6.default.existsSync(srcConfig) ? "existe" : "no existe"})`));
|
|
808
|
+
if (import_fs6.default.existsSync(rootConfig) || import_fs6.default.existsSync(srcConfig)) {
|
|
588
809
|
console.log(import_chalk4.default.yellow('\u{1F4A1} Si el archivo existe, comprueba que tenga la propiedad "apiKey" (o "api_key") con un valor no vac\xEDo.'));
|
|
589
810
|
} else {
|
|
590
811
|
console.log(import_chalk4.default.yellow("\u{1F4A1} Ejecuta el comando desde la ra\xEDz del proyecto (donde est\xE1 package.json)."));
|
|
@@ -596,8 +817,8 @@ async function uploadCommand(options) {
|
|
|
596
817
|
console.log(import_chalk4.default.red("\u274C Missing --file. Example: npx kopynator upload --file=es.json [--lang=es]"));
|
|
597
818
|
return;
|
|
598
819
|
}
|
|
599
|
-
const resolvedPath =
|
|
600
|
-
if (!
|
|
820
|
+
const resolvedPath = import_path6.default.isAbsolute(fileOption) ? fileOption : import_path6.default.join(process.cwd(), fileOption);
|
|
821
|
+
if (!import_fs6.default.existsSync(resolvedPath)) {
|
|
601
822
|
console.log(import_chalk4.default.red(`\u274C File not found: ${resolvedPath}`));
|
|
602
823
|
return;
|
|
603
824
|
}
|
|
@@ -606,7 +827,7 @@ async function uploadCommand(options) {
|
|
|
606
827
|
const token = config.apiKey;
|
|
607
828
|
let raw;
|
|
608
829
|
try {
|
|
609
|
-
raw = JSON.parse(
|
|
830
|
+
raw = JSON.parse(import_fs6.default.readFileSync(resolvedPath, "utf-8"));
|
|
610
831
|
} catch (e) {
|
|
611
832
|
console.log(import_chalk4.default.red(`\u274C Invalid JSON: ${resolvedPath}`));
|
|
612
833
|
return;
|
|
@@ -615,7 +836,7 @@ async function uploadCommand(options) {
|
|
|
615
836
|
console.log(import_chalk4.default.red("\u274C JSON root must be an object (key-value)."));
|
|
616
837
|
return;
|
|
617
838
|
}
|
|
618
|
-
const flat =
|
|
839
|
+
const flat = flatten2(raw);
|
|
619
840
|
const entries = Object.entries(flat);
|
|
620
841
|
const total = entries.length;
|
|
621
842
|
if (total === 0) {
|
|
@@ -689,15 +910,95 @@ async function uploadCommand(options) {
|
|
|
689
910
|
}
|
|
690
911
|
}
|
|
691
912
|
|
|
913
|
+
// src/commands/limits.ts
|
|
914
|
+
var import_chalk5 = __toESM(require("chalk"));
|
|
915
|
+
var import_fs7 = __toESM(require("fs"));
|
|
916
|
+
var import_path7 = __toESM(require("path"));
|
|
917
|
+
function resolveApiKey() {
|
|
918
|
+
const cwd = process.cwd();
|
|
919
|
+
const fromJson = (p) => {
|
|
920
|
+
try {
|
|
921
|
+
if (import_fs7.default.existsSync(p)) {
|
|
922
|
+
const cfg = JSON.parse(import_fs7.default.readFileSync(p, "utf-8"));
|
|
923
|
+
if (cfg && cfg.apiKey) return { apiKey: cfg.apiKey, baseUrl: cfg.baseUrl };
|
|
924
|
+
}
|
|
925
|
+
} catch {
|
|
926
|
+
}
|
|
927
|
+
return null;
|
|
928
|
+
};
|
|
929
|
+
const fromAppFile = (p) => {
|
|
930
|
+
try {
|
|
931
|
+
if (import_fs7.default.existsSync(p)) {
|
|
932
|
+
const content = import_fs7.default.readFileSync(p, "utf-8");
|
|
933
|
+
const match = content.match(/apiKey:\s*['"]([^'"]+)['"]/);
|
|
934
|
+
if (match) return { apiKey: match[1] };
|
|
935
|
+
}
|
|
936
|
+
} catch {
|
|
937
|
+
}
|
|
938
|
+
return null;
|
|
939
|
+
};
|
|
940
|
+
return fromJson(import_path7.default.join(cwd, "kopynator.config.json")) || fromJson(import_path7.default.join(cwd, "src/kopynator.config.json")) || fromAppFile(import_path7.default.join(cwd, "src/app/app.config.ts")) || fromAppFile(import_path7.default.join(cwd, "src/app/app.module.ts")) || (process.env.KOPYNATOR_API_KEY ? { apiKey: process.env.KOPYNATOR_API_KEY.trim(), baseUrl: process.env.KOPYNATOR_BASE_URL?.trim() } : null);
|
|
941
|
+
}
|
|
942
|
+
function formatLimit(value) {
|
|
943
|
+
return value === -1 ? "Unlimited" : String(value);
|
|
944
|
+
}
|
|
945
|
+
async function limitsCommand() {
|
|
946
|
+
const resolved = resolveApiKey();
|
|
947
|
+
if (!resolved) {
|
|
948
|
+
console.log(import_chalk5.default.red("\n\u2716 No API key found."));
|
|
949
|
+
console.log(import_chalk5.default.gray(" Add it to kopynator.config.json or set KOPYNATOR_API_KEY.\n"));
|
|
950
|
+
process.exit(1);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
const base = (resolved.baseUrl || process.env.KOPYNATOR_BASE_URL || "https://api.kopynator.com").replace(/\/+$/, "").replace(/\/api$/, "");
|
|
954
|
+
const url = `${base}/tokens/limits?token=${encodeURIComponent(resolved.apiKey)}`;
|
|
955
|
+
try {
|
|
956
|
+
const res = await fetch(url, { headers: { "x-kopynator-version": "1.5.0" } });
|
|
957
|
+
if (!res.ok) {
|
|
958
|
+
const body = await res.text().catch(() => "");
|
|
959
|
+
console.log(import_chalk5.default.red(`
|
|
960
|
+
\u2716 Could not fetch limits (HTTP ${res.status}). ${body}
|
|
961
|
+
`));
|
|
962
|
+
process.exit(1);
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
const data = await res.json();
|
|
966
|
+
const limits = data.limits || {};
|
|
967
|
+
const usage = data.usage || {};
|
|
968
|
+
const row = (label, used, limit) => {
|
|
969
|
+
const usedPart = used === void 0 ? "" : `${used} / `;
|
|
970
|
+
const text = ` ${label.padEnd(9)} ${usedPart}${formatLimit(limit)}`;
|
|
971
|
+
const reached = limit !== -1 && used !== void 0 && used >= limit;
|
|
972
|
+
return reached ? import_chalk5.default.red(`${text} (limit reached \u2014 upgrade your plan)`) : import_chalk5.default.green(text);
|
|
973
|
+
};
|
|
974
|
+
console.log("");
|
|
975
|
+
console.log(import_chalk5.default.bold("\u{1F4CA} Kopynator \u2014 plan limits (per organization)"));
|
|
976
|
+
const planLabel = import_chalk5.default.cyan((data.plan || "free").toUpperCase());
|
|
977
|
+
const statusLabel = data.active ? import_chalk5.default.green("active") : import_chalk5.default.yellow("inactive/expired \u2192 free limits apply");
|
|
978
|
+
console.log(` Plan: ${planLabel} (${statusLabel})`);
|
|
979
|
+
console.log("");
|
|
980
|
+
console.log(row("Projects", usage.projects, limits.projects));
|
|
981
|
+
console.log(row("Keys", usage.keys, limits.keys));
|
|
982
|
+
console.log(row("Members", void 0, limits.members));
|
|
983
|
+
console.log("");
|
|
984
|
+
} catch (error) {
|
|
985
|
+
console.log(import_chalk5.default.red(`
|
|
986
|
+
\u2716 Request failed: ${error?.message || error}
|
|
987
|
+
`));
|
|
988
|
+
process.exit(1);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
|
|
692
992
|
// src/index.ts
|
|
693
993
|
var program = new import_commander.Command();
|
|
694
|
-
program.name("kopynator").description("Kopynator CLI - Manage your i18n workflow").version("1.
|
|
994
|
+
program.name("kopynator").description("Kopynator CLI - Manage your i18n workflow").version("1.5.1", "-v, --version").helpOption("-h, --help", "Display help for command").addHelpText("beforeAll", import_chalk6.default.blue("\n\u{1F44B} Welcome to Kopynator CLI!\n"));
|
|
695
995
|
program.command("init").description("Initialize Kopynator in your project").action(initCommand);
|
|
696
|
-
program.command("check").description("Validate
|
|
996
|
+
program.command("check").description("Validate translation files: JSON syntax, broken references and duplicate global keys").option("--base-ref <ref>", "Git ref to diff against when detecting new duplicate keys", "master").option("--update-baseline", "Accept all currently-missing keys as backlog (writes kopynator.i18n-baseline.json)").option("--all", "List every missing key, including ones already accepted in the baseline").action((opts) => checkCommand({ baseRef: opts.baseRef, updateBaseline: opts.updateBaseline, all: opts.all }));
|
|
697
997
|
program.command("sync").description("Sync your translations with the Kopynator Cloud").action(syncCommand);
|
|
698
998
|
program.command("upload").description("Upload a JSON translation file to Kopynator Cloud").option("-f, --file <path>", "Path to the JSON file (e.g. es.json)").option("-l, --lang <code>", "Language code (default: inferred from filename)").action((opts) => uploadCommand({ file: opts.file, lang: opts.lang }));
|
|
999
|
+
program.command("limits").description("Show your plan limits and current usage (projects, keys, members)").action(limitsCommand);
|
|
699
1000
|
program.command("help").description("Show help for all commands").action(() => {
|
|
700
|
-
console.log(
|
|
1001
|
+
console.log(import_chalk6.default.blue("\u{1F44B} Kopynator CLI - Comandos disponibles:\n"));
|
|
701
1002
|
program.outputHelp();
|
|
702
1003
|
});
|
|
703
1004
|
program.parse(process.argv);
|