i18next-cli 1.88.1 → 1.90.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 +104 -12
- package/dist/cjs/cli.js +25 -6
- package/dist/cjs/config.js +13 -12
- package/dist/cjs/extractor/core/extractor.js +1 -3
- package/dist/cjs/extractor/core/translation-manager.js +9 -2
- package/dist/cjs/heuristic-config.js +51 -6
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/init.js +8 -11
- package/dist/cjs/instrumenter/core/instrumenter.js +1372 -218
- package/dist/cjs/instrumenter/core/key-generator.js +20 -9
- package/dist/cjs/instrumenter/core/next-files.js +104 -0
- package/dist/cjs/instrumenter/core/string-detector.js +106 -29
- package/dist/cjs/instrumenter/core/transformer.js +165 -83
- package/dist/cjs/localize/agent-prompt.js +5 -2
- package/dist/cjs/localize/detect.js +3 -11
- package/dist/cjs/localize/localize.js +27 -5
- package/dist/cjs/utils/file-utils.js +48 -0
- package/dist/cjs/utils/jsx-attributes.js +3 -1
- package/dist/esm/cli.js +25 -6
- package/dist/esm/config.js +13 -12
- package/dist/esm/extractor/core/extractor.js +1 -3
- package/dist/esm/extractor/core/translation-manager.js +9 -2
- package/dist/esm/heuristic-config.js +52 -7
- package/dist/esm/index.js +2 -1
- package/dist/esm/init.js +8 -11
- package/dist/esm/instrumenter/core/instrumenter.js +1376 -222
- package/dist/esm/instrumenter/core/key-generator.js +20 -9
- package/dist/esm/instrumenter/core/next-files.js +101 -0
- package/dist/esm/instrumenter/core/string-detector.js +107 -31
- package/dist/esm/instrumenter/core/transformer.js +165 -83
- package/dist/esm/localize/agent-prompt.js +5 -2
- package/dist/esm/localize/detect.js +4 -12
- package/dist/esm/localize/localize.js +27 -5
- package/dist/esm/utils/file-utils.js +49 -2
- package/dist/esm/utils/jsx-attributes.js +3 -1
- package/package.json +1 -1
- package/types/cli.d.ts.map +1 -1
- package/types/config.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/heuristic-config.d.ts.map +1 -1
- package/types/index.d.ts +1 -1
- package/types/index.d.ts.map +1 -1
- package/types/init.d.ts.map +1 -1
- package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
- package/types/instrumenter/core/key-generator.d.ts +2 -0
- package/types/instrumenter/core/key-generator.d.ts.map +1 -1
- package/types/instrumenter/core/next-files.d.ts +25 -0
- package/types/instrumenter/core/next-files.d.ts.map +1 -0
- package/types/instrumenter/core/string-detector.d.ts +5 -1
- package/types/instrumenter/core/string-detector.d.ts.map +1 -1
- package/types/instrumenter/core/transformer.d.ts +16 -1
- package/types/instrumenter/core/transformer.d.ts.map +1 -1
- package/types/instrumenter/index.d.ts +1 -1
- package/types/instrumenter/index.d.ts.map +1 -1
- package/types/localize/agent-prompt.d.ts +1 -1
- package/types/localize/agent-prompt.d.ts.map +1 -1
- package/types/localize/detect.d.ts +2 -0
- package/types/localize/detect.d.ts.map +1 -1
- package/types/localize/localize.d.ts.map +1 -1
- package/types/types.d.ts +87 -1
- package/types/types.d.ts.map +1 -1
- package/types/utils/file-utils.d.ts +7 -0
- package/types/utils/file-utils.d.ts.map +1 -1
- package/types/utils/jsx-attributes.d.ts.map +1 -1
package/dist/esm/cli.js
CHANGED
|
@@ -25,7 +25,7 @@ import { runUnusedReport, runStatus } from './status.js';
|
|
|
25
25
|
import { runLocizeSync, runLocizeDownload, runLocizeMigrate } from './locize.js';
|
|
26
26
|
import { runRenameKey } from './rename-key.js';
|
|
27
27
|
import { runInstrumenter } from './instrumenter/core/instrumenter.js';
|
|
28
|
-
import './
|
|
28
|
+
import './instrumenter/core/string-detector.js';
|
|
29
29
|
import 'magic-string';
|
|
30
30
|
import { runLocalize } from './localize/localize.js';
|
|
31
31
|
|
|
@@ -33,7 +33,7 @@ const program = new Command();
|
|
|
33
33
|
program
|
|
34
34
|
.name('i18next-cli')
|
|
35
35
|
.description('A unified, high-performance i18next CLI.')
|
|
36
|
-
.version('1.
|
|
36
|
+
.version('1.90.0') // This string is replaced with the actual version at build time by rollup
|
|
37
37
|
.addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
|
|
38
38
|
// new: global config override option
|
|
39
39
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
|
|
@@ -99,7 +99,7 @@ program
|
|
|
99
99
|
return inputGlobs.some(g => minimatch(f, g, { dot: true })) &&
|
|
100
100
|
!ignoreGlobs.some(g => minimatch(f, g, { dot: true }));
|
|
101
101
|
};
|
|
102
|
-
const watcher = chokidar.watch(Array.from(new Set(inputGlobs.
|
|
102
|
+
const watcher = chokidar.watch(Array.from(new Set(inputGlobs.flatMap(globBases))), {
|
|
103
103
|
ignored: (path, stats) => /node_modules/.test(path) || (!!stats?.isFile() && !isInput(path)),
|
|
104
104
|
ignoreInitial: true,
|
|
105
105
|
persistent: true,
|
|
@@ -321,6 +321,21 @@ program
|
|
|
321
321
|
});
|
|
322
322
|
// Display results
|
|
323
323
|
if (!options.quiet) {
|
|
324
|
+
// The preview: each text with the key it would get, by file
|
|
325
|
+
if (options.dryRun) {
|
|
326
|
+
for (const { file, candidates, languageChangeSites } of results.files) {
|
|
327
|
+
if (!candidates.length && !languageChangeSites?.length)
|
|
328
|
+
continue;
|
|
329
|
+
console.log(styleText('bold', `\n${file}`));
|
|
330
|
+
for (const c of candidates) {
|
|
331
|
+
const text = c.content.replace(/\s+/g, ' ');
|
|
332
|
+
console.log(` ${c.line}: "${text.length > 80 ? text.slice(0, 79) + '…' : text}" → ${c.key}`);
|
|
333
|
+
}
|
|
334
|
+
for (const site of languageChangeSites ?? []) {
|
|
335
|
+
console.log(` ${site.line}: changeLanguage(${site.languageExpression}) before the call that sets the language`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
324
339
|
console.log(styleText('bold', '\nInstrumentation Summary:'));
|
|
325
340
|
console.log(` Total candidates: ${results.totalCandidates}`);
|
|
326
341
|
console.log(` Approved: ${results.totalTransformed}`);
|
|
@@ -333,7 +348,7 @@ program
|
|
|
333
348
|
console.log('Run again without --dry-run to apply changes.');
|
|
334
349
|
}
|
|
335
350
|
if (results.files.length > 0) {
|
|
336
|
-
console.log(styleText('green', `\n✅ ${results.files.length} file(s) ready for instrumentation`));
|
|
351
|
+
console.log(styleText('green', `\n✅ ${results.files.length} file(s) ${options.dryRun ? 'ready for instrumentation' : 'instrumented'}`));
|
|
337
352
|
}
|
|
338
353
|
else {
|
|
339
354
|
console.log(styleText('yellow', '\n⚠️ No files required instrumentation'));
|
|
@@ -444,14 +459,18 @@ const deriveOutputIgnore = (output) => {
|
|
|
444
459
|
return [output.replace(/\{\{[^}]+\}\}/g, '*')];
|
|
445
460
|
};
|
|
446
461
|
// static leading folder of a glob: 'src/**/*.ts' -> 'src'
|
|
447
|
-
|
|
462
|
+
// the directories a glob starts in: `{app,components}/**` starts in two, not in the project root
|
|
463
|
+
const globBases = (pattern) => {
|
|
464
|
+
const brace = /^((?:[^*?[\]{}()!/]+\/)*)\{([^{}]+)\}(\/.*)?$/.exec(pattern);
|
|
465
|
+
if (brace)
|
|
466
|
+
return brace[2].split(',').flatMap(alt => globBases(`${brace[1]}${alt}${brace[3] ?? ''}`));
|
|
448
467
|
const parts = [];
|
|
449
468
|
for (const segment of pattern.split('/')) {
|
|
450
469
|
if (/[*?[\]{}()!]/.test(segment))
|
|
451
470
|
break;
|
|
452
471
|
parts.push(segment);
|
|
453
472
|
}
|
|
454
|
-
return parts.join('/') || '.';
|
|
473
|
+
return [parts.join('/') || '.'];
|
|
455
474
|
};
|
|
456
475
|
// helper to expand one or many glob patterns
|
|
457
476
|
const expandGlobs = async (patterns = []) => {
|
package/dist/esm/config.js
CHANGED
|
@@ -156,20 +156,21 @@ async function ensureConfig(configPath, logger = new ConsoleLogger()) {
|
|
|
156
156
|
async function findTsConfigFile() {
|
|
157
157
|
let currentDir = process.cwd();
|
|
158
158
|
while (true) {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
catch {
|
|
165
|
-
// File not found, move to parent directory
|
|
166
|
-
const parentDir = dirname(currentDir);
|
|
167
|
-
if (parentDir === currentDir) {
|
|
168
|
-
// Reached the root of the file system
|
|
169
|
-
return null;
|
|
159
|
+
// a JavaScript project keeps its `paths` in jsconfig.json (`@/*` in a Next.js app)
|
|
160
|
+
for (const name of ['tsconfig.json', 'jsconfig.json']) {
|
|
161
|
+
try {
|
|
162
|
+
await access(join(currentDir, name));
|
|
163
|
+
return join(currentDir, name);
|
|
170
164
|
}
|
|
171
|
-
|
|
165
|
+
catch { }
|
|
166
|
+
}
|
|
167
|
+
// File not found, move to parent directory
|
|
168
|
+
const parentDir = dirname(currentDir);
|
|
169
|
+
if (parentDir === currentDir) {
|
|
170
|
+
// Reached the root of the file system
|
|
171
|
+
return null;
|
|
172
172
|
}
|
|
173
|
+
currentDir = parentDir;
|
|
173
174
|
}
|
|
174
175
|
}
|
|
175
176
|
/**
|
|
@@ -256,7 +256,7 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
256
256
|
});
|
|
257
257
|
}
|
|
258
258
|
catch (err) {
|
|
259
|
-
// Fallback for .ts files with JSX (already present)
|
|
259
|
+
// Fallback for .ts files with JSX (already present); JSX in a .js file is common enough to need no note
|
|
260
260
|
if (effectiveExt === '.ts' && !isTSX) {
|
|
261
261
|
try {
|
|
262
262
|
ast = await parse(code, {
|
|
@@ -266,7 +266,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
266
266
|
dynamicImport: true,
|
|
267
267
|
comments: true,
|
|
268
268
|
});
|
|
269
|
-
logger.info?.(`Parsed ${file} using TSX fallback`);
|
|
270
269
|
}
|
|
271
270
|
catch (err2) {
|
|
272
271
|
throw new ExtractorError('Failed to process file', file, err2);
|
|
@@ -282,7 +281,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
282
281
|
dynamicImport: true,
|
|
283
282
|
comments: true,
|
|
284
283
|
});
|
|
285
|
-
logger.info?.(`Parsed ${file} using JSX fallback`);
|
|
286
284
|
}
|
|
287
285
|
catch (err2) {
|
|
288
286
|
throw new ExtractorError('Failed to process file', file, err2);
|
|
@@ -852,8 +852,15 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
852
852
|
if (separator && typeof separator === 'string') {
|
|
853
853
|
const conflictingPath = findNestingConflict(newTranslations, key, separator);
|
|
854
854
|
if (conflictingPath !== null) {
|
|
855
|
-
|
|
856
|
-
|
|
855
|
+
// The keys come from the code, the same for every language: reported once, with the primary one (or
|
|
856
|
+
// the first language, when the primary one is not among them)
|
|
857
|
+
if (locale === (config.locales.includes(primaryLanguage) ? primaryLanguage : config.locales[0])) {
|
|
858
|
+
const conflict = conflictingPath === key
|
|
859
|
+
? `key "${key}" is also the parent of nested keys ("${key}${separator}…")`
|
|
860
|
+
: `key "${key}" conflicts with existing key "${conflictingPath}"`;
|
|
861
|
+
logger.error(`Error: Nesting conflict: ${conflict}. ` +
|
|
862
|
+
`"${key}" will be skipped — fix the overlapping key paths in your source code to avoid missing translations at runtime.`);
|
|
863
|
+
}
|
|
857
864
|
continue;
|
|
858
865
|
}
|
|
859
866
|
}
|
|
@@ -1,7 +1,56 @@
|
|
|
1
1
|
import { glob } from 'glob';
|
|
2
|
-
import { readdir } from 'node:fs/promises';
|
|
2
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
3
3
|
import { extname, dirname, join } from 'node:path';
|
|
4
|
+
import { readProjectDeps } from './utils/file-utils.js';
|
|
4
5
|
|
|
6
|
+
/** The directories source files usually live in, one glob for those that exist (`{app,components}/**`). */
|
|
7
|
+
async function sourceInput() {
|
|
8
|
+
const dirs = [];
|
|
9
|
+
// not `lib`, often the build output of a package
|
|
10
|
+
for (const dir of ['src', 'app', 'pages', 'components']) {
|
|
11
|
+
if (await stat(dir).then(found => found.isDirectory(), () => false))
|
|
12
|
+
dirs.push(dir);
|
|
13
|
+
}
|
|
14
|
+
const exts = '**/*.{js,jsx,mjs,ts,tsx}';
|
|
15
|
+
return [dirs.length > 1 ? `{${dirs.join(',')}}/${exts}` : `${dirs[0] ?? 'src'}/${exts}`];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The extract options the app's own setup decides: next-i18next's `defaultNS` (from its config, `common` when it
|
|
19
|
+
* sets none), the message format of i18next-icu or i18next-mf2, and `keySeparator: false` for translation files
|
|
20
|
+
* with flat keys that contain dots (`"blog.title": "…"`).
|
|
21
|
+
*/
|
|
22
|
+
async function setupOptions(translationFiles) {
|
|
23
|
+
const deps = await readProjectDeps();
|
|
24
|
+
const options = {};
|
|
25
|
+
if (deps['next-i18next']) {
|
|
26
|
+
const configs = await glob('{i18n.config,next-i18next.config,i18n.shared}.{ts,js,mjs,cjs}', { ignore: 'node_modules/**' });
|
|
27
|
+
for (const file of configs) {
|
|
28
|
+
const ns = /\bdefaultNS\s*:\s*['"]([^'"]+)['"]/.exec(await readFile(file, 'utf-8'))?.[1];
|
|
29
|
+
if (ns) {
|
|
30
|
+
options.defaultNS = ns;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
options.defaultNS ??= 'common';
|
|
35
|
+
}
|
|
36
|
+
if (deps['i18next-icu'])
|
|
37
|
+
options.messageFormat = 'icu';
|
|
38
|
+
else if (deps['i18next-mf2'])
|
|
39
|
+
options.messageFormat = 'mf2';
|
|
40
|
+
const flat = [];
|
|
41
|
+
for (const file of translationFiles.filter(f => extname(f) === '.json')) {
|
|
42
|
+
try {
|
|
43
|
+
const json = JSON.parse(await readFile(file, 'utf-8'));
|
|
44
|
+
if (Object.values(json).some(v => typeof v === 'object'))
|
|
45
|
+
return options;
|
|
46
|
+
flat.push(Object.keys(json).some(key => key.includes('.')));
|
|
47
|
+
}
|
|
48
|
+
catch { }
|
|
49
|
+
}
|
|
50
|
+
if (flat.includes(true))
|
|
51
|
+
options.keySeparator = false;
|
|
52
|
+
return options;
|
|
53
|
+
}
|
|
5
54
|
// A list of common glob patterns for the primary language ('en') or ('dev') translation files.
|
|
6
55
|
const HEURISTIC_PATTERNS = [
|
|
7
56
|
'public/locales/dev/*.json',
|
|
@@ -88,15 +137,11 @@ async function detectConfig() {
|
|
|
88
137
|
return {
|
|
89
138
|
locales,
|
|
90
139
|
extract: {
|
|
91
|
-
input:
|
|
92
|
-
'src/**/*.{js,jsx,mjs,ts,tsx}',
|
|
93
|
-
'app/**/*.{js,jsx,mjs,ts,tsx}',
|
|
94
|
-
'pages/**/*.{js,jsx,mjs,ts,tsx}',
|
|
95
|
-
'components/**/*.{js,jsx,mjs,ts,tsx}'
|
|
96
|
-
],
|
|
140
|
+
input: await sourceInput(),
|
|
97
141
|
output: join(basePath, '{{language}}', `{{namespace}}${extension}`),
|
|
98
142
|
outputFormat,
|
|
99
143
|
primaryLanguage: locales.includes('en') ? 'en' : locales[0],
|
|
144
|
+
...await setupOptions(files),
|
|
100
145
|
},
|
|
101
146
|
};
|
|
102
147
|
}
|
package/dist/esm/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import 'node:path';
|
|
|
6
6
|
import 'node:fs/promises';
|
|
7
7
|
import 'glob';
|
|
8
8
|
import 'jsonc-parser';
|
|
9
|
+
import 'minimatch';
|
|
9
10
|
import 'jiti';
|
|
10
11
|
import '@croct/json5-parser';
|
|
11
12
|
import 'yaml';
|
|
@@ -17,7 +18,7 @@ export { runStatus, runUnusedReport } from './status.js';
|
|
|
17
18
|
export { runTypesGenerator } from './types-generator.js';
|
|
18
19
|
export { runRenameKey } from './rename-key.js';
|
|
19
20
|
export { runInstrumenter, writeExtractedKeys } from './instrumenter/core/instrumenter.js';
|
|
20
|
-
import './
|
|
21
|
+
import './instrumenter/core/string-detector.js';
|
|
21
22
|
import 'magic-string';
|
|
22
23
|
export { runLocalize } from './localize/localize.js';
|
|
23
24
|
export { AGENT_PROMPT } from './localize/agent-prompt.js';
|
package/dist/esm/init.js
CHANGED
|
@@ -5,6 +5,7 @@ import { detectConfig } from './heuristic-config.js';
|
|
|
5
5
|
import { openBrowser, promptLocizeCredentials } from './utils/locize-onboarding.js';
|
|
6
6
|
import { scaffoldInlangProject } from './utils/inlang-scaffold.js';
|
|
7
7
|
import { buildAgentNote, writeAgentNote } from './utils/agent-note.js';
|
|
8
|
+
import { readProjectDeps } from './utils/file-utils.js';
|
|
8
9
|
|
|
9
10
|
const LOCIZE_SIGNUP_URL = 'https://www.locize.app/register?from=i18next_cli__init-wizard';
|
|
10
11
|
/**
|
|
@@ -39,19 +40,10 @@ async function isEsmProject() {
|
|
|
39
40
|
* When running via `npx` without a local install, `defineConfig` would not be available
|
|
40
41
|
* at runtime, so the generated config should fall back to a plain object export.
|
|
41
42
|
*
|
|
42
|
-
* @returns Promise resolving to true if i18next-cli is
|
|
43
|
+
* @returns Promise resolving to true if i18next-cli is a declared dependency (see readProjectDeps)
|
|
43
44
|
*/
|
|
44
45
|
async function isCliLocallyInstalled() {
|
|
45
|
-
|
|
46
|
-
const packageJsonPath = resolve(process.cwd(), 'package.json');
|
|
47
|
-
const content = await readFile(packageJsonPath, 'utf-8');
|
|
48
|
-
const packageJson = JSON.parse(content);
|
|
49
|
-
const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
|
|
50
|
-
return !!deps['i18next-cli'];
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
46
|
+
return !!(await readProjectDeps())['i18next-cli'];
|
|
55
47
|
}
|
|
56
48
|
/**
|
|
57
49
|
* Checks whether the project uses TypeScript by looking for a tsconfig.json.
|
|
@@ -196,11 +188,16 @@ async function runInit(options = {}) {
|
|
|
196
188
|
const isTypeScript = answers.fileType.includes('TypeScript');
|
|
197
189
|
const isEsm = await isEsmProject();
|
|
198
190
|
const fileName = isTypeScript ? 'i18next.config.ts' : 'i18next.config.js';
|
|
191
|
+
// what the app's own setup decides (next-i18next's defaultNS, ICU, flat keys), as detected
|
|
192
|
+
const { defaultNS, messageFormat, keySeparator } = detectedConfig?.extract ?? {};
|
|
199
193
|
const configObject = {
|
|
200
194
|
locales: answers.locales,
|
|
201
195
|
extract: {
|
|
202
196
|
input: answers.input,
|
|
203
197
|
output: answers.output,
|
|
198
|
+
...(defaultNS !== undefined && { defaultNS }),
|
|
199
|
+
...(messageFormat && { messageFormat }),
|
|
200
|
+
...(keySeparator !== undefined && { keySeparator }),
|
|
204
201
|
},
|
|
205
202
|
};
|
|
206
203
|
if (locizeConfig)
|