i18next-cli 1.24.16 → 1.24.18

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/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),o=require("chokidar"),t=require("glob"),n=require("minimatch"),i=require("chalk"),r=require("./config.js"),a=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),d=require("./init.js"),g=require("./linter.js"),f=require("./status.js"),p=require("./locize.js"),m=require("./rename-key.js");const y=new e.Command;y.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.24.16"),y.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),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 e=>{try{const t=y.opts().config,i=await r.ensureConfig(t),a=async()=>{const o=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await a(),e.watch){console.log("\nWatching for changes...");const e=await x(i.extract.input),t=h(i.extract.ignore),r=w(i.extract.output),c=[...t,...r].filter(Boolean),s=e.filter(e=>!c.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(s,{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)}}),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(e,o)=>{const t=y.opts().config;let n=await r.loadConfig(t);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=e}await f.runStatus(n,{detail:e,namespace:o.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 e=>{const t=y.opts().config,i=await r.ensureConfig(t),a=()=>s.runTypesGenerator(i);if(await a(),e.watch){console.log("\nWatching for changes...");const e=await x(i.types?.input||[]),t=[...h(i.extract?.ignore)].filter(Boolean),r=e.filter(e=>!t.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(r,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),y.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=y.opts().config,o=await r.ensureConfig(e);await l.runSyncer(o)}),y.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),y.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(d.runInit),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 e=>{const t=y.opts().config,c=async()=>{let e=await r.loadConfig(t);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const o=await a.detectConfig();o||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),e=o}await g.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await r.loadConfig(t);if(e?.extract?.input){const t=await x(e.extract.input),i=[...h(e.extract.ignore),...w(e.extract.output)].filter(Boolean),r=t.filter(e=>!i.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),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 e=>{const o=y.opts().config,t=await r.ensureConfig(o);await p.runLocizeSync(t,e)}),y.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const o=y.opts().config,t=await r.ensureConfig(o);await p.runLocizeDownload(t,e)}),y.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const o=y.opts().config,t=await r.ensureConfig(o);await p.runLocizeMigrate(t,e)}),y.command("rename-key <oldKey> <newKey>").description("Rename a translation key across all source files and translation files.").option("--dry-run","Preview changes without modifying files").action(async(e,o,t)=>{try{const n=y.opts().config,a=await r.ensureConfig(n),c=await m.runRenameKey(a,e,o,t);c.success||(c.conflicts&&(console.error(i.red("\n❌ Conflicts detected:")),c.conflicts.forEach(e=>console.error(` - ${e}`))),c.error&&console.error(i.red(`\n❌ ${c.error}`)),process.exit(1));0===c.sourceFiles.reduce((e,o)=>e+o.changes,0)&&console.log(i.yellow(`\n⚠️ No usages found for "${e}"`))}catch(e){console.error(i.red("Error renaming key:"),e),process.exit(1)}}),y.parse(process.argv);const h=e=>Array.isArray(e)?e:e?[e]:[],w=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],x=async(e=[])=>{const o=h(e),n=await Promise.all(o.map(e=>t.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};exports.program=y;
2
+ "use strict";var e=require("commander"),o=require("chokidar"),t=require("glob"),n=require("minimatch"),i=require("chalk"),r=require("./config.js"),a=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),d=require("./init.js"),g=require("./linter.js"),f=require("./status.js"),p=require("./locize.js"),m=require("./rename-key.js");const y=new e.Command;y.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.24.18"),y.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),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 e=>{try{const t=y.opts().config,i=await r.ensureConfig(t),a=async()=>{const o=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await a(),e.watch){console.log("\nWatching for changes...");const e=await x(i.extract.input),t=h(i.extract.ignore),r=w(i.extract.output),c=[...t,...r].filter(Boolean),s=e.filter(e=>!c.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(s,{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)}}),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(e,o)=>{const t=y.opts().config;let n=await r.loadConfig(t);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=e}await f.runStatus(n,{detail:e,namespace:o.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 e=>{const t=y.opts().config,i=await r.ensureConfig(t),a=()=>s.runTypesGenerator(i);if(await a(),e.watch){console.log("\nWatching for changes...");const e=await x(i.types?.input||[]),t=[...h(i.extract?.ignore)].filter(Boolean),r=e.filter(e=>!t.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(r,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),y.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=y.opts().config,o=await r.ensureConfig(e);await l.runSyncer(o)}),y.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),y.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(d.runInit),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 e=>{const t=y.opts().config,c=async()=>{let e=await r.loadConfig(t);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const o=await a.detectConfig();o||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),e=o}await g.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await r.loadConfig(t);if(e?.extract?.input){const t=await x(e.extract.input),i=[...h(e.extract.ignore),...w(e.extract.output)].filter(Boolean),r=t.filter(e=>!i.some(o=>n.minimatch(e,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),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 e=>{const o=y.opts().config,t=await r.ensureConfig(o);await p.runLocizeSync(t,e)}),y.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const o=y.opts().config,t=await r.ensureConfig(o);await p.runLocizeDownload(t,e)}),y.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const o=y.opts().config,t=await r.ensureConfig(o);await p.runLocizeMigrate(t,e)}),y.command("rename-key <oldKey> <newKey>").description("Rename a translation key across all source files and translation files.").option("--dry-run","Preview changes without modifying files").action(async(e,o,t)=>{try{const n=y.opts().config,a=await r.ensureConfig(n),c=await m.runRenameKey(a,e,o,t);c.success||(c.conflicts&&(console.error(i.red("\n❌ Conflicts detected:")),c.conflicts.forEach(e=>console.error(` - ${e}`))),c.error&&console.error(i.red(`\n❌ ${c.error}`)),process.exit(1));0===c.sourceFiles.reduce((e,o)=>e+o.changes,0)&&console.log(i.yellow(`\n⚠️ No usages found for "${e}"`))}catch(e){console.error(i.red("Error renaming key:"),e),process.exit(1)}}),y.parse(process.argv);const h=e=>Array.isArray(e)?e:e?[e]:[],w=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],x=async(e=[])=>{const o=h(e),n=await Promise.all(o.map(e=>t.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};exports.program=y;
@@ -1 +1 @@
1
- "use strict";var e=require("glob"),t=require("node:fs/promises"),n=require("./utils/logger.js"),r=require("./utils/file-utils.js"),o=require("node:path"),a=require("./utils/nested-object.js"),s=require("./utils/funnel-msg-tracker.js"),i=require("chalk");function c(e,t){const n=t.extract.nsSeparator??":";if(n&&e.includes(n)){const[t,...r]=e.split(n);return{namespace:t,key:r.join(n),fullKey:e}}return{namespace:t.extract.defaultNS||"translation",key:e,fullKey:e}}async function l(e,t,n,r){return function(e,t,n,r){let o=0,a=e;const s=r.extract.nsSeparator??":",i=e=>s&&e.includes(String(s))?n.fullKey:n.key,c=r.extract.functions||["t","*.t"],l=[];for(const e of c)if(e.startsWith("*.")){const n=u(e.substring(1));l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${u(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${u(t.key)}\\1`,"g"),original:t.key})}else{const n=u(e);l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${u(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${u(t.key)}\\1`,"g"),original:t.key})}for(const{pattern:e,original:t}of l)if(e.test(a)){const n=i(t);a=a.replace(e,(e,t)=>{o++;const r=e.match(/^(\w+(?:\.\w+)*)\(/);return r?`${r[1]}(${t}${n}${t}`:e})}for(const e of c){let n;if(e.startsWith("*.")){n=`\\w+${u(e.substring(1))}`}else n=u(e);for(const e of[t.fullKey,t.key]){const t=new RegExp(`(\\b${n}\\(\\s*\\(?\\s*([a-zA-Z_$][\\w$]*)\\s*\\)?\\s*=>\\s*)\\2\\.${u(e)}(\\s*\\))`,"g");if(t.test(a)){const n=i(e);a=a.replace(t,(e,t,r,a)=>(o++,`${t}${r}.${n}${a}`))}}}const f=[{pattern:new RegExp(`i18nKey=(['"\`])${u(t.fullKey)}\\1`,"g"),original:t.fullKey},{pattern:new RegExp(`i18nKey=(['"\`])${u(t.key)}\\1`,"g"),original:t.key}];for(const{pattern:e,original:t}of f)if(e.test(a)){const n=i(t);a=a.replace(e,(e,t)=>(o++,`i18nKey=${t}${n}${t}`))}return{newCode:a,changes:o}}(e,t,n,r)}function u(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(e,t,n){if(!1===n)return void delete e[t];const r=t.split(String(n));let o=e;for(let e=0;e<r.length-1;e++){if(!o[r[e]])return;o=o[r[e]]}delete o[r[r.length-1]]}exports.runRenameKey=async function(u,g,p,y={},d=new n.ConsoleLogger){const{dryRun:w=!1}=y,$=function(e,t){if(!e||!e.trim())return{valid:!1,error:"Old key cannot be empty"};if(!t||!t.trim())return{valid:!1,error:"New key cannot be empty"};if(e===t)return{valid:!1,error:"Old and new keys are identical"};return{valid:!0}}(g,p);if(!$.valid)return{success:!1,sourceFiles:[],translationFiles:[],error:$.error};const h=c(g,u),m=c(p,u),k=await async function(e,t){const n=[];for(const s of t.locales){const i=r.getOutputPath(t.extract.output,s,e.namespace),c=o.resolve(process.cwd(),i);try{const o=await r.loadTranslationFile(c);if(o){const r=t.extract.keySeparator??".";void 0!==a.getNestedValue(o,e.key,r)&&n.push(`${s}:${e.fullKey}`)}}catch{}}return n}(m,u);if(k.length>0)return{success:!1,sourceFiles:[],translationFiles:[],conflicts:k,error:"Target key already exists in translation files"};d.info(`🔍 Scanning for usages of "${g}"...`);const x=await async function(n,r,o,a,s){const i=["node_modules/**"],c=Array.isArray(o.extract.ignore)?o.extract.ignore:o.extract.ignore?[o.extract.ignore]:[],u=Array.isArray(o.extract.input)?o.extract.input:[o.extract.input],f=u.map(e=>e.replace(/\\/g,"/")),g=await e.glob(f,{ignore:[...i,...c],cwd:process.cwd()}),p=[];for(const e of g){const i=await t.readFile(e,"utf-8"),{newCode:c,changes:u}=await l(i,n,r,o);u>0&&(a||await t.writeFile(e,c,"utf-8"),p.push({path:e,changes:u}),s.info(` ${a?"(dry-run) ":""}✓ ${e} (${u} ${1===u?"change":"changes"})`))}p.length>0&&s.info(`\n📝 Source file changes: ${p.length} file${1===p.length?"":"s"}`);return p}(h,m,u,w,d),F=await async function(e,n,s,i,c){const l=[],u=s.extract.keySeparator??".";for(const g of s.locales){const p=r.getOutputPath(s.extract.output,g,e.namespace),y=o.resolve(process.cwd(),p);try{const o=await r.loadTranslationFile(y);if(!o)continue;const g=a.getNestedValue(o,e.key,u);if(void 0===g)continue;if(f(o,e.key,u),a.setNestedValue(o,n.key,g,u),!i){const e=r.serializeTranslationFile(o,s.extract.outputFormat,s.extract.indentation);await t.writeFile(y,e,"utf-8")}l.push({path:y,updated:!0}),c.info(` ${i?"(dry-run) ":""}✓ ${y}`)}catch(e){}}l.length>0&&c.info(`\n📦 Translation file updates: ${l.length} file${1===l.length?"":"s"}`);return l}(h,m,u,w,d),K=x.reduce((e,t)=>e+t.changes,0);return!w&&K>0?(d.info("\n✨ Successfully renamed key!"),d.info(` Old: "${g}"`),d.info(` New: "${p}"`),await async function(){if(!await s.shouldShowFunnel("rename-key"))return;return console.log(i.yellow.bold("\n💡 Tip: Managing translations across multiple projects?")),console.log(" With locize, you can rename, move, and copy translation keys directly"),console.log(" in the web interface—no CLI needed. Perfect for collaboration with"),console.log(" translators and managing complex refactoring across namespaces."),console.log(` Learn more: ${i.cyan("https://www.locize.com/docs/how-can-a-segment-key-be-copied-moved-or-renamed")}`),s.recordFunnelShown("rename-key")}()):0===K&&d.info(`\n⚠️ No usages found for "${g}"`),{success:!0,sourceFiles:x,translationFiles:F}};
1
+ "use strict";var e=require("glob"),t=require("node:fs/promises"),n=require("./utils/logger.js"),r=require("./utils/file-utils.js"),o=require("node:path"),s=require("./utils/nested-object.js"),a=require("./utils/funnel-msg-tracker.js"),i=require("chalk");function c(e,t){const n=t.extract.nsSeparator??":";if(n&&e.includes(n)){const[t,...r]=e.split(n);return{namespace:t,key:r.join(n),fullKey:e}}return{namespace:t.extract.defaultNS||"translation",key:e,fullKey:e}}async function l(e,t,n,r){return function(e,t,n,r){let o=0,s=e;const a=r.extract.nsSeparator??":",i=e=>a&&e.includes(String(a))?n.fullKey:n.key,c=r.extract.functions||["t","*.t"],l=[];for(const e of c)if(e.startsWith("*.")){const n=u(e.substring(1));l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${u(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${u(t.key)}\\1`,"g"),original:t.key})}else{const n=u(e);l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${u(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${u(t.key)}\\1`,"g"),original:t.key})}for(const{pattern:e,original:t}of l)if(e.test(s)){const n=i(t);s=s.replace(e,(e,t)=>{o++;const r=e.match(/^(\w+(?:\.\w+)*)\(/);return r?`${r[1]}(${t}${n}${t}`:e})}for(const e of c){let n;if(e.startsWith("*.")){n=`\\w+${u(e.substring(1))}`}else n=u(e);for(const e of[t.fullKey,t.key]){const t=new RegExp(`(\\b${n}\\(\\s*\\(?\\s*([a-zA-Z_$][\\w$]*)\\s*\\)?\\s*=>\\s*)\\2\\.${u(e)}(\\s*\\))`,"g");if(t.test(s)){const n=i(e);s=s.replace(t,(e,t,r,s)=>(o++,`${t}${r}.${n}${s}`))}const r=new RegExp(`(\\b${n}\\(\\s*\\(?\\s*([a-zA-Z_$][\\w$]*)\\s*\\)?\\s*=>\\s*)\\2\\[\\s*(['"\`])${u(e)}\\3\\s*\\](\\s*\\))`,"g");if(r.test(s)){const t=i(e),n=e=>/^[A-Za-z_$][\w$]*$/.test(e);s=s.replace(r,(e,r,s,a,i)=>(o++,n(t)?`${r}${s}.${t}${i}`:`${r}${s}[${a}${t}${a}]${i}`))}}}const f=[{pattern:new RegExp(`i18nKey=(['"\`])${u(t.fullKey)}\\1`,"g"),original:t.fullKey},{pattern:new RegExp(`i18nKey=(['"\`])${u(t.key)}\\1`,"g"),original:t.key}];for(const{pattern:e,original:t}of f)if(e.test(s)){const n=i(t);s=s.replace(e,(e,t)=>(o++,`i18nKey=${t}${n}${t}`))}return{newCode:s,changes:o}}(e,t,n,r)}function u(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(e,t,n){if(!1===n)return void delete e[t];const r=t.split(String(n));let o=e;for(let e=0;e<r.length-1;e++){if(!o[r[e]])return;o=o[r[e]]}delete o[r[r.length-1]]}exports.runRenameKey=async function(u,g,p,y={},$=new n.ConsoleLogger){const{dryRun:d=!1}=y,w=function(e,t){if(!e||!e.trim())return{valid:!1,error:"Old key cannot be empty"};if(!t||!t.trim())return{valid:!1,error:"New key cannot be empty"};if(e===t)return{valid:!1,error:"Old and new keys are identical"};return{valid:!0}}(g,p);if(!w.valid)return{success:!1,sourceFiles:[],translationFiles:[],error:w.error};const h=c(g,u),m=c(p,u),x=await async function(e,t){const n=[];for(const a of t.locales){const i=r.getOutputPath(t.extract.output,a,e.namespace),c=o.resolve(process.cwd(),i);try{const o=await r.loadTranslationFile(c);if(o){const r=t.extract.keySeparator??".";void 0!==s.getNestedValue(o,e.key,r)&&n.push(`${a}:${e.fullKey}`)}}catch{}}return n}(m,u);if(x.length>0)return{success:!1,sourceFiles:[],translationFiles:[],conflicts:x,error:"Target key already exists in translation files"};$.info(`🔍 Scanning for usages of "${g}"...`);const k=await async function(n,r,o,s,a){const i=["node_modules/**"],c=Array.isArray(o.extract.ignore)?o.extract.ignore:o.extract.ignore?[o.extract.ignore]:[],u=Array.isArray(o.extract.input)?o.extract.input:[o.extract.input],f=u.map(e=>e.replace(/\\/g,"/")),g=await e.glob(f,{ignore:[...i,...c],cwd:process.cwd()}),p=[];for(const e of g){const i=await t.readFile(e,"utf-8"),{newCode:c,changes:u}=await l(i,n,r,o);u>0&&(s||await t.writeFile(e,c,"utf-8"),p.push({path:e,changes:u}),a.info(` ${s?"(dry-run) ":""}✓ ${e} (${u} ${1===u?"change":"changes"})`))}p.length>0&&a.info(`\n📝 Source file changes: ${p.length} file${1===p.length?"":"s"}`);return p}(h,m,u,d,$),b=await async function(e,n,a,i,c){const l=[],u=a.extract.keySeparator??".";for(const g of a.locales){const p=r.getOutputPath(a.extract.output,g,e.namespace),y=o.resolve(process.cwd(),p);try{const o=await r.loadTranslationFile(y);if(!o)continue;const g=s.getNestedValue(o,e.key,u);if(void 0===g)continue;if(f(o,e.key,u),s.setNestedValue(o,n.key,g,u),!i){const e=r.serializeTranslationFile(o,a.extract.outputFormat,a.extract.indentation);await t.writeFile(y,e,"utf-8")}l.push({path:y,updated:!0}),c.info(` ${i?"(dry-run) ":""}✓ ${y}`)}catch(e){}}l.length>0&&c.info(`\n📦 Translation file updates: ${l.length} file${1===l.length?"":"s"}`);return l}(h,m,u,d,$),F=k.reduce((e,t)=>e+t.changes,0);return!d&&F>0?($.info("\n✨ Successfully renamed key!"),$.info(` Old: "${g}"`),$.info(` New: "${p}"`),await async function(){if(!await a.shouldShowFunnel("rename-key"))return;return console.log(i.yellow.bold("\n💡 Tip: Managing translations across multiple projects?")),console.log(" With locize, you can rename, move, and copy translation keys directly"),console.log(" in the web interface—no CLI needed. Perfect for collaboration with"),console.log(" translators and managing complex refactoring across namespaces."),console.log(` Learn more: ${i.cyan("https://www.locize.com/docs/how-can-a-segment-key-be-copied-moved-or-renamed")}`),a.recordFunnelShown("rename-key")}()):0===F&&$.info(`\n⚠️ No usages found for "${g}"`),{success:!0,sourceFiles:k,translationFiles:b}};
@@ -1 +1 @@
1
- "use strict";var e=require("chalk"),t=require("ora"),a=require("node:path"),o=require("./extractor/core/key-finder.js"),s=require("./utils/nested-object.js"),n=require("./utils/file-utils.js"),l=require("./utils/funnel-msg-tracker.js");function r(t,a,o){const s=o>0?Math.round(a/o*100):100,n=c(s);console.log(`${e.bold(t)}: ${n} ${s}% (${a}/${o})`)}function c(t){const a=Math.floor(t/100*20),o=20-a;return`[${e.green("".padStart(a,"■"))}${"".padStart(o,"□")}]`}async function i(){if(await l.shouldShowFunnel("status"))return console.log(e.yellow.bold("\n✨ Take your localization to the next level!")),console.log("Manage translations with your team in the cloud with locize => https://www.locize.com/docs/getting-started"),console.log(`Run ${e.cyan("npx i18next-cli locize-migrate")} to get started.`),l.recordFunnelShown("status")}exports.runStatus=async function(l,u={}){l.extract.primaryLanguage||=l.locales[0]||"en",l.extract.secondaryLanguages||=l.locales.filter(e=>e!==l?.extract?.primaryLanguage);const d=t("Analyzing project localization status...\n").start();try{const t=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage);const{allKeys:t}=await o.findKeys(e),{secondaryLanguages:l,keySeparator:r=".",defaultNS:c="translation",mergeNamespaces:i=!1,pluralSeparator:u="_"}=e.extract,d=new Map;for(const e of t.values()){const t=e.ns||c||"translation";d.has(t)||d.set(t,[]),d.get(t).push(e)}const y={totalBaseKeys:t.size,keysByNs:d,locales:new Map};for(const t of l){let o=0,l=0;const c=new Map,g=i?await n.loadTranslationFile(a.resolve(process.cwd(),n.getOutputPath(e.extract.output,t)))||{}:null;for(const[y,f]of d.entries()){const d=i?g?.[y]||{}:await n.loadTranslationFile(a.resolve(process.cwd(),n.getOutputPath(e.extract.output,t,y)))||{};let p=0,$=0;const m=[],h=(e,t)=>{try{const a=t?"ordinal":"cardinal";return new Intl.PluralRules(e,{type:a}).resolvedOptions().pluralCategories}catch(e){return new Intl.PluralRules("en",{type:t?"ordinal":"cardinal"}).resolvedOptions().pluralCategories}};for(const{key:e,hasCount:a,isOrdinal:o,isExpandedPlural:n}of f)if(a)if(n){const a=e.split(u),o=a[a.length-1],n=a.length>=2&&"ordinal"===a[a.length-2],l=n?a[a.length-1]:o;if(h(t,n).includes(l)){$++;const t=!!s.getNestedValue(d,e,r??".");t&&p++,m.push({key:e,isTranslated:t})}}else{const a=h(t,o||!1);for(const t of a){$++;const a=o?`${e}${u}ordinal${u}${t}`:`${e}${u}${t}`,n=!!s.getNestedValue(d,a,r??".");n&&p++,m.push({key:a,isTranslated:n})}}else{$++;const t=!!s.getNestedValue(d,e,r??".");t&&p++,m.push({key:e,isTranslated:t})}c.set(y,{totalKeys:$,translatedKeys:p,keyDetails:m}),o+=p,l+=$}y.locales.set(t,{totalKeys:l,totalTranslated:o,namespaces:c})}return y}(l);d.succeed("Analysis complete."),await async function(t,a,o){o.detail?await async function(t,a,o,s){if(o===a.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${o}" is the primary language. All keys are considered present.`));if(!a.locales.includes(o))return void console.error(e.red(`Error: Locale "${o}" is not defined in your configuration.`));const n=t.locales.get(o);if(!n)return void console.error(e.red(`Error: Locale "${o}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(o)}":`));const l=Array.from(t.keysByNs.values()).flat().length;r("Overall",n.totalTranslated,n.totalKeys);const c=s?[s]:Array.from(n.namespaces.keys()).sort();for(const t of c){const a=n.namespaces.get(t);a&&(console.log(e.cyan.bold(`\nNamespace: ${t}`)),r("Namespace Progress",a.translatedKeys,a.totalKeys),a.keyDetails.forEach(({key:t,isTranslated:a})=>{const o=a?e.green("✓"):e.red("✗");console.log(` ${o} ${t}`)}))}const u=l-n.totalTranslated;u>0?console.log(e.yellow.bold(`\nSummary: Found ${u} missing translations for "${o}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${o}".`));await i()}(t,a,o.detail,o.namespace):o.namespace?await async function(t,a,o){const s=t.keysByNs.get(o);if(!s)return void console.error(e.red(`Error: Namespace "${o}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${o}"`)),console.log("------------------------");for(const[e,a]of t.locales.entries()){const t=a.namespaces.get(o);if(t){const a=t.totalKeys>0?Math.round(t.translatedKeys/t.totalKeys*100):100,o=c(a);console.log(`- ${e}: ${o} ${a}% (${t.translatedKeys}/${t.totalKeys} keys)`)}}await i()}(t,0,o.namespace):await async function(t,a){const{primaryLanguage:o}=a.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(t.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(t.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(a.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(o)}`),console.log("\nTranslation Progress:");for(const[e,a]of t.locales.entries()){const t=a.totalKeys>0?Math.round(a.totalTranslated/a.totalKeys*100):100,o=c(t);console.log(`- ${e}: ${o} ${t}% (${a.totalTranslated}/${a.totalKeys} keys)`)}await i()}(t,a)}(t,l,u)}catch(e){d.fail("Failed to generate status report."),console.error(e)}};
1
+ "use strict";var e=require("chalk"),t=require("ora"),a=require("node:path"),o=require("./extractor/core/key-finder.js"),s=require("./utils/nested-object.js"),n=require("./utils/file-utils.js"),l=require("./utils/funnel-msg-tracker.js");function r(t,a,o){const s=o>0?Math.round(a/o*100):100,n=c(s);console.log(`${e.bold(t)}: ${n} ${s}% (${a}/${o})`)}function c(t){const a=Math.floor(t/100*20),o=20-a;return`[${e.green("".padStart(a,"■"))}${"".padStart(o,"□")}]`}async function i(){if(await l.shouldShowFunnel("status"))return console.log(e.yellow.bold("\n✨ Take your localization to the next level!")),console.log("Manage translations with your team in the cloud with locize => https://www.locize.com/docs/getting-started"),console.log(`Run ${e.cyan("npx i18next-cli locize-migrate")} to get started.`),l.recordFunnelShown("status")}exports.runStatus=async function(l,u={}){l.extract.primaryLanguage||=l.locales[0]||"en",l.extract.secondaryLanguages||=l.locales.filter(e=>e!==l?.extract?.primaryLanguage);const d=t("Analyzing project localization status...\n").start();try{const t=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage);const{allKeys:t}=await o.findKeys(e),{secondaryLanguages:l,keySeparator:r=".",defaultNS:c="translation",mergeNamespaces:i=!1,pluralSeparator:u="_"}=e.extract,d=new Map;for(const e of t.values()){const t=e.ns||c||"translation";d.has(t)||d.set(t,[]),d.get(t).push(e)}const y={totalBaseKeys:t.size,keysByNs:d,locales:new Map};for(const t of l){let o=0,l=0;const g=new Map,f=i?await n.loadTranslationFile(a.resolve(process.cwd(),n.getOutputPath(e.extract.output,t,!1===c?"translation":c||"translation")))||{}:null;for(const[c,y]of d.entries()){const d=i?f?.[c]??f??{}:await n.loadTranslationFile(a.resolve(process.cwd(),n.getOutputPath(e.extract.output,t,c)))||{};let p=0,$=0;const m=[],h=(e,t)=>{try{const a=t?"ordinal":"cardinal";return new Intl.PluralRules(e,{type:a}).resolvedOptions().pluralCategories}catch(e){return new Intl.PluralRules("en",{type:t?"ordinal":"cardinal"}).resolvedOptions().pluralCategories}};for(const{key:e,hasCount:a,isOrdinal:o,isExpandedPlural:n}of y)if(a)if(n){const a=e.split(u),o=a[a.length-1],n=a.length>=2&&"ordinal"===a[a.length-2],l=n?a[a.length-1]:o;if(h(t,n).includes(l)){$++;const t=!!s.getNestedValue(d,e,r??".");t&&p++,m.push({key:e,isTranslated:t})}}else{const a=h(t,o||!1);for(const t of a){$++;const a=o?`${e}${u}ordinal${u}${t}`:`${e}${u}${t}`,n=!!s.getNestedValue(d,a,r??".");n&&p++,m.push({key:a,isTranslated:n})}}else{$++;const t=!!s.getNestedValue(d,e,r??".");t&&p++,m.push({key:e,isTranslated:t})}g.set(c,{totalKeys:$,translatedKeys:p,keyDetails:m}),o+=p,l+=$}y.locales.set(t,{totalKeys:l,totalTranslated:o,namespaces:g})}return y}(l);d.succeed("Analysis complete."),await async function(t,a,o){o.detail?await async function(t,a,o,s){if(o===a.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${o}" is the primary language. All keys are considered present.`));if(!a.locales.includes(o))return void console.error(e.red(`Error: Locale "${o}" is not defined in your configuration.`));const n=t.locales.get(o);if(!n)return void console.error(e.red(`Error: Locale "${o}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(o)}":`));const l=Array.from(t.keysByNs.values()).flat().length;r("Overall",n.totalTranslated,n.totalKeys);const c=s?[s]:Array.from(n.namespaces.keys()).sort();for(const t of c){const a=n.namespaces.get(t);a&&(console.log(e.cyan.bold(`\nNamespace: ${t}`)),r("Namespace Progress",a.translatedKeys,a.totalKeys),a.keyDetails.forEach(({key:t,isTranslated:a})=>{const o=a?e.green("✓"):e.red("✗");console.log(` ${o} ${t}`)}))}const u=l-n.totalTranslated;u>0?console.log(e.yellow.bold(`\nSummary: Found ${u} missing translations for "${o}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${o}".`));await i()}(t,a,o.detail,o.namespace):o.namespace?await async function(t,a,o){const s=t.keysByNs.get(o);if(!s)return void console.error(e.red(`Error: Namespace "${o}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${o}"`)),console.log("------------------------");for(const[e,a]of t.locales.entries()){const t=a.namespaces.get(o);if(t){const a=t.totalKeys>0?Math.round(t.translatedKeys/t.totalKeys*100):100,o=c(a);console.log(`- ${e}: ${o} ${a}% (${t.translatedKeys}/${t.totalKeys} keys)`)}}await i()}(t,0,o.namespace):await async function(t,a){const{primaryLanguage:o}=a.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(t.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(t.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(a.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(o)}`),console.log("\nTranslation Progress:");for(const[e,a]of t.locales.entries()){const t=a.totalKeys>0?Math.round(a.totalTranslated/a.totalKeys*100):100,o=c(t);console.log(`- ${e}: ${o} ${t}% (${a.totalTranslated}/${a.totalKeys} keys)`)}await i()}(t,a)}(t,l,u)}catch(e){d.fail("Failed to generate status report."),console.error(e)}};
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as o}from"commander";import e from"chokidar";import{glob as t}from"glob";import{minimatch as n}from"minimatch";import i from"chalk";import{ensureConfig as r,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as f}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinterCli as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as u,runLocizeDownload as y,runLocizeMigrate as h}from"./locize.js";import{runRenameKey as w}from"./rename-key.js";const x=new o;x.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.24.16"),x.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),x.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 o=>{try{const t=x.opts().config,i=await r(t),a=async()=>{const e=await s(i,{isWatchMode:!!o.watch,isDryRun:!!o.dryRun,syncPrimaryWithDefaults:!!o.syncPrimary});return o.ci&&!e?(console.log("✅ No files were updated."),process.exit(0)):o.ci&&e&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),e};if(await a(),o.watch){console.log("\nWatching for changes...");const o=await z(i.extract.input),t=j(i.extract.ignore),r=k(i.extract.output),c=[...t,...r].filter(Boolean),s=o.filter(o=>!c.some(e=>n(o,e,{dot:!0})));e.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}catch(o){console.error("Error running extractor:",o),process.exit(1)}}),x.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(o,e)=>{const t=x.opts().config;let n=await a(t);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=o}await g(n,{detail:o,namespace:e.namespace})}),x.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 o=>{const t=x.opts().config,i=await r(t),a=()=>l(i);if(await a(),o.watch){console.log("\nWatching for changes...");const o=await z(i.types?.input||[]),t=[...j(i.extract?.ignore)].filter(Boolean),r=o.filter(o=>!t.some(e=>n(o,e,{dot:!0})));e.watch(r,{persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}),x.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const o=x.opts().config,e=await r(o);await p(e)}),x.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async o=>{await f(o)}),x.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),x.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 o=>{const t=x.opts().config,r=async()=>{let o=await a(t);if(!o){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await c();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),o=e}await d(o)};if(await r(),o.watch){console.log("\nWatching for changes...");const o=await a(t);if(o?.extract?.input){const t=await z(o.extract.input),i=[...j(o.extract.ignore),...k(o.extract.output)].filter(Boolean),a=t.filter(o=>!i.some(e=>n(o,e,{dot:!0})));e.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),r()})}}}),x.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 o=>{const e=x.opts().config,t=await r(e);await u(t,o)}),x.command("locize-download").description("Download all translations from your locize project.").action(async o=>{const e=x.opts().config,t=await r(e);await y(t,o)}),x.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async o=>{const e=x.opts().config,t=await r(e);await h(t,o)}),x.command("rename-key <oldKey> <newKey>").description("Rename a translation key across all source files and translation files.").option("--dry-run","Preview changes without modifying files").action(async(o,e,t)=>{try{const n=x.opts().config,a=await r(n),c=await w(a,o,e,t);c.success||(c.conflicts&&(console.error(i.red("\n❌ Conflicts detected:")),c.conflicts.forEach(o=>console.error(` - ${o}`))),c.error&&console.error(i.red(`\n❌ ${c.error}`)),process.exit(1));0===c.sourceFiles.reduce((o,e)=>o+e.changes,0)&&console.log(i.yellow(`\n⚠️ No usages found for "${o}"`))}catch(o){console.error(i.red("Error renaming key:"),o),process.exit(1)}}),x.parse(process.argv);const j=o=>Array.isArray(o)?o:o?[o]:[],k=o=>o&&"string"==typeof o?[o.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(o=[])=>{const e=j(o),n=await Promise.all(e.map(o=>t(o||"",{nodir:!0})));return Array.from(new Set(n.flat()))};export{x as program};
2
+ import{Command as o}from"commander";import e from"chokidar";import{glob as t}from"glob";import{minimatch as n}from"minimatch";import i from"chalk";import{ensureConfig as r,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as f}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinterCli as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as u,runLocizeDownload as y,runLocizeMigrate as h}from"./locize.js";import{runRenameKey as w}from"./rename-key.js";const x=new o;x.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.24.18"),x.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),x.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 o=>{try{const t=x.opts().config,i=await r(t),a=async()=>{const e=await s(i,{isWatchMode:!!o.watch,isDryRun:!!o.dryRun,syncPrimaryWithDefaults:!!o.syncPrimary});return o.ci&&!e?(console.log("✅ No files were updated."),process.exit(0)):o.ci&&e&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),e};if(await a(),o.watch){console.log("\nWatching for changes...");const o=await z(i.extract.input),t=j(i.extract.ignore),r=k(i.extract.output),c=[...t,...r].filter(Boolean),s=o.filter(o=>!c.some(e=>n(o,e,{dot:!0})));e.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}catch(o){console.error("Error running extractor:",o),process.exit(1)}}),x.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(o,e)=>{const t=x.opts().config;let n=await a(t);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=o}await g(n,{detail:o,namespace:e.namespace})}),x.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 o=>{const t=x.opts().config,i=await r(t),a=()=>l(i);if(await a(),o.watch){console.log("\nWatching for changes...");const o=await z(i.types?.input||[]),t=[...j(i.extract?.ignore)].filter(Boolean),r=o.filter(o=>!t.some(e=>n(o,e,{dot:!0})));e.watch(r,{persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}),x.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const o=x.opts().config,e=await r(o);await p(e)}),x.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async o=>{await f(o)}),x.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),x.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 o=>{const t=x.opts().config,r=async()=>{let o=await a(t);if(!o){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await c();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),o=e}await d(o)};if(await r(),o.watch){console.log("\nWatching for changes...");const o=await a(t);if(o?.extract?.input){const t=await z(o.extract.input),i=[...j(o.extract.ignore),...k(o.extract.output)].filter(Boolean),a=t.filter(o=>!i.some(e=>n(o,e,{dot:!0})));e.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),r()})}}}),x.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 o=>{const e=x.opts().config,t=await r(e);await u(t,o)}),x.command("locize-download").description("Download all translations from your locize project.").action(async o=>{const e=x.opts().config,t=await r(e);await y(t,o)}),x.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async o=>{const e=x.opts().config,t=await r(e);await h(t,o)}),x.command("rename-key <oldKey> <newKey>").description("Rename a translation key across all source files and translation files.").option("--dry-run","Preview changes without modifying files").action(async(o,e,t)=>{try{const n=x.opts().config,a=await r(n),c=await w(a,o,e,t);c.success||(c.conflicts&&(console.error(i.red("\n❌ Conflicts detected:")),c.conflicts.forEach(o=>console.error(` - ${o}`))),c.error&&console.error(i.red(`\n❌ ${c.error}`)),process.exit(1));0===c.sourceFiles.reduce((o,e)=>o+e.changes,0)&&console.log(i.yellow(`\n⚠️ No usages found for "${o}"`))}catch(o){console.error(i.red("Error renaming key:"),o),process.exit(1)}}),x.parse(process.argv);const j=o=>Array.isArray(o)?o:o?[o]:[],k=o=>o&&"string"==typeof o?[o.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(o=[])=>{const e=j(o),n=await Promise.all(e.map(o=>t(o||"",{nodir:!0})));return Array.from(new Set(n.flat()))};export{x as program};
@@ -1 +1 @@
1
- import{glob as e}from"glob";import{readFile as t,writeFile as n}from"node:fs/promises";import{ConsoleLogger as r}from"./utils/logger.js";import{getOutputPath as o,loadTranslationFile as a,serializeTranslationFile as s}from"./utils/file-utils.js";import{resolve as i}from"node:path";import{getNestedValue as c,setNestedValue as l}from"./utils/nested-object.js";import{shouldShowFunnel as f,recordFunnelShown as u}from"./utils/funnel-msg-tracker.js";import p from"chalk";async function g(g,$,w,h={},k=new r){const{dryRun:x=!1}=h,K=function(e,t){if(!e||!e.trim())return{valid:!1,error:"Old key cannot be empty"};if(!t||!t.trim())return{valid:!1,error:"New key cannot be empty"};if(e===t)return{valid:!1,error:"Old and new keys are identical"};return{valid:!0}}($,w);if(!K.valid)return{success:!1,sourceFiles:[],translationFiles:[],error:K.error};const b=y($,g),v=y(w,g),S=await async function(e,t){const n=[];for(const r of t.locales){const s=o(t.extract.output,r,e.namespace),l=i(process.cwd(),s);try{const o=await a(l);if(o){const a=t.extract.keySeparator??".";void 0!==c(o,e.key,a)&&n.push(`${r}:${e.fullKey}`)}}catch{}}return n}(v,g);if(S.length>0)return{success:!1,sourceFiles:[],translationFiles:[],conflicts:S,error:"Target key already exists in translation files"};k.info(`🔍 Scanning for usages of "${$}"...`);const R=await async function(r,o,a,s,i){const c=["node_modules/**"],l=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[],f=Array.isArray(a.extract.input)?a.extract.input:[a.extract.input],u=f.map(e=>e.replace(/\\/g,"/")),p=await e(u,{ignore:[...c,...l],cwd:process.cwd()}),g=[];for(const e of p){const c=await t(e,"utf-8"),{newCode:l,changes:f}=await d(c,r,o,a);f>0&&(s||await n(e,l,"utf-8"),g.push({path:e,changes:f}),i.info(` ${s?"(dry-run) ":""}✓ ${e} (${f} ${1===f?"change":"changes"})`))}g.length>0&&i.info(`\n📝 Source file changes: ${g.length} file${1===g.length?"":"s"}`);return g}(b,v,g,x,k),j=await async function(e,t,r,f,u){const p=[],g=r.extract.keySeparator??".";for(const y of r.locales){const d=o(r.extract.output,y,e.namespace),$=i(process.cwd(),d);try{const o=await a($);if(!o)continue;const i=c(o,e.key,g);if(void 0===i)continue;if(m(o,e.key,g),l(o,t.key,i,g),!f){const e=s(o,r.extract.outputFormat,r.extract.indentation);await n($,e,"utf-8")}p.push({path:$,updated:!0}),u.info(` ${f?"(dry-run) ":""}✓ ${$}`)}catch(e){}}p.length>0&&u.info(`\n📦 Translation file updates: ${p.length} file${1===p.length?"":"s"}`);return p}(b,v,g,x,k),E=R.reduce((e,t)=>e+t.changes,0);return!x&&E>0?(k.info("\n✨ Successfully renamed key!"),k.info(` Old: "${$}"`),k.info(` New: "${w}"`),await async function(){if(!await f("rename-key"))return;return console.log(p.yellow.bold("\n💡 Tip: Managing translations across multiple projects?")),console.log(" With locize, you can rename, move, and copy translation keys directly"),console.log(" in the web interface—no CLI needed. Perfect for collaboration with"),console.log(" translators and managing complex refactoring across namespaces."),console.log(` Learn more: ${p.cyan("https://www.locize.com/docs/how-can-a-segment-key-be-copied-moved-or-renamed")}`),u("rename-key")}()):0===E&&k.info(`\n⚠️ No usages found for "${$}"`),{success:!0,sourceFiles:R,translationFiles:j}}function y(e,t){const n=t.extract.nsSeparator??":";if(n&&e.includes(n)){const[t,...r]=e.split(n);return{namespace:t,key:r.join(n),fullKey:e}}return{namespace:t.extract.defaultNS||"translation",key:e,fullKey:e}}async function d(e,t,n,r){return function(e,t,n,r){let o=0,a=e;const s=r.extract.nsSeparator??":",i=e=>s&&e.includes(String(s))?n.fullKey:n.key,c=r.extract.functions||["t","*.t"],l=[];for(const e of c)if(e.startsWith("*.")){const n=$(e.substring(1));l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${$(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${$(t.key)}\\1`,"g"),original:t.key})}else{const n=$(e);l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${$(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${$(t.key)}\\1`,"g"),original:t.key})}for(const{pattern:e,original:t}of l)if(e.test(a)){const n=i(t);a=a.replace(e,(e,t)=>{o++;const r=e.match(/^(\w+(?:\.\w+)*)\(/);return r?`${r[1]}(${t}${n}${t}`:e})}for(const e of c){let n;if(e.startsWith("*.")){n=`\\w+${$(e.substring(1))}`}else n=$(e);for(const e of[t.fullKey,t.key]){const t=new RegExp(`(\\b${n}\\(\\s*\\(?\\s*([a-zA-Z_$][\\w$]*)\\s*\\)?\\s*=>\\s*)\\2\\.${$(e)}(\\s*\\))`,"g");if(t.test(a)){const n=i(e);a=a.replace(t,(e,t,r,a)=>(o++,`${t}${r}.${n}${a}`))}}}const f=[{pattern:new RegExp(`i18nKey=(['"\`])${$(t.fullKey)}\\1`,"g"),original:t.fullKey},{pattern:new RegExp(`i18nKey=(['"\`])${$(t.key)}\\1`,"g"),original:t.key}];for(const{pattern:e,original:t}of f)if(e.test(a)){const n=i(t);a=a.replace(e,(e,t)=>(o++,`i18nKey=${t}${n}${t}`))}return{newCode:a,changes:o}}(e,t,n,r)}function $(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m(e,t,n){if(!1===n)return void delete e[t];const r=t.split(String(n));let o=e;for(let e=0;e<r.length-1;e++){if(!o[r[e]])return;o=o[r[e]]}delete o[r[r.length-1]]}export{g as runRenameKey};
1
+ import{glob as e}from"glob";import{readFile as t,writeFile as n}from"node:fs/promises";import{ConsoleLogger as r}from"./utils/logger.js";import{getOutputPath as o,loadTranslationFile as s,serializeTranslationFile as a}from"./utils/file-utils.js";import{resolve as i}from"node:path";import{getNestedValue as c,setNestedValue as l}from"./utils/nested-object.js";import{shouldShowFunnel as f,recordFunnelShown as u}from"./utils/funnel-msg-tracker.js";import p from"chalk";async function g(g,d,m,h={},x=new r){const{dryRun:k=!1}=h,b=function(e,t){if(!e||!e.trim())return{valid:!1,error:"Old key cannot be empty"};if(!t||!t.trim())return{valid:!1,error:"New key cannot be empty"};if(e===t)return{valid:!1,error:"Old and new keys are identical"};return{valid:!0}}(d,m);if(!b.valid)return{success:!1,sourceFiles:[],translationFiles:[],error:b.error};const K=y(d,g),v=y(m,g),S=await async function(e,t){const n=[];for(const r of t.locales){const a=o(t.extract.output,r,e.namespace),l=i(process.cwd(),a);try{const o=await s(l);if(o){const s=t.extract.keySeparator??".";void 0!==c(o,e.key,s)&&n.push(`${r}:${e.fullKey}`)}}catch{}}return n}(v,g);if(S.length>0)return{success:!1,sourceFiles:[],translationFiles:[],conflicts:S,error:"Target key already exists in translation files"};x.info(`🔍 Scanning for usages of "${d}"...`);const R=await async function(r,o,s,a,i){const c=["node_modules/**"],l=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],f=Array.isArray(s.extract.input)?s.extract.input:[s.extract.input],u=f.map(e=>e.replace(/\\/g,"/")),p=await e(u,{ignore:[...c,...l],cwd:process.cwd()}),g=[];for(const e of p){const c=await t(e,"utf-8"),{newCode:l,changes:f}=await $(c,r,o,s);f>0&&(a||await n(e,l,"utf-8"),g.push({path:e,changes:f}),i.info(` ${a?"(dry-run) ":""}✓ ${e} (${f} ${1===f?"change":"changes"})`))}g.length>0&&i.info(`\n📝 Source file changes: ${g.length} file${1===g.length?"":"s"}`);return g}(K,v,g,k,x),E=await async function(e,t,r,f,u){const p=[],g=r.extract.keySeparator??".";for(const y of r.locales){const $=o(r.extract.output,y,e.namespace),d=i(process.cwd(),$);try{const o=await s(d);if(!o)continue;const i=c(o,e.key,g);if(void 0===i)continue;if(w(o,e.key,g),l(o,t.key,i,g),!f){const e=a(o,r.extract.outputFormat,r.extract.indentation);await n(d,e,"utf-8")}p.push({path:d,updated:!0}),u.info(` ${f?"(dry-run) ":""}✓ ${d}`)}catch(e){}}p.length>0&&u.info(`\n📦 Translation file updates: ${p.length} file${1===p.length?"":"s"}`);return p}(K,v,g,k,x),j=R.reduce((e,t)=>e+t.changes,0);return!k&&j>0?(x.info("\n✨ Successfully renamed key!"),x.info(` Old: "${d}"`),x.info(` New: "${m}"`),await async function(){if(!await f("rename-key"))return;return console.log(p.yellow.bold("\n💡 Tip: Managing translations across multiple projects?")),console.log(" With locize, you can rename, move, and copy translation keys directly"),console.log(" in the web interface—no CLI needed. Perfect for collaboration with"),console.log(" translators and managing complex refactoring across namespaces."),console.log(` Learn more: ${p.cyan("https://www.locize.com/docs/how-can-a-segment-key-be-copied-moved-or-renamed")}`),u("rename-key")}()):0===j&&x.info(`\n⚠️ No usages found for "${d}"`),{success:!0,sourceFiles:R,translationFiles:E}}function y(e,t){const n=t.extract.nsSeparator??":";if(n&&e.includes(n)){const[t,...r]=e.split(n);return{namespace:t,key:r.join(n),fullKey:e}}return{namespace:t.extract.defaultNS||"translation",key:e,fullKey:e}}async function $(e,t,n,r){return function(e,t,n,r){let o=0,s=e;const a=r.extract.nsSeparator??":",i=e=>a&&e.includes(String(a))?n.fullKey:n.key,c=r.extract.functions||["t","*.t"],l=[];for(const e of c)if(e.startsWith("*.")){const n=d(e.substring(1));l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${d(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\w+${n}\\((['"\`])${d(t.key)}\\1`,"g"),original:t.key})}else{const n=d(e);l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${d(t.fullKey)}\\1`,"g"),original:t.fullKey}),l.push({pattern:new RegExp(`\\b${n}\\((['"\`])${d(t.key)}\\1`,"g"),original:t.key})}for(const{pattern:e,original:t}of l)if(e.test(s)){const n=i(t);s=s.replace(e,(e,t)=>{o++;const r=e.match(/^(\w+(?:\.\w+)*)\(/);return r?`${r[1]}(${t}${n}${t}`:e})}for(const e of c){let n;if(e.startsWith("*.")){n=`\\w+${d(e.substring(1))}`}else n=d(e);for(const e of[t.fullKey,t.key]){const t=new RegExp(`(\\b${n}\\(\\s*\\(?\\s*([a-zA-Z_$][\\w$]*)\\s*\\)?\\s*=>\\s*)\\2\\.${d(e)}(\\s*\\))`,"g");if(t.test(s)){const n=i(e);s=s.replace(t,(e,t,r,s)=>(o++,`${t}${r}.${n}${s}`))}const r=new RegExp(`(\\b${n}\\(\\s*\\(?\\s*([a-zA-Z_$][\\w$]*)\\s*\\)?\\s*=>\\s*)\\2\\[\\s*(['"\`])${d(e)}\\3\\s*\\](\\s*\\))`,"g");if(r.test(s)){const t=i(e),n=e=>/^[A-Za-z_$][\w$]*$/.test(e);s=s.replace(r,(e,r,s,a,i)=>(o++,n(t)?`${r}${s}.${t}${i}`:`${r}${s}[${a}${t}${a}]${i}`))}}}const f=[{pattern:new RegExp(`i18nKey=(['"\`])${d(t.fullKey)}\\1`,"g"),original:t.fullKey},{pattern:new RegExp(`i18nKey=(['"\`])${d(t.key)}\\1`,"g"),original:t.key}];for(const{pattern:e,original:t}of f)if(e.test(s)){const n=i(t);s=s.replace(e,(e,t)=>(o++,`i18nKey=${t}${n}${t}`))}return{newCode:s,changes:o}}(e,t,n,r)}function d(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function w(e,t,n){if(!1===n)return void delete e[t];const r=t.split(String(n));let o=e;for(let e=0;e<r.length-1;e++){if(!o[r[e]])return;o=o[r[e]]}delete o[r[r.length-1]]}export{g as runRenameKey};
@@ -1 +1 @@
1
- import e from"chalk";import o from"ora";import{resolve as t}from"node:path";import{findKeys as a}from"./extractor/core/key-finder.js";import{getNestedValue as s}from"./utils/nested-object.js";import{loadTranslationFile as n,getOutputPath as l}from"./utils/file-utils.js";import{shouldShowFunnel as r,recordFunnelShown as c}from"./utils/funnel-msg-tracker.js";async function i(r,c={}){r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(e=>e!==r?.extract?.primaryLanguage);const i=o("Analyzing project localization status...\n").start();try{const o=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(o=>o!==e?.extract?.primaryLanguage);const{allKeys:o}=await a(e),{secondaryLanguages:r,keySeparator:c=".",defaultNS:i="translation",mergeNamespaces:u=!1,pluralSeparator:y="_"}=e.extract,d=new Map;for(const e of o.values()){const o=e.ns||i||"translation";d.has(o)||d.set(o,[]),d.get(o).push(e)}const g={totalBaseKeys:o.size,keysByNs:d,locales:new Map};for(const o of r){let a=0,r=0;const i=new Map,f=u?await n(t(process.cwd(),l(e.extract.output,o)))||{}:null;for(const[g,p]of d.entries()){const d=u?f?.[g]||{}:await n(t(process.cwd(),l(e.extract.output,o,g)))||{};let m=0,$=0;const w=[],h=(e,o)=>{try{const t=o?"ordinal":"cardinal";return new Intl.PluralRules(e,{type:t}).resolvedOptions().pluralCategories}catch(e){return new Intl.PluralRules("en",{type:o?"ordinal":"cardinal"}).resolvedOptions().pluralCategories}};for(const{key:e,hasCount:t,isOrdinal:a,isExpandedPlural:n}of p)if(t)if(n){const t=e.split(y),a=t[t.length-1],n=t.length>=2&&"ordinal"===t[t.length-2],l=n?t[t.length-1]:a;if(h(o,n).includes(l)){$++;const o=!!s(d,e,c??".");o&&m++,w.push({key:e,isTranslated:o})}}else{const t=h(o,a||!1);for(const o of t){$++;const t=a?`${e}${y}ordinal${y}${o}`:`${e}${y}${o}`,n=!!s(d,t,c??".");n&&m++,w.push({key:t,isTranslated:n})}}else{$++;const o=!!s(d,e,c??".");o&&m++,w.push({key:e,isTranslated:o})}i.set(g,{totalKeys:$,translatedKeys:m,keyDetails:w}),a+=m,r+=$}g.locales.set(o,{totalKeys:r,totalTranslated:a,namespaces:i})}return g}(r);i.succeed("Analysis complete."),await async function(o,t,a){a.detail?await async function(o,t,a,s){if(a===t.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${a}" is the primary language. All keys are considered present.`));if(!t.locales.includes(a))return void console.error(e.red(`Error: Locale "${a}" is not defined in your configuration.`));const n=o.locales.get(a);if(!n)return void console.error(e.red(`Error: Locale "${a}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(a)}":`));const l=Array.from(o.keysByNs.values()).flat().length;u("Overall",n.totalTranslated,n.totalKeys);const r=s?[s]:Array.from(n.namespaces.keys()).sort();for(const o of r){const t=n.namespaces.get(o);t&&(console.log(e.cyan.bold(`\nNamespace: ${o}`)),u("Namespace Progress",t.translatedKeys,t.totalKeys),t.keyDetails.forEach(({key:o,isTranslated:t})=>{const a=t?e.green("✓"):e.red("✗");console.log(` ${a} ${o}`)}))}const c=l-n.totalTranslated;c>0?console.log(e.yellow.bold(`\nSummary: Found ${c} missing translations for "${a}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${a}".`));await d()}(o,t,a.detail,a.namespace):a.namespace?await async function(o,t,a){const s=o.keysByNs.get(a);if(!s)return void console.error(e.red(`Error: Namespace "${a}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${a}"`)),console.log("------------------------");for(const[e,t]of o.locales.entries()){const o=t.namespaces.get(a);if(o){const t=o.totalKeys>0?Math.round(o.translatedKeys/o.totalKeys*100):100,a=y(t);console.log(`- ${e}: ${a} ${t}% (${o.translatedKeys}/${o.totalKeys} keys)`)}}await d()}(o,0,a.namespace):await async function(o,t){const{primaryLanguage:a}=t.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(o.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(o.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(t.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(a)}`),console.log("\nTranslation Progress:");for(const[e,t]of o.locales.entries()){const o=t.totalKeys>0?Math.round(t.totalTranslated/t.totalKeys*100):100,a=y(o);console.log(`- ${e}: ${a} ${o}% (${t.totalTranslated}/${t.totalKeys} keys)`)}await d()}(o,t)}(o,r,c)}catch(e){i.fail("Failed to generate status report."),console.error(e)}}function u(o,t,a){const s=a>0?Math.round(t/a*100):100,n=y(s);console.log(`${e.bold(o)}: ${n} ${s}% (${t}/${a})`)}function y(o){const t=Math.floor(o/100*20),a=20-t;return`[${e.green("".padStart(t,"■"))}${"".padStart(a,"□")}]`}async function d(){if(await r("status"))return console.log(e.yellow.bold("\n✨ Take your localization to the next level!")),console.log("Manage translations with your team in the cloud with locize => https://www.locize.com/docs/getting-started"),console.log(`Run ${e.cyan("npx i18next-cli locize-migrate")} to get started.`),c("status")}export{i as runStatus};
1
+ import e from"chalk";import o from"ora";import{resolve as t}from"node:path";import{findKeys as a}from"./extractor/core/key-finder.js";import{getNestedValue as s}from"./utils/nested-object.js";import{loadTranslationFile as n,getOutputPath as l}from"./utils/file-utils.js";import{shouldShowFunnel as r,recordFunnelShown as c}from"./utils/funnel-msg-tracker.js";async function i(r,c={}){r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(e=>e!==r?.extract?.primaryLanguage);const i=o("Analyzing project localization status...\n").start();try{const o=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(o=>o!==e?.extract?.primaryLanguage);const{allKeys:o}=await a(e),{secondaryLanguages:r,keySeparator:c=".",defaultNS:i="translation",mergeNamespaces:u=!1,pluralSeparator:y="_"}=e.extract,d=new Map;for(const e of o.values()){const o=e.ns||i||"translation";d.has(o)||d.set(o,[]),d.get(o).push(e)}const g={totalBaseKeys:o.size,keysByNs:d,locales:new Map};for(const o of r){let a=0,r=0;const f=new Map,p=u?await n(t(process.cwd(),l(e.extract.output,o,!1===i?"translation":i||"translation")))||{}:null;for(const[i,g]of d.entries()){const d=u?p?.[i]??p??{}:await n(t(process.cwd(),l(e.extract.output,o,i)))||{};let m=0,$=0;const w=[],h=(e,o)=>{try{const t=o?"ordinal":"cardinal";return new Intl.PluralRules(e,{type:t}).resolvedOptions().pluralCategories}catch(e){return new Intl.PluralRules("en",{type:o?"ordinal":"cardinal"}).resolvedOptions().pluralCategories}};for(const{key:e,hasCount:t,isOrdinal:a,isExpandedPlural:n}of g)if(t)if(n){const t=e.split(y),a=t[t.length-1],n=t.length>=2&&"ordinal"===t[t.length-2],l=n?t[t.length-1]:a;if(h(o,n).includes(l)){$++;const o=!!s(d,e,c??".");o&&m++,w.push({key:e,isTranslated:o})}}else{const t=h(o,a||!1);for(const o of t){$++;const t=a?`${e}${y}ordinal${y}${o}`:`${e}${y}${o}`,n=!!s(d,t,c??".");n&&m++,w.push({key:t,isTranslated:n})}}else{$++;const o=!!s(d,e,c??".");o&&m++,w.push({key:e,isTranslated:o})}f.set(i,{totalKeys:$,translatedKeys:m,keyDetails:w}),a+=m,r+=$}g.locales.set(o,{totalKeys:r,totalTranslated:a,namespaces:f})}return g}(r);i.succeed("Analysis complete."),await async function(o,t,a){a.detail?await async function(o,t,a,s){if(a===t.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${a}" is the primary language. All keys are considered present.`));if(!t.locales.includes(a))return void console.error(e.red(`Error: Locale "${a}" is not defined in your configuration.`));const n=o.locales.get(a);if(!n)return void console.error(e.red(`Error: Locale "${a}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(a)}":`));const l=Array.from(o.keysByNs.values()).flat().length;u("Overall",n.totalTranslated,n.totalKeys);const r=s?[s]:Array.from(n.namespaces.keys()).sort();for(const o of r){const t=n.namespaces.get(o);t&&(console.log(e.cyan.bold(`\nNamespace: ${o}`)),u("Namespace Progress",t.translatedKeys,t.totalKeys),t.keyDetails.forEach(({key:o,isTranslated:t})=>{const a=t?e.green("✓"):e.red("✗");console.log(` ${a} ${o}`)}))}const c=l-n.totalTranslated;c>0?console.log(e.yellow.bold(`\nSummary: Found ${c} missing translations for "${a}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${a}".`));await d()}(o,t,a.detail,a.namespace):a.namespace?await async function(o,t,a){const s=o.keysByNs.get(a);if(!s)return void console.error(e.red(`Error: Namespace "${a}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${a}"`)),console.log("------------------------");for(const[e,t]of o.locales.entries()){const o=t.namespaces.get(a);if(o){const t=o.totalKeys>0?Math.round(o.translatedKeys/o.totalKeys*100):100,a=y(t);console.log(`- ${e}: ${a} ${t}% (${o.translatedKeys}/${o.totalKeys} keys)`)}}await d()}(o,0,a.namespace):await async function(o,t){const{primaryLanguage:a}=t.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(o.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(o.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(t.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(a)}`),console.log("\nTranslation Progress:");for(const[e,t]of o.locales.entries()){const o=t.totalKeys>0?Math.round(t.totalTranslated/t.totalKeys*100):100,a=y(o);console.log(`- ${e}: ${a} ${o}% (${t.totalTranslated}/${t.totalKeys} keys)`)}await d()}(o,t)}(o,r,c)}catch(e){i.fail("Failed to generate status report."),console.error(e)}}function u(o,t,a){const s=a>0?Math.round(t/a*100):100,n=y(s);console.log(`${e.bold(o)}: ${n} ${s}% (${t}/${a})`)}function y(o){const t=Math.floor(o/100*20),a=20-t;return`[${e.green("".padStart(t,"■"))}${"".padStart(a,"□")}]`}async function d(){if(await r("status"))return console.log(e.yellow.bold("\n✨ Take your localization to the next level!")),console.log("Manage translations with your team in the cloud with locize => https://www.locize.com/docs/getting-started"),console.log(`Run ${e.cyan("npx i18next-cli locize-migrate")} to get started.`),c("status")}export{i as runStatus};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.24.16",
3
+ "version": "1.24.18",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {