i18next-cli 1.89.0 → 1.91.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 (51) hide show
  1. package/README.md +57 -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/extractor/parsers/jsx-parser.js +4 -2
  6. package/dist/cjs/heuristic-config.js +51 -6
  7. package/dist/cjs/init.js +5 -0
  8. package/dist/cjs/instrumenter/core/instrumenter.js +272 -23
  9. package/dist/cjs/instrumenter/core/key-generator.js +1 -0
  10. package/dist/cjs/instrumenter/core/next-files.js +104 -0
  11. package/dist/cjs/instrumenter/core/transformer.js +97 -73
  12. package/dist/cjs/linter.js +190 -23
  13. package/dist/cjs/localize/agent-prompt.js +5 -2
  14. package/dist/cjs/localize/detect.js +1 -0
  15. package/dist/cjs/localize/localize.js +25 -4
  16. package/dist/esm/cli.js +8 -4
  17. package/dist/esm/config.js +13 -12
  18. package/dist/esm/extractor/core/extractor.js +1 -3
  19. package/dist/esm/extractor/parsers/jsx-parser.js +4 -3
  20. package/dist/esm/heuristic-config.js +52 -7
  21. package/dist/esm/init.js +5 -0
  22. package/dist/esm/instrumenter/core/instrumenter.js +273 -24
  23. package/dist/esm/instrumenter/core/key-generator.js +1 -0
  24. package/dist/esm/instrumenter/core/next-files.js +101 -0
  25. package/dist/esm/instrumenter/core/transformer.js +97 -73
  26. package/dist/esm/linter.js +192 -25
  27. package/dist/esm/localize/agent-prompt.js +5 -2
  28. package/dist/esm/localize/detect.js +1 -0
  29. package/dist/esm/localize/localize.js +25 -4
  30. package/package.json +2 -1
  31. package/types/cli.d.ts.map +1 -1
  32. package/types/config.d.ts.map +1 -1
  33. package/types/extractor/core/extractor.d.ts.map +1 -1
  34. package/types/extractor/parsers/jsx-parser.d.ts +1 -0
  35. package/types/extractor/parsers/jsx-parser.d.ts.map +1 -1
  36. package/types/heuristic-config.d.ts.map +1 -1
  37. package/types/init.d.ts.map +1 -1
  38. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  39. package/types/instrumenter/core/key-generator.d.ts.map +1 -1
  40. package/types/instrumenter/core/next-files.d.ts +25 -0
  41. package/types/instrumenter/core/next-files.d.ts.map +1 -0
  42. package/types/instrumenter/core/transformer.d.ts +6 -0
  43. package/types/instrumenter/core/transformer.d.ts.map +1 -1
  44. package/types/linter.d.ts.map +1 -1
  45. package/types/localize/agent-prompt.d.ts +1 -1
  46. package/types/localize/agent-prompt.d.ts.map +1 -1
  47. package/types/localize/detect.d.ts +2 -0
  48. package/types/localize/detect.d.ts.map +1 -1
  49. package/types/localize/localize.d.ts.map +1 -1
  50. package/types/types.d.ts +54 -2
  51. 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
@@ -398,6 +405,13 @@ npx i18next-cli lint
398
405
  - tags, in any order: the numbered ones of `<Trans>` (`<0>…</0>`, `<1/>`) and named ones like `<bold>` from its `components`, which react-i18next shows as text when a translation renames them. The basic HTML react-i18next keeps as is (`extract.transKeepBasicHtmlNodesFor`, default `br`, `strong`, `i`, `p`) is not compared, a language may add or drop it
399
406
 
400
407
  Plural forms are compared as a group (the union over `_zero`, `_one`, `_other`, ...), since `{{count}}` may be left out of `_one` or `_zero` and a language has forms the primary language lacks (`ru` `_few`). A partly translated plural is checked for unexpected placeholders only. Keys only one side has and empty values are skipped (`status` reports them). Configure with `lint.checkTranslationPlaceholders`: `'warn'` / `true` (default), `'error'` (fails the run), `'off'` / `false`. With `extract.messageFormat: 'icu'` or `'mf2'` the ICU / MF2 check above runs instead.
