i18next-cli 1.34.0 → 1.34.1

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.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/cli.js +271 -1
  3. package/dist/cjs/config.js +211 -1
  4. package/dist/cjs/extractor/core/ast-visitors.js +364 -1
  5. package/dist/cjs/extractor/core/extractor.js +245 -1
  6. package/dist/cjs/extractor/core/key-finder.js +132 -1
  7. package/dist/cjs/extractor/core/translation-manager.js +745 -1
  8. package/dist/cjs/extractor/parsers/ast-utils.js +85 -1
  9. package/dist/cjs/extractor/parsers/call-expression-handler.js +941 -1
  10. package/dist/cjs/extractor/parsers/comment-parser.js +375 -1
  11. package/dist/cjs/extractor/parsers/expression-resolver.js +362 -1
  12. package/dist/cjs/extractor/parsers/jsx-handler.js +492 -1
  13. package/dist/cjs/extractor/parsers/jsx-parser.js +355 -1
  14. package/dist/cjs/extractor/parsers/scope-manager.js +408 -1
  15. package/dist/cjs/extractor/plugin-manager.js +106 -1
  16. package/dist/cjs/heuristic-config.js +99 -1
  17. package/dist/cjs/index.js +28 -1
  18. package/dist/cjs/init.js +174 -1
  19. package/dist/cjs/linter.js +431 -1
  20. package/dist/cjs/locize.js +269 -1
  21. package/dist/cjs/migrator.js +196 -1
  22. package/dist/cjs/rename-key.js +354 -1
  23. package/dist/cjs/status.js +336 -1
  24. package/dist/cjs/syncer.js +120 -1
  25. package/dist/cjs/types-generator.js +165 -1
  26. package/dist/cjs/utils/default-value.js +43 -1
  27. package/dist/cjs/utils/file-utils.js +136 -1
  28. package/dist/cjs/utils/funnel-msg-tracker.js +75 -1
  29. package/dist/cjs/utils/logger.js +36 -1
  30. package/dist/cjs/utils/nested-object.js +124 -1
  31. package/dist/cjs/utils/validation.js +71 -1
  32. package/dist/esm/cli.js +269 -1
  33. package/dist/esm/config.js +206 -1
  34. package/dist/esm/extractor/core/ast-visitors.js +362 -1
  35. package/dist/esm/extractor/core/extractor.js +241 -1
  36. package/dist/esm/extractor/core/key-finder.js +130 -1
  37. package/dist/esm/extractor/core/translation-manager.js +743 -1
  38. package/dist/esm/extractor/parsers/ast-utils.js +80 -1
  39. package/dist/esm/extractor/parsers/call-expression-handler.js +939 -1
  40. package/dist/esm/extractor/parsers/comment-parser.js +373 -1
  41. package/dist/esm/extractor/parsers/expression-resolver.js +360 -1
  42. package/dist/esm/extractor/parsers/jsx-handler.js +490 -1
  43. package/dist/esm/extractor/parsers/jsx-parser.js +334 -1
  44. package/dist/esm/extractor/parsers/scope-manager.js +406 -1
  45. package/dist/esm/extractor/plugin-manager.js +103 -1
  46. package/dist/esm/heuristic-config.js +97 -1
  47. package/dist/esm/index.js +11 -1
  48. package/dist/esm/init.js +172 -1
  49. package/dist/esm/linter.js +425 -1
  50. package/dist/esm/locize.js +265 -1
  51. package/dist/esm/migrator.js +194 -1
  52. package/dist/esm/rename-key.js +352 -1
  53. package/dist/esm/status.js +334 -1
  54. package/dist/esm/syncer.js +118 -1
  55. package/dist/esm/types-generator.js +163 -1
  56. package/dist/esm/utils/default-value.js +41 -1
  57. package/dist/esm/utils/file-utils.js +131 -1
  58. package/dist/esm/utils/funnel-msg-tracker.js +72 -1
  59. package/dist/esm/utils/logger.js +34 -1
  60. package/dist/esm/utils/nested-object.js +120 -1
  61. package/dist/esm/utils/validation.js +68 -1
  62. package/package.json +2 -2
  63. package/types/locize.d.ts.map +1 -1
