i18next-cli 1.11.5 → 1.11.7

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/CHANGELOG.md CHANGED
@@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.11.7](https://github.com/i18next/i18next-cli/compare/v1.11.6...v1.11.7) - 2025-10-20
9
+
10
+ - improve: extractor --sync-primary (--syncPrimaryWithDefaults) incorrectly reset plural variants to empty strings, effectively removing existing plural translations [#67](https://github.com/i18next/i18next-cli/issues/67)
11
+ - improve Trans child indexing further [#63](https://github.com/i18next/i18next-cli/issues/63)
12
+
13
+ ## [1.11.6](https://github.com/i18next/i18next-cli/compare/v1.11.5...v1.11.6) - 2025-10-19
14
+
15
+ - Fix Trans child indexing to match react-i18next and handle layout-only whitespace correctly [#63](https://github.com/i18next/i18next-cli/issues/63)
16
+
8
17
  ## [1.11.5](https://github.com/i18next/i18next-cli/compare/v1.11.4...v1.11.5) - 2025-10-17
9
18
 
10
19
  - **Extractor:** ignore formatting-only JSXText nodes when serializing <Trans> children to avoid inflated component placeholder indexes and incorrect keys caused by indentation/newlines — fixes [#66](https://github.com/i18next/i18next-cli/issues/66)
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.5"),f.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.").action(async e=>{try{const o=await i.ensureConfig(),a=async()=>{const t=await r.runExtractor(o,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});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...");t.watch(await n.glob(o.extract.input),{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)}}),f.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,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.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 o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.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 r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.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.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
2
+ "use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.7"),f.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.").action(async e=>{try{const o=await i.ensureConfig(),a=async()=>{const t=await r.runExtractor(o,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});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...");t.watch(await n.glob(o.extract.input),{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)}}),f.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,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.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 o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.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 r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.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.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
@@ -1 +1 @@
1
- "use strict";var e=require("./ast-utils.js");exports.extractFromTransComponent=function(t,n){const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),r=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),a=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),p=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let s;a||"JSXAttribute"!==p?.type||"JSXExpressionContainer"!==p.value?.type||"ObjectExpression"!==p.value.expression.type||(s=e.getObjectProperty(p.value.expression,"count"));const o=!!a||!!s,l=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),u="JSXAttribute"===l?.type&&"JSXExpressionContainer"===l.value?.type&&"ObjectExpression"===l.value.expression.type?l.value.expression:void 0,y=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),f=!!y,v=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let c="JSXAttribute"===v?.type&&"JSXExpressionContainer"===v.value?.type?v.value.expression:"JSXAttribute"===v?.type&&"StringLiteral"===v.value?.type?v.value:void 0;const d=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let m;if(m="JSXAttribute"===d?.type&&"StringLiteral"===d.value?.type?d.value.value:void 0,u&&(void 0===m&&(m=e.getObjectPropValue(u,"ns")),void 0===c)){const t=e.getObjectProperty(u,"context");t?.value&&(c=t.value)}const S=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n"),r={n:0};function a(e){if(!e||!e.length)return"";let t="";for(const p of e)if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){const e=p.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type&&(t+=`{{${n.value}}}`)}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type&&(t+=`{{${e.callee.value}}}`);r.n++;continue}if("JSXElement"===p.type){let e;if(p.opening&&p.opening.name&&"Identifier"===p.opening.name.type&&(e=p.opening.name.value),e&&n.has(e)){t+=`<${e}>${a(p.children||[])}</${e}>`}else{const e=r.n;r.n++;t+=`<${e}>${a(p.children||[])}</${e}>`}continue}"JSXFragment"!==p.type||(t+=a(p.children||[]))}else i(p)||(t+=p.value,r.n++);return t}const p=a(e);return String(p).replace(/\s+/g," ").trim()}(t.children,n);let g,b,x;if("JSXAttribute"===r?.type&&"StringLiteral"===r.value?.type)g=r.value.value;else{const e=n.extract.defaultValue;g="string"==typeof e?e:""}if("JSXAttribute"===i?.type){if("StringLiteral"===i.value?.type){if(b=i.value,x=b.value,!x||""===x.trim())return console.warn("Ignoring Trans component with empty i18nKey"),null;if(m&&"StringLiteral"===b.type){const e=n.extract.nsSeparator??":",t=b.value;if(e&&t.startsWith(`${m}${e}`)){if(x=t.slice(`${m}${e}`.length),!x||""===x.trim())return console.warn("Ignoring Trans component with i18nKey that becomes empty after namespace removal"),null;b={...b,value:x}}}}else"JSXExpressionContainer"===i.value?.type&&"JSXEmptyExpression"!==i.value.expression.type&&(b=i.value.expression);if(!b)return null}return r||!x||S.trim()?!r&&S.trim()&&(g=S):g=x,{keyExpression:b,serializedChildren:S,ns:m,defaultValue:g,hasCount:o,isOrdinal:f,contextExpression:c,optionsNode:u}};
1
+ "use strict";var e=require("./ast-utils.js");exports.extractFromTransComponent=function(t,n){const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),r=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),s=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),p=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let o;s||"JSXAttribute"!==p?.type||"JSXExpressionContainer"!==p.value?.type||"ObjectExpression"!==p.value.expression.type||(o=e.getObjectProperty(p.value.expression,"count"));const a=!!s||!!o,l=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),u="JSXAttribute"===l?.type&&"JSXExpressionContainer"===l.value?.type&&"ObjectExpression"===l.value.expression.type?l.value.expression:void 0,y=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),f=!!y,c=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let v="JSXAttribute"===c?.type&&"JSXExpressionContainer"===c.value?.type?c.value.expression:"JSXAttribute"===c?.type&&"StringLiteral"===c.value?.type?c.value:void 0;const S=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let x;if(x="JSXAttribute"===S?.type&&"StringLiteral"===S.value?.type?S.value.value:void 0,u&&(void 0===x&&(x=e.getObjectPropValue(u,"ns")),void 0===v)){const t=e.getObjectProperty(u,"context");t?.value&&(v=t.value)}const d=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function r(e,t,s=!1){if(!e||!e.length)return;let p=0,o=e.length-1;for(;p<=o&&i(e[p]);)p++;for(;o>=p&&i(e[o]);)o--;const a=p<=o?e.slice(p,o+1):[];for(let e=0;e<a.length;e++){const p=a[e];if(p)if("JSXText"!==p.type)if("JSXExpressionContainer"!==p.type){if("JSXElement"===p.type){const e=p.opening&&p.opening.name&&"Identifier"===p.opening.name.type?p.opening.name.value:void 0;e&&n.has(e)?r(p.children||[],t,!1):(t.push(p),r(p.children||[],t,!0));continue}"JSXFragment"!==p.type||r(p.children||[],t,s)}else{if(s&&p.expression){const e=p.expression.type;if("ObjectExpression"===e){const e=p.expression.properties&&p.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}if("StringLiteral"===e){const e=String(p.expression.value||"");if(!(/^\s*$/.test(e)&&!e.includes("\n")))continue}else if("Identifier"===e||"MemberExpression"===e||"CallExpression"===e)continue}if(p.expression&&"StringLiteral"===p.expression.type){const n=String(p.expression.value||""),r=/^\s*$/.test(n)&&!n.includes("\n"),s=a[e-1],o=a[e+1];if(r){const n=a[e+2];if(o&&"JSXText"===o.type&&i(o)&&n&&("JSXElement"===n.type||"JSXFragment"===n.type)){const t=a[e-1],n=a[e-2];if(!t||"JSXText"!==t.type&&n&&"JSXExpressionContainer"===n.type)continue}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&i(o))continue;const r=!o||"JSXText"===o.type&&!i(o);if(s&&"JSXText"===s.type&&r){const e=t[t.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+p.expression.value;continue}}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&i(o))continue}}t.push(p)}else{if(s)continue;if(i(p)){const n=t[t.length-1],i=a[e-1];if(n){if(i&&"JSXExpressionContainer"===i.type)continue;if("JSXText"===n.type&&i&&"JSXText"===i.type){n.value=String(n.value)+p.value;continue}}}t.push(p)}}}const s=[];function p(e){if(!e||0===e.length)return"";let t="";for(const r of e)if(r)if("JSXText"!==r.type){if("JSXExpressionContainer"===r.type){const e=r.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type?t+=`{{${n.value}}}`:t+="{{value}}"}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type?t+=`{{${e.callee.value}}}`:t+="{{value}}";continue}if("JSXElement"===r.type){let e;if(r.opening&&r.opening.name&&"Identifier"===r.opening.name.type&&(e=r.opening.name.value),e&&n.has(e)){t+=`<${e}>${p(r.children||[])}</${e}>`}else{const e=s.indexOf(r);t+=`<${e}>${p(r.children||[])}</${e}>`}continue}"JSXFragment"!==r.type||(t+=p(r.children||[]))}else i(r)||(t+=r.value);return t}r(e,s,!1);const o=p(e);return String(o).replace(/\s+/g," ").trim()}(t.children,n);let g,J,X;if("JSXAttribute"===r?.type&&"StringLiteral"===r.value?.type)g=r.value.value;else{const e=n.extract.defaultValue;g="string"==typeof e?e:""}if("JSXAttribute"===i?.type){if("StringLiteral"===i.value?.type){if(J=i.value,X=J.value,!X||""===X.trim())return null;if(x&&"StringLiteral"===J.type){const e=n.extract.nsSeparator??":",t=J.value;if(e&&t.startsWith(`${x}${e}`)){if(X=t.slice(`${x}${e}`.length),!X||""===X.trim())return null;J={...J,value:X}}}}else"JSXExpressionContainer"===i.value?.type&&"JSXEmptyExpression"!==i.value.expression.type&&(J=i.value.expression);if(!J)return null}return r||!X||d.trim()?!r&&d.trim()&&(g=d):g=X,{keyExpression:J,serializedChildren:d,ns:x,defaultValue:g,hasCount:a,isOrdinal:f,contextExpression:v,optionsNode:u}};
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as t}from"commander";import e from"chokidar";import{glob as o}from"glob";import n from"chalk";import{ensureConfig as i,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as r}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as p}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as u}from"./status.js";import{runLocizeSync as f,runLocizeDownload as g,runLocizeMigrate as h}from"./locize.js";const y=new t;y.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.5"),y.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.").action(async t=>{try{const n=await i(),a=async()=>{const e=await r(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!e?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&e&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),e};if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(n.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),y.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(t,e)=>{let o=await a();if(!o){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),o=t}await u(o,{detail:t,namespace:e.namespace})}),y.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 t=>{const n=await i(),a=()=>s(n);if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),y.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),y.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await p(t)}),y.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),y.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 t=>{const i=async()=>{let t=await a();if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const e=await c();e||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=e}await d(t)};if(await i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){e.watch(await o(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),y.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.").action(async t=>{const e=await i();await f(e,t)}),y.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const e=await i();await g(e,t)}),y.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const e=await i();await h(e,t)}),y.parse(process.argv);
2
+ import{Command as t}from"commander";import e from"chokidar";import{glob as o}from"glob";import n from"chalk";import{ensureConfig as i,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as r}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as p}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as u}from"./status.js";import{runLocizeSync as f,runLocizeDownload as g,runLocizeMigrate as h}from"./locize.js";const y=new t;y.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.7"),y.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.").action(async t=>{try{const n=await i(),a=async()=>{const e=await r(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!e?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&e&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),e};if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(n.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),y.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(t,e)=>{let o=await a();if(!o){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),o=t}await u(o,{detail:t,namespace:e.namespace})}),y.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 t=>{const n=await i(),a=()=>s(n);if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),y.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),y.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await p(t)}),y.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),y.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 t=>{const i=async()=>{let t=await a();if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const e=await c();e||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=e}await d(t)};if(await i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){e.watch(await o(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),y.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.").action(async t=>{const e=await i();await f(e,t)}),y.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const e=await i();await g(e,t)}),y.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const e=await i();await h(e,t)}),y.parse(process.argv);
@@ -1 +1 @@
1
- import{getObjectProperty as e,getObjectPropValue as t}from"./ast-utils.js";function n(n,i){const r=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),a=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),p=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),s=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let l;p||"JSXAttribute"!==s?.type||"JSXExpressionContainer"!==s.value?.type||"ObjectExpression"!==s.value.expression.type||(l=e(s.value.expression,"count"));const o=!!p||!!l,u=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),y="JSXAttribute"===u?.type&&"JSXExpressionContainer"===u.value?.type&&"ObjectExpression"===u.value.expression.type?u.value.expression:void 0,f=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),v=!!f,c=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let d="JSXAttribute"===c?.type&&"JSXExpressionContainer"===c.value?.type?c.value.expression:"JSXAttribute"===c?.type&&"StringLiteral"===c.value?.type?c.value:void 0;const m=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let S;if(S="JSXAttribute"===m?.type&&"StringLiteral"===m.value?.type?m.value.value:void 0,y&&(void 0===S&&(S=t(y,"ns")),void 0===d)){const t=e(y,"context");t?.value&&(d=t.value)}const g=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n"),r={n:0};function a(e){if(!e||!e.length)return"";let t="";for(const p of e)if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){const e=p.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type&&(t+=`{{${n.value}}}`)}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type&&(t+=`{{${e.callee.value}}}`);r.n++;continue}if("JSXElement"===p.type){let e;if(p.opening&&p.opening.name&&"Identifier"===p.opening.name.type&&(e=p.opening.name.value),e&&n.has(e)){t+=`<${e}>${a(p.children||[])}</${e}>`}else{const e=r.n;r.n++;t+=`<${e}>${a(p.children||[])}</${e}>`}continue}"JSXFragment"!==p.type||(t+=a(p.children||[]))}else i(p)||(t+=p.value,r.n++);return t}const p=a(e);return String(p).replace(/\s+/g," ").trim()}(n.children,i);let x,b,J;if("JSXAttribute"===a?.type&&"StringLiteral"===a.value?.type)x=a.value.value;else{const e=i.extract.defaultValue;x="string"==typeof e?e:""}if("JSXAttribute"===r?.type){if("StringLiteral"===r.value?.type){if(b=r.value,J=b.value,!J||""===J.trim())return console.warn("Ignoring Trans component with empty i18nKey"),null;if(S&&"StringLiteral"===b.type){const e=i.extract.nsSeparator??":",t=b.value;if(e&&t.startsWith(`${S}${e}`)){if(J=t.slice(`${S}${e}`.length),!J||""===J.trim())return console.warn("Ignoring Trans component with i18nKey that becomes empty after namespace removal"),null;b={...b,value:J}}}}else"JSXExpressionContainer"===r.value?.type&&"JSXEmptyExpression"!==r.value.expression.type&&(b=r.value.expression);if(!b)return null}return a||!J||g.trim()?!a&&g.trim()&&(x=g):x=J,{keyExpression:b,serializedChildren:g,ns:S,defaultValue:x,hasCount:o,isOrdinal:v,contextExpression:d,optionsNode:y}}export{n as extractFromTransComponent};
1
+ import{getObjectProperty as e,getObjectPropValue as t}from"./ast-utils.js";function n(n,i){const r=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),s=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),p=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),o=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let l;p||"JSXAttribute"!==o?.type||"JSXExpressionContainer"!==o.value?.type||"ObjectExpression"!==o.value.expression.type||(l=e(o.value.expression,"count"));const a=!!p||!!l,u=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),y="JSXAttribute"===u?.type&&"JSXExpressionContainer"===u.value?.type&&"ObjectExpression"===u.value.expression.type?u.value.expression:void 0,f=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),c=!!f,v=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let S="JSXAttribute"===v?.type&&"JSXExpressionContainer"===v.value?.type?v.value.expression:"JSXAttribute"===v?.type&&"StringLiteral"===v.value?.type?v.value:void 0;const x=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let d;if(d="JSXAttribute"===x?.type&&"StringLiteral"===x.value?.type?x.value.value:void 0,y&&(void 0===d&&(d=t(y,"ns")),void 0===S)){const t=e(y,"context");t?.value&&(S=t.value)}const J=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function r(e,t,s=!1){if(!e||!e.length)return;let p=0,o=e.length-1;for(;p<=o&&i(e[p]);)p++;for(;o>=p&&i(e[o]);)o--;const l=p<=o?e.slice(p,o+1):[];for(let e=0;e<l.length;e++){const p=l[e];if(p)if("JSXText"!==p.type)if("JSXExpressionContainer"!==p.type){if("JSXElement"===p.type){const e=p.opening&&p.opening.name&&"Identifier"===p.opening.name.type?p.opening.name.value:void 0;e&&n.has(e)?r(p.children||[],t,!1):(t.push(p),r(p.children||[],t,!0));continue}"JSXFragment"!==p.type||r(p.children||[],t,s)}else{if(s&&p.expression){const e=p.expression.type;if("ObjectExpression"===e){const e=p.expression.properties&&p.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}if("StringLiteral"===e){const e=String(p.expression.value||"");if(!(/^\s*$/.test(e)&&!e.includes("\n")))continue}else if("Identifier"===e||"MemberExpression"===e||"CallExpression"===e)continue}if(p.expression&&"StringLiteral"===p.expression.type){const n=String(p.expression.value||""),r=/^\s*$/.test(n)&&!n.includes("\n"),s=l[e-1],o=l[e+1];if(r){const n=l[e+2];if(o&&"JSXText"===o.type&&i(o)&&n&&("JSXElement"===n.type||"JSXFragment"===n.type)){const t=l[e-1],n=l[e-2];if(!t||"JSXText"!==t.type&&n&&"JSXExpressionContainer"===n.type)continue}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&i(o))continue;const r=!o||"JSXText"===o.type&&!i(o);if(s&&"JSXText"===s.type&&r){const e=t[t.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+p.expression.value;continue}}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&i(o))continue}}t.push(p)}else{if(s)continue;if(i(p)){const n=t[t.length-1],i=l[e-1];if(n){if(i&&"JSXExpressionContainer"===i.type)continue;if("JSXText"===n.type&&i&&"JSXText"===i.type){n.value=String(n.value)+p.value;continue}}}t.push(p)}}}const s=[];function p(e){if(!e||0===e.length)return"";let t="";for(const r of e)if(r)if("JSXText"!==r.type){if("JSXExpressionContainer"===r.type){const e=r.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type?t+=`{{${n.value}}}`:t+="{{value}}"}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type?t+=`{{${e.callee.value}}}`:t+="{{value}}";continue}if("JSXElement"===r.type){let e;if(r.opening&&r.opening.name&&"Identifier"===r.opening.name.type&&(e=r.opening.name.value),e&&n.has(e)){t+=`<${e}>${p(r.children||[])}</${e}>`}else{const e=s.indexOf(r);t+=`<${e}>${p(r.children||[])}</${e}>`}continue}"JSXFragment"!==r.type||(t+=p(r.children||[]))}else i(r)||(t+=r.value);return t}r(e,s,!1);const o=p(e);return String(o).replace(/\s+/g," ").trim()}(n.children,i);let X,g,m;if("JSXAttribute"===s?.type&&"StringLiteral"===s.value?.type)X=s.value.value;else{const e=i.extract.defaultValue;X="string"==typeof e?e:""}if("JSXAttribute"===r?.type){if("StringLiteral"===r.value?.type){if(g=r.value,m=g.value,!m||""===m.trim())return null;if(d&&"StringLiteral"===g.type){const e=i.extract.nsSeparator??":",t=g.value;if(e&&t.startsWith(`${d}${e}`)){if(m=t.slice(`${d}${e}`.length),!m||""===m.trim())return null;g={...g,value:m}}}}else"JSXExpressionContainer"===r.value?.type&&"JSXEmptyExpression"!==r.value.expression.type&&(g=r.value.expression);if(!g)return null}return s||!m||J.trim()?!s&&J.trim()&&(X=J):X=m,{keyExpression:g,serializedChildren:J,ns:d,defaultValue:X,hasCount:a,isOrdinal:c,contextExpression:S,optionsNode:y}}export{n as extractFromTransComponent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.11.5",
3
+ "version": "1.11.7",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.ts CHANGED
@@ -21,7 +21,7 @@ const program = new Command()
21
21
  program
22
22
  .name('i18next-cli')
23
23
  .description('A unified, high-performance i18next CLI.')
24
- .version('1.11.5')
24
+ .version('1.11.7')
25
25
 
26
26
  program
27
27
  .command('extract')
@@ -227,6 +227,7 @@ function buildNewTranslationsForNs (
227
227
  }
228
228
 
229
229
  let valueToSet: string
230
+
230
231
  if (existingValue === undefined || isStaleObject) {
231
232
  // New key or stale object - determine what value to use
232
233
  if (locale === primaryLanguage) {
@@ -264,7 +265,22 @@ function buildNewTranslationsForNs (
264
265
  key.startsWith(defaultValue + contextSeparator)))
265
266
  )
266
267
 
267
- valueToSet = (defaultValue && !isDerivedDefault) ? defaultValue : existingValue
268
+ // Check if the current key is a plural or context variant
269
+ // const isVariantKey = key.includes(pluralSeparator) || key.includes(contextSeparator)
270
+ // A simple check to see if the default value seems like a base value reused for a variant
271
+ // This is true if the key IS a variant, but the default value is NOT derived from the key itself.
272
+ // const isBaseDefaultReusedForVariant = isVariantKey && defaultValue && !isDerivedDefault
273
+
274
+ // If a meaningful (non-derived) defaultValue is provided in code, apply it.
275
+ // This includes plural/context variant keys generated from a single explicit
276
+ // default (e.g. t('key', 'Default', { count })) — we should update all
277
+ // generated variant forms to that explicit default.
278
+ if (defaultValue && !isDerivedDefault) {
279
+ valueToSet = defaultValue
280
+ } else {
281
+ // Otherwise preserve existing translations.
282
+ valueToSet = existingValue
283
+ }
268
284
  } else {
269
285
  // Not primary language or not syncing - always preserve existing
270
286
  valueToSet = existingValue
@@ -182,7 +182,6 @@ export function extractFromTransComponent (node: JSXElement, config: I18nextTool
182
182
 
183
183
  // Validate that the key is not empty
184
184
  if (!processedKeyValue || processedKeyValue.trim() === '') {
185
- console.warn('Ignoring Trans component with empty i18nKey')
186
185
  return null
187
186
  }
188
187
 
@@ -197,7 +196,6 @@ export function extractFromTransComponent (node: JSXElement, config: I18nextTool
197
196
 
198
197
  // Validate processed key is not empty
199
198
  if (!processedKeyValue || processedKeyValue.trim() === '') {
200
- console.warn('Ignoring Trans component with i18nKey that becomes empty after namespace removal')
201
199
  return null
202
200
  }
203
201
 
@@ -254,26 +252,234 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
254
252
  /^\s*$/.test(n.value) &&
255
253
  n.value.includes('\n')
256
254
 
257
- // counter of "indexable" slots (increments for meaningful text, expression containers and non-preserved elements)
258
- const counter = { n: 0 }
255
+ // Build deterministic global slot list (pre-order)
256
+ function collectSlots (nodes: any[], slots: any[], parentIsNonPreserved = false) {
257
+ if (!nodes || !nodes.length) return
259
258
 
260
- function serialize (nodes: any[]): string {
261
- if (!nodes || !nodes.length) return ''
262
- let out = ''
259
+ // First, identify boundary whitespace nodes (start and end of sibling list)
260
+ // We trim ONLY pure-whitespace JSXText nodes from the boundaries
261
+ let startIdx = 0
262
+ let endIdx = nodes.length - 1
263
+
264
+ // Skip leading boundary whitespace (pure whitespace JSXText only)
265
+ while (startIdx <= endIdx && isFormattingWhitespace(nodes[startIdx])) {
266
+ startIdx++
267
+ }
268
+
269
+ // Skip trailing boundary whitespace (pure whitespace JSXText only)
270
+ while (endIdx >= startIdx && isFormattingWhitespace(nodes[endIdx])) {
271
+ endIdx--
272
+ }
263
273
 
264
- for (const child of nodes) {
265
- if (!child) continue
274
+ // Now process all nodes in the range [startIdx, endIdx] - this includes interior whitespace
275
+ const meaningfulNodes = startIdx <= endIdx ? nodes.slice(startIdx, endIdx + 1) : []
276
+
277
+ for (let i = 0; i < meaningfulNodes.length; i++) {
278
+ const n = meaningfulNodes[i]
279
+ if (!n) continue
280
+
281
+ if (n.type === 'JSXText') {
282
+ // Do NOT add plain text nodes as separate global slots when they are
283
+ // children of a non-preserved parent element (e.g. <pre>). The parent
284
+ // element itself is the slot; inner text must not shift indexes.
285
+ if (parentIsNonPreserved) {
286
+ // Still allow formatting-whitespace handling to be ignored here (skip)
287
+ // so they don't pollute the slot ordering.
288
+ continue
289
+ }
266
290
 
267
- if (child.type === 'JSXText') {
268
- if (!isFormattingWhitespace(child)) {
269
- out += child.value
270
- counter.n++
291
+ // Otherwise, preserve previous behavior for boundary/formatting merging.
292
+ if (isFormattingWhitespace(n)) {
293
+ const prevSlot = slots[slots.length - 1]
294
+ const prevOriginal = meaningfulNodes[i - 1]
295
+
296
+ if (prevSlot) {
297
+ // If the previous original sibling is an expression container, treat
298
+ // this formatting whitespace as formatting after an expression and skip it.
299
+ if (prevOriginal && prevOriginal.type === 'JSXExpressionContainer') {
300
+ continue
301
+ }
302
+ // Only merge into previous text when the previous original sibling was also JSXText.
303
+ if (prevSlot.type === 'JSXText' && prevOriginal && prevOriginal.type === 'JSXText') {
304
+ prevSlot.value = String(prevSlot.value) + n.value
305
+ continue
306
+ }
307
+ }
271
308
  }
309
+ // Add all other JSXText nodes
310
+ slots.push(n)
272
311
  continue
273
312
  }
274
313
 
275
- if (child.type === 'JSXExpressionContainer') {
276
- const expr = child.expression
314
+ if (n.type === 'JSXExpressionContainer') {
315
+ // If this expression is inside a non-preserved parent element, treat
316
+ // simple content-bearing expressions as part of the parent and do NOT
317
+ // add them as separate sibling/global slots. This prevents inner nodes
318
+ // (like <code>{'{{x}}'}</code> or <pre>{'foo'}</pre>) from being treated
319
+ // as extra slots which shifts global indexes.
320
+ if (parentIsNonPreserved && n.expression) {
321
+ const exprType = n.expression.type
322
+ // ObjectExpression placeholders ({{ key: value }}) should be treated
323
+ // as part of the parent.
324
+ if (exprType === 'ObjectExpression') {
325
+ const prop = n.expression.properties && n.expression.properties[0]
326
+ if (prop && prop.type === 'KeyValueProperty') {
327
+ continue
328
+ }
329
+ }
330
+
331
+ // For common simple content expressions, don't allocate a separate slot.
332
+ // However, if it's a pure-space StringLiteral ({" "}) we want to keep the
333
+ // special-space handling below, so only skip non-whitespace string literals.
334
+ if (exprType === 'StringLiteral') {
335
+ const textVal = String(n.expression.value || '')
336
+ const isPureSpaceNoNewline = /^\s*$/.test(textVal) && !textVal.includes('\n')
337
+ if (!isPureSpaceNoNewline) {
338
+ continue
339
+ }
340
+ // otherwise fall through to the pure-space handling below
341
+ } else if (exprType === 'Identifier' || exprType === 'MemberExpression' || exprType === 'CallExpression') {
342
+ continue
343
+ }
344
+ }
345
+
346
+ // Handle pure-string expression containers (e.g. {" "}):
347
+ // - If it's pure space (no newline) and it directly follows a non-text sibling
348
+ // (element/fragment), treat it as formatting and skip it.
349
+ // - Otherwise, count it as a slot (do NOT merge it into previous JSXText).
350
+ if (n.expression && n.expression.type === 'StringLiteral') {
351
+ const textVal = String(n.expression.value || '')
352
+ const isPureSpaceNoNewline = /^\s*$/.test(textVal) && !textVal.includes('\n')
353
+ const prevOriginal = meaningfulNodes[i - 1]
354
+ const nextOriginal = meaningfulNodes[i + 1]
355
+
356
+ if (isPureSpaceNoNewline) {
357
+ // If the explicit {" "} is followed by a newline-only JSXText which
358
+ // itself is followed by an element/fragment, treat the {" "}
359
+ // as layout-only and skip it. This covers cases where the space
360
+ // precedes a newline-only separator before an element (fixes index
361
+ // shifting in object-expression span tests).
362
+ const nextNextOriginal = meaningfulNodes[i + 2]
363
+ if (
364
+ nextOriginal &&
365
+ nextOriginal.type === 'JSXText' &&
366
+ isFormattingWhitespace(nextOriginal) &&
367
+ nextNextOriginal &&
368
+ (nextNextOriginal.type === 'JSXElement' || nextNextOriginal.type === 'JSXFragment')
369
+ ) {
370
+ // Only skip this pure-space when it appears in one of these cases:
371
+ // - there is no previous original sibling (leading)
372
+ // - the previous original sibling is not a JSXText (e.g. element/expr)
373
+ // - OR the previous original is JSXText but it itself follows an expression
374
+ // (pattern: <expr>, JSXText, {" "}, newline-only JSXText, <element>)
375
+ const prevOriginal = meaningfulNodes[i - 1]
376
+ const prevPrevOriginal = meaningfulNodes[i - 2]
377
+ // Only skip when there's no previous original OR when the previous
378
+ // original is not text AND the node before that is an expression.
379
+ // The previous logic skipped too aggressively when prevOriginal was
380
+ // just a non-text element (e.g. <span>), which removed the slot
381
+ // that should keep the later element index (fixes index off-by-one).
382
+ const shouldSkip =
383
+ !prevOriginal ||
384
+ (prevOriginal.type !== 'JSXText' && prevPrevOriginal && prevPrevOriginal.type === 'JSXExpressionContainer')
385
+
386
+ if (shouldSkip) {
387
+ continue
388
+ }
389
+ }
390
+
391
+ // Only treat {" "} as pure formatting to skip when it sits between
392
+ // an element/fragment and a newline-only JSXText. In that specific
393
+ // boundary case the explicit space is merely layout and must be ignored.
394
+ if (
395
+ prevOriginal &&
396
+ (prevOriginal.type === 'JSXElement' || prevOriginal.type === 'JSXFragment') &&
397
+ nextOriginal &&
398
+ nextOriginal.type === 'JSXText' &&
399
+ isFormattingWhitespace(nextOriginal)
400
+ ) {
401
+ continue
402
+ }
403
+
404
+ // 1) Merge into previous text when the previous original sibling is JSXText
405
+ // and the next original sibling is either missing or a non-formatting JSXText.
406
+ // This preserves "foo{' '}bar" as a single text node but avoids merging
407
+ // when the {" "} is followed by newline-only formatting before an element.
408
+ const nextIsTextNonFormatting = !nextOriginal || (nextOriginal.type === 'JSXText' && !isFormattingWhitespace(nextOriginal))
409
+ if (prevOriginal && prevOriginal.type === 'JSXText' && nextIsTextNonFormatting) {
410
+ const prevSlot = slots[slots.length - 1]
411
+ if (prevSlot && prevSlot.type === 'JSXText') {
412
+ prevSlot.value = String(prevSlot.value) + n.expression.value
413
+ continue
414
+ }
415
+ }
416
+
417
+ // 2) Skip when this explicit space sits between an element/fragment
418
+ // and a newline-only formatting JSXText (boundary formatting).
419
+ if (
420
+ prevOriginal &&
421
+ (prevOriginal.type === 'JSXElement' || prevOriginal.type === 'JSXFragment') &&
422
+ nextOriginal &&
423
+ nextOriginal.type === 'JSXText' &&
424
+ isFormattingWhitespace(nextOriginal)
425
+ ) {
426
+ continue
427
+ }
428
+ // 3) Otherwise fallthrough and count this expression as a slot.
429
+ }
430
+ }
431
+
432
+ // All JSXExpressionContainers count as slots for indexing.
433
+ slots.push(n)
434
+ continue
435
+ }
436
+
437
+ if (n.type === 'JSXElement') {
438
+ const tagName = n.opening && n.opening.name && n.opening.name.type === 'Identifier'
439
+ ? n.opening.name.value
440
+ : undefined
441
+ if (tagName && allowedTags.has(tagName)) {
442
+ // preserved tag: descend into children (tag itself is not a slot)
443
+ collectSlots(n.children || [], slots, false)
444
+ } else {
445
+ // non-preserved element: the element itself is a single slot.
446
+ // Pre-order: allocate the parent's slot first, then descend into its
447
+ // children. While descending, mark parentIsNonPreserved so
448
+ // KeyValueProperty-style object-expression placeholders are not added
449
+ // as separate sibling slots.
450
+ slots.push(n)
451
+ collectSlots(n.children || [], slots, true)
452
+ }
453
+ continue
454
+ }
455
+
456
+ if (n.type === 'JSXFragment') {
457
+ collectSlots(n.children || [], slots, parentIsNonPreserved)
458
+ continue
459
+ }
460
+
461
+ // ignore unknown node types
462
+ }
463
+ }
464
+
465
+ // prepare the global slot list for the whole subtree
466
+ const globalSlots: any[] = []
467
+ collectSlots(children, globalSlots, false)
468
+
469
+ function visitNodes (nodes: any[]): string {
470
+ if (!nodes || nodes.length === 0) return ''
471
+ let out = ''
472
+
473
+ for (const node of nodes) {
474
+ if (!node) continue
475
+
476
+ if (node.type === 'JSXText') {
477
+ if (!isFormattingWhitespace(node)) out += node.value
478
+ continue
479
+ }
480
+
481
+ if (node.type === 'JSXExpressionContainer') {
482
+ const expr = node.expression
277
483
  if (!expr) continue
278
484
 
279
485
  if (expr.type === 'StringLiteral') {
@@ -286,39 +492,40 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
286
492
  out += `{{${prop.key.value}}}`
287
493
  } else if (prop && prop.type === 'Identifier') {
288
494
  out += `{{${prop.value}}}`
495
+ } else {
496
+ out += '{{value}}'
289
497
  }
290
498
  } else if (expr.type === 'MemberExpression' && expr.property && expr.property.type === 'Identifier') {
291
499
  out += `{{${expr.property.value}}}`
292
500
  } else if (expr.type === 'CallExpression' && expr.callee?.type === 'Identifier') {
293
501
  out += `{{${expr.callee.value}}}`
502
+ } else {
503
+ out += '{{value}}'
294
504
  }
295
- // expression containers (including explicit {' '}) consume a slot
296
- counter.n++
297
505
  continue
298
506
  }
299
507
 
300
- if (child.type === 'JSXElement') {
508
+ if (node.type === 'JSXElement') {
301
509
  let tag: string | undefined
302
- if (child.opening && child.opening.name && child.opening.name.type === 'Identifier') {
303
- tag = child.opening.name.value
510
+ if (node.opening && node.opening.name && node.opening.name.type === 'Identifier') {
511
+ tag = node.opening.name.value
304
512
  }
305
513
 
306
514
  if (tag && allowedTags.has(tag)) {
307
- // preserved HTML tag: do NOT consume a numeric slot for the tag itself
308
- const inner = serialize(child.children || [])
515
+ const inner = visitNodes(node.children || [])
309
516
  out += `<${tag}>${inner}</${tag}>`
310
517
  } else {
311
- // non-preserved element: use current counter value as numeric index, then consume the slot
312
- const myIndex = counter.n
313
- counter.n++
314
- const inner = serialize(child.children || [])
315
- out += `<${myIndex}>${inner}</${myIndex}>`
518
+ // Use the pre-order globalSlots index so placeholder numbers reflect
519
+ // the global ordering (including nested slots collected earlier).
520
+ const idx = globalSlots.indexOf(node)
521
+ const inner = visitNodes(node.children || [])
522
+ out += `<${idx}>${inner}</${idx}>`
316
523
  }
317
524
  continue
318
525
  }
319
526
 
320
- if (child.type === 'JSXFragment') {
321
- out += serialize(child.children || [])
527
+ if (node.type === 'JSXFragment') {
528
+ out += visitNodes(node.children || [])
322
529
  continue
323
530
  }
324
531
 
@@ -328,6 +535,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
328
535
  return out
329
536
  }
330
537
 
331
- const result = serialize(children)
538
+ const result = visitNodes(children)
332
539
  return String(result).replace(/\s+/g, ' ').trim()
333
540
  }
@@ -1 +1 @@
1
- {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAgUnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA8E9B"}
1
+ {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAgVnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA8E9B"}
@@ -1 +1 @@
1
- {"version":3,"file":"jsx-parser.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/jsx-parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,gBAAgB,EAAY,MAAM,WAAW,CAAA;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAGvD,MAAM,WAAW,sBAAsB;IACrC,gDAAgD;IAChD,aAAa,CAAC,EAAE,UAAU,CAAC;IAE3B,qDAAqD;IACrD,kBAAkB,EAAE,MAAM,CAAC;IAE3B,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,8DAA8D;IAC9D,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ,oEAAoE;IACpE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,0DAA0D;IAC1D,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,8EAA8E;IAC9E,WAAW,CAAC,EAAE,gBAAgB,CAAC;IAE/B,mDAAmD;IACnD,iBAAiB,CAAC,EAAE,UAAU,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,yBAAyB,CAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,oBAAoB,GAAG,sBAAsB,GAAG,IAAI,CAgLxH"}
1
+ {"version":3,"file":"jsx-parser.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/jsx-parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,gBAAgB,EAAY,MAAM,WAAW,CAAA;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAGvD,MAAM,WAAW,sBAAsB;IACrC,gDAAgD;IAChD,aAAa,CAAC,EAAE,UAAU,CAAC;IAE3B,qDAAqD;IACrD,kBAAkB,EAAE,MAAM,CAAC;IAE3B,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,8DAA8D;IAC9D,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ,oEAAoE;IACpE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,0DAA0D;IAC1D,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,8EAA8E;IAC9E,WAAW,CAAC,EAAE,gBAAgB,CAAC;IAE/B,mDAAmD;IACnD,iBAAiB,CAAC,EAAE,UAAU,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,yBAAyB,CAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,oBAAoB,GAAG,sBAAsB,GAAG,IAAI,CA8KxH"}