408
+ - **`<Trans>` tags against the children** *(warning by default)*: `<Trans>` numbers its children, text included, so the `{' '}` a formatter inserts at a line break shifts every later index. In `Hello{' '}<Bold>world</Bold>` the `{' '}` is `<1>` and `<Bold>` is `<2>`, and a translation `Hello <1>world</1>` renders `Hello `. The tags of the primary language's translation of every `<Trans>` with children (context and plural forms included) are resolved like react-i18next does at runtime, and a tag that does not render what it wraps is reported, e.g. `reminder:disclosure: <1> points to the text " ", which replaces its content`:
409
+ - a tag with content on a text child, which renders that text instead
410
+ - a tag past the last child, which loses its markup
411
+ - an empty tag (`<2/>`) on an element with text, which renders the element without its text
412
+ - a tag with content on a `<br/>` (or another void element), which makes React throw
413
+
414
+ A tag on an interpolation object (`<1>{{count}}</1>`) is fine, react-i18next renders its content. A tag on an expression (`{link}`) is not checked, its value is known only at runtime. A `<Trans>` with `components` is skipped. Only the primary language is checked; in the i18next format the placeholder check above compares the tags of the other languages with it. Configure with `lint.checkTransIndices`: `'warn'` / `true` (default), `'error'` (fails the run), `'off'` / `false`.
401
415
  - **String concatenation** *(warning by default)* — translated strings glued together with `+`, or a sentence split across multiple adjacent translations (`<Trans>` components and/or `{t()}` expressions rendered as siblings). This breaks in languages that reorder or inflect the pieces; use a single key with placeholders instead. Configure with `lint.checkConcatenation`: `'warn'` / `true` (default) reports it without failing the run, `'error'` makes it fail (exit non-zero, useful for CI), and `'off'` / `false` disables it.
402
416
 
403
417
  ```jsx
@@ -589,8 +603,8 @@ The instrumenter uses confidence heuristics to avoid transforming:
589
603
  built in code (`` `${projectId}-${version}` ``, `` `weight_${code}` ``, `` `${baseUrl}/api/${id}` ``,
590
604
  `` `zh-${country}` ``); and values of technical properties (`` { 'Authorization': `Bearer ${token}` } ``,
591
605
  `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`
606
+ - Strings already inside `t()` calls or `<Trans>`, `<IcuTrans>` and their `…WithoutContext` components (their
607
+ `values` too), including the project's own `extract.functions` and `extract.transComponents`
594
608
  - **Module-scope strings** — anything outside a function body, e.g. a top-level config/registry array:
595
609
  ```ts
596
610
  export const SETTINGS_SECTIONS = [
@@ -612,12 +626,41 @@ The instrumenter uses confidence heuristics to avoid transforming:
612
626
  When transformations are applied, the command automatically:
613
627
  - Injects `import { useTranslation } from 'react-i18next'` in React files (or `import i18next from 'i18next'` for non-React files)
614
628
  - 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
629
+ - 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
630
+ - 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
631
  - 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
632
  - 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
633
+ - 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
634
  - 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
635
 
636
+ **Next.js apps ([next-i18next](https://github.com/i18next/next-i18next)):**
637
+
638
+ An app with next-i18next (a dependency, or imported), and a Next.js app with no i18next set up at all, gets
639
+ next-i18next's calls, by where each file renders. The import graph decides: a file under `app/` is a Server
640
+ Component unless it says `'use client'`, a `'use client'` file and all it imports are Client Components, a file
641
+ under `pages/` and all it imports render with the Pages Router (imports resolve relative, through the `paths` of
642
+ `tsconfig.json` or `jsconfig.json` and from the project root). A Next.js app with i18next or react-i18next and no
643
+ next-i18next keeps `react-i18next`.
644
+
645
+ - **Server Components:** `const { t } = await getT()` from `next-i18next/server` (or from the module the app
646
+ imports `getT` from, such as its own `createServerI18next` file), and the component becomes `async`. A
647
+ `<Trans>` gets `t={t} i18n={i18n}` and comes from `react-i18next/TransWithoutContext`. `generateMetadata()`
648
+ and other async functions get `getT()` as well, and `export const metadata = { title: '…' }` becomes
649
+ `export async function generateMetadata () { const { t } = await getT(); return { title: t(…) } }`.
650
+ - **Client Components:** `const { t } = useT()` and `Trans` from `next-i18next/client`.
651
+ - **Pages Router:** `useTranslation` and `Trans` from `next-i18next/pages`. A page that loads no translations
652
+ (no `serverSideTranslations()` in it or in a helper it imports) is named in a warning.
653
+ - **A component that Server and Client Components both render** works with neither: its texts stay, named in a
654
+ warning, unless it gets `t` as a prop (and `i18n` too for a `<Trans>`), which it then uses.
655
+ - Left as they are, each named in a warning: texts outside components (next-i18next has no global `t`), files
656
+ no page or layout imports (which side renders them is not known), API routes (`route.ts` under `app/`,
657
+ `pages/api/`), Server Actions and cached functions (`'use server'`, `'use cache'`: `getT()` there needs
658
+ `{ lng }`), a Server Component wrapped in `memo()` or `forwardRef()`, and language switches: next-i18next
659
+ changes the language through the route or `useChangeLanguage()`.
660
+ - No init file: next-i18next sets i18next up itself. When it is not set up yet, the steps are printed (install,
661
+ then `i18n.config`, proxy and root layout for the App Router, `appWithTranslation` and `serverSideTranslations`
662
+ for the Pages Router).
663
+
621
664
  **Recommended workflow:**
622
665
 
623
666
  1. **Preview first:** Always run with `--dry-run` to see what will change:
@@ -727,7 +770,7 @@ The command walks through six steps:
727
770
 
728
771
  **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
772
 
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.
773
+ > **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
774
 
732
775
  **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
776
 
@@ -780,8 +823,11 @@ all commands.
780
823
  for future agent sessions.
781
824
  3. Instrument: run `npx i18next-cli instrument --dry-run` and review the
782
825
  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.
826
+ git diff carefully and the warnings it prints. In a Next.js app it writes
827
+ next-i18next's calls (await getT() in Server Components, useT() in Client
828
+ Components); texts it left (components that Server and Client Components
829
+ both render, texts outside components) are listed: move them or give the
830
+ component a t prop. If it printed next-i18next setup steps, do them. Commit.
785
831
  4. Extract: run `npx i18next-cli extract`. Verify the locale JSON files were
786
832
  written (check the extract.output path in the config). If the developer
787
833
  chose repository files only: translate the extracted keys yourself or
@@ -1202,6 +1248,10 @@ export default defineConfig({
1202
1248
  * language (default: 'warn'). Accepts the same values as checkConcatenation. */
1203
1249
  checkTranslationPlaceholders: 'warn',
1204
1250
 
1251
+ /** Report <Trans> tags of the primary translation that miss the component's children, e.g. a <1>
1252
+ * on the {' '} a formatter inserted (default: 'warn'). Accepts the same values as checkConcatenation. */
1253
+ checkTransIndices: 'warn',
1254
+
1205
1255
  /** Baseline file written by `lint --update-baseline` (default: 'i18next-lint-baseline.json') */
1206
1256
  baseline: 'i18next-lint-baseline.json',
1207
1257
  },
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.91.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);
@@ -504,8 +504,9 @@ function getElementName(element) {
504
504
  }
505
505
  function trimTextNode(text) {
506
506
  text = text.replace(/\r\n/g, '\n'); // Normalize line endings
507
- // If text is ONLY whitespace AND contains a newline, remove it entirely
508
- if (/^\s+$/.test(text) && /\n/.test(text)) {
507
+ // If text is ONLY whitespace AND contains a newline, remove it entirely. Only spaces and tabs, like
508
+ // Babel and SWC: an `&nbsp;` at the end of a line (U+00A0, which `\s` matches) stays a child
509
+ if (/^[ \t\n]+$/.test(text) && /\n/.test(text)) {
509
510
  return null;
510
511
  }
511
512
  // Trim leading/trailing whitespace sequences containing newlines
@@ -674,3 +675,4 @@ function serializeJSXChildren(children, config) {
674
675
  exports.extractFromIcuMacro = extractFromIcuMacro;
675
676
  exports.extractFromIcuTrans = extractFromIcuTrans;
676
677
  exports.extractFromTransComponent = extractFromTransComponent;
678
+ exports.trimTextNode = trimTextNode;
@@ -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)