i18n-ai-cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,498 @@
1
+ # i18n-ai-cli
2
+
3
+ AI-powered CLI tool for managing translation files in internationalized applications. Simplify your i18n workflow with automated key management, unused key detection, AI-powered translations via OpenAI, and flexible configuration.
4
+
5
+ ## Features
6
+
7
+ - **AI-Powered Translation**: Translate text using OpenAI GPT models with context-aware accuracy.
8
+ - **Language Management**: Add or remove locales with ease, with optional cloning from existing locales.
9
+ - **Key Management**: Add, update, or remove translation keys across all locales.
10
+ - **Cleanup**: Identify and remove unused translation keys by scanning source code.
11
+ - **Structural Validation**: Prevents conflicts between nested and flat key structures.
12
+ - **Dry Run**: Preview changes before they are applied.
13
+ - **CI Friendly**: Non-interactive mode with deterministic exit codes and fail-on-change semantics.
14
+ - **Auto Sort**: Automatically sorts keys in translation files.
15
+ - **Flexible Key Styles**: Support for both flat (`auth.login.title`) and nested (`auth: { login: { title: ... } }`) key styles.
16
+ - **Init Wizard**: Interactive configuration generator with sensible defaults.
17
+ - **ISO 639-1 Validation**: Validates language codes against the ISO 639-1 standard.
18
+ - **TypeScript**: Written in TypeScript with full type safety.
19
+
20
+ ## Installation
21
+
22
+ ### Global Installation
23
+
24
+ ```bash
25
+ npm install -g i18n-ai-cli
26
+ ```
27
+
28
+ ### Local Installation
29
+
30
+ ```bash
31
+ npm install --save-dev i18n-ai-cli
32
+ ```
33
+
34
+ Then use with `npx`:
35
+
36
+ ```bash
37
+ npx i18n-ai-cli --help
38
+ ```
39
+
40
+ ## Quick Start
41
+
42
+ ```bash
43
+ # Initialize configuration
44
+ i18n-ai-cli init
45
+
46
+ # Add a new language
47
+ i18n-ai-cli add:lang es --from en
48
+
49
+ # Add a translation key
50
+ i18n-ai-cli add:key welcome.message --value "Welcome to our app"
51
+
52
+ # Clean up unused keys
53
+ i18n-ai-cli clean:unused
54
+ ```
55
+
56
+ ## Configuration
57
+
58
+ Create an `i18n-cli.config.json` file in your project root:
59
+
60
+ ```bash
61
+ i18n-ai-cli init
62
+ ```
63
+
64
+ Or create it manually:
65
+
66
+ ```json
67
+ {
68
+ "localesPath": "./locales",
69
+ "defaultLocale": "en",
70
+ "supportedLocales": ["en", "es", "fr"],
71
+ "keyStyle": "nested",
72
+ "usagePatterns": [
73
+ "t\\(['\"](?<key>.*?)['\"]\\)",
74
+ "translate\\(['\"](?<key>.*?)['\"]\\)",
75
+ "i18n\\.t\\(['\"](?<key>.*?)['\"]\\)"
76
+ ],
77
+ "autoSort": true
78
+ }
79
+ ```
80
+
81
+ ### Configuration Options
82
+
83
+ | Option | Type | Required | Default | Description |
84
+ |--------|------|----------|---------|-------------|
85
+ | `localesPath` | `string` | Yes | - | Directory containing translation files |
86
+ | `defaultLocale` | `string` | Yes | - | Default language code (e.g., "en", "en-US") |
87
+ | `supportedLocales` | `string[]` | Yes | - | List of supported language codes |
88
+ | `keyStyle` | `"flat" \| "nested"` | No | `"nested"` | Key structure style |
89
+ | `usagePatterns` | `string[]` | No | `[]` | Regex patterns to detect key usage in source code (must include a capturing group) |
90
+ | `autoSort` | `boolean` | No | `true` | Automatically sort keys alphabetically |
91
+
92
+ ### Key Style Examples
93
+
94
+ **Nested style** (`auth.login.title`):
95
+ ```json
96
+ {
97
+ "auth": {
98
+ "login": {
99
+ "title": "Login"
100
+ }
101
+ }
102
+ }
103
+ ```
104
+
105
+ **Flat style** (`auth.login.title`):
106
+ ```json
107
+ {
108
+ "auth.login.title": "Login"
109
+ }
110
+ ```
111
+
112
+ ### Usage Patterns
113
+
114
+ The `usagePatterns` array contains regex patterns used by the `clean:unused` command to detect which translation keys are actively used in your source code. Patterns must include a capturing group for the key.
115
+
116
+ **Default patterns detect:**
117
+ - `t('key')` or `t("key")`
118
+ - `translate('key')` or `translate("key")`
119
+ - `i18n.t('key')` or `i18n.t("key")`
120
+
121
+ **Custom pattern with named group:**
122
+ ```json
123
+ {
124
+ "usagePatterns": [
125
+ "useTranslation\\(['\"](?<key>[^'\"]+)['\"]\\)"
126
+ ]
127
+ }
128
+ ```
129
+
130
+ ## Usage
131
+
132
+ ### Initialize configuration
133
+ ```bash
134
+ i18n-ai-cli init
135
+ ```
136
+
137
+ Options:
138
+ - `-f, --force`: Overwrite an existing config file
139
+
140
+ ### Language Commands
141
+
142
+ #### Add a new language
143
+ ```bash
144
+ i18n-ai-cli add:lang <lang-code> [--from <locale>] [--strict]
145
+ ```
146
+ Example: `i18n-ai-cli add:lang fr`
147
+
148
+ Options:
149
+ - `--from <locale>`: Clone translations from an existing locale
150
+ - `--strict`: Enable strict mode for additional validations
151
+
152
+ The language code is validated against ISO 639-1 standard (e.g., `en`, `es`, `fr` or `en-US`, `pt-BR`).
153
+
154
+ #### Remove a language
155
+ ```bash
156
+ i18n-ai-cli remove:lang <lang-code>
157
+ ```
158
+ Example: `i18n-ai-cli remove:lang fr`
159
+
160
+ ### Key Commands
161
+
162
+ #### Add a new translation key
163
+ ```bash
164
+ i18n-ai-cli add:key <key> --value <value>
165
+ ```
166
+ Example: `i18n-ai-cli add:key auth.login.title --value "Login"`
167
+
168
+ The key will be added to all locales with an empty string for non-default locales.
169
+
170
+ #### Update a translation key
171
+ ```bash
172
+ i18n-ai-cli update:key <key> --value <value> [--locale <locale>]
173
+ ```
174
+ Example: `i18n-ai-cli update:key auth.login.title --value "Sign In" --locale en`
175
+
176
+ If `--locale` is omitted, updates the default locale.
177
+
178
+ #### Remove a translation key
179
+ ```bash
180
+ i18n-ai-cli remove:key <key>
181
+ ```
182
+ Example: `i18n-ai-cli remove:key auth.login.title`
183
+
184
+ Removes the key from all locales.
185
+
186
+ ### Maintenance Commands
187
+
188
+ #### Clean unused keys
189
+ ```bash
190
+ i18n-ai-cli clean:unused
191
+ ```
192
+
193
+ Scans your source code (using patterns defined in `usagePatterns`) to identify translation keys that are no longer used and removes them from all locales.
194
+
195
+ **How it works:**
196
+ 1. Scans files in `src/**/*.{ts,tsx,js,jsx,html}`
197
+ 2. Matches patterns against file contents
198
+ 3. Compares found keys against your translation files
199
+ 4. Removes unused keys from all locales
200
+
201
+ **Note:** This command respects your `keyStyle` setting and will rebuild the structure accordingly.
202
+
203
+ ## Global Options
204
+
205
+ All commands support the following global options:
206
+
207
+ | Option | Description |
208
+ |--------|-------------|
209
+ | `-y, --yes` | Skip confirmation prompts |
210
+ | `--dry-run` | Preview changes without writing files |
211
+ | `--ci` | Run in CI mode (non-interactive; fails with exit code if changes would be made without `--yes`) |
212
+ | `-f, --force` | Force operation even if validation fails (used by `init` to overwrite config) |
213
+
214
+ ### Global Option Details
215
+
216
+ **Dry Run (`--dry-run`)**
217
+ Preview what changes would be made without actually modifying any files. Useful for reviewing changes before applying them.
218
+
219
+ ```bash
220
+ i18n-ai-cli clean:unused --dry-run
221
+ ```
222
+
223
+ **CI Mode (`--ci`)**
224
+ Runs in non-interactive mode suitable for CI/CD pipelines. If changes would be made, the command exits with an error code unless `--yes` is also provided.
225
+
226
+ ```bash
227
+ # Check for unused keys in CI (fails if any found)
228
+ i18n-ai-cli clean:unused --ci --dry-run
229
+
230
+ # Auto-remove unused keys in CI
231
+ i18n-ai-cli clean:unused --ci --yes
232
+ ```
233
+
234
+ **Skip Confirmation (`-y, --yes`)**
235
+ Automatically confirms all prompts without user interaction.
236
+
237
+ ```bash
238
+ i18n-ai-cli remove:key auth.legacy --yes
239
+ ```
240
+
241
+ ## Examples
242
+
243
+ ### Add a new locale with fallback content
244
+ ```bash
245
+ i18n-ai-cli add:lang de --from en
246
+ ```
247
+
248
+ ### Preview changes before applying
249
+ ```bash
250
+ i18n-ai-cli remove:key auth.legacy --dry-run
251
+ ```
252
+
253
+ ### Skip confirmation prompts
254
+ ```bash
255
+ i18n-ai-cli clean:unused --yes
256
+ ```
257
+
258
+ ### CI/CD integration
259
+ ```bash
260
+ i18n-ai-cli clean:unused --ci --dry-run
261
+ ```
262
+
263
+ To apply changes in CI:
264
+ ```bash
265
+ i18n-ai-cli clean:unused --ci --yes
266
+ ```
267
+
268
+ ### Initialize in non-interactive mode
269
+ ```bash
270
+ i18n-ai-cli init --yes
271
+ ```
272
+
273
+ ### Force overwrite existing config
274
+ ```bash
275
+ i18n-ai-cli init --force
276
+ ```
277
+
278
+ ## Translation Providers
279
+
280
+ i18n-ai-cli includes a flexible provider system for translation services. The following providers are available:
281
+
282
+ - **OpenAI** - AI-powered translation using GPT models (context-aware, high quality)
283
+ - **Google Translate** - Free translation via `@vitalets/google-translate-api`
284
+ - **DeepL** - Stub implementation (coming soon)
285
+
286
+ ### OpenAI Provider
287
+
288
+ The OpenAI provider uses GPT models to deliver context-aware, high-quality translations.
289
+
290
+ #### Getting an OpenAI API Key
291
+
292
+ 1. **Sign up for OpenAI**: Go to [platform.openai.com](https://platform.openai.com) and create an account
293
+ 2. **Navigate to API Keys**: Click on your profile → "View API Keys" or go to [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
294
+ 3. **Create a new key**: Click "Create new secret key", give it a name (e.g., "i18n-cli"), and copy the key
295
+ 4. **Secure your key**: Store it securely - you won't be able to see it again after closing the dialog
296
+
297
+ **Note**: OpenAI requires a valid payment method to use the API. New accounts may receive free credits to start.
298
+
299
+ #### Setup
300
+
301
+ Provide your OpenAI API key using one of these methods:
302
+
303
+ **Option 1: Environment variable (recommended for CLI usage)**
304
+ ```bash
305
+ export OPENAI_API_KEY=sk-your-api-key-here
306
+ ```
307
+
308
+ Or add it to your `.env` file in your project root:
309
+ ```
310
+ OPENAI_API_KEY=sk-your-api-key-here
311
+ ```
312
+
313
+ **Option 2: Constructor option (recommended for programmatic usage)**
314
+ ```typescript
315
+ const translator = new OpenAITranslator({
316
+ apiKey: 'sk-your-api-key-here'
317
+ });
318
+ ```
319
+
320
+ If both are set, the constructor option takes precedence over the environment variable.
321
+
322
+ **Security best practices:**
323
+ - Never commit your API key to version control
324
+ - Add `.env` to your `.gitignore` file
325
+ - Use environment variables in CI/CD pipelines
326
+ - Rotate keys periodically for security
327
+
328
+ #### Usage
329
+
330
+ **Basic translation example:**
331
+
332
+ ```typescript
333
+ import { TranslationService } from 'i18n-ai-cli/services';
334
+ import { OpenAITranslator } from 'i18n-ai-cli/providers';
335
+
336
+ // The API key will be read from OPENAI_API_KEY environment variable
337
+ const translator = new OpenAITranslator({
338
+ apiKey: 'sk-your-api-key-here', // or use OPENAI_API_KEY env var
339
+ model: 'gpt-3.5-turbo', // default model
340
+ });
341
+ const service = new TranslationService(translator);
342
+
343
+ const result = await service.translate({
344
+ text: 'Hello world',
345
+ targetLocale: 'es',
346
+ sourceLocale: 'en',
347
+ });
348
+
349
+ console.log(result.text); // "Hola mundo"
350
+ ```
351
+
352
+ **Using with CLI commands:**
353
+
354
+ When using the `add:lang` command with the `--from` option, the CLI can automatically translate all keys from your default locale:
355
+
356
+ ```bash
357
+ # Set your API key
358
+ export OPENAI_API_KEY=sk-your-api-key-here
359
+
360
+ # Add a new language with AI-powered translation
361
+ i18n-ai-cli add:lang fr --from en
362
+ ```
363
+
364
+ This will:
365
+ 1. Create a new translation file for French (`fr`)
366
+ 2. Copy all keys from the English (`en`) locale
367
+ 3. Automatically translate all values using OpenAI
368
+ 4. Save the translated content to the new locale file
369
+
370
+ #### Context-Aware Translation
371
+
372
+ Pass a `context` field to improve translation accuracy for ambiguous terms:
373
+
374
+ ```typescript
375
+ const result = await service.translate({
376
+ text: 'Bank',
377
+ targetLocale: 'es',
378
+ context: 'financial institution',
379
+ });
380
+ // Returns "Banco" (not "Orilla" which means riverbank)
381
+ ```
382
+
383
+ #### Options
384
+
385
+ | Option | Type | Default | Description |
386
+ |--------|------|---------|-------------|
387
+ | `apiKey` | `string` | `process.env.OPENAI_API_KEY` | OpenAI API key |
388
+ | `model` | `string` | `"gpt-3.5-turbo"` | GPT model to use |
389
+ | `baseUrl` | `string` | OpenAI default | Custom API base URL (for Azure OpenAI, local models, etc.) |
390
+
391
+ **Available models:**
392
+ - `gpt-4o` - Latest flagship model, best quality (recommended)
393
+ - `gpt-4o-mini` - Faster and more cost-effective
394
+ - `gpt-4-turbo` - Previous generation, high quality
395
+ - `gpt-3.5-turbo` - Default, fast and cost-effective
396
+
397
+ Choose a model based on your quality needs and budget. GPT-4 models provide better translation quality for complex or nuanced content.
398
+
399
+ #### Custom Endpoint
400
+
401
+ Use the `baseUrl` option to point to Azure OpenAI, a local LLM, or any OpenAI-compatible API:
402
+
403
+ ```typescript
404
+ const translator = new OpenAITranslator({
405
+ apiKey: 'your-key',
406
+ baseUrl: 'https://your-resource.openai.azure.com',
407
+ model: 'your-deployment-name',
408
+ });
409
+ ```
410
+
411
+ #### Troubleshooting
412
+
413
+ **Error: "OpenAI API key is required"**
414
+ - Ensure you've set the `OPENAI_API_KEY` environment variable or passed the `apiKey` option
415
+ - Verify the key starts with `sk-` (or `sk-proj-` for project keys)
416
+ - Check that there are no extra spaces or quotes around the key
417
+
418
+ **Error: "Incorrect API key provided"**
419
+ - Verify your API key is valid at [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
420
+ - Ensure you have billing set up at [platform.openai.com/settings/organization/billing/overview](https://platform.openai.com/settings/organization/billing/overview)
421
+ - Check if your API key has been revoked or expired
422
+
423
+ **Error: "Rate limit exceeded"**
424
+ - You're making too many requests too quickly
425
+ - Implement delays between requests or upgrade your OpenAI plan
426
+ - Consider using a less expensive model like `gpt-3.5-turbo` for bulk translations
427
+
428
+ **Error: "Model not found"**
429
+ - Verify the model name is correct (e.g., `gpt-4o`, not `gpt-4`)
430
+ - Check that your OpenAI account has access to the requested model
431
+ - Some models require specific permissions or higher tier access
432
+
433
+ **Poor translation quality**
434
+ - Use a more capable model like `gpt-4o` for better results
435
+ - Provide context using the `context` parameter for ambiguous terms
436
+ - Consider post-editing critical translations manually
437
+
438
+ ### Google Translate Provider
439
+
440
+ ```typescript
441
+ import { TranslationService } from 'i18n-ai-cli/services';
442
+ import { GoogleTranslator } from 'i18n-ai-cli/providers';
443
+
444
+ const translator = new GoogleTranslator();
445
+ const service = new TranslationService(translator);
446
+
447
+ const result = await service.translate({
448
+ text: "Hello world",
449
+ targetLocale: "es",
450
+ sourceLocale: "en"
451
+ });
452
+ ```
453
+
454
+ ## Programmatic API
455
+
456
+ You can also use i18n-ai-cli programmatically in your Node.js applications:
457
+
458
+ ```typescript
459
+ import { loadConfig } from 'i18n-ai-cli/config/config-loader';
460
+ import { FileManager } from 'i18n-ai-cli/core/file-manager';
461
+
462
+ const config = await loadConfig();
463
+ const fileManager = new FileManager(config);
464
+
465
+ // Read a locale
466
+ const enTranslations = await fileManager.readLocale('en');
467
+
468
+ // Write a locale
469
+ await fileManager.writeLocale('en', { greeting: 'Hello' }, { dryRun: false });
470
+ ```
471
+
472
+ ## Development
473
+
474
+ ### Prerequisites
475
+
476
+ - Node.js 18+
477
+ - npm or yarn
478
+
479
+ ### Build
480
+
481
+ ```bash
482
+ npm install
483
+ npm run build
484
+ ```
485
+
486
+ ### Local Testing
487
+
488
+ ```bash
489
+ # Link the package locally
490
+ npm link
491
+
492
+ # Use in another project
493
+ i18n-ai-cli --help
494
+ ```
495
+
496
+ ## License
497
+
498
+ ISC