i18next-cli 1.19.0 → 1.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/extractor.js +1 -1
- package/dist/cjs/extractor/core/translation-manager.js +1 -1
- package/dist/cjs/linter.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/extractor.js +1 -1
- package/dist/esm/extractor/core/translation-manager.js +1 -1
- package/dist/esm/linter.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +1 -1
- package/src/extractor/core/extractor.ts +10 -4
- package/src/extractor/core/translation-manager.ts +44 -3
- package/src/linter.ts +9 -2
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/linter.d.ts.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.19.2](https://github.com/i18next/i18next-cli/compare/v1.19.1...v1.19.2) - 2025-11-02
|
|
9
|
+
|
|
10
|
+
- fix(extractor): preserve flat output when extract.defaultNS is false on re-extracttion. [#73](https://github.com/i18next/i18next-cli/issues/73)
|
|
11
|
+
|
|
12
|
+
## [1.19.1](https://github.com/i18next/i18next-cli/compare/v1.19.0...v1.19.1) - 2025-10-31
|
|
13
|
+
|
|
14
|
+
- fix: Prevent parser crashes on TypeScript files that use angle‑bracket type assertions (e.g. `const x = <SomeType>getValue()`). The extractor and linter now choose SWC's TSX parsing mode based on the file extension (`.tsx` => JSX enabled, `.ts`/`.mts`/`.cts` => JSX disabled), avoiding accidental JSX parsing of compile‑time casts. [#84](https://github.com/i18next/i18next-cli/issues/84)
|
|
15
|
+
|
|
8
16
|
## [1.19.0](https://github.com/i18next/i18next-cli/compare/v1.18.1...v1.19.0) - 2025-10-31
|
|
9
17
|
|
|
10
18
|
- feat(extractor): improve key extraction to detect translation keys stored in local variables, object properties and simple string expressions [#83](https://github.com/i18next/i18next-cli/issues/83)
|
package/dist/cjs/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("commander"),t=require("chokidar"),o=require("glob"),n=require("minimatch"),i=require("chalk"),a=require("./config.js"),r=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"),g=require("./init.js"),d=require("./linter.js"),p=require("./status.js"),f=require("./locize.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.19.
|
|
2
|
+
"use strict";var e=require("commander"),t=require("chokidar"),o=require("glob"),n=require("minimatch"),i=require("chalk"),a=require("./config.js"),r=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"),g=require("./init.js"),d=require("./linter.js"),p=require("./status.js"),f=require("./locize.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.19.2"),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.").action(async e=>{try{const o=m.opts().config,i=await a.ensureConfig(o),r=async()=>{const t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.extract.input),o=y(i.extract.ignore),a=h(i.extract.output),c=[...o,...a].filter(Boolean),s=e.filter(e=>!c.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}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,t)=>{const o=m.opts().config;let n=await a.loadConfig(o);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await r.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 p.runStatus(n,{detail:e,namespace:t.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 o=m.opts().config,i=await a.ensureConfig(o),r=()=>s.runTypesGenerator(i);if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.types?.input||[]),o=[...y(i.extract?.ignore)].filter(Boolean),a=e.filter(e=>!o.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,t=await a.ensureConfig(e);await l.runSyncer(t)}),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(g.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 o=m.opts().config,c=async()=>{let e=await a.loadConfig(o);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const t=await r.detectConfig();t||(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=t}await d.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await a.loadConfig(o);if(e?.extract?.input){const o=await w(e.extract.input),i=[...y(e.extract.ignore),...h(e.extract.output)].filter(Boolean),a=o.filter(e=>!i.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{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 t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeSync(o,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeDownload(o,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeMigrate(o,e)}),m.parse(process.argv);const y=e=>Array.isArray(e)?e:e?[e]:[],h=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],w=async(e=[])=>{const t=y(e),n=await Promise.all(t.map(e=>o.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var t=require("ora"),e=require("chalk"),a=require("@swc/core"),r=require("node:fs/promises"),n=require("node:path"),o=require("./key-finder.js"),s=require("./translation-manager.js"),i=require("../../utils/validation.js"),c=require("../parsers/comment-parser.js"),l=require("../../utils/logger.js"),u=require("../../utils/file-utils.js"),g=require("../../utils/funnel-msg-tracker.js");exports.extract=async function(t,{syncPrimaryWithDefaults:e=!1}={}){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(e=>e!==t?.extract?.primaryLanguage),t.extract.functions||=["t","*.t"],t.extract.transComponents||=["Trans"];const{allKeys:a,objectKeys:r}=await o.findKeys(t);return s.getTranslations(a,r,t,{syncPrimaryWithDefaults:e})},exports.processFile=async function(t,e,o,s,u,g=new l.ConsoleLogger){try{let i=await r.readFile(t,"utf-8");for(const a of e)try{const e=await(a.onLoad?.(i,t));void 0!==e&&(i=e)}catch(t){g.warn(`Plugin ${a.name} onLoad failed:`,t)}const l=n.extname(t).toLowerCase(),y=".ts"===l||".tsx"===l||".mts"===l||".cts"===l,d=".tsx"===l,m=await a.parse(i,{syntax:y?"typescript":"ecmascript",tsx:d,decorators:!0,dynamicImport:!0,comments:!0});s.getVarFromScope=o.getVarFromScope.bind(o),o.visit(m),c.extractKeysFromComments(i,s,u,o.getVarFromScope.bind(o))}catch(e){throw new i.ExtractorError("Failed to process file",t,e)}},exports.runExtractor=async function(a,{isWatchMode:c=!1,isDryRun:y=!1,syncPrimaryWithDefaults:d=!1}={},m=new l.ConsoleLogger){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(t=>t!==a?.extract?.primaryLanguage),a.extract.functions||=["t","*.t"],a.extract.transComponents||=["Trans"],i.validateExtractorConfig(a);const f=a.plugins||[],p=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:i}=await o.findKeys(a,m);p.text=`Found ${t.size} unique keys. Updating translation files...`;const c=await s.getTranslations(t,i,a,{syncPrimaryWithDefaults:d});let l=!1;for(const t of c)if(t.updated&&(l=!0,!y)){const o=u.serializeTranslationFile(t.newTranslations,a.extract.outputFormat,a.extract.indentation);await r.mkdir(n.dirname(t.path),{recursive:!0}),await r.writeFile(t.path,o),m.info(e.green(`Updated: ${t.path}`))}if(f.length>0){p.text="Running post-extraction plugins...";for(const t of f)await(t.afterSync?.(c,a))}return p.succeed(e.bold("Extraction complete!")),l&&await async function(){if(!await g.shouldShowFunnel("extract"))return;return console.log(e.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${e.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${e.cyan("https://youtu.be/joPsZghT3wM")}`),g.recordFunnelShown("extract")}(),l}catch(t){throw p.fail(e.red("Extraction failed.")),t}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),
|
|
1
|
+
"use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),a=require("../../utils/default-value.js");function r(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function o(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},n=t?.extract?.pluralSeparator??"_",a=["zero","one","two","few","many","other"],r=a.map(e=>`ordinal${n}${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of r)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of a)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},o=s(e),l=s(t);if(o.isPlural&&l.isPlural){const e=o.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(o.isOrdinal!==l.isOrdinal)return o.isOrdinal?1:-1;const t=o.isOrdinal?r:a,s=t.indexOf(o.form),n=t.indexOf(l.form);return-1!==s&&-1!==n?s-n:o.form.localeCompare(l.form)}const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t,void 0,{sensitivity:"case"}):i});for(const n of l)s[n]=o(e[n],t);return s}function l(e,t,n,r,l,i=[],c=new Set,u=!1){const{keySeparator:f=".",sort:d=!0,removeUnusedKeys:p=!0,primaryLanguage:g,defaultValue:y="",pluralSeparator:h="_",contextSeparator:x="_"}=n.extract,m=(...e)=>{console.log("[i18next-debug]",...e)};m("buildNewTranslationsForNs start",{locale:r,namespace:l,keySeparator:f,pluralSeparator:h,primaryLanguage:g}),m("nsKeys (count):",e.length);try{m("existingTranslations keys:",s.getNestedKeys(t,f??".").slice(0,50))}catch(e){m("could not list existing keys",e)}const v=new Set;let O=[],S=[];try{const e=new Intl.PluralRules(r,{type:"cardinal"}),t=new Intl.PluralRules(r,{type:"ordinal"});O=e.resolvedOptions().pluralCategories,S=t.resolvedOptions().pluralCategories,O.forEach(e=>v.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}catch(e){const t=g||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});O=s.resolvedOptions().pluralCategories,S=n.resolvedOptions().pluralCategories,O.forEach(e=>v.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}const N=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if(i.some(t=>t.test(e)))return!1;if(!t)return!0;const n=e.split(h);if(t&&1===n.length)return!0;if(1===O.length&&"other"===O[0]&&1===n.length)return!0;if(s&&n.includes("ordinal")){const e=n[n.length-1];return v.has(`ordinal_${e}`)}if(t){const e=n[n.length-1];return v.has(e)}return!0}),b=new Set;for(const e of N)if(e.isExpandedPlural){const t=String(e.key).split(h);t.length>=3&&"ordinal"===t[t.length-2]?b.add(t.slice(0,-2).join(h)):b.add(t.slice(0,-1).join(h))}let w=p?{}:JSON.parse(JSON.stringify(t));const V=s.getNestedKeys(t,f??".");for(const e of V)if(i.some(t=>t.test(e))){const n=s.getNestedValue(t,e,f??".");s.setNestedValue(w,e,n,f??".")}if(p){const e=s.getNestedKeys(t,f??".");for(const n of e){const e=n.split(h);if("zero"===e[e.length-1]){const a=e.slice(0,-1).join(h);if(N.some(({key:e})=>e.split(h).slice(0,-1).join(h)===a)){const e=s.getNestedValue(t,n,f??".");s.setNestedValue(w,n,e,f??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:i,hasCount:d,isExpandedPlural:p,isOrdinal:v}of N){if(d&&!p){const t=String(e).split(h);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(h):t.length>=2&&(s=t.slice(0,-1).join(h)),b.has(s))continue}if(d&&!p){if(1===String(e).split(h).length&&r!==g){const i=e;if(b.has(i));else{const e=v?S:O;for(const c of e){const e=v?`${i}${h}ordinal${h}${c}`:`${i}${h}${c}`,u=s.getNestedValue(t,e,f??".");if(void 0===u){let t;t="string"==typeof o?o:a.resolveDefaultValue(y,String(i),l||n?.extract?.defaultNS||"translation",r,o),m("expanding plural variant",{finalKey:e,existingVariantValue:u,resolvedValue:t}),s.setNestedValue(w,e,t,f??".")}else m("keeping existing plural variant",{finalKey:e,existingVariantValue:u}),s.setNestedValue(w,e,u,f??".")}}continue}}const V=s.getNestedValue(t,e,f??"."),k=!1===f||!N.some(t=>t.key!==e&&t.key.startsWith(`${e}${f}`)),$="object"==typeof V&&null!==V&&(c.has(e)||!o||o===e),j="object"==typeof V&&null!==V&&k&&!c.has(e)&&!$;if(m("processing key",{key:e,existingValueType:typeof V,isLeafInNewKeys:k,shouldPreserveObject:$,isStaleObject:j,defaultValue:o}),$){s.setNestedValue(w,e,V,f??".");continue}let P;if(void 0===V||j)if(r===g)if(u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));P=o&&!t?o:a.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",r,o)}else P=o||e;else P=a.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",r,o);else if(r===g&&u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));P=(e.includes(h)||e.includes(x))&&!i?V:o&&!t?o:V}else P=V;m("final decision for key",{key:e,existingValue:V,valueToSet:P,typeofExisting:typeof V,typeofValueToSet:typeof P}),s.setNestedValue(w,e,P,f??".")}if(!0===d)return o(w,n);if("function"==typeof d){const e={},t=Object.keys(w),s=new Map;for(const e of N){const t=!1===f?e.key:e.key.split(f)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof d){const n=s.get(e),a=s.get(t);if(n&&a)return d(n,a)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=o(w[s],n);w=e}return w}exports.getTranslations=async function(s,a,o,{syncPrimaryWithDefaults:i=!1}={}){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(e=>e!==o?.extract?.primaryLanguage);const c=[...o.extract.preservePatterns||[]],u=o.extract.indentation??2;for(const e of a)c.push(`${e}.*`);const f=c.map(r),d="__no_namespace__",p=new Map;for(const e of s.values()){const t=e.nsIsImplicit&&!1===o.extract.defaultNS?d:String(e.ns??o.extract.defaultNS??"translation");p.has(t)||p.set(t,[]),p.get(t).push(e)}const g=[],y=Array.isArray(o.extract.ignore)?o.extract.ignore:o.extract.ignore?[o.extract.ignore]:[];for(const s of o.locales){if(o.extract.mergeNamespaces||"string"==typeof o.extract.output&&!o.extract.output.includes("{{namespace}}")){const t={},r=n.getOutputPath(o.extract.output,s),c=e.resolve(process.cwd(),r),y=await n.loadTranslationFile(c)||{},h=Object.keys(y),x=h.some(e=>{const t=y[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...p.keys(),...h]):new Set([...p.keys(),d]);for(const e of x){const n=p.get(e)||[];if(e===d){const e=l(n,y,o,s,void 0,f,a,i);Object.assign(t,e)}else{const r=y[e]||{};t[e]=l(n,r,o,s,e,f,a,i)}}const m=JSON.stringify(y,null,u),v=JSON.stringify(t,null,u);g.push({path:c,updated:v!==m,newTranslations:t,existingTranslations:y})}else{const r=new Set(p.keys()),c=n.getOutputPath(o.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});for(const t of d)r.add(e.basename(t,e.extname(t)));for(const t of r){const r=p.get(t)||[],c=n.getOutputPath(o.extract.output,s,t),d=e.resolve(process.cwd(),c),y=await n.loadTranslationFile(d)||{},h=l(r,y,o,s,t,f,a,i),x=JSON.stringify(y,null,u),m=JSON.stringify(h,null,u);g.push({path:d,updated:m!==x,newTranslations:h,existingTranslations:y})}}}return g};
|
package/dist/cjs/linter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("glob"),t=require("node:fs/promises"),r=require("@swc/core"),n=require("node:
|
|
1
|
+
"use strict";var e=require("glob"),t=require("node:fs/promises"),r=require("@swc/core"),n=require("node:path"),s=require("node:events"),o=require("chalk"),i=require("ora");class a extends s.EventEmitter{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:s}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const o=["node_modules/**"],i=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],a=await e.glob(s.extract.input,{ignore:[...o,...i]});this.emit("progress",{message:`Analyzing ${a.length} source files...`});let c=0;const l=new Map;for(const e of a){const o=await t.readFile(e,"utf-8"),i=n.extname(e).toLowerCase(),a=".ts"===i||".tsx"===i||".mts"===i||".cts"===i,f=".tsx"===i,p=u(await r.parse(o,{syntax:a?"typescript":"ecmascript",tsx:f,decorators:!0}),o,s);p.length>0&&(c+=p.length,l.set(e,p))}const f={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",f),f}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}const c=e=>/^(https|http|\/\/|^\/)/.test(e);function u(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],u=new Set([...i,"script","style","code",...a]),l=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},g=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&u.has(e))return!0}}return!1},m=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!g(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!c(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=g(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!c(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>m(e,r)):n&&"object"==typeof n&&m(n,r)}};m(e,[]);let y=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,y);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),y=s+r.length)}return n}exports.Linter=a,exports.runLinter=async function(e){return new a(e).run()},exports.runLinterCli=async function(e){const t=new a(e),r=i().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:s}=await t.run();if(e)r.succeed(o.green.bold(n));else{r.fail(o.red.bold(n));for(const[e,t]of Object.entries(s))console.log(o.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${o.gray(`${t}:`)} ${o.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}};
|
package/dist/esm/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n 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{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}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";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.19.
|
|
2
|
+
import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n 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{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}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";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.19.2"),w.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),w.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async t=>{try{const e=w.opts().config,n=await a(e),r=async()=>{const o=await s(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.extract.input),e=x(n.extract.ignore),a=j(n.extract.output),c=[...e,...a].filter(Boolean),s=t.filter(t=>!c.some(o=>i(t,o,{dot:!0})));o.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),w.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(t,o)=>{const e=w.opts().config;let i=await r(e);if(!i){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),i=t}await g(i,{detail:t,namespace:o.namespace})}),w.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async t=>{const e=w.opts().config,n=await a(e),r=()=>l(n);if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.types?.input||[]),e=[...x(n.extract?.ignore)].filter(Boolean),a=t.filter(t=>!e.some(o=>i(t,o,{dot:!0})));o.watch(a,{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=w.opts().config,o=await a(t);await p(o)}),w.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await m(t)}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(f),w.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async t=>{const e=w.opts().config,a=async()=>{let t=await r(e);if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await a(),t.watch){console.log("\nWatching for changes...");const t=await r(e);if(t?.extract?.input){const e=await z(t.extract.input),n=[...x(t.extract.ignore),...j(t.extract.output)].filter(Boolean),r=e.filter(t=>!n.some(o=>i(t,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}}),w.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async t=>{const o=w.opts().config,e=await a(o);await u(e,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await y(e,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await h(e,t)}),w.parse(process.argv);const x=t=>Array.isArray(t)?t:t?[t]:[],j=t=>t&&"string"==typeof t?[t.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(t=[])=>{const o=x(t),i=await Promise.all(o.map(t=>e(t||"",{nodir:!0})));return Array.from(new Set(i.flat()))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"ora";import a from"chalk";import{parse as e}from"@swc/core";import{mkdir as o,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as i}from"node:path";import{findKeys as
|
|
1
|
+
import t from"ora";import a from"chalk";import{parse as e}from"@swc/core";import{mkdir as o,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as s,extname as i}from"node:path";import{findKeys as c}from"./key-finder.js";import{getTranslations as l}from"./translation-manager.js";import{validateExtractorConfig as m,ExtractorError as u}from"../../utils/validation.js";import{extractKeysFromComments as f}from"../parsers/comment-parser.js";import{ConsoleLogger as p}from"../../utils/logger.js";import{serializeTranslationFile as y}from"../../utils/file-utils.js";import{shouldShowFunnel as g,recordFunnelShown as d}from"../../utils/funnel-msg-tracker.js";async function w(e,{isWatchMode:n=!1,isDryRun:i=!1,syncPrimaryWithDefaults:u=!1}={},f=new p){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),e.extract.functions||=["t","*.t"],e.extract.transComponents||=["Trans"],m(e);const w=e.plugins||[],x=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:n}=await c(e,f);x.text=`Found ${t.size} unique keys. Updating translation files...`;const m=await l(t,n,e,{syncPrimaryWithDefaults:u});let p=!1;for(const t of m)if(t.updated&&(p=!0,!i)){const n=y(t.newTranslations,e.extract.outputFormat,e.extract.indentation);await o(s(t.path),{recursive:!0}),await r(t.path,n),f.info(a.green(`Updated: ${t.path}`))}if(w.length>0){x.text="Running post-extraction plugins...";for(const t of w)await(t.afterSync?.(m,e))}return x.succeed(a.bold("Extraction complete!")),p&&await async function(){if(!await g("extract"))return;return console.log(a.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${a.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${a.cyan("https://youtu.be/joPsZghT3wM")}`),d("extract")}(),p}catch(t){throw x.fail(a.red("Extraction failed.")),t}}async function x(t,a,o,r,s,c=new p){try{let l=await n(t,"utf-8");for(const e of a)try{const a=await(e.onLoad?.(l,t));void 0!==a&&(l=a)}catch(t){c.warn(`Plugin ${e.name} onLoad failed:`,t)}const m=i(t).toLowerCase(),u=".ts"===m||".tsx"===m||".mts"===m||".cts"===m,p=".tsx"===m,y=await e(l,{syntax:u?"typescript":"ecmascript",tsx:p,decorators:!0,dynamicImport:!0,comments:!0});r.getVarFromScope=o.getVarFromScope.bind(o),o.visit(y),f(l,r,s,o.getVarFromScope.bind(o))}catch(a){throw new u("Failed to process file",t,a)}}async function h(t,{syncPrimaryWithDefaults:a=!1}={}){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(a=>a!==t?.extract?.primaryLanguage),t.extract.functions||=["t","*.t"],t.extract.transComponents||=["Trans"];const{allKeys:e,objectKeys:o}=await c(t);return l(e,o,t,{syncPrimaryWithDefaults:a})}export{h as extract,x as processFile,w as runExtractor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve as
|
|
1
|
+
import{resolve as e,basename as t,extname as n}from"node:path";import{glob as s}from"glob";import{getNestedKeys as r,getNestedValue as o,setNestedValue as a}from"../../utils/nested-object.js";import{getOutputPath as i,loadTranslationFile as l}from"../../utils/file-utils.js";import{resolveDefaultValue as c}from"../../utils/default-value.js";function f(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function u(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const n={},s=t?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],o=r.map(e=>`ordinal${s}${e}`),a=Object.keys(e).sort((e,t)=>{const n=e=>{for(const t of o)if(e.endsWith(`${s}${t}`)){return{base:e.slice(0,-(s.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of r)if(e.endsWith(`${s}${t}`)){return{base:e.slice(0,-(s.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},a=n(e),i=n(t);if(a.isPlural&&i.isPlural){const e=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const t=a.isOrdinal?o:r,n=t.indexOf(a.form),s=t.indexOf(i.form);return-1!==n&&-1!==s?n-s:a.form.localeCompare(i.form)}const l=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===l?e.localeCompare(t,void 0,{sensitivity:"case"}):l});for(const s of a)n[s]=u(e[s],t);return n}function p(e,t,n,s,i,l=[],f=new Set,p=!1){const{keySeparator:d=".",sort:g=!0,removeUnusedKeys:y=!0,primaryLanguage:h,defaultValue:m="",pluralSeparator:x="_",contextSeparator:S="_"}=n.extract,O=(...e)=>{console.log("[i18next-debug]",...e)};O("buildNewTranslationsForNs start",{locale:s,namespace:i,keySeparator:d,pluralSeparator:x,primaryLanguage:h}),O("nsKeys (count):",e.length);try{O("existingTranslations keys:",r(t,d??".").slice(0,50))}catch(e){O("could not list existing keys",e)}const v=new Set;let w=[],k=[];try{const e=new Intl.PluralRules(s,{type:"cardinal"}),t=new Intl.PluralRules(s,{type:"ordinal"});w=e.resolvedOptions().pluralCategories,k=t.resolvedOptions().pluralCategories,w.forEach(e=>v.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}catch(e){const t=h||"en",n=new Intl.PluralRules(t,{type:"cardinal"}),s=new Intl.PluralRules(t,{type:"ordinal"});w=n.resolvedOptions().pluralCategories,k=s.resolvedOptions().pluralCategories,w.forEach(e=>v.add(e)),s.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}const $=e.filter(({key:e,hasCount:t,isOrdinal:n})=>{if(l.some(t=>t.test(e)))return!1;if(!t)return!0;const s=e.split(x);if(t&&1===s.length)return!0;if(1===w.length&&"other"===w[0]&&1===s.length)return!0;if(n&&s.includes("ordinal")){const e=s[s.length-1];return v.has(`ordinal_${e}`)}if(t){const e=s[s.length-1];return v.has(e)}return!0}),b=new Set;for(const e of $)if(e.isExpandedPlural){const t=String(e.key).split(x);t.length>=3&&"ordinal"===t[t.length-2]?b.add(t.slice(0,-2).join(x)):b.add(t.slice(0,-1).join(x))}let j=y?{}:JSON.parse(JSON.stringify(t));const N=r(t,d??".");for(const e of N)if(l.some(t=>t.test(e))){const n=o(t,e,d??".");a(j,e,n,d??".")}if(y){const e=r(t,d??".");for(const n of e){const e=n.split(x);if("zero"===e[e.length-1]){const s=e.slice(0,-1).join(x);if($.some(({key:e})=>e.split(x).slice(0,-1).join(x)===s)){const e=o(t,n,d??".");a(j,n,e,d??".")}}}}for(const{key:e,defaultValue:r,explicitDefault:l,hasCount:u,isExpandedPlural:g,isOrdinal:y}of $){if(u&&!g){const t=String(e).split(x);let n=e;if(t.length>=3&&"ordinal"===t[t.length-2]?n=t.slice(0,-2).join(x):t.length>=2&&(n=t.slice(0,-1).join(x)),b.has(n))continue}if(u&&!g){if(1===String(e).split(x).length&&s!==h){const l=e;if(b.has(l));else{const e=y?k:w;for(const f of e){const e=y?`${l}${x}ordinal${x}${f}`:`${l}${x}${f}`,u=o(t,e,d??".");if(void 0===u){let t;t="string"==typeof r?r:c(m,String(l),i||n?.extract?.defaultNS||"translation",s,r),O("expanding plural variant",{finalKey:e,existingVariantValue:u,resolvedValue:t}),a(j,e,t,d??".")}else O("keeping existing plural variant",{finalKey:e,existingVariantValue:u}),a(j,e,u,d??".")}}continue}}const v=o(t,e,d??"."),N=!1===d||!$.some(t=>t.key!==e&&t.key.startsWith(`${e}${d}`)),P="object"==typeof v&&null!==v&&(f.has(e)||!r||r===e),C="object"==typeof v&&null!==v&&N&&!f.has(e)&&!P;if(O("processing key",{key:e,existingValueType:typeof v,isLeafInNewKeys:N,shouldPreserveObject:P,isStaleObject:C,defaultValue:r}),P){a(j,e,v,d??".");continue}let V;if(void 0===v||C)if(s===h)if(p){const t=r&&(r===e||e!==r&&(e.startsWith(r+x)||e.startsWith(r+S)));V=r&&!t?r:c(m,e,i||n?.extract?.defaultNS||"translation",s,r)}else V=r||e;else V=c(m,e,i||n?.extract?.defaultNS||"translation",s,r);else if(s===h&&p){const t=r&&(r===e||e!==r&&(e.startsWith(r+x)||e.startsWith(r+S)));V=(e.includes(x)||e.includes(S))&&!l?v:r&&!t?r:v}else V=v;O("final decision for key",{key:e,existingValue:v,valueToSet:V,typeofExisting:typeof v,typeofValueToSet:typeof V}),a(j,e,V,d??".")}if(!0===g)return u(j,n);if("function"==typeof g){const e={},t=Object.keys(j),s=new Map;for(const e of $){const t=!1===d?e.key:e.key.split(d)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof g){const n=s.get(e),r=s.get(t);if(n&&r)return g(n,r)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=u(j[s],n);j=e}return j}async function d(r,o,a,{syncPrimaryWithDefaults:c=!1}={}){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage);const u=[...a.extract.preservePatterns||[]],d=a.extract.indentation??2;for(const e of o)u.push(`${e}.*`);const g=u.map(f),y="__no_namespace__",h=new Map;for(const e of r.values()){const t=e.nsIsImplicit&&!1===a.extract.defaultNS?y:String(e.ns??a.extract.defaultNS??"translation");h.has(t)||h.set(t,[]),h.get(t).push(e)}const m=[],x=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const r of a.locales){if(a.extract.mergeNamespaces||"string"==typeof a.extract.output&&!a.extract.output.includes("{{namespace}}")){const t={},n=i(a.extract.output,r),s=e(process.cwd(),n),f=await l(s)||{},u=Object.keys(f),x=u.some(e=>{const t=f[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...h.keys(),...u]):new Set([...h.keys(),y]);for(const e of x){const n=h.get(e)||[];if(e===y){const e=p(n,f,a,r,void 0,g,o,c);Object.assign(t,e)}else{const s=f[e]||{};t[e]=p(n,s,a,r,e,g,o,c)}}const S=JSON.stringify(f,null,d),O=JSON.stringify(t,null,d);m.push({path:s,updated:O!==S,newTranslations:t,existingTranslations:f})}else{const f=new Set(h.keys()),u=i(a.extract.output,r,"*").replace(/\\/g,"/"),y=await s(u,{ignore:x});for(const e of y)f.add(t(e,n(e)));for(const t of f){const n=h.get(t)||[],s=i(a.extract.output,r,t),f=e(process.cwd(),s),u=await l(f)||{},y=p(n,u,a,r,t,g,o,c),x=JSON.stringify(u,null,d),S=JSON.stringify(y,null,d);m.push({path:f,updated:S!==x,newTranslations:y,existingTranslations:u})}}}return m}export{d as getTranslations};
|
package/dist/esm/linter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{glob as e}from"glob";import{readFile as t}from"node:fs/promises";import{parse as r}from"@swc/core";import{
|
|
1
|
+
import{glob as e}from"glob";import{readFile as t}from"node:fs/promises";import{parse as r}from"@swc/core";import{extname as n}from"node:path";import{EventEmitter as s}from"node:events";import o from"chalk";import i from"ora";class a extends s{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:s}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const o=["node_modules/**"],i=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],a=await e(s.extract.input,{ignore:[...o,...i]});this.emit("progress",{message:`Analyzing ${a.length} source files...`});let c=0;const l=new Map;for(const e of a){const o=await t(e,"utf-8"),i=n(e).toLowerCase(),a=".ts"===i||".tsx"===i||".mts"===i||".cts"===i,u=".tsx"===i,p=f(await r(o,{syntax:a?"typescript":"ecmascript",tsx:u,decorators:!0}),o,s);p.length>0&&(c+=p.length,l.set(e,p))}const u={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",u),u}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}async function c(e){return new a(e).run()}async function l(e){const t=new a(e),r=i().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:s}=await t.run();if(e)r.succeed(o.green.bold(n));else{r.fail(o.red.bold(n));for(const[e,t]of Object.entries(s))console.log(o.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${o.gray(`${t}:`)} ${o.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}}const u=e=>/^(https|http|\/\/|^\/)/.test(e);function f(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],c=new Set([...i,"script","style","code",...a]),l=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},m=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&c.has(e))return!0}}return!1},g=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!m(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!u(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=m(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!u(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>g(e,r)):n&&"object"==typeof n&&g(n,r)}};g(e,[]);let y=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,y);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),y=s+r.length)}return n}export{a as Linter,c as runLinter,l as runLinterCli};
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -22,7 +22,7 @@ const program = new Command()
|
|
|
22
22
|
program
|
|
23
23
|
.name('i18next-cli')
|
|
24
24
|
.description('A unified, high-performance i18next CLI.')
|
|
25
|
-
.version('1.19.
|
|
25
|
+
.version('1.19.2')
|
|
26
26
|
|
|
27
27
|
// new: global config override option
|
|
28
28
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
|
|
@@ -2,7 +2,7 @@ import ora from 'ora'
|
|
|
2
2
|
import chalk from 'chalk'
|
|
3
3
|
import { parse } from '@swc/core'
|
|
4
4
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
5
|
-
import { dirname } from 'node:path'
|
|
5
|
+
import { dirname, extname } from 'node:path'
|
|
6
6
|
import type { Logger, I18nextToolkitConfig, Plugin, PluginContext } from '../../types'
|
|
7
7
|
import { findKeys } from './key-finder'
|
|
8
8
|
import { getTranslations } from './translation-manager'
|
|
@@ -154,11 +154,17 @@ export async function processFile (
|
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
+
// Determine parser options from file extension so .ts is not parsed as TSX
|
|
158
|
+
const fileExt = extname(file).toLowerCase()
|
|
159
|
+
const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
|
|
160
|
+
const isTSX = fileExt === '.tsx'
|
|
161
|
+
|
|
157
162
|
const ast = await parse(code, {
|
|
158
|
-
syntax: 'typescript',
|
|
159
|
-
tsx:
|
|
163
|
+
syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
|
|
164
|
+
tsx: isTSX,
|
|
160
165
|
decorators: true,
|
|
161
|
-
|
|
166
|
+
dynamicImport: true,
|
|
167
|
+
comments: true,
|
|
162
168
|
})
|
|
163
169
|
|
|
164
170
|
// "Wire up" the visitor's scope method to the context.
|
|
@@ -121,6 +121,18 @@ function buildNewTranslationsForNs (
|
|
|
121
121
|
contextSeparator = '_',
|
|
122
122
|
} = config.extract
|
|
123
123
|
|
|
124
|
+
// Debugging hook: enable detailed logs by setting environment variable
|
|
125
|
+
// I18NEXT_DEBUG=1 when running tests (or local runs).
|
|
126
|
+
const DEBUG = true
|
|
127
|
+
const debugLog = (...args: any[]) => { if (DEBUG) console.log('[i18next-debug]', ...args) }
|
|
128
|
+
|
|
129
|
+
if (DEBUG) {
|
|
130
|
+
debugLog('buildNewTranslationsForNs start', { locale, namespace, keySeparator, pluralSeparator, primaryLanguage })
|
|
131
|
+
debugLog('nsKeys (count):', nsKeys.length)
|
|
132
|
+
// shallow snapshot of existingTranslations (avoid huge dumps)
|
|
133
|
+
try { debugLog('existingTranslations keys:', getNestedKeys(existingTranslations, keySeparator ?? '.').slice(0, 50)) } catch (e) { debugLog('could not list existing keys', e) }
|
|
134
|
+
}
|
|
135
|
+
|
|
124
136
|
// Get the plural categories for the target language
|
|
125
137
|
const targetLanguagePluralCategories = new Set<string>()
|
|
126
138
|
// Track cardinal plural categories separately so we can special-case single-"other" languages
|
|
@@ -298,9 +310,11 @@ function buildNewTranslationsForNs (
|
|
|
298
310
|
// Use resolveDefaultValue to compute a sensible default, providing namespace and locale context.
|
|
299
311
|
resolvedValue = resolveDefaultValue(emptyDefaultValue, String(base), namespace || config?.extract?.defaultNS || 'translation', locale, defaultValue)
|
|
300
312
|
}
|
|
313
|
+
debugLog('expanding plural variant', { finalKey, existingVariantValue, resolvedValue })
|
|
301
314
|
|
|
302
315
|
setNestedValue(newTranslations, finalKey, resolvedValue, keySeparator ?? '.')
|
|
303
316
|
} else {
|
|
317
|
+
debugLog('keeping existing plural variant', { finalKey, existingVariantValue })
|
|
304
318
|
// Keep existing translation
|
|
305
319
|
setNestedValue(newTranslations, finalKey, existingVariantValue, keySeparator ?? '.')
|
|
306
320
|
}
|
|
@@ -312,7 +326,12 @@ function buildNewTranslationsForNs (
|
|
|
312
326
|
}
|
|
313
327
|
|
|
314
328
|
const existingValue = getNestedValue(existingTranslations, key, keySeparator ?? '.')
|
|
315
|
-
|
|
329
|
+
// When keySeparator === false we are working with flat keys (no nesting).
|
|
330
|
+
// Avoid concatenating false into strings (``${key}${false}`` => "keyfalse") which breaks the startsWith check.
|
|
331
|
+
// For flat keys there cannot be nested children, so treat them as leaves.
|
|
332
|
+
const isLeafInNewKeys = keySeparator === false
|
|
333
|
+
? true
|
|
334
|
+
: !filteredKeys.some(otherKey => otherKey.key !== key && otherKey.key.startsWith(`${key}${keySeparator}`))
|
|
316
335
|
|
|
317
336
|
// Determine if we should preserve an existing object
|
|
318
337
|
const shouldPreserveObject = typeof existingValue === 'object' && existingValue !== null && (
|
|
@@ -322,6 +341,10 @@ function buildNewTranslationsForNs (
|
|
|
322
341
|
|
|
323
342
|
const isStaleObject = typeof existingValue === 'object' && existingValue !== null && isLeafInNewKeys && !objectKeys.has(key) && !shouldPreserveObject
|
|
324
343
|
|
|
344
|
+
if (DEBUG) {
|
|
345
|
+
debugLog('processing key', { key, existingValueType: typeof existingValue, isLeafInNewKeys, shouldPreserveObject, isStaleObject, defaultValue })
|
|
346
|
+
}
|
|
347
|
+
|
|
325
348
|
// Special handling for existing objects that should be preserved
|
|
326
349
|
if (shouldPreserveObject) {
|
|
327
350
|
setNestedValue(newTranslations, key, existingValue, keySeparator ?? '.')
|
|
@@ -384,6 +407,10 @@ function buildNewTranslationsForNs (
|
|
|
384
407
|
}
|
|
385
408
|
}
|
|
386
409
|
|
|
410
|
+
if (DEBUG) {
|
|
411
|
+
debugLog('final decision for key', { key, existingValue, valueToSet, typeofExisting: typeof existingValue, typeofValueToSet: typeof valueToSet })
|
|
412
|
+
}
|
|
413
|
+
|
|
387
414
|
setNestedValue(newTranslations, key, valueToSet, keySeparator ?? '.')
|
|
388
415
|
}
|
|
389
416
|
|
|
@@ -510,8 +537,22 @@ export async function getTranslations (
|
|
|
510
537
|
const fullPath = resolve(process.cwd(), outputPath)
|
|
511
538
|
const existingMergedFile = await loadTranslationFile(fullPath) || {}
|
|
512
539
|
|
|
513
|
-
//
|
|
514
|
-
|
|
540
|
+
// Determine whether the existing merged file already uses namespace objects
|
|
541
|
+
// or is a flat mapping of translation keys -> values.
|
|
542
|
+
// If it's flat (values are primitives), we must NOT treat each translation key as a namespace.
|
|
543
|
+
const existingKeys = Object.keys(existingMergedFile)
|
|
544
|
+
const existingIsNamespaced = existingKeys.some(k => {
|
|
545
|
+
const v = (existingMergedFile as any)[k]
|
|
546
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
547
|
+
})
|
|
548
|
+
|
|
549
|
+
// The namespaces to process:
|
|
550
|
+
// - If existing file is namespaced, combine keysByNS with existingMergedFile namespaces.
|
|
551
|
+
// - If existing file is flat (top-level translations), ensure NO_NS_TOKEN is processed.
|
|
552
|
+
const namespacesToProcess = existingIsNamespaced
|
|
553
|
+
? new Set<string>([...keysByNS.keys(), ...existingKeys])
|
|
554
|
+
: new Set<string>([...keysByNS.keys(), NO_NS_TOKEN])
|
|
555
|
+
|
|
515
556
|
for (const nsKey of namespacesToProcess) {
|
|
516
557
|
const nsKeys = keysByNS.get(nsKey) || []
|
|
517
558
|
if (nsKey === NO_NS_TOKEN) {
|
package/src/linter.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { glob } from 'glob'
|
|
2
2
|
import { readFile } from 'node:fs/promises'
|
|
3
3
|
import { parse } from '@swc/core'
|
|
4
|
+
import { extname } from 'node:path'
|
|
4
5
|
import { EventEmitter } from 'node:events'
|
|
5
6
|
import chalk from 'chalk'
|
|
6
7
|
import ora from 'ora'
|
|
@@ -57,9 +58,15 @@ export class Linter extends EventEmitter<LinterEventMap> {
|
|
|
57
58
|
|
|
58
59
|
for (const file of sourceFiles) {
|
|
59
60
|
const code = await readFile(file, 'utf-8')
|
|
61
|
+
|
|
62
|
+
// Determine parser options from file extension so .ts is not parsed as TSX
|
|
63
|
+
const fileExt = extname(file).toLowerCase()
|
|
64
|
+
const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
|
|
65
|
+
const isTSX = fileExt === '.tsx'
|
|
66
|
+
|
|
60
67
|
const ast = await parse(code, {
|
|
61
|
-
syntax: 'typescript',
|
|
62
|
-
tsx:
|
|
68
|
+
syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
|
|
69
|
+
tsx: isTSX,
|
|
63
70
|
decorators: true
|
|
64
71
|
})
|
|
65
72
|
const hardcodedStrings = findHardcodedStrings(ast, code, config)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAKtF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAK5C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,oBAAoB,EAC5B,EACE,WAAmB,EACnB,QAAgB,EAChB,uBAA+B,EAChC,GAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,uBAAuB,CAAC,EAAE,OAAO,CAAC;CAC9B,EACN,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,OAAO,CAAC,CAyDlB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EAAE,EACjB,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,EAC7C,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAKtF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAK5C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,oBAAoB,EAC5B,EACE,WAAmB,EACnB,QAAgB,EAChB,uBAA+B,EAChC,GAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,uBAAuB,CAAC,EAAE,OAAO,CAAC;CAC9B,EACN,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,OAAO,CAAC,CAyDlB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EAAE,EACjB,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,EAC7C,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,CA0Cf;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAE,MAAM,EAAE,oBAAoB,EAAE,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,sDAO3I"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AA4cnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA2G9B"}
|
package/types/linter.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAG1C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD,KAAK,cAAc,GAAG;IACpB,QAAQ,EAAE;QAAC;YACT,OAAO,EAAE,MAAM,CAAC;SACjB;KAAC,CAAC;IACH,IAAI,EAAE;QAAC;YACL,OAAO,EAAE,OAAO,CAAC;YACjB,OAAO,EAAE,MAAM,CAAC;YAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;SAC1C;KAAC,CAAC;IACH,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;CACvB,CAAA;AAED,qBAAa,MAAO,SAAQ,YAAY,CAAC,cAAc,CAAC;IACtD,OAAO,CAAC,MAAM,CAAsB;gBAEvB,MAAM,EAAE,oBAAoB;IAKzC,SAAS,CAAE,KAAK,EAAE,OAAO;IAanB,GAAG;;;;;;;CA+CV;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,SAAS,CAAE,MAAM,EAAE,oBAAoB;;;;;;GAE5D;AAED,wBAAsB,YAAY,CAAE,MAAM,EAAE,oBAAoB,iBA4B/D;AAED;;GAEG;AACH,UAAU,eAAe;IACvB,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd"}
|