i18next-cli 1.30.1 → 1.30.3

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"),require("@croct/json5-parser");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"),y=require("./rename-key.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.30.1"),m.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),m.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.").option("--sync-all","Sync primary language values with default values from code AND clear synced keys in all other locales.").action(async e=>{try{const t=m.opts().config,i=await r.ensureConfig(t),a=async()=>{const o=!!e.syncPrimary||!!e.syncAll,t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:o,syncAll:!!e.syncAll});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...");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)}}),m.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=m.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})}),m.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=m.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()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,o=await r.ensureConfig(e);await l.runSyncer(o)}),m.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),m.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(d.runInit),m.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=m.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()})}}}),m.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=m.opts().config,t=await r.ensureConfig(o);await p.runLocizeSync(t,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const o=m.opts().config,t=await r.ensureConfig(o);await p.runLocizeDownload(t,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const o=m.opts().config,t=await r.ensureConfig(o);await p.runLocizeMigrate(t,e)}),m.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=m.opts().config,a=await r.ensureConfig(n),c=await y.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)}}),m.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=m;
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"),require("@croct/json5-parser");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"),y=require("./rename-key.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.30.3"),m.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),m.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.").option("--sync-all","Sync primary language values with default values from code AND clear synced keys in all other locales.").action(async e=>{try{const t=m.opts().config,i=await r.ensureConfig(t),a=async()=>{const o=!!e.syncPrimary||!!e.syncAll,t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:o,syncAll:!!e.syncAll});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...");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)}}),m.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=m.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})}),m.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=m.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()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,o=await r.ensureConfig(e);await l.runSyncer(o)}),m.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),m.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(d.runInit),m.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=m.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()})}}}),m.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=m.opts().config,t=await r.ensureConfig(o);await p.runLocizeSync(t,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const o=m.opts().config,t=await r.ensureConfig(o);await p.runLocizeDownload(t,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const o=m.opts().config,t=await r.ensureConfig(o);await p.runLocizeMigrate(t,e)}),m.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=m.opts().config,a=await r.ensureConfig(n),c=await y.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)}}),m.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=m;
@@ -1 +1 @@
1
- "use strict";var e=require("i18next-resources-for-ts"),t=require("glob"),s=require("ora"),r=require("chalk"),i=require("node:fs/promises"),n=require("node:path"),o=require("@swc/core"),a=require("./utils/file-utils.js"),c=require("node:vm");async function u(e){const t=n.extname(e);if([".ts",".mts",".cts",".js",".mjs",".cjs"].includes(t)){const t=await i.readFile(e,"utf-8"),{code:s}=await o.transform(t,{filename:e,jsc:{parser:{syntax:"typescript"},target:"es2018"},module:{type:"commonjs"}}),r={},n={exports:r},a=c.createContext({exports:r,module:n,require:e=>require(e),console:console,process:process});new c.Script(s,{filename:e}).runInContext(a);return a.module.exports?.default||a.module.exports}const s=await i.readFile(e,"utf-8");return JSON.parse(s)}exports.runTypesGenerator=async function(o){const c=s("Generating TypeScript types for translations...\n").start();try{o.extract.primaryLanguage||=o.locales[0]||"en";let s=o.extract.output||`locales/${o.extract.primaryLanguage}/*.json`;if(s=a.getOutputPath(s,o.extract.primaryLanguage||"en","*"),o.types||(o.types={input:s,output:"src/@types/i18next.d.ts"}),void 0===o.types.input&&(o.types.input=s),o.types.output||(o.types.output="src/@types/i18next.d.ts"),o.types.resourcesFile||(o.types.resourcesFile=n.join(n.dirname(o.types?.output),"resources.d.ts")),!o.types?.input||o.types?.input.length<0)return void console.log("No input defined!");const p=await t.glob(o.types?.input||[],{cwd:process.cwd()}),l=[];for(const e of p){const t=n.basename(e,n.extname(e)),s=await u(e);if(o.extract?.mergeNamespaces&&s&&"object"==typeof s){const e=Object.keys(s);if(e.length>0&&e.every(e=>s[e]&&"object"==typeof s[e])){for(const t of e)l.push({name:t,resources:s[t]});continue}}l.push({name:t,resources:s})}const d=[],y=o.types?.enableSelector||!1,m=o.types?.indentation??o.extract.indentation??2,f=`// This file is automatically generated by i18next-cli. Do not edit manually.\n${e.mergeResourcesAsInterface(l,{optimize:!!y,indentation:m})}`,g=n.resolve(process.cwd(),o.types?.output||""),w=n.resolve(process.cwd(),o.types.resourcesFile);let x;await i.mkdir(n.dirname(w),{recursive:!0}),await i.writeFile(w,f),d.push(` ${r.green("✓")} Resources interface written to ${o.types.resourcesFile}`);try{await i.access(g),x=!0}catch(e){x=!1}if(!x){const e=`// This file is automatically generated by i18next-cli, because it was not existing. You can edit it based on your needs: https://www.i18next.com/overview/typescript#custom-type-options\nimport Resources from './${n.relative(n.dirname(g),w).replace(/\\/g,"/").replace(/\.d\.ts$/,"")}';\n\ndeclare module 'i18next' {\n interface CustomTypeOptions {\n enableSelector: ${"string"==typeof y?`"${y}"`:y};\n defaultNS: '${o.extract.defaultNS||"translation"}';\n resources: Resources;\n }\n}`;await i.mkdir(n.dirname(g),{recursive:!0}),await i.writeFile(g,e),d.push(` ${r.green("✓")} TypeScript definitions written to ${o.types.output||""}`)}c.succeed(r.bold("TypeScript definitions generated successfully.")),d.forEach(e=>console.log(e))}catch(e){c.fail(r.red("Failed to generate TypeScript definitions.")),console.error(e)}};
1
+ "use strict";var e=require("i18next-resources-for-ts"),t=require("glob"),s=require("ora"),r=require("chalk"),n=require("node:fs/promises"),o=require("node:path"),i=require("@swc/core"),a=require("./utils/file-utils.js"),c=require("node:vm");async function p(e){const t=o.extname(e);if([".ts",".mts",".cts",".js",".mjs",".cjs"].includes(t)){const t=await n.readFile(e,"utf-8"),{code:s}=await i.transform(t,{filename:e,jsc:{parser:{syntax:"typescript"},target:"es2018"},module:{type:"commonjs"}}),r={},o={exports:r},a=c.createContext({exports:r,module:o,require:e=>require(e),console:console,process:process});new c.Script(s,{filename:e}).runInContext(a);return a.module.exports?.default||a.module.exports}const s=await n.readFile(e,"utf-8");return JSON.parse(s)}exports.runTypesGenerator=async function(i){const c=s("Generating TypeScript types for translations...\n").start();try{i.extract.primaryLanguage||=i.locales[0]||"en";let s=i.extract.output||`locales/${i.extract.primaryLanguage}/*.json`;if(s=a.getOutputPath(s,i.extract.primaryLanguage||"en","*"),i.types||(i.types={input:s,output:"src/@types/i18next.d.ts"}),void 0===i.types.input&&(i.types.input=s),i.types.output||(i.types.output="src/@types/i18next.d.ts"),i.types.resourcesFile||(i.types.resourcesFile=o.join(o.dirname(i.types?.output),"resources.d.ts")),!i.types?.input||i.types?.input.length<0)return void console.log("No input defined!");const u=await t.glob(i.types?.input||[],{cwd:process.cwd()}),l=[];for(const e of u){const t=o.basename(e,o.extname(e)),s=await p(e);if(i.extract?.mergeNamespaces&&s&&"object"==typeof s){const t=Object.keys(s),n=t.filter(e=>s[e]&&"object"==typeof s[e]);if(n.length>0){for(const e of n)l.push({name:e,resources:s[e]});const o=t.filter(e=>!s[e]||"object"!=typeof s[e]);o.length>0&&console.warn(r.yellow(`Warning: The file ${e} contains top-level keys that are not objects (${o.join(", ")}). When 'mergeNamespaces' is enabled, top-level keys are treated as namespaces. These keys will be ignored.`));continue}}l.push({name:t,resources:s})}const d=[],y=i.types?.enableSelector||!1,f=i.types?.indentation??i.extract.indentation??2,m=`// This file is automatically generated by i18next-cli. Do not edit manually.\n${e.mergeResourcesAsInterface(l,{optimize:!!y,indentation:f})}`,g=o.resolve(process.cwd(),i.types?.output||""),w=o.resolve(process.cwd(),i.types.resourcesFile);let x;await n.mkdir(o.dirname(w),{recursive:!0}),await n.writeFile(w,m),d.push(` ${r.green("✓")} Resources interface written to ${i.types.resourcesFile}`);try{await n.access(g),x=!0}catch(e){x=!1}if(!x){const e=o.relative(o.dirname(g),w).replace(/\\/g,"/").replace(/\.d\.ts$/,""),t=`// This file is automatically generated by i18next-cli, because it was not existing. You can edit it based on your needs: https://www.i18next.com/overview/typescript#custom-type-options\nimport Resources from './${e}';\n\ndeclare module 'i18next' {\n interface CustomTypeOptions {\n enableSelector: ${"string"==typeof y?`"${y}"`:y};\n defaultNS: ${!1===i.extract.defaultNS?"false":`'${i.extract.defaultNS||"translation"}'`};\n resources: Resources;\n }\n}`;await n.mkdir(o.dirname(g),{recursive:!0}),await n.writeFile(g,t),d.push(` ${r.green("✓")} TypeScript definitions written to ${i.types.output||""}`)}c.succeed(r.bold("TypeScript definitions generated successfully.")),d.forEach(e=>console.log(e))}catch(e){c.fail(r.red("Failed to generate TypeScript definitions.")),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 a,loadConfig as r}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"@croct/json5-parser";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.30.1"),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.").option("--sync-all","Sync primary language values with default values from code AND clear synced keys in all other locales.").action(async o=>{try{const t=x.opts().config,i=await a(t),r=async()=>{const e=!!o.syncPrimary||!!o.syncAll,t=await s(i,{isWatchMode:!!o.watch,isDryRun:!!o.dryRun,syncPrimaryWithDefaults:e,syncAll:!!o.syncAll});return o.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):o.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),o.watch){console.log("\nWatching for changes...");const o=await v(i.extract.input),t=j(i.extract.ignore),a=k(i.extract.output),c=[...t,...a].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}`),r()})}}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 r(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 a(t),r=()=>l(i);if(await r(),o.watch){console.log("\nWatching for changes...");const o=await v(i.types?.input||[]),t=[...j(i.extract?.ignore)].filter(Boolean),a=o.filter(o=>!t.some(e=>n(o,e,{dot:!0})));e.watch(a,{persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),r()})}}),x.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const o=x.opts().config,e=await a(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,a=async()=>{let o=await r(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 a(),o.watch){console.log("\nWatching for changes...");const o=await r(t);if(o?.extract?.input){const t=await v(o.extract.input),i=[...j(o.extract.ignore),...k(o.extract.output)].filter(Boolean),r=t.filter(o=>!i.some(e=>n(o,e,{dot:!0})));e.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}}),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 a(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 a(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 a(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,r=await a(n),c=await w(r,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,"*")]:[],v=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 a,loadConfig as r}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"@croct/json5-parser";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.30.3"),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.").option("--sync-all","Sync primary language values with default values from code AND clear synced keys in all other locales.").action(async o=>{try{const t=x.opts().config,i=await a(t),r=async()=>{const e=!!o.syncPrimary||!!o.syncAll,t=await s(i,{isWatchMode:!!o.watch,isDryRun:!!o.dryRun,syncPrimaryWithDefaults:e,syncAll:!!o.syncAll});return o.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):o.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),o.watch){console.log("\nWatching for changes...");const o=await v(i.extract.input),t=j(i.extract.ignore),a=k(i.extract.output),c=[...t,...a].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}`),r()})}}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 r(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 a(t),r=()=>l(i);if(await r(),o.watch){console.log("\nWatching for changes...");const o=await v(i.types?.input||[]),t=[...j(i.extract?.ignore)].filter(Boolean),a=o.filter(o=>!t.some(e=>n(o,e,{dot:!0})));e.watch(a,{persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),r()})}}),x.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const o=x.opts().config,e=await a(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,a=async()=>{let o=await r(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 a(),o.watch){console.log("\nWatching for changes...");const o=await r(t);if(o?.extract?.input){const t=await v(o.extract.input),i=[...j(o.extract.ignore),...k(o.extract.output)].filter(Boolean),r=t.filter(o=>!i.some(e=>n(o,e,{dot:!0})));e.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}}),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 a(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 a(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 a(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,r=await a(n),c=await w(r,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,"*")]:[],v=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{mergeResourcesAsInterface as e}from"i18next-resources-for-ts";import{glob as t}from"glob";import s from"ora";import o from"chalk";import{mkdir as r,writeFile as n,access as i,readFile as c}from"node:fs/promises";import{join as a,dirname as p,basename as u,extname as l,resolve as y,relative as m}from"node:path";import{transform as f}from"@swc/core";import{getOutputPath as d}from"./utils/file-utils.js";import g from"node:vm";async function w(e){const t=l(e);if([".ts",".mts",".cts",".js",".mjs",".cjs"].includes(t)){const t=await c(e,"utf-8"),{code:s}=await f(t,{filename:e,jsc:{parser:{syntax:"typescript"},target:"es2018"},module:{type:"commonjs"}}),o={},r={exports:o},n=g.createContext({exports:o,module:r,require:e=>require(e),console:console,process:process});new g.Script(s,{filename:e}).runInContext(n);return n.module.exports?.default||n.module.exports}const s=await c(e,"utf-8");return JSON.parse(s)}async function x(c){const f=s("Generating TypeScript types for translations...\n").start();try{c.extract.primaryLanguage||=c.locales[0]||"en";let s=c.extract.output||`locales/${c.extract.primaryLanguage}/*.json`;if(s=d(s,c.extract.primaryLanguage||"en","*"),c.types||(c.types={input:s,output:"src/@types/i18next.d.ts"}),void 0===c.types.input&&(c.types.input=s),c.types.output||(c.types.output="src/@types/i18next.d.ts"),c.types.resourcesFile||(c.types.resourcesFile=a(p(c.types?.output),"resources.d.ts")),!c.types?.input||c.types?.input.length<0)return void console.log("No input defined!");const g=await t(c.types?.input||[],{cwd:process.cwd()}),x=[];for(const e of g){const t=u(e,l(e)),s=await w(e);if(c.extract?.mergeNamespaces&&s&&"object"==typeof s){const e=Object.keys(s);if(e.length>0&&e.every(e=>s[e]&&"object"==typeof s[e])){for(const t of e)x.push({name:t,resources:s[t]});continue}}x.push({name:t,resources:s})}const h=[],b=c.types?.enableSelector||!1,$=c.types?.indentation??c.extract.indentation??2,j=`// This file is automatically generated by i18next-cli. Do not edit manually.\n${e(x,{optimize:!!b,indentation:$})}`,S=y(process.cwd(),c.types?.output||""),v=y(process.cwd(),c.types.resourcesFile);let T;await r(p(v),{recursive:!0}),await n(v,j),h.push(` ${o.green("✓")} Resources interface written to ${c.types.resourcesFile}`);try{await i(S),T=!0}catch(e){T=!1}if(!T){const e=`// This file is automatically generated by i18next-cli, because it was not existing. You can edit it based on your needs: https://www.i18next.com/overview/typescript#custom-type-options\nimport Resources from './${m(p(S),v).replace(/\\/g,"/").replace(/\.d\.ts$/,"")}';\n\ndeclare module 'i18next' {\n interface CustomTypeOptions {\n enableSelector: ${"string"==typeof b?`"${b}"`:b};\n defaultNS: '${c.extract.defaultNS||"translation"}';\n resources: Resources;\n }\n}`;await r(p(S),{recursive:!0}),await n(S,e),h.push(` ${o.green("✓")} TypeScript definitions written to ${c.types.output||""}`)}f.succeed(o.bold("TypeScript definitions generated successfully.")),h.forEach(e=>console.log(e))}catch(e){f.fail(o.red("Failed to generate TypeScript definitions.")),console.error(e)}}export{x as runTypesGenerator};
1
+ import{mergeResourcesAsInterface as e}from"i18next-resources-for-ts";import{glob as t}from"glob";import s from"ora";import o from"chalk";import{mkdir as r,writeFile as n,access as i,readFile as a}from"node:fs/promises";import{join as c,dirname as p,basename as u,extname as l,resolve as y,relative as f}from"node:path";import{transform as m}from"@swc/core";import{getOutputPath as d}from"./utils/file-utils.js";import g from"node:vm";async function w(e){const t=l(e);if([".ts",".mts",".cts",".js",".mjs",".cjs"].includes(t)){const t=await a(e,"utf-8"),{code:s}=await m(t,{filename:e,jsc:{parser:{syntax:"typescript"},target:"es2018"},module:{type:"commonjs"}}),o={},r={exports:o},n=g.createContext({exports:o,module:r,require:e=>require(e),console:console,process:process});new g.Script(s,{filename:e}).runInContext(n);return n.module.exports?.default||n.module.exports}const s=await a(e,"utf-8");return JSON.parse(s)}async function x(a){const m=s("Generating TypeScript types for translations...\n").start();try{a.extract.primaryLanguage||=a.locales[0]||"en";let s=a.extract.output||`locales/${a.extract.primaryLanguage}/*.json`;if(s=d(s,a.extract.primaryLanguage||"en","*"),a.types||(a.types={input:s,output:"src/@types/i18next.d.ts"}),void 0===a.types.input&&(a.types.input=s),a.types.output||(a.types.output="src/@types/i18next.d.ts"),a.types.resourcesFile||(a.types.resourcesFile=c(p(a.types?.output),"resources.d.ts")),!a.types?.input||a.types?.input.length<0)return void console.log("No input defined!");const g=await t(a.types?.input||[],{cwd:process.cwd()}),x=[];for(const e of g){const t=u(e,l(e)),s=await w(e);if(a.extract?.mergeNamespaces&&s&&"object"==typeof s){const t=Object.keys(s),r=t.filter(e=>s[e]&&"object"==typeof s[e]);if(r.length>0){for(const e of r)x.push({name:e,resources:s[e]});const n=t.filter(e=>!s[e]||"object"!=typeof s[e]);n.length>0&&console.warn(o.yellow(`Warning: The file ${e} contains top-level keys that are not objects (${n.join(", ")}). When 'mergeNamespaces' is enabled, top-level keys are treated as namespaces. These keys will be ignored.`));continue}}x.push({name:t,resources:s})}const h=[],b=a.types?.enableSelector||!1,$=a.types?.indentation??a.extract.indentation??2,j=`// This file is automatically generated by i18next-cli. Do not edit manually.\n${e(x,{optimize:!!b,indentation:$})}`,S=y(process.cwd(),a.types?.output||""),v=y(process.cwd(),a.types.resourcesFile);let T;await r(p(v),{recursive:!0}),await n(v,j),h.push(` ${o.green("✓")} Resources interface written to ${a.types.resourcesFile}`);try{await i(S),T=!0}catch(e){T=!1}if(!T){const e=f(p(S),v).replace(/\\/g,"/").replace(/\.d\.ts$/,""),t=`// This file is automatically generated by i18next-cli, because it was not existing. You can edit it based on your needs: https://www.i18next.com/overview/typescript#custom-type-options\nimport Resources from './${e}';\n\ndeclare module 'i18next' {\n interface CustomTypeOptions {\n enableSelector: ${"string"==typeof b?`"${b}"`:b};\n defaultNS: ${!1===a.extract.defaultNS?"false":`'${a.extract.defaultNS||"translation"}'`};\n resources: Resources;\n }\n}`;await r(p(S),{recursive:!0}),await n(S,t),h.push(` ${o.green("✓")} TypeScript definitions written to ${a.types.output||""}`)}m.succeed(o.bold("TypeScript definitions generated successfully.")),h.forEach(e=>console.log(e))}catch(e){m.fail(o.red("Failed to generate TypeScript definitions.")),console.error(e)}}export{x as runTypesGenerator};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.30.1",
3
+ "version": "1.30.3",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +1 @@
1
- {"version":3,"file":"types-generator.d.ts","sourceRoot":"","sources":["../src/types-generator.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAsDnD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,iBAAiB,CAAE,MAAM,EAAE,oBAAoB,iBA4FpE"}
1
+ {"version":3,"file":"types-generator.d.ts","sourceRoot":"","sources":["../src/types-generator.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAsDnD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,iBAAiB,CAAE,MAAM,EAAE,oBAAoB,iBAqGpE"}