i18next-cli 1.89.0 → 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.
Files changed (44) hide show
  1. package/README.md +46 -7
  2. package/dist/cjs/cli.js +8 -4
  3. package/dist/cjs/config.js +13 -12
  4. package/dist/cjs/extractor/core/extractor.js +1 -3
  5. package/dist/cjs/heuristic-config.js +51 -6
  6. package/dist/cjs/init.js +5 -0
  7. package/dist/cjs/instrumenter/core/instrumenter.js +272 -23
  8. package/dist/cjs/instrumenter/core/key-generator.js +1 -0
  9. package/dist/cjs/instrumenter/core/next-files.js +104 -0
  10. package/dist/cjs/instrumenter/core/transformer.js +97 -73
  11. package/dist/cjs/localize/agent-prompt.js +5 -2
  12. package/dist/cjs/localize/detect.js +1 -0
  13. package/dist/cjs/localize/localize.js +25 -4
  14. package/dist/esm/cli.js +8 -4
  15. package/dist/esm/config.js +13 -12
  16. package/dist/esm/extractor/core/extractor.js +1 -3
  17. package/dist/esm/heuristic-config.js +52 -7
  18. package/dist/esm/init.js +5 -0
  19. package/dist/esm/instrumenter/core/instrumenter.js +273 -24
  20. package/dist/esm/instrumenter/core/key-generator.js +1 -0
  21. package/dist/esm/instrumenter/core/next-files.js +101 -0
  22. package/dist/esm/instrumenter/core/transformer.js +97 -73
  23. package/dist/esm/localize/agent-prompt.js +5 -2
  24. package/dist/esm/localize/detect.js +1 -0
  25. package/dist/esm/localize/localize.js +25 -4
  26. package/package.json +1 -1
  27. package/types/cli.d.ts.map +1 -1
  28. package/types/config.d.ts.map +1 -1
  29. package/types/extractor/core/extractor.d.ts.map +1 -1
  30. package/types/heuristic-config.d.ts.map +1 -1
  31. package/types/init.d.ts.map +1 -1
  32. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  33. package/types/instrumenter/core/key-generator.d.ts.map +1 -1
  34. package/types/instrumenter/core/next-files.d.ts +25 -0
  35. package/types/instrumenter/core/next-files.d.ts.map +1 -0
  36. package/types/instrumenter/core/transformer.d.ts +6 -0
  37. package/types/instrumenter/core/transformer.d.ts.map +1 -1
  38. package/types/localize/agent-prompt.d.ts +1 -1
  39. package/types/localize/agent-prompt.d.ts.map +1 -1
  40. package/types/localize/detect.d.ts +2 -0
  41. package/types/localize/detect.d.ts.map +1 -1
  42. package/types/localize/localize.d.ts.map +1 -1
  43. package/types/types.d.ts +39 -0
  44. package/types/types.d.ts.map +1 -1
package/README.md CHANGED
@@ -168,6 +168,13 @@ write a note for AI coding agents:
168
168
  mode); add it later via a `LOCIZE_API_KEY` environment variable.
169
169
  - **Other / skip** — same as "Local files only" for the wizard's purposes.
170
170
 
171
+ The defaults come from the project: the locales and output path from the translation files it finds, the
172
+ source glob from the directories that exist of `src`, `app`, `pages` and `components` (`{app,components}/**/*.{js,jsx,mjs,ts,tsx}` in a Next.js app
173
+ without `src/`), and what the app's own setup decides is written into `extract` as well: next-i18next's
174
+ `defaultNS` (from `i18n.config` or `next-i18next.config`, `common` when it sets none), `messageFormat` for
175
+ i18next-icu or i18next-mf2, and `keySeparator: false` for translation files whose flat keys contain dots
176
+ (`"blog.title": "…"`), so `extract` keeps them as they are.
177
+
171
178
  **Note for AI coding agents** (off by default): the last question offers to
172
179
  append a short `## Internationalization` section to `AGENTS.md` and, if it
173
180
  exists, `CLAUDE.md` (when neither exists, `AGENTS.md` is created, plus a
@@ -589,8 +596,8 @@ The instrumenter uses confidence heuristics to avoid transforming:
589
596
  built in code (`` `${projectId}-${version}` ``, `` `weight_${code}` ``, `` `${baseUrl}/api/${id}` ``,
590
597
  `` `zh-${country}` ``); and values of technical properties (`` { 'Authorization': `Bearer ${token}` } ``,
591
598
  `url`, `id`, `type`, `code`, `className`, …)
592
- - Strings already inside `t()` calls or `<Trans>` components, including the project's own `extract.functions`
593
- and `extract.transComponents`
599
+ - Strings already inside `t()` calls or `<Trans>`, `<IcuTrans>` and their `…WithoutContext` components (their
600
+ `values` too), including the project's own `extract.functions` and `extract.transComponents`
594
601
  - **Module-scope strings** — anything outside a function body, e.g. a top-level config/registry array:
595
602
  ```ts
596
603
  export const SETTINGS_SECTIONS = [
@@ -612,12 +619,41 @@ The instrumenter uses confidence heuristics to avoid transforming:
612
619
  When transformations are applied, the command automatically:
613
620
  - Injects `import { useTranslation } from 'react-i18next'` in React files (or `import i18next from 'i18next'` for non-React files)
614
621
  - Injects `const { t } = useTranslation()` into each React function component that contains transformed strings (an arrow component with an expression body, `() => <p>…</p>`, gets a block for it), unless it has a `t` already (a prop, or a hook from a module that re-exports it), and adds `t` to the dependencies of a `useMemo` or `useCallback` whose callback now calls it
615
- - Places the imports after the file's import declarations (never inside a string that shows code), and imports no name the file has already, from whatever module
622
+ - Places the imports after the file's import declarations and directives (`'use client'` stays first; never inside a string that shows code), and imports no name the file has already, from whatever module
623
+ - Takes `t` from a hook call the component makes already, unless a text comes before it: `const { i18n } = useTranslation('settings')` becomes `const { t, i18n } = useTranslation('settings')`, so the new keys go to that namespace; a function that is no component but binds `t` from a translation hook (a custom hook, `generateMetadata` with `getT()`) uses that `t`, not `i18next.t()`
616
624
  - Detects the project's framework from `package.json` dependencies, dev and peer dependencies included; in a workspace package (npm/yarn `workspaces`, `pnpm-workspace.yaml`) also from the workspace root's
617
625
  - Uses `useTranslation()` hook style `t()` inside React components, or `i18next.t()` for utility / non-component code
618
- - Generates an `i18n.ts` (or `i18n.js` for JS-only projects) initialization file if none exists and the code imports neither `i18next` nor `react-i18next` yet (an app that does is set up somewhere, perhaps in a shared package), pre-configured with [`i18next-resources-to-backend`](https://github.com/i18next/i18next-resources-to-backend) to lazy-load your translation files via dynamic imports
626
+ - Generates an `i18n.ts` (or `i18n.js` for JS-only projects) initialization file if none exists and the code imports neither `i18next` nor `react-i18next` yet (an app that does is set up somewhere, perhaps in a shared package), pre-configured with [`i18next-resources-to-backend`](https://github.com/i18next/i18next-resources-to-backend) to lazy-load your translation files via dynamic imports; not in a Next.js app, see below
619
627
  - Adds `i18n.changeLanguage()` next to a call that sets the user's language: `setLanguage(code)`, or a settings, profile or user call with a `language`/`locale` property (`updateSettings({ language: code })`). Only where that call is a statement of its own in a block or an arrow function's body, with a plain variable or property as the language (the injected call repeats it), and not for a `language` property passed as data (`fetchTranslations({ lng })`). `--dry-run` lists every such site; in an app where a language is data (a translation tool's view filter), review them
620
628
 
629
+ **Next.js apps ([next-i18next](https://github.com/i18next/next-i18next)):**
630
+
631
+ An app with next-i18next (a dependency, or imported), and a Next.js app with no i18next set up at all, gets
632
+ next-i18next's calls, by where each file renders. The import graph decides: a file under `app/` is a Server
633
+ Component unless it says `'use client'`, a `'use client'` file and all it imports are Client Components, a file
634
+ under `pages/` and all it imports render with the Pages Router (imports resolve relative, through the `paths` of
635
+ `tsconfig.json` or `jsconfig.json` and from the project root). A Next.js app with i18next or react-i18next and no
636
+ next-i18next keeps `react-i18next`.
637
+
638
+ - **Server Components:** `const { t } = await getT()` from `next-i18next/server` (or from the module the app
639
+ imports `getT` from, such as its own `createServerI18next` file), and the component becomes `async`. A
640
+ `<Trans>` gets `t={t} i18n={i18n}` and comes from `react-i18next/TransWithoutContext`. `generateMetadata()`
641
+ and other async functions get `getT()` as well, and `export const metadata = { title: '…' }` becomes
642
+ `export async function generateMetadata () { const { t } = await getT(); return { title: t(…) } }`.
643
+ - **Client Components:** `const { t } = useT()` and `Trans` from `next-i18next/client`.
644
+ - **Pages Router:** `useTranslation` and `Trans` from `next-i18next/pages`. A page that loads no translations
645
+ (no `serverSideTranslations()` in it or in a helper it imports) is named in a warning.
646
+ - **A component that Server and Client Components both render** works with neither: its texts stay, named in a
647
+ warning, unless it gets `t` as a prop (and `i18n` too for a `<Trans>`), which it then uses.
648
+ - Left as they are, each named in a warning: texts outside components (next-i18next has no global `t`), files
649
+ no page or layout imports (which side renders them is not known), API routes (`route.ts` under `app/`,
650
+ `pages/api/`), Server Actions and cached functions (`'use server'`, `'use cache'`: `getT()` there needs
651
+ `{ lng }`), a Server Component wrapped in `memo()` or `forwardRef()`, and language switches: next-i18next
652
+ changes the language through the route or `useChangeLanguage()`.
653
+ - No init file: next-i18next sets i18next up itself. When it is not set up yet, the steps are printed (install,
654
+ then `i18n.config`, proxy and root layout for the App Router, `appWithTranslation` and `serverSideTranslations`
655
+ for the Pages Router).
656
+
621
657
  **Recommended workflow:**
622
658
 
623
659
  1. **Preview first:** Always run with `--dry-run` to see what will change:
@@ -727,7 +763,7 @@ The command walks through six steps:
727
763
 
728
764
  **Safe to re-run:** the command is idempotent. Already-wrapped strings are not re-instrumented, extraction is deterministic, and syncing never overwrites translations edited remotely (no `--update-values` unless you pass it; locize-cli's `--reference-language-only` default keeps target languages safe).
729
765
 
730
- > **Next.js App Router:** instrument injects `useTranslation()`, which is client-only. Review the diff for server components — add `'use client'` or switch those to a server-side `t()` pattern.
766
+ > **Next.js:** instrument writes next-i18next's calls, `await getT()` in Server Components and `useT()` in Client Components (see [instrument](#instrument)). Review the warnings: texts in components that both render stay as they are.
731
767
 
732
768
  **Non-React stacks (Vue, Svelte, …):** the instrument step transforms React/JSX out of the box. For other stacks, add a plugin that covers your file type (community: [i18next-cli-vue](https://github.com/PBK-B/i18next-cli-vue), [i18next-cli-plugin-svelte](https://github.com/dreamscached/i18next-cli-plugin-svelte) — or write your own via the [Plugin System](#plugin-system) `instrumentOnLoad`/`onLoad` hooks). With a matching plugin configured, `localize` runs the full flow; without one, the instrument step is skipped with guidance and the remaining steps (extract → Locize → auto-translate) still run.
733
769
 
@@ -780,8 +816,11 @@ all commands.
780
816
  for future agent sessions.
781
817
  3. Instrument: run `npx i18next-cli instrument --dry-run` and review the
782
818
  planned changes; then `npx i18next-cli instrument` to apply. Inspect the
783
- git diff carefully: fix any t() wrapping inside Next.js *server components*
784
- (add 'use client' or refactor to a server-side t() pattern). Commit.
819
+ git diff carefully and the warnings it prints. In a Next.js app it writes
820
+ next-i18next's calls (await getT() in Server Components, useT() in Client
821
+ Components); texts it left (components that Server and Client Components
822
+ both render, texts outside components) are listed: move them or give the
823
+ component a t prop. If it printed next-i18next setup steps, do them. Commit.
785
824
  4. Extract: run `npx i18next-cli extract`. Verify the locale JSON files were
786
825
  written (check the extract.output path in the config). If the developer
787
826
  chose repository files only: translate the extracted keys yourself or
package/dist/cjs/cli.js CHANGED
@@ -39,7 +39,7 @@ const program = new commander.Command();
39
39
  program
40
40
  .name('i18next-cli')
41
41
  .description('A unified, high-performance i18next CLI.')
42
- .version('1.89.0') // This string is replaced with the actual version at build time by rollup
42
+ .version('1.90.0') // This string is replaced with the actual version at build time by rollup
43
43
  .addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
44
44
  // new: global config override option
45
45
  program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
@@ -105,7 +105,7 @@ program
105
105
  return inputGlobs.some(g => minimatch.minimatch(f, g, { dot: true })) &&
106
106
  !ignoreGlobs.some(g => minimatch.minimatch(f, g, { dot: true }));
107
107
  };
108
- const watcher = chokidar__default.default.watch(Array.from(new Set(inputGlobs.map(globBase))), {
108
+ const watcher = chokidar__default.default.watch(Array.from(new Set(inputGlobs.flatMap(globBases))), {
109
109
  ignored: (path, stats) => /node_modules/.test(path) || (!!stats?.isFile() && !isInput(path)),
110
110
  ignoreInitial: true,
111
111
  persistent: true,
@@ -465,14 +465,18 @@ const deriveOutputIgnore = (output) => {
465
465
  return [output.replace(/\{\{[^}]+\}\}/g, '*')];
466
466
  };
467
467
  // static leading folder of a glob: 'src/**/*.ts' -> 'src'
468
- const globBase = (pattern) => {
468
+ // the directories a glob starts in: `{app,components}/**` starts in two, not in the project root
469
+ const globBases = (pattern) => {
470
+ const brace = /^((?:[^*?[\]{}()!/]+\/)*)\{([^{}]+)\}(\/.*)?$/.exec(pattern);
471
+ if (brace)
472
+ return brace[2].split(',').flatMap(alt => globBases(`${brace[1]}${alt}${brace[3] ?? ''}`));
469
473
  const parts = [];
470
474
  for (const segment of pattern.split('/')) {
471
475
  if (/[*?[\]{}()!]/.test(segment))
472
476
  break;
473
477
  parts.push(segment);
474
478
  }
475
- return parts.join('/') || '.';
479
+ return [parts.join('/') || '.'];
476
480
  };
477
481
  // helper to expand one or many glob patterns
478
482
  const expandGlobs = async (patterns = []) => {
@@ -158,20 +158,21 @@ async function ensureConfig(configPath, logger$1 = new logger.ConsoleLogger()) {
158
158
  async function findTsConfigFile() {
159
159
  let currentDir = process.cwd();
160
160
  while (true) {
161
- const tsConfigPath = node_path.join(currentDir, 'tsconfig.json');
162
- try {
163
- await promises.access(tsConfigPath);
164
- return tsConfigPath;
165
- }
166
- catch {
167
- // File not found, move to parent directory
168
- const parentDir = node_path.dirname(currentDir);
169
- if (parentDir === currentDir) {
170
- // Reached the root of the file system
171
- return null;
161
+ // a JavaScript project keeps its `paths` in jsconfig.json (`@/*` in a Next.js app)
162
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
163
+ try {
164
+ await promises.access(node_path.join(currentDir, name));
165
+ return node_path.join(currentDir, name);
172
166
  }
173
- currentDir = parentDir;
167
+ catch { }
168
+ }
169
+ // File not found, move to parent directory
170
+ const parentDir = node_path.dirname(currentDir);
171
+ if (parentDir === currentDir) {
172
+ // Reached the root of the file system
173
+ return null;
174
174
  }
175
+ currentDir = parentDir;
175
176
  }
176
177
  }
177
178
  /**
@@ -258,7 +258,7 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
258
258
  });
259
259
  }
260
260
  catch (err) {
261
- // Fallback for .ts files with JSX (already present)
261
+ // Fallback for .ts files with JSX (already present); JSX in a .js file is common enough to need no note
262
262
  if (effectiveExt === '.ts' && !isTSX) {
263
263
  try {
264
264
  ast = await core.parse(code, {
@@ -268,7 +268,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
268
268
  dynamicImport: true,
269
269
  comments: true,
270
270
  });
271
- logger$1.info?.(`Parsed ${file} using TSX fallback`);
272
271
  }
273
272
  catch (err2) {
274
273
  throw new validation.ExtractorError('Failed to process file', file, err2);
@@ -284,7 +283,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
284
283
  dynamicImport: true,
285
284
  comments: true,
286
285
  });
287
- logger$1.info?.(`Parsed ${file} using JSX fallback`);
288
286
  }
289
287
  catch (err2) {
290
288
  throw new validation.ExtractorError('Failed to process file', file, err2);
@@ -3,7 +3,56 @@
3
3
  var glob = require('glob');
4
4
  var promises = require('node:fs/promises');
5
5
  var node_path = require('node:path');
6
+ var fileUtils = require('./utils/file-utils.js');
6
7
 
8
+ /** The directories source files usually live in, one glob for those that exist (`{app,components}/**`). */
9
+ async function sourceInput() {
10
+ const dirs = [];
11
+ // not `lib`, often the build output of a package
12
+ for (const dir of ['src', 'app', 'pages', 'components']) {
13
+ if (await promises.stat(dir).then(found => found.isDirectory(), () => false))
14
+ dirs.push(dir);
15
+ }
16
+ const exts = '**/*.{js,jsx,mjs,ts,tsx}';
17
+ return [dirs.length > 1 ? `{${dirs.join(',')}}/${exts}` : `${dirs[0] ?? 'src'}/${exts}`];
18
+ }
19
+ /**
20
+ * The extract options the app's own setup decides: next-i18next's `defaultNS` (from its config, `common` when it
21
+ * sets none), the message format of i18next-icu or i18next-mf2, and `keySeparator: false` for translation files
22
+ * with flat keys that contain dots (`"blog.title": "…"`).
23
+ */
24
+ async function setupOptions(translationFiles) {
25
+ const deps = await fileUtils.readProjectDeps();
26
+ const options = {};
27
+ if (deps['next-i18next']) {
28
+ const configs = await glob.glob('{i18n.config,next-i18next.config,i18n.shared}.{ts,js,mjs,cjs}', { ignore: 'node_modules/**' });
29
+ for (const file of configs) {
30
+ const ns = /\bdefaultNS\s*:\s*['"]([^'"]+)['"]/.exec(await promises.readFile(file, 'utf-8'))?.[1];
31
+ if (ns) {
32
+ options.defaultNS = ns;
33
+ break;
34
+ }
35
+ }
36
+ options.defaultNS ??= 'common';
37
+ }
38
+ if (deps['i18next-icu'])
39
+ options.messageFormat = 'icu';
40
+ else if (deps['i18next-mf2'])
41
+ options.messageFormat = 'mf2';
42
+ const flat = [];
43
+ for (const file of translationFiles.filter(f => node_path.extname(f) === '.json')) {
44
+ try {
45
+ const json = JSON.parse(await promises.readFile(file, 'utf-8'));
46
+ if (Object.values(json).some(v => typeof v === 'object'))
47
+ return options;
48
+ flat.push(Object.keys(json).some(key => key.includes('.')));
49
+ }
50
+ catch { }
51
+ }
52
+ if (flat.includes(true))
53
+ options.keySeparator = false;
54
+ return options;
55
+ }
7
56
  // A list of common glob patterns for the primary language ('en') or ('dev') translation files.
8
57
  const HEURISTIC_PATTERNS = [
9
58
  'public/locales/dev/*.json',
@@ -90,15 +139,11 @@ async function detectConfig() {
90
139
  return {
91
140
  locales,
92
141
  extract: {
93
- input: [
94
- 'src/**/*.{js,jsx,mjs,ts,tsx}',
95
- 'app/**/*.{js,jsx,mjs,ts,tsx}',
96
- 'pages/**/*.{js,jsx,mjs,ts,tsx}',
97
- 'components/**/*.{js,jsx,mjs,ts,tsx}'
98
- ],
142
+ input: await sourceInput(),
99
143
  output: node_path.join(basePath, '{{language}}', `{{namespace}}${extension}`),
100
144
  outputFormat,
101
145
  primaryLanguage: locales.includes('en') ? 'en' : locales[0],
146
+ ...await setupOptions(files),
102
147
  },
103
148
  };
104
149
  }
package/dist/cjs/init.js CHANGED
@@ -190,11 +190,16 @@ async function runInit(options = {}) {
190
190
  const isTypeScript = answers.fileType.includes('TypeScript');
191
191
  const isEsm = await isEsmProject();
192
192
  const fileName = isTypeScript ? 'i18next.config.ts' : 'i18next.config.js';
193
+ // what the app's own setup decides (next-i18next's defaultNS, ICU, flat keys), as detected
194
+ const { defaultNS, messageFormat, keySeparator } = detectedConfig?.extract ?? {};
193
195
  const configObject = {
194
196
  locales: answers.locales,
195
197
  extract: {
196
198
  input: answers.input,
197
199
  output: answers.output,
200
+ ...(defaultNS !== undefined && { defaultNS }),
201
+ ...(messageFormat && { messageFormat }),
202
+ ...(keySeparator !== undefined && { keySeparator }),
198
203
  },
199
204
  };
200
205
  if (locizeConfig)