package/README.md CHANGED
@@ -1120,7 +1120,7 @@ This programmatic API gives you the same power as the CLI but with full control
1120
1120
 
1121
1121
  A translation management system built around the i18next ecosystem - [locize.com](https://www.locize.com).
1122
1122
 
1123
- ![locize](https://cdn.prod.website-files.com/67a323e323a50df7f24f0a6f/67b8bbb29365c3a3c21c0898_github_locize.png)
1123
+ ![locize](https://www.locize.com/img/ads/github_locize.png)
1124
1124
 
1125
1125
  With using [locize](https://locize.com/?utm_source=i18next_readme&utm_medium=github) you directly support the future of i18next.
1126
1126
 
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,272 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),o=require("chokidar"),t=require("glob"),n=require("minimatch"),i=require("chalk"),r=require("./config.js"),a=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("react"),require("react-i18next"),require("node:path"),require("node:fs/promises"),require("jiti"),require("@croct/json5-parser");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),d=require("./init.js"),p=require("./linter.js"),g=require("./status.js"),f=require("./locize.js"),y=require("./rename-key.js");const h=new e.Command;h.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.34.0"),h.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),h.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").option("--sync-all","Sync primary language values with default values from code AND clear synced keys in all other locales.").action(async e=>{try{const t=h.opts().config,i=await r.ensureConfig(t),a=async()=>{const o=!!e.syncPrimary||!!e.syncAll,t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:o,syncAll:!!e.syncAll});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await a(),e.watch){console.log("\nWatching for changes...");const e=await x(i.extract.input),t=m(i.extract.ignore),r=w(i.extract.output),c=[...t,...r].filter(Boolean),s=e.filter(e=>!c.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),h.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,o)=>{const t=h.opts().config;let n=await r.loadConfig(t);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:o.namespace})}),h.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const t=h.opts().config,i=await r.ensureConfig(t),a=()=>s.runTypesGenerator(i);if(await a(),e.watch){console.log("\nWatching for changes...");const e=await x(i.types?.input||[]),t=[...m(i.extract?.ignore)].filter(Boolean),r=e.filter(e=>!t.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(r,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),h.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=h.opts().config,o=await r.ensureConfig(e);await l.runSyncer(o)}),h.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),h.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(d.runInit),h.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const t=h.opts().config,c=async()=>{let e=await r.loadConfig(t);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const o=await a.detectConfig();o||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),e=o}await p.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await r.loadConfig(t);if(e?.extract?.input){const t=await x(e.extract.input),i=[...m(e.extract.ignore),...w(e.extract.output)].filter(Boolean),r=t.filter(e=>!i.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),h.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").option("--cdn-type <standard|pro>","Specify the cdn endpoint that should be used (depends on which cdn type you've in your locize project)").action(async e=>{const o=h.opts().config,t=await r.ensureConfig(o);await f.runLocizeSync(t,e)}),h.command("locize-download").description("Download all translations from your locize project.").option("--cdn-type <standard|pro>","Specify the cdn endpoint that should be used (depends on which cdn type you've in your locize project)").action(async e=>{const o=h.opts().config,t=await r.ensureConfig(o);await f.runLocizeDownload(t,e)}),h.command("locize-migrate").description("Migrate local translation files to a new locize project.").option("--cdn-type <standard|pro>","Specify the cdn endpoint that should be used (depends on which cdn type you've in your locize project)").action(async e=>{const o=h.opts().config,t=await r.ensureConfig(o);await f.runLocizeMigrate(t,e)}),h.command("rename-key <oldKey> <newKey>").description("Rename a translation key across all source files and translation files.").option("--dry-run","Preview changes without modifying files").action(async(e,o,t)=>{try{const n=h.opts().config,a=await r.ensureConfig(n),c=await y.runRenameKey(a,e,o,t);c.success||(c.conflicts&&(console.error(i.red("\n❌ Conflicts detected:")),c.conflicts.forEach(e=>console.error(` - ${e}`))),c.error&&console.error(i.red(`\n❌ ${c.error}`)),process.exit(1));0===c.sourceFiles.reduce((e,o)=>e+o.changes,0)&&console.log(i.yellow(`\n⚠️ No usages found for "${e}"`))}catch(e){console.error(i.red("Error renaming key:"),e),process.exit(1)}}),h.parse(process.argv);const m=e=>Array.isArray(e)?e:e?[e]:[],w=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],x=async(e=[])=>{const o=m(e),n=await Promise.all(o.map(e=>t.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};exports.program=h;
2
+ 'use strict';
3
+
4
+ var commander = require('commander');
5
+ var chokidar = require('chokidar');
6
+ var glob = require('glob');
7
+ var minimatch = require('minimatch');
8
+ var chalk = require('chalk');
9
+ var config = require('./config.js');
10
+ var heuristicConfig = require('./heuristic-config.js');
11
+ var extractor = require('./extractor/core/extractor.js');
12
+ require('react');
13
+ require('react-i18next');
14
+ require('node:path');
15
+ require('node:fs/promises');
16
+ require('jiti');
17
+ require('@croct/json5-parser');
18
+ var typesGenerator = require('./types-generator.js');
19
+ var syncer = require('./syncer.js');
20
+ var migrator = require('./migrator.js');
21
+ var init = require('./init.js');
22
+ var linter = require('./linter.js');
23
+ var status = require('./status.js');
24
+ var locize = require('./locize.js');
25
+ var renameKey = require('./rename-key.js');
26
+
27
+ const program = new commander.Command();
28
+ program
29
+ .name('i18next-cli')
30
+ .description('A unified, high-performance i18next CLI.')
31
+ .version('1.34.1'); // This string is replaced with the actual version at build time by rollup
32
+ // new: global config override option
33
+ program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
34
+ program
35
+ .command('extract')
36
+ .description('Extract translation keys from source files and update resource files.')
37
+ .option('-w, --watch', 'Watch for file changes and re-run the extractor.')
38
+ .option('--ci', 'Exit with a non-zero status code if any files are updated.')
39
+ .option('--dry-run', 'Run the extractor without writing any files to disk.')
40
+ .option('--sync-primary', 'Sync primary language values with default values from code.')
41
+ .option('--sync-all', 'Sync primary language values with default values from code AND clear synced keys in all other locales.')
42
+ .action(async (options) => {
43
+ try {
44
+ const cfgPath = program.opts().config;
45
+ const config$1 = await config.ensureConfig(cfgPath);
46
+ const runExtract = async () => {
47
+ // --sync-all implies sync-primary behavior
48
+ const syncPrimary = !!options.syncPrimary || !!options.syncAll;
49
+ const success = await extractor.runExtractor(config$1, {
50
+ isWatchMode: !!options.watch,
51
+ isDryRun: !!options.dryRun,
52
+ syncPrimaryWithDefaults: syncPrimary,
53
+ syncAll: !!options.syncAll
54
+ });
55
+ if (options.ci && !success) {
56
+ console.log('✅ No files were updated.');
57
+ process.exit(0);
58
+ }
59
+ else if (options.ci && success) {
60
+ console.error('❌ Some files were updated. This should not happen in CI mode.');
61
+ process.exit(1);
62
+ }
63
+ return success;
64
+ };
65
+ // Run the extractor once initially
66
+ await runExtract();
67
+ // If in watch mode, set up the chokidar watcher
68
+ if (options.watch) {
69
+ console.log('\nWatching for changes...');
70
+ // expand configured input globs (keep original behavior for detection)
71
+ const expanded = await expandGlobs(config$1.extract.input);
72
+ // build ignore list (configured + derived from output template)
73
+ const configuredIgnore = toArray(config$1.extract.ignore);
74
+ const derivedIgnore = deriveOutputIgnore(config$1.extract.output);
75
+ const ignoreGlobs = [...configuredIgnore, ...derivedIgnore].filter(Boolean);
76
+ // filter expanded files by ignore globs
77
+ const watchFiles = expanded.filter(f => !ignoreGlobs.some(g => minimatch.minimatch(f, g, { dot: true })));
78
+ const watcher = chokidar.watch(watchFiles, {
79
+ ignored: /node_modules/,
80
+ persistent: true,
81
+ });
82
+ watcher.on('change', path => {
83
+ console.log(`\nFile changed: ${path}`);
84
+ runExtract();
85
+ });
86
+ }
87
+ }
88
+ catch (error) {
89
+ console.error('Error running extractor:', error);
90
+ process.exit(1);
91
+ }
92
+ });
93
+ program
94
+ .command('status [locale]')
95
+ .description('Display translation status. Provide a locale for a detailed key-by-key view.')
96
+ .option('-n, --namespace <ns>', 'Filter the status report by a specific namespace')
97
+ .action(async (locale, options) => {
98
+ const cfgPath = program.opts().config;
99
+ let config$1 = await config.loadConfig(cfgPath);
100
+ if (!config$1) {
101
+ console.log(chalk.blue('No config file found. Attempting to detect project structure...'));
102
+ const detected = await heuristicConfig.detectConfig();
103
+ if (!detected) {
104
+ console.error(chalk.red('Could not automatically detect your project structure.'));
105
+ console.log(`Please create a config file first by running: ${chalk.cyan('npx i18next-cli init')}`);
106
+ process.exit(1);
107
+ }
108
+ console.log(chalk.green('Project structure detected successfully!'));
109
+ config$1 = detected;
110
+ }
111
+ await status.runStatus(config$1, { detail: locale, namespace: options.namespace });
112
+ });
113
+ program
114
+ .command('types')
115
+ .description('Generate TypeScript definitions from translation resource files.')
116
+ .option('-w, --watch', 'Watch for file changes and re-run the type generator.')
117
+ .action(async (options) => {
118
+ const cfgPath = program.opts().config;
119
+ const config$1 = await config.ensureConfig(cfgPath);
120
+ const run = () => typesGenerator.runTypesGenerator(config$1);
121
+ await run();
122
+ if (options.watch) {
123
+ console.log('\nWatching for changes...');
124
+ const expandedTypes = await expandGlobs(config$1.types?.input || []);
125
+ const ignoredTypes = [...toArray(config$1.extract?.ignore)].filter(Boolean);
126
+ const watchTypes = expandedTypes.filter(f => !ignoredTypes.some(g => minimatch.minimatch(f, g, { dot: true })));
127
+ const watcher = chokidar.watch(watchTypes, { persistent: true });
128
+ watcher.on('change', path => {
129
+ console.log(`\nFile changed: ${path}`);
130
+ run();
131
+ });
132
+ }
133
+ });
134
+ program
135
+ .command('sync')
136
+ .description('Synchronize secondary language files with the primary language file.')
137
+ .action(async () => {
138
+ const cfgPath = program.opts().config;
139
+ const config$1 = await config.ensureConfig(cfgPath);
140
+ await syncer.runSyncer(config$1);
141
+ });
142
+ program
143
+ .command('migrate-config [configPath]')
144
+ .description('Migrate a legacy i18next-parser.config.js to the new format.')
145
+ .action(async (configPath) => {
146
+ await migrator.runMigrator(configPath);
147
+ });
148
+ program
149
+ .command('init')
150
+ .description('Create a new i18next.config.ts/js file with an interactive setup wizard.')
151
+ .action(init.runInit);
152
+ program
153
+ .command('lint')
154
+ .description('Find potential issues like hardcoded strings in your codebase.')
155
+ .option('-w, --watch', 'Watch for file changes and re-run the linter.')
156
+ .action(async (options) => {
157
+ const cfgPath = program.opts().config;
158
+ const loadAndRunLinter = async () => {
159
+ // The existing logic for loading the config or detecting it is now inside this function
160
+ let config$1 = await config.loadConfig(cfgPath);
161
+ if (!config$1) {
162
+ console.log(chalk.blue('No config file found. Attempting to detect project structure...'));
163
+ const detected = await heuristicConfig.detectConfig();
164
+ if (!detected) {
165
+ console.error(chalk.red('Could not automatically detect your project structure.'));
166
+ console.log(`Please create a config file first by running: ${chalk.cyan('npx i18next-cli init')}`);
167
+ process.exit(1);
168
+ }
169
+ console.log(chalk.green('Project structure detected successfully!'));
170
+ config$1 = detected;
171
+ }
172
+ await linter.runLinterCli(config$1);
173
+ };
174
+ // Run the linter once initially
175
+ await loadAndRunLinter();
176
+ // If in watch mode, set up the chokidar watcher
177
+ if (options.watch) {
178
+ console.log('\nWatching for changes...');
179
+ // Re-load the config to get the correct input paths for the watcher
180
+ const config$1 = await config.loadConfig(cfgPath);
181
+ if (config$1?.extract?.input) {
182
+ const expandedLint = await expandGlobs(config$1.extract.input);
183
+ const configuredIgnore2 = toArray(config$1.extract.ignore);
184
+ const derivedIgnore2 = deriveOutputIgnore(config$1.extract.output);
185
+ const ignoredLint = [...configuredIgnore2, ...derivedIgnore2].filter(Boolean);
186
+ const watchLint = expandedLint.filter(f => !ignoredLint.some(g => minimatch.minimatch(f, g, { dot: true })));
187
+ const watcher = chokidar.watch(watchLint, {
188
+ ignored: /node_modules/,
189
+ persistent: true,
190
+ });
191
+ watcher.on('change', path => {
192
+ console.log(`\nFile changed: ${path}`);
193
+ loadAndRunLinter(); // Re-run on change
194
+ });
195
+ }
196
+ }
197
+ });
198
+ program
199
+ .command('locize-sync')
200
+ .description('Synchronize local translations with your locize project.')
201
+ .option('--update-values', 'Update values of existing translations on locize.')
202
+ .option('--src-lng-only', 'Check for changes in source language only.')
203
+ .option('--compare-mtime', 'Compare modification times when syncing.')
204
+ .option('--dry-run', 'Run the command without making any changes.')
205
+ .option('--cdn-type <standard|pro>', 'Specify the cdn endpoint that should be used (depends on which cdn type you\'ve in your locize project)')
206
+ .action(async (options) => {
207
+ const cfgPath = program.opts().config;
208
+ const config$1 = await config.ensureConfig(cfgPath);
209
+ await locize.runLocizeSync(config$1, options);
210
+ });
211
+ program
212
+ .command('locize-download')
213
+ .description('Download all translations from your locize project.')
214
+ .option('--cdn-type <standard|pro>', 'Specify the cdn endpoint that should be used (depends on which cdn type you\'ve in your locize project)')
215
+ .action(async (options) => {
216
+ const cfgPath = program.opts().config;
217
+ const config$1 = await config.ensureConfig(cfgPath);
218
+ await locize.runLocizeDownload(config$1, options);
219
+ });
220
+ program
221
+ .command('locize-migrate')
222
+ .description('Migrate local translation files to a new locize project.')
223
+ .option('--cdn-type <standard|pro>', 'Specify the cdn endpoint that should be used (depends on which cdn type you\'ve in your locize project)')
224
+ .action(async (options) => {
225
+ const cfgPath = program.opts().config;
226
+ const config$1 = await config.ensureConfig(cfgPath);
227
+ await locize.runLocizeMigrate(config$1, options);
228
+ });
229
+ program
230
+ .command('rename-key <oldKey> <newKey>')
231
+ .description('Rename a translation key across all source files and translation files.')
232
+ .option('--dry-run', 'Preview changes without modifying files')
233
+ .action(async (oldKey, newKey, options) => {
234
+ try {
235
+ const cfgPath = program.opts().config;
236
+ const config$1 = await config.ensureConfig(cfgPath);
237
+ const result = await renameKey.runRenameKey(config$1, oldKey, newKey, options);
238
+ if (!result.success) {
239
+ if (result.conflicts) {
240
+ console.error(chalk.red('\n❌ Conflicts detected:'));
241
+ result.conflicts.forEach(c => console.error(` - ${c}`));
242
+ }
243
+ if (result.error) {
244
+ console.error(chalk.red(`\n❌ ${result.error}`));
245
+ }
246
+ process.exit(1);
247
+ }
248
+ const totalChanges = result.sourceFiles.reduce((sum, f) => sum + f.changes, 0);
249
+ if (totalChanges === 0) {
250
+ console.log(chalk.yellow(`\n⚠️ No usages found for "${oldKey}"`));
251
+ }
252
+ }
253
+ catch (error) {
254
+ console.error(chalk.red('Error renaming key:'), error);
255
+ process.exit(1);
256
+ }
257
+ });
258
+ program.parse(process.argv);
259
+ const toArray = (v) => Array.isArray(v) ? v : (v ? [v] : []);
260
+ const deriveOutputIgnore = (output) => {
261
+ if (!output || typeof output !== 'string')
262
+ return [];
263
+ return [output.replace(/\{\{[^}]+\}\}/g, '*')];
264
+ };
265
+ // helper to expand one or many glob patterns
266
+ const expandGlobs = async (patterns = []) => {
267
+ const arr = toArray(patterns);
268
+ const sets = await Promise.all(arr.map(p => glob.glob(p || '', { nodir: true })));
269
+ return Array.from(new Set(sets.flat()));
270
+ };
271
+
272
+ exports.program = program;
@@ -1 +1,211 @@
1
- "use strict";var e=require("node:path"),r=require("node:url"),t=require("node:fs/promises"),n=require("jiti"),o=require("jsonc-parser"),i=require("inquirer"),a=require("chalk"),s=require("./init.js"),c=require("./utils/logger.js");const u=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"];async function l(o,i=new c.ConsoleLogger){const a=await async function(r){if(r){const n=e.resolve(process.cwd(),r);try{return await t.access(n),n}catch{return null}}for(const r of u){const n=e.resolve(process.cwd(),r);try{return await t.access(n),n}catch{}}return null}(o);if(!a)return o&&i.error(`Error: Config file not found at "${o}"`),null;try{let e;if(a.endsWith(".ts")){const r=await f(),t=n.createJiti(process.cwd(),{alias:r,interopDefault:!1}),o=await t.import(a,{default:!0});e=o}else{const t=r.pathToFileURL(a).href,n=await import(`${t}?t=${Date.now()}`);e=n.default}return e?(e.extract||={},e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(r=>r!==e.extract.primaryLanguage),e):(i.error(`Error: No default export found in ${a}`),null)}catch(e){return i.error(`Error loading configuration from ${a}`),i.error(e),null}}async function f(){try{const r=await async function(){let r=process.cwd();for(;;){const n=e.join(r,"tsconfig.json");try{return await t.access(n),n}catch{const t=e.dirname(r);if(t===r)return null;r=t}}}();if(!r)return{};const n=await t.readFile(r,"utf-8"),i=o.parse(n),a=i.compilerOptions?.paths,s=i.compilerOptions?.baseUrl||".";if(!a)return{};const c={};for(const[r,t]of Object.entries(a))if(Array.isArray(t)&&t.length>0){const n=r.replace("/*",""),o=e.resolve(process.cwd(),s,t[0].replace("/*",""));c[n]=o}return c}catch(e){return{}}}exports.defineConfig=function(e){return e},exports.ensureConfig=async function(e,r=new c.ConsoleLogger){let t=await l(e,r);if(t)return t;const{shouldInit:n}=await i.prompt([{type:"confirm",name:"shouldInit",message:a.yellow("Configuration file not found. Would you like to create one now?"),default:!0}]);if(n){if(await s.runInit(),r.info(a.green("Configuration created. Resuming command...")),t=await l(e,r),t)return t;r.error(a.red("Error: Failed to load configuration after creation. Please try running the command again.")),process.exit(1)}else r.info("Operation cancelled. Please create a configuration file to proceed."),process.exit(0)},exports.getTsConfigAliases=f,exports.loadConfig=l;
1
+ 'use strict';
2
+
3
+ var node_path = require('node:path');
4
+ var node_url = require('node:url');
5
+ var promises = require('node:fs/promises');
6
+ var jiti = require('jiti');
7
+ var jsoncParser = require('jsonc-parser');
8
+ var inquirer = require('inquirer');
9
+ var chalk = require('chalk');
10
+ var init = require('./init.js');
11
+ var logger = require('./utils/logger.js');
12
+
13
+ /**
14
+ * List of supported configuration file names in order of precedence
15
+ */
16
+ const CONFIG_FILES = [
17
+ 'i18next.config.ts',
18
+ 'i18next.config.js',
19
+ 'i18next.config.mjs',
20
+ 'i18next.config.cjs',
21
+ ];
22
+ /**
23
+ * A helper function for defining the i18next-cli config with type-safety.
24
+ *
25
+ * @param config - The configuration object to define
26
+ * @returns The same configuration object with type safety
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * export default defineConfig({
31
+ * locales: ['en', 'de'],
32
+ * extract: {
33
+ * input: 'src',
34
+ * output: 'locales/{{language}}/{{namespace}}.json'
35
+ * }
36
+ * })
37
+ * ```
38
+ */
39
+ function defineConfig(config) {
40
+ return config;
41
+ }
42
+ /**
43
+ * Helper function to find the first existing config file in the current working directory.
44
+ * Searches for files in the order defined by CONFIG_FILES.
45
+ *
46
+ * @returns Promise that resolves to the full path of the found config file, or null if none found
47
+ */
48
+ async function findConfigFile(configPath) {
49
+ if (configPath) {
50
+ // Allow relative or absolute path provided by the user
51
+ const resolved = node_path.resolve(process.cwd(), configPath);
52
+ try {
53
+ await promises.access(resolved);
54
+ return resolved;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ for (const file of CONFIG_FILES) {
61
+ const fullPath = node_path.resolve(process.cwd(), file);
62
+ try {
63
+ await promises.access(fullPath);
64
+ return fullPath;
65
+ }
66
+ catch {
67
+ // File doesn't exist, continue to the next one
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+ /**
73
+ * Loads and validates the i18next toolkit configuration from the project root or a provided path.
74
+ *
75
+ * @param configPath - Optional explicit path to a config file (relative to cwd or absolute)
76
+ * @param logger - Optional logger instance
77
+ */
78
+ async function loadConfig(configPath, logger$1 = new logger.ConsoleLogger()) {
79
+ const configPathFound = await findConfigFile(configPath);
80
+ if (!configPathFound) {
81
+ if (configPath) {
82
+ logger$1.error(`Error: Config file not found at "${configPath}"`);
83
+ }
84
+ // QUIETLY RETURN NULL: The caller will handle the "not found" case.
85
+ return null;
86
+ }
87
+ try {
88
+ let config;
89
+ // Use jiti for TypeScript files, native import for JavaScript
90
+ if (configPathFound.endsWith('.ts')) {
91
+ const aliases = await getTsConfigAliases();
92
+ const jiti$1 = jiti.createJiti(process.cwd(), {
93
+ alias: aliases,
94
+ interopDefault: false,
95
+ });
96
+ const configModule = await jiti$1.import(configPathFound, { default: true });
97
+ config = configModule;
98
+ }
99
+ else {
100
+ const configUrl = node_url.pathToFileURL(configPathFound).href;
101
+ const configModule = await import(`${configUrl}?t=${Date.now()}`);
102
+ config = configModule.default;
103
+ }
104
+ if (!config) {
105
+ logger$1.error(`Error: No default export found in ${configPathFound}`);
106
+ return null;
107
+ }
108
+ // Set default sync options
109
+ config.extract ||= {};
110
+ config.extract.primaryLanguage ||= config.locales[0] || 'en';
111
+ config.extract.secondaryLanguages ||= config.locales.filter((l) => l !== config.extract.primaryLanguage);
112
+ return config;
113
+ }
114
+ catch (error) {
115
+ logger$1.error(`Error loading configuration from ${configPathFound}`);
116
+ logger$1.error(error);
117
+ return null;
118
+ }
119
+ }
120
+ /**
121
+ * Ensures a configuration exists, prompting the user to create one if necessary.
122
+ * Accepts an optional configPath which will be used when loading the config.
123
+ */
124
+ async function ensureConfig(configPath, logger$1 = new logger.ConsoleLogger()) {
125
+ let config = await loadConfig(configPath, logger$1);
126
+ if (config) {
127
+ return config;
128
+ }
129
+ // No config found, so we prompt the user.
130
+ const { shouldInit } = await inquirer.prompt([{
131
+ type: 'confirm',
132
+ name: 'shouldInit',
133
+ message: chalk.yellow('Configuration file not found. Would you like to create one now?'),
134
+ default: true,
135
+ }]);
136
+ if (shouldInit) {
137
+ await init.runInit(); // Run the interactive setup wizard (keeps existing behavior)
138
+ logger$1.info(chalk.green('Configuration created. Resuming command...'));
139
+ config = await loadConfig(configPath, logger$1); // Try loading the newly created config
140
+ if (config) {
141
+ return config;
142
+ }
143
+ else {
144
+ logger$1.error(chalk.red('Error: Failed to load configuration after creation. Please try running the command again.'));
145
+ process.exit(1);
146
+ }
147
+ }
148
+ else {
149
+ logger$1.info('Operation cancelled. Please create a configuration file to proceed.');
150
+ process.exit(0);
151
+ }
152
+ }
153
+ /**
154
+ * Searches upwards from the current directory to find the tsconfig.json file.
155
+ * @returns The full path to the tsconfig.json file, or null if not found.
156
+ */
157
+ async function findTsConfigFile() {
158
+ let currentDir = process.cwd();
159
+ while (true) {
160
+ const tsConfigPath = node_path.join(currentDir, 'tsconfig.json');
161
+ try {
162
+ await promises.access(tsConfigPath);
163
+ return tsConfigPath;
164
+ }
165
+ catch {
166
+ // File not found, move to parent directory
167
+ const parentDir = node_path.dirname(currentDir);
168
+ if (parentDir === currentDir) {
169
+ // Reached the root of the file system
170
+ return null;
171
+ }
172
+ currentDir = parentDir;
173
+ }
174
+ }
175
+ }
176
+ /**
177
+ * Parses the project's tsconfig.json to extract path aliases for jiti.
178
+ * @returns A record of aliases for jiti's configuration.
179
+ */
180
+ async function getTsConfigAliases() {
181
+ try {
182
+ const tsConfigPath = await findTsConfigFile();
183
+ if (!tsConfigPath)
184
+ return {};
185
+ const tsConfigStr = await promises.readFile(tsConfigPath, 'utf-8');
186
+ const tsConfig = jsoncParser.parse(tsConfigStr);
187
+ const paths = tsConfig.compilerOptions?.paths;
188
+ const baseUrl = tsConfig.compilerOptions?.baseUrl || '.';
189
+ if (!paths)
190
+ return {};
191
+ const aliases = {};
192
+ for (const [alias, aliasPaths] of Object.entries(paths)) {
193
+ if (Array.isArray(aliasPaths) && aliasPaths.length > 0) {
194
+ // Convert "@/*": ["./src/*"] to "@": "./src"
195
+ const key = alias.replace('/*', '');
196
+ const value = node_path.resolve(process.cwd(), baseUrl, aliasPaths[0].replace('/*', ''));
197
+ aliases[key] = value;
198
+ }
199
+ }
200
+ return aliases;
201
+ }
202
+ catch (e) {
203
+ // Return empty if tsconfig doesn't exist or fails to parse
204
+ return {};
205
+ }
206
+ }
207
+
208
+ exports.defineConfig = defineConfig;
209
+ exports.ensureConfig = ensureConfig;
210
+ exports.getTsConfigAliases = getTsConfigAliases;
211
+ exports.loadConfig = loadConfig;