i18next-cli 1.23.4 → 1.23.6
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 +9 -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/extractor/parsers/jsx-parser.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/extractor/parsers/jsx-parser.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 +2 -0
- package/src/extractor/core/translation-manager.ts +45 -25
- package/src/extractor/parsers/jsx-parser.ts +14 -14
- package/src/linter.ts +2 -0
- 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,15 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.23.6](https://github.com/i18next/i18next-cli/compare/v1.23.5...v1.23.6) - 2025-11-12
|
|
9
|
+
|
|
10
|
+
- fix jsx extraction [#108](https://github.com/i18next/i18next-cli/issues/108)
|
|
11
|
+
- improved Trans component parsing for spaces [102](https://github.com/i18next/i18next-cli/issues/102)
|
|
12
|
+
|
|
13
|
+
## [1.23.5](https://github.com/i18next/i18next-cli/compare/v1.23.4...v1.23.5) - 2025-11-11
|
|
14
|
+
|
|
15
|
+
- **Extractor:** Fixed custom sort function not being applied to nested keys. When providing a custom `sort` function (e.g., for case-insensitive sorting to match locize's behavior), the sorting logic is now correctly applied throughout the entire object hierarchy, not just at the top level. This ensures consistent key ordering at all nesting levels in translation files. [#106](https://github.com/i18next/i18next-cli/issues/106)
|
|
16
|
+
|
|
8
17
|
## [1.23.4](https://github.com/i18next/i18next-cli/compare/v1.23.3...v1.23.4) - 2025-11-11
|
|
9
18
|
|
|
10
19
|
- Fix preservingContextVariants when using shorthand property for context in options. [#105](https://github.com/i18next/i18next-cli/pull/105)
|
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.23.
|
|
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.23.6"),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 t=require("ora"),e=require("chalk"),r=require("@swc/core"),a=require("node:fs/promises"),o=require("node:path"),n=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"),y=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:r,objectKeys:a}=await n.findKeys(t);return s.getTranslations(r,a,t,{syncPrimaryWithDefaults:e})},exports.processFile=async function(t,e,n,s,u,y=new l.ConsoleLogger){try{let l=await a.readFile(t,"utf-8");for(const r of e)try{const e=await(r.onLoad?.(l,t));void 0!==e&&(l=e)}catch(t){y.warn(`Plugin ${r.name} onLoad failed:`,t)}const d=o.extname(t).toLowerCase(),g=".ts"===d||".tsx"===d||".mts"===d||".cts"===d,m=".tsx"===d;let
|
|
1
|
+
"use strict";var t=require("ora"),e=require("chalk"),r=require("@swc/core"),a=require("node:fs/promises"),o=require("node:path"),n=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"),y=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:r,objectKeys:a}=await n.findKeys(t);return s.getTranslations(r,a,t,{syncPrimaryWithDefaults:e})},exports.processFile=async function(t,e,n,s,u,y=new l.ConsoleLogger){try{let l=await a.readFile(t,"utf-8");for(const r of e)try{const e=await(r.onLoad?.(l,t));void 0!==e&&(l=e)}catch(t){y.warn(`Plugin ${r.name} onLoad failed:`,t)}const d=o.extname(t).toLowerCase(),g=".ts"===d||".tsx"===d||".mts"===d||".cts"===d,m=".tsx"===d,p=".jsx"===d;let f;try{f=await r.parse(l,{syntax:g?"typescript":"ecmascript",tsx:m,jsx:p,decorators:!0,dynamicImport:!0,comments:!0})}catch(e){if(".ts"!==d||m)throw new i.ExtractorError("Failed to process file",t,e);try{f=await r.parse(l,{syntax:"typescript",tsx:!0,decorators:!0,dynamicImport:!0,comments:!0}),y.info?.(`Parsed ${t} using TSX fallback`)}catch(e){throw new i.ExtractorError("Failed to process file",t,e)}}s.getVarFromScope=n.getVarFromScope.bind(n),n.setCurrentFile(t,l),n.visit(f),c.extractKeysFromComments(l,s,u,n.getVarFromScope.bind(n))}catch(e){throw new i.ExtractorError("Failed to process file",t,e)}},exports.runExtractor=async function(r,{isWatchMode:c=!1,isDryRun:d=!1,syncPrimaryWithDefaults:g=!1}={},m=new l.ConsoleLogger){r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(t=>t!==r?.extract?.primaryLanguage),r.extract.functions||=["t","*.t"],r.extract.transComponents||=["Trans"],i.validateExtractorConfig(r);const p=r.plugins||[],f=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:i}=await n.findKeys(r,m);f.text=`Found ${t.size} unique keys. Updating translation files...`;const c=await s.getTranslations(t,i,r,{syncPrimaryWithDefaults:g});let l=!1;for(const t of c)if(t.updated&&(l=!0,!d)){const n=u.serializeTranslationFile(t.newTranslations,r.extract.outputFormat,r.extract.indentation);await a.mkdir(o.dirname(t.path),{recursive:!0}),await a.writeFile(t.path,n),m.info(e.green(`Updated: ${t.path}`))}if(p.length>0){f.text="Running post-extraction plugins...";for(const t of p)await(t.afterSync?.(c,r))}return f.succeed(e.bold("Extraction complete!")),l&&await async function(){if(!await y.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")}`),y.recordFunnelShown("extract")}(),l}catch(t){throw f.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"),r=require("../../utils/default-value.js");function o(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function a(e,t,s,n){if(0===t.size)return!1;let r=e;const o=["zero","one","two","few","many","other"];for(const e of o){if(r.endsWith(`${s}${e}`)){r=r.slice(0,-(s.length+e.length));break}if(r.endsWith(`${s}ordinal${s}${e}`)){r=r.slice(0,-(s.length+7+s.length+e.length));break}}const a=r.split(n);if(a.length>1)for(let e=1;e<a.length;e++){const s=a.slice(0,-e).join(n);if(t.has(s))return!0}return!!t.has(r)}function i(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const
|
|
1
|
+
"use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),r=require("../../utils/default-value.js");function o(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function a(e,t,s,n){if(0===t.size)return!1;let r=e;const o=["zero","one","two","few","many","other"];for(const e of o){if(r.endsWith(`${s}${e}`)){r=r.slice(0,-(s.length+e.length));break}if(r.endsWith(`${s}ordinal${s}${e}`)){r=r.slice(0,-(s.length+7+s.length+e.length));break}}const a=r.split(n);if(a.length>1)for(let e=1;e<a.length;e++){const s=a.slice(0,-e).join(n);if(t.has(s))return!0}return!!t.has(r)}function i(e,t,s){if("object"!=typeof e||null===e||Array.isArray(e))return e;const n={},r=t?.extract?.pluralSeparator??"_",o=["zero","one","two","few","many","other"],a=o.map(e=>`ordinal${r}${e}`),l=Object.keys(e).sort((e,t)=>{const n=e=>{for(const t of a)if(e.endsWith(`${r}${t}`)){return{base:e.slice(0,-(r.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of o)if(e.endsWith(`${r}${t}`)){return{base:e.slice(0,-(r.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},i=n(e),l=n(t);if(i.isPlural&&l.isPlural){const e=s?s(i.base,l.base):i.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(i.isOrdinal!==l.isOrdinal)return i.isOrdinal?1:-1;const t=i.isOrdinal?a:o,n=t.indexOf(i.form),r=t.indexOf(l.form);return-1!==n&&-1!==r?n-r:i.form.localeCompare(l.form)}if(s)return s(e,t);const c=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===c?e.localeCompare(t,void 0,{sensitivity:"case"}):c});for(const r of l)n[r]=i(e[r],t,s);return n}function l(e,t,n,l,c,u=[],f=new Set,d=!1){const{keySeparator:p=".",sort:g=!0,removeUnusedKeys:h=!0,primaryLanguage:y,defaultValue:x="",pluralSeparator:m="_",contextSeparator:S="_",preserveContextVariants:O=!1}=n.extract,$=new Set;if(O)for(const{keyAcceptingContext:t}of e)t&&$.add(t);const v=new Set;let w=[],N=[];try{const e=new Intl.PluralRules(l,{type:"cardinal"}),t=new Intl.PluralRules(l,{type:"ordinal"});w=e.resolvedOptions().pluralCategories,N=t.resolvedOptions().pluralCategories,w.forEach(e=>v.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}catch(e){const t=y||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});w=s.resolvedOptions().pluralCategories,N=n.resolvedOptions().pluralCategories,w.forEach(e=>v.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}const b=n.extract.preservePatterns||[],k="string"==typeof n.extract.nsSeparator?n.extract.nsSeparator:":",j=e=>{if(u.some(t=>t.test(e)))return!0;for(const t of b)if("string"==typeof t){if(t.endsWith(`${k}*`)){const e=t.slice(0,-(k.length+1));if("*"===e||c&&e===c)return!0}if(t.includes(k)&&c){const[s,n]=t.split(k);if(s===c){if(o(n).test(e))return!0}}}return!1},P=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if((e=>{if(u.some(t=>t.test(e)))return!0;for(const e of b)if("string"==typeof e&&e.endsWith(`${k}*`)){const t=e.slice(0,-(k.length+1));if("*"===t||c&&t===c)return!0}return!1})(e))return!1;if(!t)return!0;const n=e.split(m);if(t&&1===n.length)return!0;if(1===w.length&&"other"===w[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}),V=new Set;for(const e of P)if(e.isExpandedPlural){const t=String(e.key).split(m);t.length>=3&&"ordinal"===t[t.length-2]?V.add(t.slice(0,-2).join(m)):V.add(t.slice(0,-1).join(m))}let C=h?{}:JSON.parse(JSON.stringify(t));const W=s.getNestedKeys(t,p??".");for(const e of W){const n=j(e),r=!n&&a(e,$,m,S);if(n||O&&r){const n=s.getNestedValue(t,e,p??".");s.setNestedValue(C,e,n,p??".")}}if(h){const e=s.getNestedKeys(t,p??".");for(const n of e){const e=n.split(m);if("zero"===e[e.length-1]){const r=e.slice(0,-1).join(m);if(P.some(({key:e})=>e.split(m).slice(0,-1).join(m)===r)){const e=s.getNestedValue(t,n,p??".");s.setNestedValue(C,n,e,p??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:a,hasCount:i,isExpandedPlural:u,isOrdinal:g}of P){if(i&&!u){const t=String(e).split(m);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(m):t.length>=2&&(s=t.slice(0,-1).join(m)),V.has(s))continue}if(i&&!u){if(1===String(e).split(m).length&&l!==y){const a=e;if(V.has(a));else{const e=g?N:w;for(const i of e){const e=g?`${a}${m}ordinal${m}${i}`:`${a}${m}${i}`,u=s.getNestedValue(t,e,p??".");if(void 0===u){let t;t="string"==typeof o?o:r.resolveDefaultValue(x,String(a),c||n?.extract?.defaultNS||"translation",l,o),s.setNestedValue(C,e,t,p??".")}else s.setNestedValue(C,e,u,p??".")}}continue}}const h=s.getNestedValue(t,e,p??"."),O=!1===p||!P.some(t=>t.key!==e&&t.key.startsWith(`${e}${p}`)),$="object"==typeof h&&null!==h&&(f.has(e)||!o||o===e),v="object"==typeof h&&null!==h&&O&&!f.has(e)&&!$;if($){s.setNestedValue(C,e,h,p??".");continue}let b;if(void 0===h||v)if(l===y)if(d){const t=o&&(o===e||o.includes(k)||e!==o&&(e.startsWith(o+m)||e.startsWith(o+S)));b=o&&!t?o:r.resolveDefaultValue(x,e,c||n?.extract?.defaultNS||"translation",l,o)}else b=o||e;else b=r.resolveDefaultValue(x,e,c||n?.extract?.defaultNS||"translation",l,o);else if(l===y&&d){const t=o&&(o===e||o.includes(k)||e!==o&&(e.startsWith(o+m)||e.startsWith(o+S)));b=(e.includes(m)||e.includes(S))&&!a?h:o&&!t?o:h}else b=h;s.setNestedValue(C,e,b,p??".")}if(!0===g)return i(C,n);if("function"==typeof g){const t={},s=Object.keys(C),r=new Map;for(const t of e)if(r.set(String(t.key),t),p){const e=String(t.key).split(p)[0];r.has(e)||r.set(e,t)}const o=(e,t)=>{const s=r.get(e),n=r.get(t);if(s&&n)return g(s,n);return g({key:e},{key:t})};s.sort(o);for(const e of s)t[e]=i(C[e],n,o);C=t}return C}exports.getTranslations=async function(s,r,a,{syncPrimaryWithDefaults:i=!1}={}){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage);const c=[...a.extract.preservePatterns||[]],u=a.extract.indentation??2;for(const e of r)c.push(`${e}.*`);const f=c.map(o),d="__no_namespace__",p=new Map;for(const e of s.values()){const t=e.nsIsImplicit&&!1===a.extract.defaultNS?d:String(e.ns??a.extract.defaultNS??"translation");p.has(t)||p.set(t,[]),p.get(t).push(e)}const g=[],h=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const s of a.locales){if(a.extract.mergeNamespaces||"string"==typeof a.extract.output&&!a.extract.output.includes("{{namespace}}")){const t={},o=n.getOutputPath(a.extract.output,s),c=e.resolve(process.cwd(),o),h=await n.loadTranslationFile(c)||{},y=Object.keys(h),x=!1!==a.extract.defaultNS&&y.some(e=>{const t=h[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...p.keys(),...y]):new Set([...p.keys(),d]);for(const e of x){const n=p.get(e)||[];if(e===d){const e=l(n,h,a,s,void 0,f,r,i);Object.assign(t,e)}else{const o=h[e]||{};t[e]=l(n,o,a,s,e,f,r,i)}}const m=JSON.stringify(h,null,u),S=JSON.stringify(t,null,u);g.push({path:c,updated:S!==m,newTranslations:t,existingTranslations:h})}else{const o=new Set(p.keys()),c=n.getOutputPath(a.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:h});for(const t of d)o.add(e.basename(t,e.extname(t)));for(const t of o){const o=p.get(t)||[],c=n.getOutputPath(a.extract.output,s,t),d=e.resolve(process.cwd(),c),h=await n.loadTranslationFile(d)||{},y=l(o,h,a,s,t,f,r,i),x=JSON.stringify(h,null,u),m=JSON.stringify(y,null,u);g.push({path:d,updated:m!==x,newTranslations:y,existingTranslations:h})}}}return g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./ast-utils.js");function t(t){if(t)return"StringLiteral"===t.type?t.value:"TemplateLiteral"===t.type&&e.isSimpleTemplateLiteral(t)?t.quasis[0].cooked:void 0}function n(e){return"StringLiteral"===e.value?.type?e.value.value:"JSXExpressionContainer"===e.value?.type?t(e.value.expression):void 0}exports.extractFromTransComponent=function(i,r){const s=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),o=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),p=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),l=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let a;p||"JSXAttribute"!==l?.type||"JSXExpressionContainer"!==l.value?.type||"ObjectExpression"!==l.value.expression.type||(a=e.getObjectPropValueExpression(l.value.expression,"count"));const u=!!p||!!a,y=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),f="JSXAttribute"===y?.type&&"JSXExpressionContainer"===y.value?.type&&"ObjectExpression"===y.value.expression.type?y.value.expression:void 0,c=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),v=!!c,S=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let
|
|
1
|
+
"use strict";var e=require("./ast-utils.js");function t(t){if(t)return"StringLiteral"===t.type?t.value:"TemplateLiteral"===t.type&&e.isSimpleTemplateLiteral(t)?t.quasis[0].cooked:void 0}function n(e){return"StringLiteral"===e.value?.type?e.value.value:"JSXExpressionContainer"===e.value?.type?t(e.value.expression):void 0}exports.extractFromTransComponent=function(i,r){const s=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),o=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),p=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),l=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let a;p||"JSXAttribute"!==l?.type||"JSXExpressionContainer"!==l.value?.type||"ObjectExpression"!==l.value.expression.type||(a=e.getObjectPropValueExpression(l.value.expression,"count"));const u=!!p||!!a,y=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),f="JSXAttribute"===y?.type&&"JSXExpressionContainer"===y.value?.type&&"ObjectExpression"===y.value.expression.type?y.value.expression:void 0,c=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),v=!!c,S=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let g="JSXAttribute"===S?.type&&"JSXExpressionContainer"===S.value?.type?S.value.expression:"JSXAttribute"===S?.type&&"StringLiteral"===S.value?.type?S.value:void 0;const d=i.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let x;x="JSXAttribute"===d?.type?n(d):void 0,f&&(void 0===x&&(x=e.getObjectPropValue(f,"ns")),void 0===g&&(g=e.getObjectPropValueExpression(f,"context")));const m=function(e,n){if(!e||0===e.length)return"";const i=new Set(n.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),r=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function s(e,n,o=!1){if(!e||!e.length)return;let p=0,l=e.length-1;for(;p<=l&&r(e[p]);)p++;for(;l>=p&&r(e[l]);)l--;const a=p<=l?e.slice(p,l+1):[],u=a.some(e=>e&&("JSXElement"===e.type||"JSXFragment"===e.type));for(let e=0;e<a.length;e++){const p=a[e];if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){if(o&&!u&&p.expression){const e=p.expression.type;if("ObjectExpression"===e){const e=p.expression.properties&&p.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}const n=t(p.expression);if(void 0!==n){if(!(/^\s*$/.test(n)&&!n.includes("\n")))continue}else if("Identifier"===e||"MemberExpression"===e||"CallExpression"===e)continue}const i=t(p.expression);if(void 0!==i){const t=/^\s*$/.test(i)&&!i.includes("\n"),s=a[e-1],o=a[e+1];if(t){const t=a[e+2];if(o&&"JSXText"===o.type&&r(o)&&t&&("JSXElement"===t.type||"JSXFragment"===t.type)){const t=a[e-1],n=a[e-2];if(!t||"JSXText"!==t.type&&n&&"JSXExpressionContainer"===n.type)continue}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&r(o))continue;const i=!o||"JSXText"===o.type&&!r(o);if(s&&"JSXText"===s.type&&i){const e=n[n.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+p.expression.value;continue}}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&r(o))continue}}n.push(p);continue}if("JSXElement"===p.type){const e=p.opening&&p.opening.name&&"Identifier"===p.opening.name.type?p.opening.name.value:void 0;if(e&&i.has(e)){!(!p.opening||!p.opening.selfClosing)&&n.push(p),s(p.children||[],n,!1)}else n.push(p),s(p.children||[],n,!0);continue}"JSXFragment"!==p.type||s(p.children||[],n,o)}else{if(o&&!u)continue;if(o&&r(p))continue;if(r(p)){const t=a[e-1],i=a[e+1];if(t&&("JSXElement"===t.type||"JSXFragment"===t.type)&&i&&("JSXElement"===i.type||"JSXFragment"===i.type))continue;const r=n[n.length-1],s=a[e-1];if(r){if(s&&"JSXExpressionContainer"===s.type)continue;if("JSXText"===r.type&&s&&"JSXText"===s.type){r.value=String(r.value)+p.value;continue}}}if(o&&u&&0===e)continue;n.push(p)}}}const o=[];s(e,o,!1);const p=e=>String(e).replace(/^\s*\n\s*/g,"").replace(/\s*\n\s*$/g,"");function l(e,n){if(!e||0===e.length)return"";let s="";for(let a=0;a<e.length;a++){const u=e[a];if(u)if("JSXText"!==u.type){if("JSXExpressionContainer"===u.type){const e=u.expression;if(!e)continue;const n=t(e);if(void 0!==n)s+=n;else if("Identifier"===e.type)s+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const t=e.properties[0];t&&"KeyValueProperty"===t.type&&t.key&&"Identifier"===t.key.type?s+=`{{${t.key.value}}}`:t&&"Identifier"===t.type?s+=`{{${t.value}}}`:s+="{{value}}"}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?s+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type?s+=`{{${e.callee.value}}}`:s+="{{value}}";continue}if("JSXElement"===u.type){let t;if(u.opening&&u.opening.name&&"Identifier"===u.opening.name.type&&(t=u.opening.name.value),t&&i.has(t)){const i=l(u.children||[],n),r=!(!u.opening||!u.opening.selfClosing),o=""!==String(i).trim();if(r||!o){const n=e[a-1];n&&"JSXText"===n.type&&/\n\s*$/.test(n.value)&&(s=s.replace(/\s+$/,"")),s+=`<${t} />`}else s+=`<${t}>${i}</${t}>`}else{const e=u.children||[];if(e.some(e=>e&&("JSXText"===e.type||"JSXExpressionContainer"===e.type)&&-1!==o.indexOf(e))){const t=o.indexOf(u),n=l(e,void 0);s+=`<${t}>${p(n)}</${t}>`}else{const t=new Map;let r=0;for(const n of e)if(n&&"JSXElement"===n.type){const e=n.opening&&n.opening.name&&"Identifier"===n.opening.name.type?n.opening.name.value:void 0;if(e&&i.has(e)){!(!n.opening||!n.opening.selfClosing)&&t.set(n,r++)}else t.set(n,r++)}const a=n&&n.has(u)?n.get(u):o.indexOf(u),y=l(e,t.size?t:void 0);s+=`<${a}>${p(y)}</${a}>`}}continue}"JSXFragment"!==u.type||(s+=l(u.children||[]))}else{if(r(u))continue;s+=u.value}}return s}const a=l(e),u=String(a).replace(/<br \/>\s*\n\s*/g,"<br />").replace(/\s+/g," ");return u.replace(/\s+\./g,".").trim()}(i.children,r);let J;const X="JSXAttribute"===o?.type?n(o):void 0;if(void 0!==X)J=X;else{const e=r.extract.defaultValue;J="string"==typeof e?e:""}let b,E;if("JSXAttribute"===s?.type){if("StringLiteral"===s.value?.type){if(b=s.value,E=b.value,!E||""===E.trim())return null;if(x&&"StringLiteral"===b.type){const e=r.extract.nsSeparator??":",t=b.value;if(e&&t.startsWith(`${x}${e}`)){if(E=t.slice(`${x}${e}`.length),!E||""===E.trim())return null;b={...b,value:E}}}}else"JSXExpressionContainer"===s.value?.type&&"JSXEmptyExpression"!==s.value.expression.type&&(b=s.value.expression);if(!b)return null}return o||!E||m.trim()?!o&&m.trim()&&(J=m):J=E,{keyExpression:b,serializedChildren:m,ns:x,defaultValue:J,hasCount:u,isOrdinal:v,contextExpression:g,optionsNode:f,explicitDefault:void 0!==X||(e=>{if(!e||!Array.isArray(e.properties))return!1;for(const t of e.properties)if(t&&"KeyValueProperty"===t.type&&t.key){const e="Identifier"===t.key.type&&t.key.value||"StringLiteral"===t.key.type&&t.key.value;if("string"==typeof e&&e.startsWith("defaultValue"))return!0}return!1})(f)}};
|
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: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,p=".tsx"===i;let
|
|
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,p=".tsx"===i,f=".jsx"===i;let g;try{g=await r.parse(o,{syntax:a?"typescript":"ecmascript",tsx:p,jsx:f,decorators:!0})}catch(t){if(".ts"!==i||p){const e=this.wrapError(t);this.emit("error",e);continue}try{g=await r.parse(o,{syntax:"typescript",tsx:!0,decorators:!0}),this.emit("progress",{message:`Parsed ${e} using TSX fallback`})}catch(e){const t=this.wrapError(e);this.emit("error",t);continue}}const m=u(g,o,s);m.length>0&&(c+=m.length,l.set(e,m))}const p={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",p),p}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||[],p=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),f=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?f({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=f(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&&!p.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 h=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,h);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),h=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.23.
|
|
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.23.6"),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 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 f}from"../../utils/validation.js";import{extractKeysFromComments as p}from"../parsers/comment-parser.js";import{ConsoleLogger as u}from"../../utils/logger.js";import{serializeTranslationFile as y}from"../../utils/file-utils.js";import{shouldShowFunnel as d,recordFunnelShown as g}from"../../utils/funnel-msg-tracker.js";async function w(e,{isWatchMode:n=!1,isDryRun:i=!1,syncPrimaryWithDefaults:f=!1}={},p=new u){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,p);x.text=`Found ${t.size} unique keys. Updating translation files...`;const m=await l(t,n,e,{syncPrimaryWithDefaults:f});let u=!1;for(const t of m)if(t.updated&&(u=!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),p.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!")),u&&await async function(){if(!await d("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")}`),g("extract")}(),u}catch(t){throw x.fail(a.red("Extraction failed.")),t}}async function x(t,a,o,r,s,c=new u){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,y=".tsx"===m;let
|
|
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 f}from"../../utils/validation.js";import{extractKeysFromComments as p}from"../parsers/comment-parser.js";import{ConsoleLogger as u}from"../../utils/logger.js";import{serializeTranslationFile as y}from"../../utils/file-utils.js";import{shouldShowFunnel as d,recordFunnelShown as g}from"../../utils/funnel-msg-tracker.js";async function w(e,{isWatchMode:n=!1,isDryRun:i=!1,syncPrimaryWithDefaults:f=!1}={},p=new u){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,p);x.text=`Found ${t.size} unique keys. Updating translation files...`;const m=await l(t,n,e,{syncPrimaryWithDefaults:f});let u=!1;for(const t of m)if(t.updated&&(u=!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),p.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!")),u&&await async function(){if(!await d("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")}`),g("extract")}(),u}catch(t){throw x.fail(a.red("Extraction failed.")),t}}async function x(t,a,o,r,s,c=new u){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,y=".tsx"===m,d=".jsx"===m;let g;try{g=await e(l,{syntax:u?"typescript":"ecmascript",tsx:y,jsx:d,decorators:!0,dynamicImport:!0,comments:!0})}catch(a){if(".ts"!==m||y)throw new f("Failed to process file",t,a);try{g=await e(l,{syntax:"typescript",tsx:!0,decorators:!0,dynamicImport:!0,comments:!0}),c.info?.(`Parsed ${t} using TSX fallback`)}catch(a){throw new f("Failed to process file",t,a)}}r.getVarFromScope=o.getVarFromScope.bind(o),o.setCurrentFile(t,l),o.visit(g),p(l,r,s,o.getVarFromScope.bind(o))}catch(a){throw new f("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 t,basename as e,extname as n}from"node:path";import{glob as r}from"glob";import{getNestedKeys as s,getNestedValue as o,setNestedValue as i}from"../../utils/nested-object.js";import{getOutputPath as a,loadTranslationFile as l}from"../../utils/file-utils.js";import{resolveDefaultValue as c}from"../../utils/default-value.js";function f(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e,n,r){if(0===e.size)return!1;let s=t;const o=["zero","one","two","few","many","other"];for(const t of o){if(s.endsWith(`${n}${t}`)){s=s.slice(0,-(n.length+t.length));break}if(s.endsWith(`${n}ordinal${n}${t}`)){s=s.slice(0,-(n.length+7+n.length+t.length));break}}const i=s.split(r);if(i.length>1)for(let t=1;t<i.length;t++){const n=i.slice(0,-t).join(r);if(e.has(n))return!0}return!!e.has(s)}function p(t,e){if("object"!=typeof t||null===t||Array.isArray(t))return t;const
|
|
1
|
+
import{resolve as t,basename as e,extname as n}from"node:path";import{glob as r}from"glob";import{getNestedKeys as s,getNestedValue as o,setNestedValue as i}from"../../utils/nested-object.js";import{getOutputPath as a,loadTranslationFile as l}from"../../utils/file-utils.js";import{resolveDefaultValue as c}from"../../utils/default-value.js";function f(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e,n,r){if(0===e.size)return!1;let s=t;const o=["zero","one","two","few","many","other"];for(const t of o){if(s.endsWith(`${n}${t}`)){s=s.slice(0,-(n.length+t.length));break}if(s.endsWith(`${n}ordinal${n}${t}`)){s=s.slice(0,-(n.length+7+n.length+t.length));break}}const i=s.split(r);if(i.length>1)for(let t=1;t<i.length;t++){const n=i.slice(0,-t).join(r);if(e.has(n))return!0}return!!e.has(s)}function p(t,e,n){if("object"!=typeof t||null===t||Array.isArray(t))return t;const r={},s=e?.extract?.pluralSeparator??"_",o=["zero","one","two","few","many","other"],i=o.map(t=>`ordinal${s}${t}`),a=Object.keys(t).sort((t,e)=>{const r=t=>{for(const e of i)if(t.endsWith(`${s}${e}`)){return{base:t.slice(0,-(s.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of o)if(t.endsWith(`${s}${e}`)){return{base:t.slice(0,-(s.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},a=r(t),l=r(e);if(a.isPlural&&l.isPlural){const t=n?n(a.base,l.base):a.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(a.isOrdinal!==l.isOrdinal)return a.isOrdinal?1:-1;const e=a.isOrdinal?i:o,r=e.indexOf(a.form),s=e.indexOf(l.form);return-1!==r&&-1!==s?r-s:a.form.localeCompare(l.form)}if(n)return n(t,e);const c=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===c?t.localeCompare(e,void 0,{sensitivity:"case"}):c});for(const s of a)r[s]=p(t[s],e,n);return r}function d(t,e,n,r,a,l=[],d=new Set,g=!1){const{keySeparator:h=".",sort:y=!0,removeUnusedKeys:m=!0,primaryLanguage:x,defaultValue:S="",pluralSeparator:$="_",contextSeparator:O="_",preserveContextVariants:w=!1}=n.extract,b=new Set;if(w)for(const{keyAcceptingContext:e}of t)e&&b.add(e);const v=new Set;let k=[],j=[];try{const t=new Intl.PluralRules(r,{type:"cardinal"}),e=new Intl.PluralRules(r,{type:"ordinal"});k=t.resolvedOptions().pluralCategories,j=e.resolvedOptions().pluralCategories,k.forEach(t=>v.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>v.add(`ordinal_${t}`))}catch(t){const e=x||"en",n=new Intl.PluralRules(e,{type:"cardinal"}),r=new Intl.PluralRules(e,{type:"ordinal"});k=n.resolvedOptions().pluralCategories,j=r.resolvedOptions().pluralCategories,k.forEach(t=>v.add(t)),r.resolvedOptions().pluralCategories.forEach(t=>v.add(`ordinal_${t}`))}const C=n.extract.preservePatterns||[],P="string"==typeof n.extract.nsSeparator?n.extract.nsSeparator:":",N=t=>{if(l.some(e=>e.test(t)))return!0;for(const e of C)if("string"==typeof e){if(e.endsWith(`${P}*`)){const t=e.slice(0,-(P.length+1));if("*"===t||a&&t===a)return!0}if(e.includes(P)&&a){const[n,r]=e.split(P);if(n===a){if(f(r).test(t))return!0}}}return!1},W=t.filter(({key:t,hasCount:e,isOrdinal:n})=>{if((t=>{if(l.some(e=>e.test(t)))return!0;for(const t of C)if("string"==typeof t&&t.endsWith(`${P}*`)){const e=t.slice(0,-(P.length+1));if("*"===e||a&&e===a)return!0}return!1})(t))return!1;if(!e)return!0;const r=t.split($);if(e&&1===r.length)return!0;if(1===k.length&&"other"===k[0]&&1===r.length)return!0;if(n&&r.includes("ordinal")){const t=r[r.length-1];return v.has(`ordinal_${t}`)}if(e){const t=r[r.length-1];return v.has(t)}return!0}),_=new Set;for(const t of W)if(t.isExpandedPlural){const e=String(t.key).split($);e.length>=3&&"ordinal"===e[e.length-2]?_.add(e.slice(0,-2).join($)):_.add(e.slice(0,-1).join($))}let A=m?{}:JSON.parse(JSON.stringify(e));const E=s(e,h??".");for(const t of E){const n=N(t),r=!n&&u(t,b,$,O);if(n||w&&r){const n=o(e,t,h??".");i(A,t,n,h??".")}}if(m){const t=s(e,h??".");for(const n of t){const t=n.split($);if("zero"===t[t.length-1]){const r=t.slice(0,-1).join($);if(W.some(({key:t})=>t.split($).slice(0,-1).join($)===r)){const t=o(e,n,h??".");i(A,n,t,h??".")}}}}for(const{key:t,defaultValue:s,explicitDefault:l,hasCount:f,isExpandedPlural:u,isOrdinal:p}of W){if(f&&!u){const e=String(t).split($);let n=t;if(e.length>=3&&"ordinal"===e[e.length-2]?n=e.slice(0,-2).join($):e.length>=2&&(n=e.slice(0,-1).join($)),_.has(n))continue}if(f&&!u){if(1===String(t).split($).length&&r!==x){const l=t;if(_.has(l));else{const t=p?j:k;for(const f of t){const t=p?`${l}${$}ordinal${$}${f}`:`${l}${$}${f}`,u=o(e,t,h??".");if(void 0===u){let e;e="string"==typeof s?s:c(S,String(l),a||n?.extract?.defaultNS||"translation",r,s),i(A,t,e,h??".")}else i(A,t,u,h??".")}}continue}}const y=o(e,t,h??"."),m=!1===h||!W.some(e=>e.key!==t&&e.key.startsWith(`${t}${h}`)),w="object"==typeof y&&null!==y&&(d.has(t)||!s||s===t),b="object"==typeof y&&null!==y&&m&&!d.has(t)&&!w;if(w){i(A,t,y,h??".");continue}let v;if(void 0===y||b)if(r===x)if(g){const e=s&&(s===t||s.includes(P)||t!==s&&(t.startsWith(s+$)||t.startsWith(s+O)));v=s&&!e?s:c(S,t,a||n?.extract?.defaultNS||"translation",r,s)}else v=s||t;else v=c(S,t,a||n?.extract?.defaultNS||"translation",r,s);else if(r===x&&g){const e=s&&(s===t||s.includes(P)||t!==s&&(t.startsWith(s+$)||t.startsWith(s+O)));v=(t.includes($)||t.includes(O))&&!l?y:s&&!e?s:y}else v=y;i(A,t,v,h??".")}if(!0===y)return p(A,n);if("function"==typeof y){const e={},r=Object.keys(A),s=new Map;for(const e of t)if(s.set(String(e.key),e),h){const t=String(e.key).split(h)[0];s.has(t)||s.set(t,e)}const o=(t,e)=>{const n=s.get(t),r=s.get(e);if(n&&r)return y(n,r);return y({key:t},{key:e})};r.sort(o);for(const t of r)e[t]=p(A[t],n,o);A=e}return A}async function g(s,o,i,{syncPrimaryWithDefaults:c=!1}={}){i.extract.primaryLanguage||=i.locales[0]||"en",i.extract.secondaryLanguages||=i.locales.filter(t=>t!==i?.extract?.primaryLanguage);const u=[...i.extract.preservePatterns||[]],p=i.extract.indentation??2;for(const t of o)u.push(`${t}.*`);const g=u.map(f),h="__no_namespace__",y=new Map;for(const t of s.values()){const e=t.nsIsImplicit&&!1===i.extract.defaultNS?h:String(t.ns??i.extract.defaultNS??"translation");y.has(e)||y.set(e,[]),y.get(e).push(t)}const m=[],x=Array.isArray(i.extract.ignore)?i.extract.ignore:i.extract.ignore?[i.extract.ignore]:[];for(const s of i.locales){if(i.extract.mergeNamespaces||"string"==typeof i.extract.output&&!i.extract.output.includes("{{namespace}}")){const e={},n=a(i.extract.output,s),r=t(process.cwd(),n),f=await l(r)||{},u=Object.keys(f),x=!1!==i.extract.defaultNS&&u.some(t=>{const e=f[t];return"object"==typeof e&&null!==e&&!Array.isArray(e)})?new Set([...y.keys(),...u]):new Set([...y.keys(),h]);for(const t of x){const n=y.get(t)||[];if(t===h){const t=d(n,f,i,s,void 0,g,o,c);Object.assign(e,t)}else{const r=f[t]||{};e[t]=d(n,r,i,s,t,g,o,c)}}const S=JSON.stringify(f,null,p),$=JSON.stringify(e,null,p);m.push({path:r,updated:$!==S,newTranslations:e,existingTranslations:f})}else{const f=new Set(y.keys()),u=a(i.extract.output,s,"*").replace(/\\/g,"/"),h=await r(u,{ignore:x});for(const t of h)f.add(e(t,n(t)));for(const e of f){const n=y.get(e)||[],r=a(i.extract.output,s,e),f=t(process.cwd(),r),u=await l(f)||{},h=d(n,u,i,s,e,g,o,c),x=JSON.stringify(u,null,p),S=JSON.stringify(h,null,p);m.push({path:f,updated:S!==x,newTranslations:h,existingTranslations:u})}}}return m}export{g as getTranslations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getObjectPropValueExpression as e,getObjectPropValue as t,isSimpleTemplateLiteral as n}from"./ast-utils.js";function i(e){if(e)return"StringLiteral"===e.type?e.value:"TemplateLiteral"===e.type&&n(e)?e.quasis[0].cooked:void 0}function r(e){return"StringLiteral"===e.value?.type?e.value.value:"JSXExpressionContainer"===e.value?.type?i(e.value.expression):void 0}function s(n,s){const o=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),p=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),l=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),a=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let u;l||"JSXAttribute"!==a?.type||"JSXExpressionContainer"!==a.value?.type||"ObjectExpression"!==a.value.expression.type||(u=e(a.value.expression,"count"));const y=!!l||!!u,f=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),c="JSXAttribute"===f?.type&&"JSXExpressionContainer"===f.value?.type&&"ObjectExpression"===f.value.expression.type?f.value.expression:void 0,v=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),S=!!v,d=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let g="JSXAttribute"===d?.type&&"JSXExpressionContainer"===d.value?.type?d.value.expression:"JSXAttribute"===d?.type&&"StringLiteral"===d.value?.type?d.value:void 0;const x=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let m;m="JSXAttribute"===x?.type?r(x):void 0,c&&(void 0===m&&(m=t(c,"ns")),void 0===g&&(g=e(c,"context")));const J=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),r=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function s(e,t,o=!1){if(!e||!e.length)return;let p=0,l=e.length-1;for(;p<=l&&r(e[p]);)p++;for(;l>=p&&r(e[l]);)l--;const a=p<=l?e.slice(p,l+1):[],u=a.some(e=>e&&("JSXElement"===e.type||"JSXFragment"===e.type));for(let e=0;e<a.length;e++){const p=a[e];if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){if(o&&!u&&p.expression){const e=p.expression.type;if("ObjectExpression"===e){const e=p.expression.properties&&p.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}const t=i(p.expression);if(void 0!==t){if(!(/^\s*$/.test(t)&&!t.includes("\n")))continue}else if("Identifier"===e||"MemberExpression"===e||"CallExpression"===e)continue}const n=i(p.expression);if(void 0!==n){const i=/^\s*$/.test(n)&&!n.includes("\n"),s=a[e-1],o=a[e+1];if(i){const n=a[e+2];if(o&&"JSXText"===o.type&&r(o)&&n&&("JSXElement"===n.type||"JSXFragment"===n.type)){const t=a[e-1],n=a[e-2];if(!t||"JSXText"!==t.type&&n&&"JSXExpressionContainer"===n.type)continue}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&r(o))continue;const i=!o||"JSXText"===o.type&&!r(o);if(s&&"JSXText"===s.type&&i){const e=t[t.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+p.expression.value;continue}}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&r(o))continue}}t.push(p);continue}if("JSXElement"===p.type){const e=p.opening&&p.opening.name&&"Identifier"===p.opening.name.type?p.opening.name.value:void 0;if(e&&n.has(e)){!(!p.opening||!p.opening.selfClosing)&&t.push(p),s(p.children||[],t,!1)}else t.push(p),s(p.children||[],t,!0);continue}"JSXFragment"!==p.type||s(p.children||[],t,o)}else{if(o&&!u)continue;if(o&&r(p))continue;if(r(p)){const n=a[e-1],i=a[e+1];if(n&&("JSXElement"===n.type||"JSXFragment"===n.type)&&i&&("JSXElement"===i.type||"JSXFragment"===i.type))continue;const r=t[t.length-1],s=a[e-1];if(r){if(s&&"JSXExpressionContainer"===s.type)continue;if("JSXText"===r.type&&s&&"JSXText"===s.type){r.value=String(r.value)+p.value;continue}}}if(o&&u&&0===e)continue;t.push(p)}}}const o=[];s(e,o,!1);const p=e=>String(e).replace(/^\s*\n\s*/g,"").replace(/\s*\n\s*$/g,"");function l(e,t){if(!e||0===e.length)return"";let s=""
|
|
1
|
+
import{getObjectPropValueExpression as e,getObjectPropValue as t,isSimpleTemplateLiteral as n}from"./ast-utils.js";function i(e){if(e)return"StringLiteral"===e.type?e.value:"TemplateLiteral"===e.type&&n(e)?e.quasis[0].cooked:void 0}function r(e){return"StringLiteral"===e.value?.type?e.value.value:"JSXExpressionContainer"===e.value?.type?i(e.value.expression):void 0}function s(n,s){const o=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),p=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),l=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),a=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let u;l||"JSXAttribute"!==a?.type||"JSXExpressionContainer"!==a.value?.type||"ObjectExpression"!==a.value.expression.type||(u=e(a.value.expression,"count"));const y=!!l||!!u,f=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),c="JSXAttribute"===f?.type&&"JSXExpressionContainer"===f.value?.type&&"ObjectExpression"===f.value.expression.type?f.value.expression:void 0,v=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),S=!!v,d=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let g="JSXAttribute"===d?.type&&"JSXExpressionContainer"===d.value?.type?d.value.expression:"JSXAttribute"===d?.type&&"StringLiteral"===d.value?.type?d.value:void 0;const x=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let m;m="JSXAttribute"===x?.type?r(x):void 0,c&&(void 0===m&&(m=t(c,"ns")),void 0===g&&(g=e(c,"context")));const J=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),r=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function s(e,t,o=!1){if(!e||!e.length)return;let p=0,l=e.length-1;for(;p<=l&&r(e[p]);)p++;for(;l>=p&&r(e[l]);)l--;const a=p<=l?e.slice(p,l+1):[],u=a.some(e=>e&&("JSXElement"===e.type||"JSXFragment"===e.type));for(let e=0;e<a.length;e++){const p=a[e];if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){if(o&&!u&&p.expression){const e=p.expression.type;if("ObjectExpression"===e){const e=p.expression.properties&&p.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}const t=i(p.expression);if(void 0!==t){if(!(/^\s*$/.test(t)&&!t.includes("\n")))continue}else if("Identifier"===e||"MemberExpression"===e||"CallExpression"===e)continue}const n=i(p.expression);if(void 0!==n){const i=/^\s*$/.test(n)&&!n.includes("\n"),s=a[e-1],o=a[e+1];if(i){const n=a[e+2];if(o&&"JSXText"===o.type&&r(o)&&n&&("JSXElement"===n.type||"JSXFragment"===n.type)){const t=a[e-1],n=a[e-2];if(!t||"JSXText"!==t.type&&n&&"JSXExpressionContainer"===n.type)continue}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&r(o))continue;const i=!o||"JSXText"===o.type&&!r(o);if(s&&"JSXText"===s.type&&i){const e=t[t.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+p.expression.value;continue}}if(s&&("JSXElement"===s.type||"JSXFragment"===s.type)&&o&&"JSXText"===o.type&&r(o))continue}}t.push(p);continue}if("JSXElement"===p.type){const e=p.opening&&p.opening.name&&"Identifier"===p.opening.name.type?p.opening.name.value:void 0;if(e&&n.has(e)){!(!p.opening||!p.opening.selfClosing)&&t.push(p),s(p.children||[],t,!1)}else t.push(p),s(p.children||[],t,!0);continue}"JSXFragment"!==p.type||s(p.children||[],t,o)}else{if(o&&!u)continue;if(o&&r(p))continue;if(r(p)){const n=a[e-1],i=a[e+1];if(n&&("JSXElement"===n.type||"JSXFragment"===n.type)&&i&&("JSXElement"===i.type||"JSXFragment"===i.type))continue;const r=t[t.length-1],s=a[e-1];if(r){if(s&&"JSXExpressionContainer"===s.type)continue;if("JSXText"===r.type&&s&&"JSXText"===s.type){r.value=String(r.value)+p.value;continue}}}if(o&&u&&0===e)continue;t.push(p)}}}const o=[];s(e,o,!1);const p=e=>String(e).replace(/^\s*\n\s*/g,"").replace(/\s*\n\s*$/g,"");function l(e,t){if(!e||0===e.length)return"";let s="";for(let a=0;a<e.length;a++){const u=e[a];if(u)if("JSXText"!==u.type){if("JSXExpressionContainer"===u.type){const e=u.expression;if(!e)continue;const t=i(e);if(void 0!==t)s+=t;else if("Identifier"===e.type)s+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const t=e.properties[0];t&&"KeyValueProperty"===t.type&&t.key&&"Identifier"===t.key.type?s+=`{{${t.key.value}}}`:t&&"Identifier"===t.type?s+=`{{${t.value}}}`:s+="{{value}}"}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?s+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type?s+=`{{${e.callee.value}}}`:s+="{{value}}";continue}if("JSXElement"===u.type){let i;if(u.opening&&u.opening.name&&"Identifier"===u.opening.name.type&&(i=u.opening.name.value),i&&n.has(i)){const n=l(u.children||[],t),r=!(!u.opening||!u.opening.selfClosing),o=""!==String(n).trim();if(r||!o){const t=e[a-1];t&&"JSXText"===t.type&&/\n\s*$/.test(t.value)&&(s=s.replace(/\s+$/,"")),s+=`<${i} />`}else s+=`<${i}>${n}</${i}>`}else{const e=u.children||[];if(e.some(e=>e&&("JSXText"===e.type||"JSXExpressionContainer"===e.type)&&-1!==o.indexOf(e))){const t=o.indexOf(u),n=l(e,void 0);s+=`<${t}>${p(n)}</${t}>`}else{const i=new Map;let r=0;for(const t of e)if(t&&"JSXElement"===t.type){const e=t.opening&&t.opening.name&&"Identifier"===t.opening.name.type?t.opening.name.value:void 0;if(e&&n.has(e)){!(!t.opening||!t.opening.selfClosing)&&i.set(t,r++)}else i.set(t,r++)}const a=t&&t.has(u)?t.get(u):o.indexOf(u),y=l(e,i.size?i:void 0);s+=`<${a}>${p(y)}</${a}>`}}continue}"JSXFragment"!==u.type||(s+=l(u.children||[]))}else{if(r(u))continue;s+=u.value}}return s}const a=l(e),u=String(a).replace(/<br \/>\s*\n\s*/g,"<br />").replace(/\s+/g," ");return u.replace(/\s+\./g,".").trim()}(n.children,s);let X;const b="JSXAttribute"===p?.type?r(p):void 0;if(void 0!==b)X=b;else{const e=s.extract.defaultValue;X="string"==typeof e?e:""}let E,h;if("JSXAttribute"===o?.type){if("StringLiteral"===o.value?.type){if(E=o.value,h=E.value,!h||""===h.trim())return null;if(m&&"StringLiteral"===E.type){const e=s.extract.nsSeparator??":",t=E.value;if(e&&t.startsWith(`${m}${e}`)){if(h=t.slice(`${m}${e}`.length),!h||""===h.trim())return null;E={...E,value:h}}}}else"JSXExpressionContainer"===o.value?.type&&"JSXEmptyExpression"!==o.value.expression.type&&(E=o.value.expression);if(!E)return null}p||!h||J.trim()?!p&&J.trim()&&(X=J):X=h;return{keyExpression:E,serializedChildren:J,ns:m,defaultValue:X,hasCount:y,isOrdinal:S,contextExpression:g,optionsNode:c,explicitDefault:void 0!==b||(e=>{if(!e||!Array.isArray(e.properties))return!1;for(const t of e.properties)if(t&&"KeyValueProperty"===t.type&&t.key){const e="Identifier"===t.key.type&&t.key.value||"StringLiteral"===t.key.type&&t.key.value;if("string"==typeof e&&e.startsWith("defaultValue"))return!0}return!1})(c)}}export{s as extractFromTransComponent};
|
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{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;let
|
|
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=".jsx"===i;let m;try{m=await r(o,{syntax:a?"typescript":"ecmascript",tsx:u,jsx:p,decorators:!0})}catch(t){if(".ts"!==i||u){const e=this.wrapError(t);this.emit("error",e);continue}try{m=await r(o,{syntax:"typescript",tsx:!0,decorators:!0}),this.emit("progress",{message:`Parsed ${e} using TSX fallback`})}catch(e){const t=this.wrapError(e);this.emit("error",t);continue}}const g=f(m,o,s);g.length>0&&(c+=g.length,l.set(e,g))}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 h=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,h);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),h=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.23.
|
|
25
|
+
.version('1.23.6')
|
|
26
26
|
|
|
27
27
|
// new: global config override option
|
|
28
28
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
|
|
@@ -158,12 +158,14 @@ export async function processFile (
|
|
|
158
158
|
const fileExt = extname(file).toLowerCase()
|
|
159
159
|
const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
|
|
160
160
|
const isTSX = fileExt === '.tsx'
|
|
161
|
+
const isJSX = fileExt === '.jsx'
|
|
161
162
|
|
|
162
163
|
let ast: any
|
|
163
164
|
try {
|
|
164
165
|
ast = await parse(code, {
|
|
165
166
|
syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
|
|
166
167
|
tsx: isTSX,
|
|
168
|
+
jsx: isJSX,
|
|
167
169
|
decorators: true,
|
|
168
170
|
dynamicImport: true,
|
|
169
171
|
comments: true,
|
|
@@ -83,7 +83,7 @@ function isContextVariantOfAcceptingKey (
|
|
|
83
83
|
/**
|
|
84
84
|
* Recursively sorts the keys of an object.
|
|
85
85
|
*/
|
|
86
|
-
function sortObject (obj: any, config?: I18nextToolkitConfig): any {
|
|
86
|
+
function sortObject (obj: any, config?: I18nextToolkitConfig, customSort?: (a: string, b: string) => number): any {
|
|
87
87
|
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
|
|
88
88
|
return obj
|
|
89
89
|
}
|
|
@@ -120,8 +120,10 @@ function sortObject (obj: any, config?: I18nextToolkitConfig): any {
|
|
|
120
120
|
|
|
121
121
|
// If both are plural forms
|
|
122
122
|
if (aInfo.isPlural && bInfo.isPlural) {
|
|
123
|
-
// First compare by base key
|
|
124
|
-
const baseComparison =
|
|
123
|
+
// First compare by base key
|
|
124
|
+
const baseComparison = customSort
|
|
125
|
+
? customSort(aInfo.base, bInfo.base)
|
|
126
|
+
: aInfo.base.localeCompare(bInfo.base, undefined, { sensitivity: 'base' })
|
|
125
127
|
if (baseComparison !== 0) {
|
|
126
128
|
return baseComparison
|
|
127
129
|
}
|
|
@@ -145,8 +147,12 @@ function sortObject (obj: any, config?: I18nextToolkitConfig): any {
|
|
|
145
147
|
return aInfo.form.localeCompare(bInfo.form)
|
|
146
148
|
}
|
|
147
149
|
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
+
// Use custom sort if provided, otherwise default sorting
|
|
151
|
+
if (customSort) {
|
|
152
|
+
return customSort(a, b)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Default: case-insensitive, then by case
|
|
150
156
|
const caseInsensitiveComparison = a.localeCompare(b, undefined, { sensitivity: 'base' })
|
|
151
157
|
if (caseInsensitiveComparison === 0) {
|
|
152
158
|
return a.localeCompare(b, undefined, { sensitivity: 'case' })
|
|
@@ -155,7 +161,7 @@ function sortObject (obj: any, config?: I18nextToolkitConfig): any {
|
|
|
155
161
|
})
|
|
156
162
|
|
|
157
163
|
for (const key of keys) {
|
|
158
|
-
sortedObj[key] = sortObject(obj[key], config)
|
|
164
|
+
sortedObj[key] = sortObject(obj[key], config, customSort)
|
|
159
165
|
}
|
|
160
166
|
|
|
161
167
|
return sortedObj
|
|
@@ -548,32 +554,46 @@ function buildNewTranslationsForNs (
|
|
|
548
554
|
const sortedObject: Record<string, any> = {}
|
|
549
555
|
const topLevelKeys = Object.keys(newTranslations)
|
|
550
556
|
|
|
551
|
-
// Create a map
|
|
552
|
-
// This is needed for the custom sort function.
|
|
557
|
+
// Create a map from key string to ExtractedKey for lookup
|
|
553
558
|
const keyMap = new Map<string, ExtractedKey>()
|
|
554
|
-
for (const
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
559
|
+
for (const extractedKey of nsKeys) {
|
|
560
|
+
// Store the full key path
|
|
561
|
+
keyMap.set(String(extractedKey.key), extractedKey)
|
|
562
|
+
|
|
563
|
+
// For nested keys, also store the top-level part
|
|
564
|
+
if (keySeparator) {
|
|
565
|
+
const topLevelKey = String(extractedKey.key).split(keySeparator)[0]
|
|
566
|
+
if (!keyMap.has(topLevelKey)) {
|
|
567
|
+
keyMap.set(topLevelKey, extractedKey)
|
|
568
|
+
}
|
|
558
569
|
}
|
|
559
570
|
}
|
|
560
571
|
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
572
|
+
// Create a string comparator that applies the same logic as the custom sort function
|
|
573
|
+
// by extracting the actual comparison behavior
|
|
574
|
+
const stringSort = (a: string, b: string) => {
|
|
575
|
+
// Try to find ExtractedKey objects to use the custom comparator
|
|
576
|
+
const keyA = keyMap.get(a)
|
|
577
|
+
const keyB = keyMap.get(b)
|
|
578
|
+
|
|
579
|
+
if (keyA && keyB) {
|
|
580
|
+
return sort(keyA, keyB)
|
|
569
581
|
}
|
|
570
|
-
// Fallback to a case-insensitive alphabetical sort.
|
|
571
|
-
return a.localeCompare(b, undefined, { sensitivity: 'base' })
|
|
572
|
-
})
|
|
573
582
|
|
|
574
|
-
|
|
583
|
+
// If we don't have ExtractedKey objects, we need to apply the same sorting logic
|
|
584
|
+
// Create mock ExtractedKey objects with just the key property
|
|
585
|
+
const mockKeyA = { key: a } as ExtractedKey
|
|
586
|
+
const mockKeyB = { key: b } as ExtractedKey
|
|
587
|
+
|
|
588
|
+
return sort(mockKeyA, mockKeyB)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// Sort top-level keys
|
|
592
|
+
topLevelKeys.sort(stringSort)
|
|
593
|
+
|
|
594
|
+
// Pass the same string comparator to sortObject for nested keys
|
|
575
595
|
for (const key of topLevelKeys) {
|
|
576
|
-
sortedObject[key] = sortObject(newTranslations[key], config)
|
|
596
|
+
sortedObject[key] = sortObject(newTranslations[key], config, stringSort)
|
|
577
597
|
}
|
|
578
598
|
newTranslations = sortedObject
|
|
579
599
|
}
|
|
@@ -551,7 +551,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
551
551
|
function visitNodes (nodes: any[], localIndexMap?: Map<any, number>): string {
|
|
552
552
|
if (!nodes || nodes.length === 0) return ''
|
|
553
553
|
let out = ''
|
|
554
|
-
let lastWasSelfClosing = false
|
|
555
554
|
|
|
556
555
|
for (let i = 0; i < nodes.length; i++) {
|
|
557
556
|
const node = nodes[i]
|
|
@@ -559,12 +558,7 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
559
558
|
|
|
560
559
|
if (node.type === 'JSXText') {
|
|
561
560
|
if (isFormattingWhitespace(node)) continue
|
|
562
|
-
|
|
563
|
-
out += node.value.replace(/^\s+/, '')
|
|
564
|
-
lastWasSelfClosing = false
|
|
565
|
-
} else {
|
|
566
|
-
out += node.value
|
|
567
|
-
}
|
|
561
|
+
out += node.value
|
|
568
562
|
continue
|
|
569
563
|
}
|
|
570
564
|
|
|
@@ -593,7 +587,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
593
587
|
} else {
|
|
594
588
|
out += '{{value}}'
|
|
595
589
|
}
|
|
596
|
-
lastWasSelfClosing = false
|
|
597
590
|
continue
|
|
598
591
|
}
|
|
599
592
|
|
|
@@ -608,6 +601,7 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
608
601
|
// consider element self-closing for rendering when AST marks it so or it has no meaningful children
|
|
609
602
|
const isAstSelfClosing = !!(node.opening && (node.opening as any).selfClosing)
|
|
610
603
|
const hasMeaningfulChildren = String(inner).trim() !== ''
|
|
604
|
+
|
|
611
605
|
if (isAstSelfClosing || !hasMeaningfulChildren) {
|
|
612
606
|
// If the previous original sibling is a JSXText that ends with a
|
|
613
607
|
// newline (the tag was placed on its own indented line), trim any
|
|
@@ -618,10 +612,8 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
618
612
|
out = out.replace(/\s+$/, '')
|
|
619
613
|
}
|
|
620
614
|
out += `<${tag} />`
|
|
621
|
-
lastWasSelfClosing = true
|
|
622
615
|
} else {
|
|
623
616
|
out += `<${tag}>${inner}</${tag}>`
|
|
624
|
-
lastWasSelfClosing = false
|
|
625
617
|
}
|
|
626
618
|
} else {
|
|
627
619
|
// Decide whether to use local (restarted) indexes for this element's
|
|
@@ -641,7 +633,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
641
633
|
const idx = globalSlots.indexOf(node)
|
|
642
634
|
const inner = visitNodes(children, undefined)
|
|
643
635
|
out += `<${idx}>${trimFormattingEdges(inner)}</${idx}>`
|
|
644
|
-
lastWasSelfClosing = false
|
|
645
636
|
} else {
|
|
646
637
|
const childrenLocalMap = new Map<any, number>()
|
|
647
638
|
let localIdxCounter = 0
|
|
@@ -665,7 +656,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
665
656
|
const idx = localIndexMap && localIndexMap.has(node) ? localIndexMap.get(node) : globalSlots.indexOf(node)
|
|
666
657
|
const inner = visitNodes(children, childrenLocalMap.size ? childrenLocalMap : undefined)
|
|
667
658
|
out += `<${idx}>${trimFormattingEdges(inner)}</${idx}>`
|
|
668
|
-
lastWasSelfClosing = false
|
|
669
659
|
}
|
|
670
660
|
}
|
|
671
661
|
continue
|
|
@@ -673,7 +663,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
673
663
|
|
|
674
664
|
if (node.type === 'JSXFragment') {
|
|
675
665
|
out += visitNodes(node.children || [])
|
|
676
|
-
lastWasSelfClosing = false
|
|
677
666
|
continue
|
|
678
667
|
}
|
|
679
668
|
|
|
@@ -684,5 +673,16 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
|
|
|
684
673
|
}
|
|
685
674
|
|
|
686
675
|
const result = visitNodes(children)
|
|
687
|
-
|
|
676
|
+
|
|
677
|
+
// Final cleanup in correct order:
|
|
678
|
+
// 1. First, handle <br /> followed by whitespace+newline (boundary formatting)
|
|
679
|
+
const afterBrCleanup = String(result).replace(/<br \/>\s*\n\s*/g, '<br />')
|
|
680
|
+
|
|
681
|
+
// 2. Then normalize remaining whitespace sequences to single space
|
|
682
|
+
const normalized = afterBrCleanup.replace(/\s+/g, ' ')
|
|
683
|
+
|
|
684
|
+
// 3. Remove space before period at end
|
|
685
|
+
const finalResult = normalized.replace(/\s+\./g, '.')
|
|
686
|
+
|
|
687
|
+
return finalResult.trim()
|
|
688
688
|
}
|
package/src/linter.ts
CHANGED
|
@@ -63,12 +63,14 @@ export class Linter extends EventEmitter<LinterEventMap> {
|
|
|
63
63
|
const fileExt = extname(file).toLowerCase()
|
|
64
64
|
const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
|
|
65
65
|
const isTSX = fileExt === '.tsx'
|
|
66
|
+
const isJSX = fileExt === '.jsx'
|
|
66
67
|
|
|
67
68
|
let ast: any
|
|
68
69
|
try {
|
|
69
70
|
ast = await parse(code, {
|
|
70
71
|
syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
|
|
71
72
|
tsx: isTSX,
|
|
73
|
+
jsx: isJSX,
|
|
72
74
|
decorators: true
|
|
73
75
|
})
|
|
74
76
|
} catch (err) {
|
|
@@ -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,CAsEf;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;AA2lBnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CAgH9B"}
|
package/types/linter.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;;;;;;;
|
|
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;;;;;;;CA2EV;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"}
|