@kopynator/cli 1.5.1 → 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 +316 -95
- package/package.json +1 -1
- package/src/commands/check.ts +118 -10
- package/src/commands/sync.ts +1 -48
- package/src/index.ts +5 -2
- package/src/lib/i18n-guardian.ts +190 -0
- package/src/lib/project.ts +60 -0
package/README.md
CHANGED
|
@@ -3,7 +3,13 @@
|
|
|
3
3
|
The official Command Line Interface for [Kopynator](https://kopynator.com).
|
|
4
4
|
Manage your internationalization workflow directly from your terminal.
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
**Languages / Idiomas:** [English](#english) · [Español](#español)
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## English
|
|
11
|
+
|
|
12
|
+
### Installation
|
|
7
13
|
|
|
8
14
|
You don't need to install it globally! We recommend using `npx` for the latest version:
|
|
9
15
|
|
|
@@ -17,33 +23,67 @@ If you prefer a global installation:
|
|
|
17
23
|
npm install -g @kopynator/cli
|
|
18
24
|
```
|
|
19
25
|
|
|
20
|
-
|
|
26
|
+
### Commands
|
|
21
27
|
|
|
22
|
-
|
|
23
|
-
|
|
28
|
+
| Command | What it does |
|
|
29
|
+
| --- | --- |
|
|
30
|
+
| [`init`](#1-init) | Sets up Kopynator in your project (framework detection, config injection). |
|
|
31
|
+
| [`check`](#2-check) | Validates local translation files: JSON syntax, broken references, duplicate global keys. |
|
|
32
|
+
| [`sync`](#3-sync) | Downloads translations from Kopynator Cloud into local JSON files. |
|
|
33
|
+
| [`upload`](#4-upload) | Uploads a local JSON file to Kopynator Cloud. |
|
|
34
|
+
| [`limits`](#5-limits) | Shows your plan's limits and current usage. |
|
|
35
|
+
| [`help`](#6-help) | Prints help for all commands. |
|
|
36
|
+
|
|
37
|
+
#### 1. `init`
|
|
38
|
+
Sets up Kopynator in your project. Auto-detects your framework (Angular, React, Vue, React Native, Ionic) and either injects `provideKopynator(...)` directly into your app config, or falls back to creating a `kopynator.config.json` file. Interactively asks for your default locale and supported languages.
|
|
24
39
|
|
|
25
40
|
```bash
|
|
26
41
|
npx -y @kopynator/cli init
|
|
27
42
|
```
|
|
28
43
|
|
|
29
|
-
|
|
30
|
-
Validates your local
|
|
44
|
+
#### 2. `check`
|
|
45
|
+
Validates your local translation files. Three things, in order:
|
|
46
|
+
|
|
47
|
+
1. **JSON syntax** — every locale file must parse.
|
|
48
|
+
2. **Broken references** — translation keys used in your source code (`| kopy`, `[kopy]="'...'"`, `.translate()`/`.t()`) that don't exist in *any* locale file.
|
|
49
|
+
3. **Duplicate global keys** — keys whose value duplicates an existing `global.*` key, so your team converges on one canonical key instead of silently drifting into copies.
|
|
50
|
+
|
|
51
|
+
Useful for CI/CD pipelines and pre-commit hooks — it exits with a non-zero code on failure.
|
|
31
52
|
|
|
32
53
|
```bash
|
|
33
54
|
npx -y @kopynator/cli check
|
|
34
55
|
```
|
|
35
56
|
|
|
36
|
-
|
|
37
|
-
|
|
57
|
+
Flags:
|
|
58
|
+
- `--base-ref <ref>` — git ref to diff against when deciding which duplicate keys are *new* (default: `master`). Duplicates that already existed at that ref aren't re-flagged, so adopting `check` doesn't force you to clean up all pre-existing debt at once.
|
|
59
|
+
- `--update-baseline` — accepts every currently-missing key as backlog, writing `kopynator.i18n-baseline.json`. From then on, `check` only fails on keys that go missing *after* that point.
|
|
60
|
+
- `--all` — lists every missing key (baseline + new), tagging which ones are already accepted.
|
|
61
|
+
|
|
62
|
+
Two optional project-root config files:
|
|
63
|
+
- `kopynator.i18n-baseline.json` — `{ "keys": [...] }`, written automatically by `--update-baseline`.
|
|
64
|
+
- `kopynator.i18n-safelist.json` — `{ "dynamicPrefixes": ["status."] }`. Protects key families built dynamically at runtime (e.g. `` `status.${s}` ``) from being flagged as missing. You can also declare a prefix inline, right next to the code that uses it, with a comment: `// kopynator-keys: status.*`.
|
|
65
|
+
|
|
66
|
+
Set `KOPYNATOR_I18N_SKIP=1` to bypass the check entirely (e.g. an emergency commit).
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
# CI example: only fail on regressions since main
|
|
70
|
+
npx -y @kopynator/cli check --base-ref origin/main
|
|
71
|
+
|
|
72
|
+
# Adopt the check on a legacy project without a big-bang cleanup
|
|
73
|
+
npx -y @kopynator/cli check --update-baseline
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
#### 3. `sync`
|
|
77
|
+
Downloads translations from the Kopynator Cloud and saves them as local JSON files (e.g. `src/assets/i18n/en.json`). On first run it asks how you want the output formatted (nested vs. flat keys, pretty-print, indentation) and remembers your choice in `kopynator.sync.config.json`.
|
|
38
78
|
|
|
39
79
|
```bash
|
|
40
80
|
npx -y @kopynator/cli sync
|
|
41
81
|
```
|
|
42
82
|
|
|
43
|
-
|
|
44
|
-
Uploads a JSON translation file to the Kopynator Cloud. Keys are merged/updated for the given language.
|
|
83
|
+
#### 4. `upload`
|
|
84
|
+
Uploads a JSON translation file to the Kopynator Cloud. Keys are merged/updated for the given language. Uses the same API key (token) as your app or `kopynator.config.json`.
|
|
45
85
|
|
|
46
|
-
**Project:**
|
|
86
|
+
**Project:** the target project is determined by the token. Each token is linked to one project when created in [Dashboard → Settings → Tokens](https://www.kopynator.com/dashboard/settings/tokens). To upload to a different project, use that project's token.
|
|
47
87
|
|
|
48
88
|
```bash
|
|
49
89
|
# Language inferred from filename (es.json → es)
|
|
@@ -55,8 +95,140 @@ npx -y @kopynator/cli upload --file=locales/en.json --lang=en
|
|
|
55
95
|
|
|
56
96
|
After uploading, run `sync` to download the latest state from the cloud if needed.
|
|
57
97
|
|
|
58
|
-
|
|
59
|
-
|
|
98
|
+
#### 5. `limits`
|
|
99
|
+
Shows your current plan, and per-organization limits and usage (projects, translation keys, members). Reads the same API key resolution as `sync`/`upload` (`kopynator.config.json`, `app.config.ts`/`app.module.ts`, or `KOPYNATOR_API_KEY`).
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
npx -y @kopynator/cli limits
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
#### 6. `help`
|
|
106
|
+
Prints help for every command.
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
npx -y @kopynator/cli help
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Configuration
|
|
113
|
+
The `init` command creates a `kopynator.config.json` file in your root (used as a fallback when it can't inject config directly into your app):
|
|
114
|
+
|
|
115
|
+
```json
|
|
116
|
+
{
|
|
117
|
+
"apiKey": "YOUR_API_KEY",
|
|
118
|
+
"defaultLocale": "en",
|
|
119
|
+
"languages": ["en", "es"],
|
|
120
|
+
"mode": "local"
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
For CI environments without a config file, set `KOPYNATOR_API_KEY` (and optionally `KOPYNATOR_BASE_URL`) instead.
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## Español
|
|
129
|
+
|
|
130
|
+
### Instalación
|
|
131
|
+
|
|
132
|
+
No hace falta instalarlo globalmente. Recomendamos usar `npx` para tener siempre la última versión:
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
npx -y @kopynator/cli <comando>
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Si prefieres instalarlo de forma global:
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
npm install -g @kopynator/cli
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Comandos
|
|
145
|
+
|
|
146
|
+
| Comando | Qué hace |
|
|
147
|
+
| --- | --- |
|
|
148
|
+
| [`init`](#1-init-1) | Configura Kopynator en tu proyecto (detecta el framework e inyecta la configuración). |
|
|
149
|
+
| [`check`](#2-check-1) | Valida los ficheros de traducción locales: sintaxis JSON, referencias rotas, claves globales duplicadas. |
|
|
150
|
+
| [`sync`](#3-sync-1) | Descarga las traducciones de Kopynator Cloud a ficheros JSON locales. |
|
|
151
|
+
| [`upload`](#4-upload-1) | Sube un fichero JSON local a Kopynator Cloud. |
|
|
152
|
+
| [`limits`](#5-limits-1) | Muestra los límites de tu plan y el uso actual. |
|
|
153
|
+
| [`help`](#6-help-1) | Muestra la ayuda de todos los comandos. |
|
|
154
|
+
|
|
155
|
+
#### 1. `init`
|
|
156
|
+
Configura Kopynator en tu proyecto. Detecta automáticamente el framework (Angular, React, Vue, React Native, Ionic) e inyecta `provideKopynator(...)` directamente en la configuración de tu app, o crea un `kopynator.config.json` si no puede hacerlo. Te pregunta interactivamente el idioma por defecto y los idiomas que quieres soportar.
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
npx -y @kopynator/cli init
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
#### 2. `check`
|
|
163
|
+
Valida tus ficheros de traducción locales. Comprueba tres cosas, en este orden:
|
|
164
|
+
|
|
165
|
+
1. **Sintaxis JSON** — todos los ficheros de idioma deben parsear correctamente.
|
|
166
|
+
2. **Referencias rotas** — claves de traducción usadas en tu código (`| kopy`, `[kopy]="'...'"`, `.translate()`/`.t()`) que no existen en *ningún* fichero de idioma.
|
|
167
|
+
3. **Claves globales duplicadas** — claves cuyo valor duplica el de una clave `global.*` ya existente, para que el equipo converja en una única clave canónica en vez de ir creando copias sin darse cuenta.
|
|
168
|
+
|
|
169
|
+
Útil en pipelines de CI/CD y hooks de pre-commit — termina con código de salida distinto de cero si falla.
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
npx -y @kopynator/cli check
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Flags:
|
|
176
|
+
- `--base-ref <ref>` — referencia git contra la que comparar para decidir qué claves duplicadas son *nuevas* (por defecto: `master`). Los duplicados que ya existían en esa referencia no se vuelven a marcar, así que adoptar `check` no obliga a limpiar toda la deuda existente de golpe.
|
|
177
|
+
- `--update-baseline` — acepta todas las claves actualmente rotas como deuda pendiente, escribiendo `kopynator.i18n-baseline.json`. A partir de ahí, `check` solo falla con claves que se rompan *después* de ese punto.
|
|
178
|
+
- `--all` — lista todas las claves rotas (aceptadas + nuevas), indicando cuáles ya están aceptadas.
|
|
179
|
+
|
|
180
|
+
Dos ficheros de configuración opcionales en la raíz del proyecto:
|
|
181
|
+
- `kopynator.i18n-baseline.json` — `{ "keys": [...] }`, se escribe automáticamente con `--update-baseline`.
|
|
182
|
+
- `kopynator.i18n-safelist.json` — `{ "dynamicPrefixes": ["status."] }`. Protege familias de claves construidas dinámicamente en tiempo de ejecución (p. ej. `` `status.${s}` ``) para que no se marquen como rotas. También puedes declarar un prefijo en línea, junto al código que lo usa, con un comentario: `// kopynator-keys: status.*`.
|
|
183
|
+
|
|
184
|
+
Define `KOPYNATOR_I18N_SKIP=1` para saltarte el check por completo (p. ej. un commit de emergencia).
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
# Ejemplo de CI: solo falla con regresiones desde main
|
|
188
|
+
npx -y @kopynator/cli check --base-ref origin/main
|
|
189
|
+
|
|
190
|
+
# Adoptar el check en un proyecto legacy sin limpieza masiva previa
|
|
191
|
+
npx -y @kopynator/cli check --update-baseline
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
#### 3. `sync`
|
|
195
|
+
Descarga las traducciones de Kopynator Cloud y las guarda como ficheros JSON locales (p. ej. `src/assets/i18n/en.json`). La primera vez te pregunta cómo quieres el formato de salida (claves anidadas o planas, formato legible, indentación) y recuerda tu elección en `kopynator.sync.config.json`.
|
|
196
|
+
|
|
197
|
+
```bash
|
|
198
|
+
npx -y @kopynator/cli sync
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
#### 4. `upload`
|
|
202
|
+
Sube un fichero JSON de traducción a Kopynator Cloud. Las claves se fusionan/actualizan para el idioma indicado. Usa la misma API key (token) que tu app o `kopynator.config.json`.
|
|
203
|
+
|
|
204
|
+
**Proyecto:** el proyecto de destino lo determina el token. Cada token está vinculado a un proyecto al crearse en [Dashboard → Settings → Tokens](https://www.kopynator.com/dashboard/settings/tokens). Para subir a otro proyecto, usa el token de ese proyecto.
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
# Idioma inferido del nombre del fichero (es.json → es)
|
|
208
|
+
npx -y @kopynator/cli upload --file=src/assets/i18n/es.json
|
|
209
|
+
|
|
210
|
+
# Idioma explícito
|
|
211
|
+
npx -y @kopynator/cli upload --file=locales/en.json --lang=en
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Después de subir, ejecuta `sync` si necesitas descargar el estado más reciente de la nube.
|
|
215
|
+
|
|
216
|
+
#### 5. `limits`
|
|
217
|
+
Muestra tu plan actual y los límites y uso por organización (proyectos, claves de traducción, miembros). Resuelve la API key igual que `sync`/`upload` (`kopynator.config.json`, `app.config.ts`/`app.module.ts`, o `KOPYNATOR_API_KEY`).
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
npx -y @kopynator/cli limits
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
#### 6. `help`
|
|
224
|
+
Muestra la ayuda de todos los comandos.
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
npx -y @kopynator/cli help
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
### Configuración
|
|
231
|
+
El comando `init` crea un fichero `kopynator.config.json` en la raíz (se usa como alternativa cuando no puede inyectar la configuración directamente en tu app):
|
|
60
232
|
|
|
61
233
|
```json
|
|
62
234
|
{
|
|
@@ -66,3 +238,5 @@ The `init` command creates a `kopynator.config.json` file in your root:
|
|
|
66
238
|
"mode": "local"
|
|
67
239
|
}
|
|
68
240
|
```
|
|
241
|
+
|
|
242
|
+
Para entornos de CI sin fichero de configuración, define `KOPYNATOR_API_KEY` (y opcionalmente `KOPYNATOR_BASE_URL`).
|
package/dist/index.js
CHANGED
|
@@ -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) {
|
|
@@ -691,14 +912,14 @@ async function uploadCommand(options) {
|
|
|
691
912
|
|
|
692
913
|
// src/commands/limits.ts
|
|
693
914
|
var import_chalk5 = __toESM(require("chalk"));
|
|
694
|
-
var
|
|
695
|
-
var
|
|
915
|
+
var import_fs7 = __toESM(require("fs"));
|
|
916
|
+
var import_path7 = __toESM(require("path"));
|
|
696
917
|
function resolveApiKey() {
|
|
697
918
|
const cwd = process.cwd();
|
|
698
919
|
const fromJson = (p) => {
|
|
699
920
|
try {
|
|
700
|
-
if (
|
|
701
|
-
const cfg = JSON.parse(
|
|
921
|
+
if (import_fs7.default.existsSync(p)) {
|
|
922
|
+
const cfg = JSON.parse(import_fs7.default.readFileSync(p, "utf-8"));
|
|
702
923
|
if (cfg && cfg.apiKey) return { apiKey: cfg.apiKey, baseUrl: cfg.baseUrl };
|
|
703
924
|
}
|
|
704
925
|
} catch {
|
|
@@ -707,8 +928,8 @@ function resolveApiKey() {
|
|
|
707
928
|
};
|
|
708
929
|
const fromAppFile = (p) => {
|
|
709
930
|
try {
|
|
710
|
-
if (
|
|
711
|
-
const content =
|
|
931
|
+
if (import_fs7.default.existsSync(p)) {
|
|
932
|
+
const content = import_fs7.default.readFileSync(p, "utf-8");
|
|
712
933
|
const match = content.match(/apiKey:\s*['"]([^'"]+)['"]/);
|
|
713
934
|
if (match) return { apiKey: match[1] };
|
|
714
935
|
}
|
|
@@ -716,7 +937,7 @@ function resolveApiKey() {
|
|
|
716
937
|
}
|
|
717
938
|
return null;
|
|
718
939
|
};
|
|
719
|
-
return fromJson(
|
|
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);
|
|
720
941
|
}
|
|
721
942
|
function formatLimit(value) {
|
|
722
943
|
return value === -1 ? "Unlimited" : String(value);
|
|
@@ -772,7 +993,7 @@ async function limitsCommand() {
|
|
|
772
993
|
var program = new import_commander.Command();
|
|
773
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"));
|
|
774
995
|
program.command("init").description("Initialize Kopynator in your project").action(initCommand);
|
|
775
|
-
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 }));
|
|
776
997
|
program.command("sync").description("Sync your translations with the Kopynator Cloud").action(syncCommand);
|
|
777
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 }));
|
|
778
999
|
program.command("limits").description("Show your plan limits and current usage (projects, keys, members)").action(limitsCommand);
|
package/package.json
CHANGED
package/src/commands/check.ts
CHANGED
|
@@ -1,43 +1,151 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
|
+
import { detectFramework, getSourceRoot, getTranslationDir } from '../lib/project';
|
|
5
|
+
import {
|
|
6
|
+
findGlobalDuplicates,
|
|
7
|
+
flatten,
|
|
8
|
+
gitShowFile,
|
|
9
|
+
isProtectedByPrefix,
|
|
10
|
+
loadBaseline,
|
|
11
|
+
loadSafelist,
|
|
12
|
+
saveBaseline,
|
|
13
|
+
scanUsedKeys,
|
|
14
|
+
walkSourceFiles,
|
|
15
|
+
} from '../lib/i18n-guardian';
|
|
16
|
+
|
|
17
|
+
export interface CheckOptions {
|
|
18
|
+
baseRef?: string;
|
|
19
|
+
updateBaseline?: boolean;
|
|
20
|
+
all?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function checkCommand(opts: CheckOptions = {}) {
|
|
24
|
+
if (process.env.KOPYNATOR_I18N_SKIP === '1') {
|
|
25
|
+
console.log(chalk.yellow('⚠️ KOPYNATOR_I18N_SKIP=1 — skipping i18n check.'));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
4
28
|
|
|
5
|
-
export async function checkCommand() {
|
|
6
29
|
console.log(chalk.bold.blue('\n🔍 Validating JSON translation files...\n'));
|
|
7
30
|
|
|
8
|
-
const
|
|
31
|
+
const cwd = process.cwd();
|
|
32
|
+
const framework = detectFramework();
|
|
33
|
+
const assetsDir = getTranslationDir(framework);
|
|
9
34
|
|
|
10
35
|
if (!fs.existsSync(assetsDir)) {
|
|
11
36
|
console.log(chalk.red(`❌ Could not find directory: ${assetsDir}`));
|
|
12
37
|
console.log(chalk.yellow('Make sure you are running this from your project root.'));
|
|
13
|
-
|
|
38
|
+
process.exit(1);
|
|
14
39
|
}
|
|
15
40
|
|
|
16
41
|
const files = fs.readdirSync(assetsDir).filter(f => f.endsWith('.json'));
|
|
17
42
|
|
|
18
43
|
if (files.length === 0) {
|
|
19
|
-
console.log(chalk.yellow('⚠️ No JSON files found in
|
|
44
|
+
console.log(chalk.yellow('⚠️ No JSON files found in ' + assetsDir + '.'));
|
|
20
45
|
return;
|
|
21
46
|
}
|
|
22
47
|
|
|
23
|
-
let
|
|
48
|
+
let hasJsonErrors = false;
|
|
49
|
+
const parsed: Record<string, any> = {};
|
|
24
50
|
|
|
25
51
|
files.forEach(file => {
|
|
26
52
|
try {
|
|
27
53
|
const content = fs.readFileSync(path.join(assetsDir, file), 'utf-8');
|
|
28
|
-
JSON.parse(content);
|
|
54
|
+
parsed[file] = JSON.parse(content);
|
|
29
55
|
console.log(chalk.green(`✓ ${file} is valid JSON.`));
|
|
30
56
|
} catch (e: any) {
|
|
31
|
-
|
|
57
|
+
hasJsonErrors = true;
|
|
32
58
|
console.log(chalk.red(`❌ ${file} has syntax errors:`));
|
|
33
59
|
console.log(chalk.red(` ${e.message}`));
|
|
34
60
|
}
|
|
35
61
|
});
|
|
36
62
|
|
|
37
|
-
if (
|
|
63
|
+
if (hasJsonErrors) {
|
|
38
64
|
console.log(chalk.red('\n💥 Validation failed. Please fix the errors above.'));
|
|
39
65
|
process.exit(1);
|
|
40
|
-
} else {
|
|
41
|
-
console.log(chalk.bold.green('\n✨ All files are valid! You are ready to go.'));
|
|
42
66
|
}
|
|
67
|
+
|
|
68
|
+
console.log(chalk.bold.blue('\n🛡️ Guarding against broken references and duplicate keys...\n'));
|
|
69
|
+
|
|
70
|
+
// Defined keys: union across every locale file (a key only needs to exist somewhere).
|
|
71
|
+
const definedKeys = new Set<string>();
|
|
72
|
+
for (const file of files) {
|
|
73
|
+
Object.keys(flatten(parsed[file])).forEach(k => definedKeys.add(k));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Reference locale for value-based duplicate detection: prefer en.json, else first alphabetically.
|
|
77
|
+
const refFile = files.includes('en.json') ? 'en.json' : files.sort()[0];
|
|
78
|
+
const refValues = flatten(parsed[refFile]);
|
|
79
|
+
|
|
80
|
+
// Scan app source for key usage + inline `kopynator-keys: prefix.*` declarations.
|
|
81
|
+
const sourceRoot = getSourceRoot(framework);
|
|
82
|
+
const sourceFiles = walkSourceFiles(sourceRoot);
|
|
83
|
+
const { used, dynamicPrefixes: magicPrefixes } = scanUsedKeys(sourceFiles);
|
|
84
|
+
|
|
85
|
+
const safelist = loadSafelist(cwd);
|
|
86
|
+
const protectedPrefixes = new Set([...(safelist.dynamicPrefixes || []), ...magicPrefixes]);
|
|
87
|
+
|
|
88
|
+
// --- Broken references: used in code, not defined in any locale file ---
|
|
89
|
+
const missing = [...used.keys()]
|
|
90
|
+
.filter(k => !definedKeys.has(k))
|
|
91
|
+
.filter(k => !isProtectedByPrefix(k, protectedPrefixes));
|
|
92
|
+
|
|
93
|
+
const baseline = loadBaseline(cwd);
|
|
94
|
+
const baselineSet = new Set(baseline.keys);
|
|
95
|
+
const freshMissing = missing.filter(k => !baselineSet.has(k));
|
|
96
|
+
const staleBaseline = baseline.keys.filter(k => !missing.includes(k));
|
|
97
|
+
|
|
98
|
+
if (opts.updateBaseline) {
|
|
99
|
+
saveBaseline(cwd, missing);
|
|
100
|
+
console.log(chalk.green(`✅ Baseline updated: ${missing.length} accepted missing key(s) written to kopynator.i18n-baseline.json`));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (opts.all) {
|
|
105
|
+
console.log(chalk.bold(`\nAll missing keys (${missing.length}):`));
|
|
106
|
+
missing
|
|
107
|
+
.slice()
|
|
108
|
+
.sort()
|
|
109
|
+
.forEach(k => {
|
|
110
|
+
const tag = baselineSet.has(k) ? chalk.gray('[baseline]') : chalk.red('[NEW]');
|
|
111
|
+
console.log(` ${tag} ${k} ${chalk.gray(`(used ${used.get(k)}x)`)}`);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// --- Duplicate-of-global values: only flag keys that are new since the base ref ---
|
|
116
|
+
const baseRef = opts.baseRef || 'master';
|
|
117
|
+
const oldRefContent = gitShowFile(cwd, baseRef, path.relative(cwd, path.join(assetsDir, refFile)));
|
|
118
|
+
const oldRefValues = oldRefContent ? flatten(JSON.parse(oldRefContent)) : {};
|
|
119
|
+
const duplicates = findGlobalDuplicates(refValues, new Set(used.keys())).filter(
|
|
120
|
+
d => oldRefValues[d.key] === undefined || oldRefValues[d.key] !== refValues[d.key]
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
let hasFailures = false;
|
|
124
|
+
|
|
125
|
+
if (freshMissing.length) {
|
|
126
|
+
hasFailures = true;
|
|
127
|
+
console.log(chalk.red(`\n❌ ${freshMissing.length} translation key(s) used in code but missing from ${assetsDir}:`));
|
|
128
|
+
freshMissing.sort().forEach(k => console.log(chalk.red(` - ${k} ${chalk.gray(`(used ${used.get(k)}x)`)}`)));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (duplicates.length) {
|
|
132
|
+
hasFailures = true;
|
|
133
|
+
console.log(chalk.red(`\n❌ ${duplicates.length} key(s) duplicate an existing global value:`));
|
|
134
|
+
duplicates.forEach(d =>
|
|
135
|
+
console.log(chalk.red(` - "${d.key}" duplicates "${d.canonical}"${d.canonicalIsNew ? chalk.gray(' (not created yet — proposed)') : ''} → "${d.value}"`))
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (staleBaseline.length) {
|
|
140
|
+
console.log(
|
|
141
|
+
chalk.blue(`\nℹ️ i18n: ${staleBaseline.length} baseline key(s) no longer missing; regenerate: kopynator check --update-baseline`)
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (hasFailures) {
|
|
146
|
+
console.log(chalk.red('\n💥 i18n check failed. Fix the issues above, or run with --update-baseline to accept current debt.'));
|
|
147
|
+
process.exit(1);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
console.log(chalk.bold.green(`\n✨ i18n check passed (${files.length} locale file(s); baseline=${baselineSet.size}; scanned ${sourceFiles.length} source file(s)).`));
|
|
43
151
|
}
|
package/src/commands/sync.ts
CHANGED
|
@@ -3,6 +3,7 @@ import fs from 'fs';
|
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import inquirer from 'inquirer';
|
|
5
5
|
import ora from 'ora';
|
|
6
|
+
import { detectFramework, getTranslationDir } from '../lib/project';
|
|
6
7
|
|
|
7
8
|
interface KopyConfig {
|
|
8
9
|
apiKey: string;
|
|
@@ -16,54 +17,6 @@ interface SyncConfig {
|
|
|
16
17
|
indent: '2' | '4' | 'tab';
|
|
17
18
|
}
|
|
18
19
|
|
|
19
|
-
/**
|
|
20
|
-
* Detect the framework being used in the current project
|
|
21
|
-
*/
|
|
22
|
-
function detectFramework(): 'Angular' | 'React' | 'Vue' | 'Other' {
|
|
23
|
-
const angularJson = path.join(process.cwd(), 'angular.json');
|
|
24
|
-
const packageJson = path.join(process.cwd(), 'package.json');
|
|
25
|
-
|
|
26
|
-
// Check for Angular
|
|
27
|
-
if (fs.existsSync(angularJson)) {
|
|
28
|
-
return 'Angular';
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// Check package.json for React/Vue
|
|
32
|
-
if (fs.existsSync(packageJson)) {
|
|
33
|
-
try {
|
|
34
|
-
const pkg = JSON.parse(fs.readFileSync(packageJson, 'utf-8'));
|
|
35
|
-
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
36
|
-
|
|
37
|
-
if (deps['@angular/core']) return 'Angular';
|
|
38
|
-
if (deps['react']) return 'React';
|
|
39
|
-
if (deps['vue']) return 'Vue';
|
|
40
|
-
} catch (e) {
|
|
41
|
-
// Ignore parse errors
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
return 'Other';
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Get the translation directory path based on framework
|
|
50
|
-
*/
|
|
51
|
-
function getTranslationDir(framework: string): string {
|
|
52
|
-
switch (framework) {
|
|
53
|
-
case 'Angular':
|
|
54
|
-
return path.join(process.cwd(), 'src/assets/i18n');
|
|
55
|
-
case 'React':
|
|
56
|
-
// Common React patterns, can be customized later
|
|
57
|
-
return path.join(process.cwd(), 'public/locales');
|
|
58
|
-
case 'Vue':
|
|
59
|
-
// Common Vue patterns, can be customized later
|
|
60
|
-
return path.join(process.cwd(), 'public/locales');
|
|
61
|
-
default:
|
|
62
|
-
// Default fallback
|
|
63
|
-
return path.join(process.cwd(), 'locales');
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
20
|
/**
|
|
68
21
|
* API key del proyecto primero (no hace falta en el comando), luego env para CI.
|
|
69
22
|
* Order: app.config.ts -> app.module.ts -> kopynator.config.json -> KOPYNATOR_API_KEY
|
package/src/index.ts
CHANGED
|
@@ -19,8 +19,11 @@ program
|
|
|
19
19
|
|
|
20
20
|
program
|
|
21
21
|
.command('check')
|
|
22
|
-
.description('Validate
|
|
23
|
-
.
|
|
22
|
+
.description('Validate translation files: JSON syntax, broken references and duplicate global keys')
|
|
23
|
+
.option('--base-ref <ref>', 'Git ref to diff against when detecting new duplicate keys', 'master')
|
|
24
|
+
.option('--update-baseline', 'Accept all currently-missing keys as backlog (writes kopynator.i18n-baseline.json)')
|
|
25
|
+
.option('--all', 'List every missing key, including ones already accepted in the baseline')
|
|
26
|
+
.action((opts) => checkCommand({ baseRef: opts.baseRef, updateBaseline: opts.updateBaseline, all: opts.all }));
|
|
24
27
|
|
|
25
28
|
program
|
|
26
29
|
.command('sync')
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { execFileSync } from 'child_process';
|
|
4
|
+
|
|
5
|
+
export interface SafelistConfig {
|
|
6
|
+
dynamicPrefixes?: string[];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface BaselineConfig {
|
|
10
|
+
keys: string[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface UsedKey {
|
|
14
|
+
key: string;
|
|
15
|
+
count: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface DuplicateFinding {
|
|
19
|
+
key: string;
|
|
20
|
+
value: string;
|
|
21
|
+
canonical: string;
|
|
22
|
+
canonicalIsNew: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const SAFELIST_FILE = 'kopynator.i18n-safelist.json';
|
|
26
|
+
const BASELINE_FILE = 'kopynator.i18n-baseline.json';
|
|
27
|
+
const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.html', '.vue'];
|
|
28
|
+
const EXCLUDED_DIRS = new Set(['node_modules', 'dist', 'build', '.git', '.angular', 'coverage', '.next', '.nuxt', 'out']);
|
|
29
|
+
|
|
30
|
+
const KEY = `[\\w.:-]+`;
|
|
31
|
+
const USE_PATTERNS: { re: RegExp; group: number }[] = [
|
|
32
|
+
// {{ 'key' | kopy }} — Angular pipe
|
|
33
|
+
{ re: new RegExp(`(['"\`])(${KEY})\\1\\s*\\|\\s*kopy`, 'g'), group: 2 },
|
|
34
|
+
// [kopy]="'key'" — Angular directive with a string literal binding
|
|
35
|
+
{ re: new RegExp(`\\[kopy\\]\\s*=\\s*"'(${KEY})'"`, 'g'), group: 1 },
|
|
36
|
+
// .translate('key') / .t('key') — @kopynator/core & @kopynator/react API
|
|
37
|
+
{ re: new RegExp(`\\.(?:translate|t)\\(\\s*(['"\`])(${KEY})\\1`, 'g'), group: 2 },
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
const MAGIC_RE = /kopynator-keys\s*:\s*([^\n]+)/g;
|
|
41
|
+
|
|
42
|
+
/** Recursively flattens a nested translation object into dot-notation keys. */
|
|
43
|
+
export function flatten(obj: Record<string, any>, prefix = ''): Record<string, string> {
|
|
44
|
+
const out: Record<string, string> = {};
|
|
45
|
+
for (const [k, v] of Object.entries(obj || {})) {
|
|
46
|
+
const key = prefix ? `${prefix}.${k}` : k;
|
|
47
|
+
if (v && typeof v === 'object' && !Array.isArray(v)) {
|
|
48
|
+
Object.assign(out, flatten(v, key));
|
|
49
|
+
} else {
|
|
50
|
+
out[key] = String(v);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function walkSourceFiles(rootDir: string): string[] {
|
|
57
|
+
if (!fs.existsSync(rootDir)) return [];
|
|
58
|
+
const results: string[] = [];
|
|
59
|
+
|
|
60
|
+
function walk(dir: string) {
|
|
61
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
62
|
+
if (entry.isDirectory()) {
|
|
63
|
+
if (EXCLUDED_DIRS.has(entry.name)) continue;
|
|
64
|
+
walk(path.join(dir, entry.name));
|
|
65
|
+
} else if (SOURCE_EXTENSIONS.includes(path.extname(entry.name))) {
|
|
66
|
+
results.push(path.join(dir, entry.name));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
walk(rootDir);
|
|
72
|
+
return results;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Scans source files for translation key usage and inline `kopynator-keys:` dynamic-prefix declarations. */
|
|
76
|
+
export function scanUsedKeys(files: string[]): { used: Map<string, number>; dynamicPrefixes: Set<string> } {
|
|
77
|
+
const used = new Map<string, number>();
|
|
78
|
+
const dynamicPrefixes = new Set<string>();
|
|
79
|
+
|
|
80
|
+
for (const file of files) {
|
|
81
|
+
const content = fs.readFileSync(file, 'utf-8');
|
|
82
|
+
|
|
83
|
+
for (const { re, group } of USE_PATTERNS) {
|
|
84
|
+
re.lastIndex = 0;
|
|
85
|
+
let match: RegExpExecArray | null;
|
|
86
|
+
while ((match = re.exec(content))) {
|
|
87
|
+
const key = match[group];
|
|
88
|
+
used.set(key, (used.get(key) || 0) + 1);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
MAGIC_RE.lastIndex = 0;
|
|
93
|
+
let magicMatch: RegExpExecArray | null;
|
|
94
|
+
while ((magicMatch = MAGIC_RE.exec(content))) {
|
|
95
|
+
for (const raw of magicMatch[1].split(',')) {
|
|
96
|
+
const prefix = raw.trim().replace(/\*$/, '');
|
|
97
|
+
if (prefix) dynamicPrefixes.add(prefix);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { used, dynamicPrefixes };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function loadSafelist(cwd: string): SafelistConfig {
|
|
106
|
+
const p = path.join(cwd, SAFELIST_FILE);
|
|
107
|
+
if (!fs.existsSync(p)) return { dynamicPrefixes: [] };
|
|
108
|
+
try {
|
|
109
|
+
return JSON.parse(fs.readFileSync(p, 'utf-8'));
|
|
110
|
+
} catch {
|
|
111
|
+
return { dynamicPrefixes: [] };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function loadBaseline(cwd: string): BaselineConfig {
|
|
116
|
+
const p = path.join(cwd, BASELINE_FILE);
|
|
117
|
+
if (!fs.existsSync(p)) return { keys: [] };
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(fs.readFileSync(p, 'utf-8'));
|
|
120
|
+
return { keys: Array.isArray(parsed.keys) ? parsed.keys : [] };
|
|
121
|
+
} catch {
|
|
122
|
+
return { keys: [] };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function saveBaseline(cwd: string, keys: string[]): void {
|
|
127
|
+
const p = path.join(cwd, BASELINE_FILE);
|
|
128
|
+
fs.writeFileSync(p, JSON.stringify({ keys: keys.sort() }, null, 2) + '\n');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function isProtectedByPrefix(key: string, prefixes: Set<string> | string[]): boolean {
|
|
132
|
+
for (const prefix of prefixes) {
|
|
133
|
+
if (key.startsWith(prefix)) return true;
|
|
134
|
+
}
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Reads a file's content at a given git ref, or null if git/ref/file is unavailable. */
|
|
139
|
+
export function gitShowFile(cwd: string, ref: string, relPath: string): string | null {
|
|
140
|
+
try {
|
|
141
|
+
return execFileSync('git', ['show', `${ref}:${relPath}`], { cwd, stdio: ['pipe', 'pipe', 'ignore'] }).toString('utf-8');
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function slugify(value: string, maxLen = 40): string {
|
|
148
|
+
return String(value)
|
|
149
|
+
.replace(/<[^>]+>/g, '')
|
|
150
|
+
.replace(/\{\{[^}]+\}\}/g, '')
|
|
151
|
+
.normalize('NFD')
|
|
152
|
+
.replace(/[̀-ͯ]/g, '')
|
|
153
|
+
.toLowerCase()
|
|
154
|
+
.replace(/[^a-z0-9]+/g, '_')
|
|
155
|
+
.replace(/^_+|_+$/g, '')
|
|
156
|
+
.slice(0, maxLen) || 'value';
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Picks the canonical key among a group of keys sharing the same value: prefers a category-segmented `global.*` key, else the shortest `global.*`, else null (no existing canonical). */
|
|
160
|
+
export function pickGlobal(keys: string[]): string | null {
|
|
161
|
+
const globals = keys.filter(k => k.startsWith('global.'));
|
|
162
|
+
if (!globals.length) return null;
|
|
163
|
+
const segmented = globals.filter(k => /^global\.(status|error|action)\./.test(k));
|
|
164
|
+
const pool = segmented.length ? segmented : globals;
|
|
165
|
+
return pool.reduce((shortest, k) => (k.length < shortest.length ? k : shortest), pool[0]);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Finds keys whose value duplicates an existing (or proposable) `global.*` canonical, restricted to keys actually used in source. */
|
|
169
|
+
export function findGlobalDuplicates(values: Record<string, string>, usedKeys: Set<string>): DuplicateFinding[] {
|
|
170
|
+
const byValue = new Map<string, string[]>();
|
|
171
|
+
for (const [key, value] of Object.entries(values)) {
|
|
172
|
+
const trimmed = value.trim();
|
|
173
|
+
if (!trimmed) continue;
|
|
174
|
+
const group = byValue.get(trimmed) || [];
|
|
175
|
+
group.push(key);
|
|
176
|
+
byValue.set(trimmed, group);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const findings: DuplicateFinding[] = [];
|
|
180
|
+
for (const [value, keys] of byValue) {
|
|
181
|
+
if (keys.length < 2) continue;
|
|
182
|
+
const canonical = pickGlobal(keys) || `global.${slugify(value)}`;
|
|
183
|
+
for (const key of keys) {
|
|
184
|
+
if (key === canonical) continue;
|
|
185
|
+
if (!usedKeys.has(key)) continue;
|
|
186
|
+
findings.push({ key, value, canonical, canonicalIsNew: !keys.includes(canonical) });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return findings;
|
|
190
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
|
|
4
|
+
export type Framework = 'Angular' | 'React' | 'Vue' | 'Other';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Detect the framework being used in the current project
|
|
8
|
+
*/
|
|
9
|
+
export function detectFramework(): Framework {
|
|
10
|
+
const angularJson = path.join(process.cwd(), 'angular.json');
|
|
11
|
+
const packageJson = path.join(process.cwd(), 'package.json');
|
|
12
|
+
|
|
13
|
+
if (fs.existsSync(angularJson)) {
|
|
14
|
+
return 'Angular';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (fs.existsSync(packageJson)) {
|
|
18
|
+
try {
|
|
19
|
+
const pkg = JSON.parse(fs.readFileSync(packageJson, 'utf-8'));
|
|
20
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
21
|
+
|
|
22
|
+
if (deps['@angular/core']) return 'Angular';
|
|
23
|
+
if (deps['react']) return 'React';
|
|
24
|
+
if (deps['vue']) return 'Vue';
|
|
25
|
+
} catch (e) {
|
|
26
|
+
// Ignore parse errors
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return 'Other';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Get the translation directory path based on framework
|
|
35
|
+
*/
|
|
36
|
+
export function getTranslationDir(framework: Framework): string {
|
|
37
|
+
switch (framework) {
|
|
38
|
+
case 'Angular':
|
|
39
|
+
return path.join(process.cwd(), 'src/assets/i18n');
|
|
40
|
+
case 'React':
|
|
41
|
+
case 'Vue':
|
|
42
|
+
return path.join(process.cwd(), 'public/locales');
|
|
43
|
+
default:
|
|
44
|
+
return path.join(process.cwd(), 'locales');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Get the app source root to scan for translation key usage.
|
|
50
|
+
*/
|
|
51
|
+
export function getSourceRoot(framework: Framework): string {
|
|
52
|
+
switch (framework) {
|
|
53
|
+
case 'Angular':
|
|
54
|
+
case 'React':
|
|
55
|
+
case 'Vue':
|
|
56
|
+
return path.join(process.cwd(), 'src');
|
|
57
|
+
default:
|
|
58
|
+
return process.cwd();
|
|
59
|
+
}
|
|
60
|
+
}
|