i18next-cli 1.24.12 → 1.24.14

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