i18next-cli 1.10.4 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,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.11.1](https://github.com/i18next/i18next-cli/compare/v1.11.0...v1.11.1) - 2025-10-12
9
+
10
+ - **Syncer:** Enhanced fix for TypeScript resource file handling in `sync` command. Building on the initial fix in v1.10.4 that resolved sync command failures with `outputFormat: 'ts'`, this release improves the TypeScript file parsing reliability and error handling when loading translation files with complex export patterns and TypeScript-specific syntax. [#59](https://github.com/i18next/i18next-cli/issues/59)
11
+
12
+ ## [1.11.0](https://github.com/i18next/i18next-cli/compare/v1.10.4...v1.11.0) - 2025-10-11
13
+
14
+ - **Extractor:** Introduced `--sync-primary` CLI option to automatically synchronize primary language values with default values from code. When enabled, the extractor updates existing primary language translations to match the default values specified in your source code (e.g., `t('key', 'New default')` will update the primary language JSON), while preserving secondary language translations and keys without explicit defaults. This enables a streamlined development workflow where developers can focus on editing translation defaults directly in code without manually managing JSON files. Perfect for rapid prototyping and watch mode development. [#60](https://github.com/i18next/i18next-cli/issues/60)
15
+
8
16
  ## [1.10.4](https://github.com/i18next/i18next-cli/compare/v1.10.3...v1.10.4) - 2025-10-10
9
17
 
10
18
  - **Syncer:** Fixed `sync` command failure when using TypeScript resource files with `outputFormat: 'ts'`. The syncer now properly loads and parses TypeScript translation files (e.g., `export default { ... } as const`) using jiti with TypeScript path alias support, enabling seamless synchronization across all supported file formats. [#59](https://github.com/i18next/i18next-cli/issues/59)
package/README.md CHANGED
@@ -112,6 +112,7 @@ npx i18next-cli extract [options]
112
112
  - `--watch, -w`: Re-run automatically when files change
113
113
  - `--ci`: Exit with non-zero status if any files are updated (for CI/CD)
114
114
  - `--dry-run`: Does not change any files - useful in combination with `--ci` (for CI/CD)
115
+ - `--sync-primary`: Sync primary language values with default values from code
115
116
 
116
117
  **Examples:**
117
118
  ```bash
@@ -123,6 +124,12 @@ npx i18next-cli extract --watch
123
124
 
124
125
  # CI mode (fails if files changed)
125
126
  npx i18next-cli extract --ci
127
+
128
+ # Sync primary language with code defaults
129
+ npx i18next-cli extract --sync-primary
130
+
131
+ # Combine options for optimal development workflow
132
+ npx i18next-cli extract --sync-primary --watch
126
133
  ```
127
134
 
128
135
  ### `status [locale]`
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.10.4"),f.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").action(async e=>{const a=await i.ensureConfig(),c=async()=>{const t=await r.runExtractor(a,{isWatchMode:e.watch,isDryRun:e.dryRun});e.ci&&t&&(console.error(o.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(o.yellow("šŸ’” Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${o.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}),f.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
2
+ "use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.1"),f.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async e=>{try{const t=await i.ensureConfig(),n=await r.runExtractor(t,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});e.ci&&!n?(console.log("āœ… No files were updated."),process.exit(0)):e.ci&&n&&(console.error("āŒ Some files were updated. This should not happen in CI mode."),process.exit(1))}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),f.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
@@ -1 +1 @@
1
- "use strict";var e=require("ora"),t=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(e){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"];const{allKeys:t,objectKeys:a}=await o.findKeys(e);return s.getTranslations(t,a,e)},exports.processFile=async function(e,t,n,o,s,u=new l.ConsoleLogger){try{let i=await r.readFile(e,"utf-8");for(const a of t)try{const t=await(a.onLoad?.(i,e));void 0!==t&&(i=t)}catch(e){u.warn(`Plugin ${a.name} onLoad failed:`,e)}const l=await a.parse(i,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0});o.getVarFromScope=n.getVarFromScope.bind(n),n.visit(l),c.extractKeysFromComments(i,o,s,n.getVarFromScope.bind(n))}catch(t){throw new i.ExtractorError("Failed to process file",e,t)}},exports.runExtractor=async function(a,{isWatchMode:c=!1,isDryRun:d=!1}={},p=new l.ConsoleLogger){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage),a.extract.functions||=["t","*.t"],a.extract.transComponents||=["Trans"],i.validateExtractorConfig(a);const y=a.plugins||[],f=e("Running i18next key extractor...\n").start();try{const{allKeys:e,objectKeys:i}=await o.findKeys(a,p);f.text=`Found ${e.size} unique keys. Updating translation files...`;const c=await s.getTranslations(e,i,a);let l=!1;for(const e of c)if(e.updated&&(l=!0,!d)){const o=u.serializeTranslationFile(e.newTranslations,a.extract.outputFormat,a.extract.indentation);await r.mkdir(n.dirname(e.path),{recursive:!0}),await r.writeFile(e.path,o),p.info(t.green(`Updated: ${e.path}`))}if(y.length>0){f.text="Running post-extraction plugins...";for(const e of y)await(e.afterSync?.(c,a))}return f.succeed(t.bold("Extraction complete!")),l&&await async function(){if(!await g.shouldShowFunnel("extract"))return;return console.log(t.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: ${t.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${t.cyan("https://youtu.be/joPsZghT3wM")}`),g.recordFunnelShown("extract")}(),l}catch(e){throw f.fail(t.red("Extraction failed.")),e}};
1
+ "use strict";var e=require("ora"),t=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(e,{syncPrimaryWithDefaults:t=!1}={}){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"];const{allKeys:a,objectKeys:r}=await o.findKeys(e);return s.getTranslations(a,r,e,{syncPrimaryWithDefaults:t})},exports.processFile=async function(e,t,n,o,s,u=new l.ConsoleLogger){try{let i=await r.readFile(e,"utf-8");for(const a of t)try{const t=await(a.onLoad?.(i,e));void 0!==t&&(i=t)}catch(e){u.warn(`Plugin ${a.name} onLoad failed:`,e)}const l=await a.parse(i,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0});o.getVarFromScope=n.getVarFromScope.bind(n),n.visit(l),c.extractKeysFromComments(i,o,s,n.getVarFromScope.bind(n))}catch(t){throw new i.ExtractorError("Failed to process file",e,t)}},exports.runExtractor=async function(a,{isWatchMode:c=!1,isDryRun:y=!1,syncPrimaryWithDefaults:d=!1}={},f=new l.ConsoleLogger){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage),a.extract.functions||=["t","*.t"],a.extract.transComponents||=["Trans"],i.validateExtractorConfig(a);const p=a.plugins||[],m=e("Running i18next key extractor...\n").start();try{const{allKeys:e,objectKeys:i}=await o.findKeys(a,f);m.text=`Found ${e.size} unique keys. Updating translation files...`;const c=await s.getTranslations(e,i,a,{syncPrimaryWithDefaults:d});let l=!1;for(const e of c)if(e.updated&&(l=!0,!y)){const o=u.serializeTranslationFile(e.newTranslations,a.extract.outputFormat,a.extract.indentation);await r.mkdir(n.dirname(e.path),{recursive:!0}),await r.writeFile(e.path,o),f.info(t.green(`Updated: ${e.path}`))}if(p.length>0){m.text="Running post-extraction plugins...";for(const e of p)await(e.afterSync?.(c,a))}return m.succeed(t.bold("Extraction complete!")),l&&await async function(){if(!await g.shouldShowFunnel("extract"))return;return console.log(t.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: ${t.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${t.cyan("https://youtu.be/joPsZghT3wM")}`),g.recordFunnelShown("extract")}(),l}catch(e){throw m.fail(t.red("Extraction failed.")),e}};
@@ -1 +1 @@
1
- "use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),r=require("../../utils/file-utils.js"),n=require("../../utils/default-value.js");function o(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function a(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},r=t?.extract?.pluralSeparator??"_",n=["zero","one","two","few","many","other"],o=n.map(e=>`ordinal_${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of o)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 n)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}},a=s(e),l=s(t);if(a.isPlural&&l.isPlural){const e=a.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(a.isOrdinal!==l.isOrdinal)return a.isOrdinal?1:-1;const t=a.isOrdinal?o:n,s=t.indexOf(a.form),r=t.indexOf(l.form);return-1!==s&&-1!==r?s-r:a.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 r of l)s[r]=a(e[r],t);return s}function l(e,t,r,o,l,i,c){const{keySeparator:u=".",sort:f=!0,removeUnusedKeys:d=!0,primaryLanguage:p,defaultValue:g="",pluralSeparator:y="_"}=r.extract,h=new Set;try{const e=new Intl.PluralRules(o,{type:"cardinal"}),t=new Intl.PluralRules(o,{type:"ordinal"});e.resolvedOptions().pluralCategories.forEach(e=>h.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>h.add(`ordinal_${e}`))}catch(e){const t=new Intl.PluralRules(p||"en",{type:"cardinal"}),s=new Intl.PluralRules(p||"en",{type:"ordinal"});t.resolvedOptions().pluralCategories.forEach(e=>h.add(e)),s.resolvedOptions().pluralCategories.forEach(e=>h.add(`ordinal_${e}`))}const m=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if(i.some(t=>t.test(e)))return!1;if(!t)return!0;const r=e.split(y);if(s&&r.includes("ordinal")){const e=r[r.length-1];return h.has(`ordinal_${e}`)}if(t){const e=r[r.length-1];return h.has(e)}return!0});let O=d?{}:JSON.parse(JSON.stringify(t));const x=s.getNestedKeys(t,u??".");for(const e of x)if(i.some(t=>t.test(e))){const r=s.getNestedValue(t,e,u??".");s.setNestedValue(O,e,r,u??".")}if(d){const e=s.getNestedKeys(t,u??".");for(const r of e){const e=r.split(y);if("zero"===e[e.length-1]){const n=e.slice(0,-1).join(y);if(m.some(({key:e})=>e.split(y).slice(0,-1).join(y)===n)){const e=s.getNestedValue(t,r,u??".");s.setNestedValue(O,r,e,u??".")}}}}for(const{key:e,defaultValue:r}of m){const a=s.getNestedValue(t,e,u??"."),i=!m.some(t=>t.key.startsWith(`${e}${u}`)&&t.key!==e),f="object"==typeof a&&null!==a&&(c.has(e)||!r||r===e),d="object"==typeof a&&null!==a&&i&&!c.has(e)&&!f;if(f){s.setNestedValue(O,e,a,u??".");continue}let y;y=void 0===a||d?o===p?r||e:n.resolveDefaultValue(g,e,l,o):a,s.setNestedValue(O,e,y,u??".")}if(!0===f)return a(O,r);if("function"==typeof f){const e={},t=Object.keys(O),s=new Map;for(const e of m){const t=!1===u?e.key:e.key.split(u)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof f){const r=s.get(e),n=s.get(t);if(r&&n)return f(r,n)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=a(O[s],r);O=e}return O}exports.getTranslations=async function(s,n,a){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage);const i=a.extract.defaultNS??"translation",c=[...a.extract.preservePatterns||[]],u=a.extract.indentation??2;for(const e of n)c.push(`${e}.*`);const f=c.map(o),d=new Map;for(const e of s.values()){const t=e.ns||i;d.has(t)||d.set(t,[]),d.get(t).push(e)}const p=[],g=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const s of a.locales){if(a.extract.mergeNamespaces||!a.extract.output.includes("{{namespace}}")){const t={},o=r.getOutputPath(a.extract.output,s),i=e.resolve(process.cwd(),o),c=await r.loadTranslationFile(i)||{},g=new Set([...d.keys(),...Object.keys(c)]);for(const e of g){const r=d.get(e)||[],o=c[e]||{};t[e]=l(r,o,a,s,e,f,n)}const y=JSON.stringify(c,null,u),h=JSON.stringify(t,null,u);p.push({path:i,updated:h!==y,newTranslations:t,existingTranslations:c})}else{const o=new Set(d.keys()),i=r.getOutputPath(a.extract.output,s,"*"),c=await t.glob(i,{ignore:g});for(const t of c)o.add(e.basename(t,e.extname(t)));for(const t of o){const o=d.get(t)||[],i=r.getOutputPath(a.extract.output,s,t),c=e.resolve(process.cwd(),i),g=await r.loadTranslationFile(c)||{},y=l(o,g,a,s,t,f,n),h=JSON.stringify(g,null,u),m=JSON.stringify(y,null,u);p.push({path:c,updated:m!==h,newTranslations:y,existingTranslations:g})}}}return p};
1
+ "use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),r=require("../../utils/file-utils.js"),n=require("../../utils/default-value.js");function a(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={},r=t?.extract?.pluralSeparator??"_",n=["zero","one","two","few","many","other"],a=n.map(e=>`ordinal_${e}`),l=Object.keys(e).sort((e,t)=>{const s=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 n)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}},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?a:n,s=t.indexOf(o.form),r=t.indexOf(l.form);return-1!==s&&-1!==r?s-r: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 r of l)s[r]=o(e[r],t);return s}function l(e,t,r,a,l,i,c,u=!1){const{keySeparator:f=".",sort:d=!0,removeUnusedKeys:p=!0,primaryLanguage:g,defaultValue:y="",pluralSeparator:h="_"}=r.extract,m=new Set;try{const e=new Intl.PluralRules(a,{type:"cardinal"}),t=new Intl.PluralRules(a,{type:"ordinal"});e.resolvedOptions().pluralCategories.forEach(e=>m.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}catch(e){const t=new Intl.PluralRules(g||"en",{type:"cardinal"}),s=new Intl.PluralRules(g||"en",{type:"ordinal"});t.resolvedOptions().pluralCategories.forEach(e=>m.add(e)),s.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}const O=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if(i.some(t=>t.test(e)))return!1;if(!t)return!0;const r=e.split(h);if(s&&r.includes("ordinal")){const e=r[r.length-1];return m.has(`ordinal_${e}`)}if(t){const e=r[r.length-1];return m.has(e)}return!0});let x=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 r=s.getNestedValue(t,e,f??".");s.setNestedValue(x,e,r,f??".")}if(p){const e=s.getNestedKeys(t,f??".");for(const r of e){const e=r.split(h);if("zero"===e[e.length-1]){const n=e.slice(0,-1).join(h);if(O.some(({key:e})=>e.split(h).slice(0,-1).join(h)===n)){const e=s.getNestedValue(t,r,f??".");s.setNestedValue(x,r,e,f??".")}}}}for(const{key:e,defaultValue:r}of O){const o=s.getNestedValue(t,e,f??"."),i=!O.some(t=>t.key.startsWith(`${e}${f}`)&&t.key!==e),d="object"==typeof o&&null!==o&&(c.has(e)||!r||r===e),p="object"==typeof o&&null!==o&&i&&!c.has(e)&&!d;if(d){s.setNestedValue(x,e,o,f??".");continue}let h;h=void 0===o||p?a===g?r||e:n.resolveDefaultValue(y,e,l,a):a===g&&u&&r&&r!==e?r:o,s.setNestedValue(x,e,h,f??".")}if(!0===d)return o(x,r);if("function"==typeof d){const e={},t=Object.keys(x),s=new Map;for(const e of O){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 r=s.get(e),n=s.get(t);if(r&&n)return d(r,n)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=o(x[s],r);x=e}return x}exports.getTranslations=async function(s,n,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.defaultNS??"translation",u=[...o.extract.preservePatterns||[]],f=o.extract.indentation??2;for(const e of n)u.push(`${e}.*`);const d=u.map(a),p=new Map;for(const e of s.values()){const t=e.ns||c;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||!o.extract.output.includes("{{namespace}}")){const t={},a=r.getOutputPath(o.extract.output,s),c=e.resolve(process.cwd(),a),u=await r.loadTranslationFile(c)||{},y=new Set([...p.keys(),...Object.keys(u)]);for(const e of y){const r=p.get(e)||[],a=u[e]||{};t[e]=l(r,a,o,s,e,d,n,i)}const h=JSON.stringify(u,null,f),m=JSON.stringify(t,null,f);g.push({path:c,updated:m!==h,newTranslations:t,existingTranslations:u})}else{const a=new Set(p.keys()),c=r.getOutputPath(o.extract.output,s,"*"),u=await t.glob(c,{ignore:y});for(const t of u)a.add(e.basename(t,e.extname(t)));for(const t of a){const a=p.get(t)||[],c=r.getOutputPath(o.extract.output,s,t),u=e.resolve(process.cwd(),c),y=await r.loadTranslationFile(u)||{},h=l(a,y,o,s,t,d,n,i),m=JSON.stringify(y,null,f),O=JSON.stringify(h,null,f);g.push({path:u,updated:O!==m,newTranslations:h,existingTranslations:y})}}}return g};
@@ -1 +1 @@
1
- "use strict";var e=require("node:fs/promises"),t=require("node:path"),n=require("jiti"),r=require("../config.js"),a="undefined"!=typeof document?document.currentScript:null;exports.getOutputPath=function(e,t,n=""){return e.replace("{{language}}",t).replace("{{lng}}",t).replace("{{namespace}}",n).replace("{{ns}}",n)},exports.loadTranslationFile=async function(s){try{await e.access(s)}catch{return null}try{const i=t.extname(s).toLowerCase();if(".json"===i){const t=await e.readFile(s,"utf-8");return JSON.parse(t)}if(".ts"===i||".js"===i){const e=await r.getTsConfigAliases(),t=n.createJiti("undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&"SCRIPT"===a.tagName.toUpperCase()&&a.src||new URL("utils/file-utils.js",document.baseURI).href,{alias:e,interopDefault:!0}),i=await t.import(s);return i&&"object"==typeof i?"default"in i&&void 0!==i.default?i.default:i:null}return null}catch(e){return console.warn(`Could not parse translation file ${s}:`,e),null}},exports.serializeTranslationFile=function(e,t="json",n=2){const r=JSON.stringify(e,null,n);switch(t){case"js":case"js-esm":return`export default ${r};\n`;case"js-cjs":return`module.exports = ${r};\n`;case"ts":return`export default ${r} as const;\n`;default:return`${r}\n`}};
1
+ "use strict";var e=require("node:fs/promises"),t=require("node:path"),r=require("jiti"),s=require("../config.js");exports.getOutputPath=function(e,t,r=""){return e.replace("{{language}}",t).replace("{{lng}}",t).replace("{{namespace}}",r).replace("{{ns}}",r)},exports.loadTranslationFile=async function(n){const a=t.resolve(process.cwd(),n);try{await e.access(a)}catch{return null}try{const n=t.extname(a).toLowerCase();if(".json"===n){const t=await e.readFile(a,"utf-8");return JSON.parse(t)}if(".ts"===n||".js"===n){const e=await s.getTsConfigAliases(),t=r.createJiti(process.cwd(),{alias:e,interopDefault:!0});return await t.import(a,{default:!0})}return null}catch(e){return console.warn(`Could not parse translation file ${n}:`,e),null}},exports.serializeTranslationFile=function(e,t="json",r=2){const s=JSON.stringify(e,null,r);switch(t){case"js":case"js-esm":return`export default ${s};\n`;case"js-cjs":return`module.exports = ${s};\n`;case"ts":return`export default ${s} as const;\n`;default:return`${s}\n`}};
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 n from"chalk";import{ensureConfig as i,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as r}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as p}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as f,runLocizeDownload as u,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.10.4"),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.").action(async t=>{const a=await i(),c=async()=>{const o=await r(a,{isWatchMode:t.watch,isDryRun:t.dryRun});t.ci&&o&&(console.error(n.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(n.yellow("šŸ’” Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${n.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),t.watch){console.log("\nWatching for changes...");o.watch(await e(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),c()})}}),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)=>{let e=await a();if(!e){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!")),e=t}await g(e,{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 n=await i(),a=()=>s(n);if(await a(),t.watch){console.log("\nWatching for changes...");o.watch(await e(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),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(p),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 i=async()=>{let t=await a();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 i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){o.watch(await e(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),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=await i();await f(o,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=await i();await u(o,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=await i();await h(o,t)}),w.parse(process.argv);
2
+ import{Command as t}from"commander";import e from"chokidar";import{glob as o}from"glob";import i from"chalk";import{ensureConfig as n,loadConfig as a}from"./config.js";import{detectConfig as r}from"./heuristic-config.js";import{runExtractor as c}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as p}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as u}from"./status.js";import{runLocizeSync as f,runLocizeDownload as g,runLocizeMigrate as y}from"./locize.js";const h=new t;h.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.1"),h.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=await n(),o=await c(e,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});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))}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),h.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(t,e)=>{let o=await a();if(!o){console.log(i.blue("No config file found. Attempting to detect project structure..."));const t=await r();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!")),o=t}await u(o,{detail:t,namespace:e.namespace})}),h.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 i=await n(),a=()=>s(i);if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(i.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),h.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await n();await l(t)}),h.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await p(t)}),h.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),h.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 n=async()=>{let t=await a();if(!t){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await r();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!")),t=e}await d(t)};if(await n(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){e.watch(await o(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),n()})}}}),h.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async t=>{const e=await n();await f(e,t)}),h.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const e=await n();await g(e,t)}),h.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const e=await n();await y(e,t)}),h.parse(process.argv);
@@ -1 +1 @@
1
- import t from"ora";import a from"chalk";import{parse as o}from"@swc/core";import{mkdir as e,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as i}from"node:path";import{findKeys as s}from"./key-finder.js";import{getTranslations as c}from"./translation-manager.js";import{validateExtractorConfig as l,ExtractorError as m}from"../../utils/validation.js";import{extractKeysFromComments as u}from"../parsers/comment-parser.js";import{ConsoleLogger as p}from"../../utils/logger.js";import{serializeTranslationFile as f}from"../../utils/file-utils.js";import{shouldShowFunnel as g,recordFunnelShown as d}from"../../utils/funnel-msg-tracker.js";async function y(o,{isWatchMode:n=!1,isDryRun:m=!1}={},u=new p){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(t=>t!==o?.extract?.primaryLanguage),o.extract.functions||=["t","*.t"],o.extract.transComponents||=["Trans"],l(o);const y=o.plugins||[],w=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:n}=await s(o,u);w.text=`Found ${t.size} unique keys. Updating translation files...`;const l=await c(t,n,o);let p=!1;for(const t of l)if(t.updated&&(p=!0,!m)){const n=f(t.newTranslations,o.extract.outputFormat,o.extract.indentation);await e(i(t.path),{recursive:!0}),await r(t.path,n),u.info(a.green(`Updated: ${t.path}`))}if(y.length>0){w.text="Running post-extraction plugins...";for(const t of y)await(t.afterSync?.(l,o))}return w.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 w.fail(a.red("Extraction failed.")),t}}async function w(t,a,e,r,i,s=new p){try{let c=await n(t,"utf-8");for(const o of a)try{const a=await(o.onLoad?.(c,t));void 0!==a&&(c=a)}catch(t){s.warn(`Plugin ${o.name} onLoad failed:`,t)}const l=await o(c,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0});r.getVarFromScope=e.getVarFromScope.bind(e),e.visit(l),u(c,r,i,e.getVarFromScope.bind(e))}catch(a){throw new m("Failed to process file",t,a)}}async function x(t){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:a,objectKeys:o}=await s(t);return c(a,o,t)}export{x as extract,w as processFile,y as runExtractor};
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 s}from"./key-finder.js";import{getTranslations as c}from"./translation-manager.js";import{validateExtractorConfig as l,ExtractorError as m}from"../../utils/validation.js";import{extractKeysFromComments as u}from"../parsers/comment-parser.js";import{ConsoleLogger as f}from"../../utils/logger.js";import{serializeTranslationFile as p}from"../../utils/file-utils.js";import{shouldShowFunnel as y,recordFunnelShown as g}from"../../utils/funnel-msg-tracker.js";async function d(e,{isWatchMode:n=!1,isDryRun:m=!1,syncPrimaryWithDefaults:u=!1}={},d=new f){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"],l(e);const w=e.plugins||[],x=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:n}=await s(e,d);x.text=`Found ${t.size} unique keys. Updating translation files...`;const l=await c(t,n,e,{syncPrimaryWithDefaults:u});let f=!1;for(const t of l)if(t.updated&&(f=!0,!m)){const n=p(t.newTranslations,e.extract.outputFormat,e.extract.indentation);await o(i(t.path),{recursive:!0}),await r(t.path,n),d.info(a.green(`Updated: ${t.path}`))}if(w.length>0){x.text="Running post-extraction plugins...";for(const t of w)await(t.afterSync?.(l,e))}return x.succeed(a.bold("Extraction complete!")),f&&await async function(){if(!await y("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")}(),f}catch(t){throw x.fail(a.red("Extraction failed.")),t}}async function w(t,a,o,r,i,s=new f){try{let c=await n(t,"utf-8");for(const e of a)try{const a=await(e.onLoad?.(c,t));void 0!==a&&(c=a)}catch(t){s.warn(`Plugin ${e.name} onLoad failed:`,t)}const l=await e(c,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0});r.getVarFromScope=o.getVarFromScope.bind(o),o.visit(l),u(c,r,i,o.getVarFromScope.bind(o))}catch(a){throw new m("Failed to process file",t,a)}}async function x(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 s(t);return c(e,o,t,{syncPrimaryWithDefaults:a})}export{x as extract,w as processFile,d as runExtractor};
@@ -1 +1 @@
1
- import{resolve as t,basename as e,extname as r}from"node:path";import{glob as o}from"glob";import{getNestedKeys as n,getNestedValue as s,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(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e){if("object"!=typeof t||null===t||Array.isArray(t))return t;const r={},o=e?.extract?.pluralSeparator??"_",n=["zero","one","two","few","many","other"],s=n.map(t=>`ordinal_${t}`),a=Object.keys(t).sort((t,e)=>{const r=t=>{for(const e of s)if(t.endsWith(`${o}${e}`)){return{base:t.slice(0,-(o.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of n)if(t.endsWith(`${o}${e}`)){return{base:t.slice(0,-(o.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},a=r(t),i=r(e);if(a.isPlural&&i.isPlural){const t=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const e=a.isOrdinal?s:n,r=e.indexOf(a.form),o=e.indexOf(i.form);return-1!==r&&-1!==o?r-o:a.form.localeCompare(i.form)}const l=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===l?t.localeCompare(e,void 0,{sensitivity:"case"}):l});for(const o of a)r[o]=u(t[o],e);return r}function p(t,e,r,o,i,l,f){const{keySeparator:p=".",sort:d=!0,removeUnusedKeys:y=!0,primaryLanguage:g,defaultValue:m="",pluralSeparator:h="_"}=r.extract,x=new Set;try{const t=new Intl.PluralRules(o,{type:"cardinal"}),e=new Intl.PluralRules(o,{type:"ordinal"});t.resolvedOptions().pluralCategories.forEach(t=>x.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>x.add(`ordinal_${t}`))}catch(t){const e=new Intl.PluralRules(g||"en",{type:"cardinal"}),r=new Intl.PluralRules(g||"en",{type:"ordinal"});e.resolvedOptions().pluralCategories.forEach(t=>x.add(t)),r.resolvedOptions().pluralCategories.forEach(t=>x.add(`ordinal_${t}`))}const O=t.filter(({key:t,hasCount:e,isOrdinal:r})=>{if(l.some(e=>e.test(t)))return!1;if(!e)return!0;const o=t.split(h);if(r&&o.includes("ordinal")){const t=o[o.length-1];return x.has(`ordinal_${t}`)}if(e){const t=o[o.length-1];return x.has(t)}return!0});let w=y?{}:JSON.parse(JSON.stringify(e));const v=n(e,p??".");for(const t of v)if(l.some(e=>e.test(t))){const r=s(e,t,p??".");a(w,t,r,p??".")}if(y){const t=n(e,p??".");for(const r of t){const t=r.split(h);if("zero"===t[t.length-1]){const o=t.slice(0,-1).join(h);if(O.some(({key:t})=>t.split(h).slice(0,-1).join(h)===o)){const t=s(e,r,p??".");a(w,r,t,p??".")}}}}for(const{key:t,defaultValue:r}of O){const n=s(e,t,p??"."),l=!O.some(e=>e.key.startsWith(`${t}${p}`)&&e.key!==t),u="object"==typeof n&&null!==n&&(f.has(t)||!r||r===t),d="object"==typeof n&&null!==n&&l&&!f.has(t)&&!u;if(u){a(w,t,n,p??".");continue}let y;y=void 0===n||d?o===g?r||t:c(m,t,i,o):n,a(w,t,y,p??".")}if(!0===d)return u(w,r);if("function"==typeof d){const t={},e=Object.keys(w),o=new Map;for(const t of O){const e=!1===p?t.key:t.key.split(p)[0];o.has(e)||o.set(e,t)}e.sort((t,e)=>{if("function"==typeof d){const r=o.get(t),n=o.get(e);if(r&&n)return d(r,n)}return t.localeCompare(e,void 0,{sensitivity:"base"})});for(const o of e)t[o]=u(w[o],r);w=t}return w}async function d(n,s,a){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(t=>t!==a?.extract?.primaryLanguage);const c=a.extract.defaultNS??"translation",u=[...a.extract.preservePatterns||[]],d=a.extract.indentation??2;for(const t of s)u.push(`${t}.*`);const y=u.map(f),g=new Map;for(const t of n.values()){const e=t.ns||c;g.has(e)||g.set(e,[]),g.get(e).push(t)}const m=[],h=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const n of a.locales){if(a.extract.mergeNamespaces||!a.extract.output.includes("{{namespace}}")){const e={},r=i(a.extract.output,n),o=t(process.cwd(),r),c=await l(o)||{},f=new Set([...g.keys(),...Object.keys(c)]);for(const t of f){const r=g.get(t)||[],o=c[t]||{};e[t]=p(r,o,a,n,t,y,s)}const u=JSON.stringify(c,null,d),h=JSON.stringify(e,null,d);m.push({path:o,updated:h!==u,newTranslations:e,existingTranslations:c})}else{const c=new Set(g.keys()),f=i(a.extract.output,n,"*"),u=await o(f,{ignore:h});for(const t of u)c.add(e(t,r(t)));for(const e of c){const r=g.get(e)||[],o=i(a.extract.output,n,e),c=t(process.cwd(),o),f=await l(c)||{},u=p(r,f,a,n,e,y,s),h=JSON.stringify(f,null,d),x=JSON.stringify(u,null,d);m.push({path:c,updated:x!==h,newTranslations:u,existingTranslations:f})}}}return m}export{d as getTranslations};
1
+ import{resolve as t,basename as e,extname as r}from"node:path";import{glob as o}from"glob";import{getNestedKeys as n,getNestedValue as s,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(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e){if("object"!=typeof t||null===t||Array.isArray(t))return t;const r={},o=e?.extract?.pluralSeparator??"_",n=["zero","one","two","few","many","other"],s=n.map(t=>`ordinal_${t}`),a=Object.keys(t).sort((t,e)=>{const r=t=>{for(const e of s)if(t.endsWith(`${o}${e}`)){return{base:t.slice(0,-(o.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of n)if(t.endsWith(`${o}${e}`)){return{base:t.slice(0,-(o.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},a=r(t),i=r(e);if(a.isPlural&&i.isPlural){const t=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const e=a.isOrdinal?s:n,r=e.indexOf(a.form),o=e.indexOf(i.form);return-1!==r&&-1!==o?r-o:a.form.localeCompare(i.form)}const l=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===l?t.localeCompare(e,void 0,{sensitivity:"case"}):l});for(const o of a)r[o]=u(t[o],e);return r}function p(t,e,r,o,i,l,f,p=!1){const{keySeparator:d=".",sort:y=!0,removeUnusedKeys:g=!0,primaryLanguage:m,defaultValue:h="",pluralSeparator:x="_"}=r.extract,O=new Set;try{const t=new Intl.PluralRules(o,{type:"cardinal"}),e=new Intl.PluralRules(o,{type:"ordinal"});t.resolvedOptions().pluralCategories.forEach(t=>O.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>O.add(`ordinal_${t}`))}catch(t){const e=new Intl.PluralRules(m||"en",{type:"cardinal"}),r=new Intl.PluralRules(m||"en",{type:"ordinal"});e.resolvedOptions().pluralCategories.forEach(t=>O.add(t)),r.resolvedOptions().pluralCategories.forEach(t=>O.add(`ordinal_${t}`))}const w=t.filter(({key:t,hasCount:e,isOrdinal:r})=>{if(l.some(e=>e.test(t)))return!1;if(!e)return!0;const o=t.split(x);if(r&&o.includes("ordinal")){const t=o[o.length-1];return O.has(`ordinal_${t}`)}if(e){const t=o[o.length-1];return O.has(t)}return!0});let v=g?{}:JSON.parse(JSON.stringify(e));const b=n(e,d??".");for(const t of b)if(l.some(e=>e.test(t))){const r=s(e,t,d??".");a(v,t,r,d??".")}if(g){const t=n(e,d??".");for(const r of t){const t=r.split(x);if("zero"===t[t.length-1]){const o=t.slice(0,-1).join(x);if(w.some(({key:t})=>t.split(x).slice(0,-1).join(x)===o)){const t=s(e,r,d??".");a(v,r,t,d??".")}}}}for(const{key:t,defaultValue:r}of w){const n=s(e,t,d??"."),l=!w.some(e=>e.key.startsWith(`${t}${d}`)&&e.key!==t),u="object"==typeof n&&null!==n&&(f.has(t)||!r||r===t),y="object"==typeof n&&null!==n&&l&&!f.has(t)&&!u;if(u){a(v,t,n,d??".");continue}let g;g=void 0===n||y?o===m?r||t:c(h,t,i,o):o===m&&p&&r&&r!==t?r:n,a(v,t,g,d??".")}if(!0===y)return u(v,r);if("function"==typeof y){const t={},e=Object.keys(v),o=new Map;for(const t of w){const e=!1===d?t.key:t.key.split(d)[0];o.has(e)||o.set(e,t)}e.sort((t,e)=>{if("function"==typeof y){const r=o.get(t),n=o.get(e);if(r&&n)return y(r,n)}return t.localeCompare(e,void 0,{sensitivity:"base"})});for(const o of e)t[o]=u(v[o],r);v=t}return v}async function d(n,s,a,{syncPrimaryWithDefaults:c=!1}={}){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(t=>t!==a?.extract?.primaryLanguage);const u=a.extract.defaultNS??"translation",d=[...a.extract.preservePatterns||[]],y=a.extract.indentation??2;for(const t of s)d.push(`${t}.*`);const g=d.map(f),m=new Map;for(const t of n.values()){const e=t.ns||u;m.has(e)||m.set(e,[]),m.get(e).push(t)}const h=[],x=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const n of a.locales){if(a.extract.mergeNamespaces||!a.extract.output.includes("{{namespace}}")){const e={},r=i(a.extract.output,n),o=t(process.cwd(),r),f=await l(o)||{},u=new Set([...m.keys(),...Object.keys(f)]);for(const t of u){const r=m.get(t)||[],o=f[t]||{};e[t]=p(r,o,a,n,t,g,s,c)}const d=JSON.stringify(f,null,y),x=JSON.stringify(e,null,y);h.push({path:o,updated:x!==d,newTranslations:e,existingTranslations:f})}else{const f=new Set(m.keys()),u=i(a.extract.output,n,"*"),d=await o(u,{ignore:x});for(const t of d)f.add(e(t,r(t)));for(const e of f){const r=m.get(e)||[],o=i(a.extract.output,n,e),f=t(process.cwd(),o),u=await l(f)||{},d=p(r,u,a,n,e,g,s,c),x=JSON.stringify(u,null,y),O=JSON.stringify(d,null,y);h.push({path:f,updated:O!==x,newTranslations:d,existingTranslations:u})}}}return h}export{d as getTranslations};
@@ -1 +1 @@
1
- import{access as t,readFile as e}from"node:fs/promises";import{extname as r}from"node:path";import{createJiti as n}from"jiti";import{getTsConfigAliases as a}from"../config.js";function o(t,e,r=""){return t.replace("{{language}}",e).replace("{{lng}}",e).replace("{{namespace}}",r).replace("{{ns}}",r)}async function s(o){try{await t(o)}catch{return null}try{const t=r(o).toLowerCase();if(".json"===t){const t=await e(o,"utf-8");return JSON.parse(t)}if(".ts"===t||".js"===t){const t=await a(),e=n(import.meta.url,{alias:t,interopDefault:!0}),r=await e.import(o);return r&&"object"==typeof r?"default"in r&&void 0!==r.default?r.default:r:null}return null}catch(t){return console.warn(`Could not parse translation file ${o}:`,t),null}}function l(t,e="json",r=2){const n=JSON.stringify(t,null,r);switch(e){case"js":case"js-esm":return`export default ${n};\n`;case"js-cjs":return`module.exports = ${n};\n`;case"ts":return`export default ${n} as const;\n`;default:return`${n}\n`}}export{o as getOutputPath,s as loadTranslationFile,l as serializeTranslationFile};
1
+ import{access as t,readFile as r}from"node:fs/promises";import{resolve as e,extname as n}from"node:path";import{createJiti as s}from"jiti";import{getTsConfigAliases as o}from"../config.js";function a(t,r,e=""){return t.replace("{{language}}",r).replace("{{lng}}",r).replace("{{namespace}}",e).replace("{{ns}}",e)}async function c(a){const c=e(process.cwd(),a);try{await t(c)}catch{return null}try{const t=n(c).toLowerCase();if(".json"===t){const t=await r(c,"utf-8");return JSON.parse(t)}if(".ts"===t||".js"===t){const t=await o(),r=s(process.cwd(),{alias:t,interopDefault:!0});return await r.import(c,{default:!0})}return null}catch(t){return console.warn(`Could not parse translation file ${a}:`,t),null}}function u(t,r="json",e=2){const n=JSON.stringify(t,null,e);switch(r){case"js":case"js-esm":return`export default ${n};\n`;case"js-cjs":return`module.exports = ${n};\n`;case"ts":return`export default ${n} as const;\n`;default:return`${n}\n`}}export{a as getOutputPath,c as loadTranslationFile,u as serializeTranslationFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.10.4",
3
+ "version": "1.11.1",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.ts CHANGED
@@ -21,7 +21,7 @@ const program = new Command()
21
21
  program
22
22
  .name('i18next-cli')
23
23
  .description('A unified, high-performance i18next CLI.')
24
- .version('1.10.4')
24
+ .version('1.11.1')
25
25
 
26
26
  program
27
27
  .command('extract')
@@ -29,30 +29,27 @@ program
29
29
  .option('-w, --watch', 'Watch for file changes and re-run the extractor.')
30
30
  .option('--ci', 'Exit with a non-zero status code if any files are updated.')
31
31
  .option('--dry-run', 'Run the extractor without writing any files to disk.')
32
+ .option('--sync-primary', 'Sync primary language values with default values from code.')
32
33
  .action(async (options) => {
33
- const config = await ensureConfig()
34
+ try {
35
+ const config = await ensureConfig()
36
+
37
+ const success = await runExtractor(config, {
38
+ isWatchMode: !!options.watch,
39
+ isDryRun: !!options.dryRun,
40
+ syncPrimaryWithDefaults: !!options.syncPrimary
41
+ })
34
42
 
35
- const run = async () => {
36
- const filesWereUpdated = await runExtractor(config, { isWatchMode: options.watch, isDryRun: options.dryRun })
37
- if (options.ci && filesWereUpdated) {
38
- console.error(chalk.red.bold('\n[CI Mode] Error: Translation files were updated. Please commit the changes.'))
39
- console.log(chalk.yellow('šŸ’” Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started'))
40
- console.log(` Learn more: ${chalk.cyan('npx i18next-cli locize-sync')}`)
43
+ if (options.ci && !success) {
44
+ console.log('āœ… No files were updated.')
45
+ process.exit(0)
46
+ } else if (options.ci && success) {
47
+ console.error('āŒ Some files were updated. This should not happen in CI mode.')
41
48
  process.exit(1)
42
49
  }
43
- }
44
- await run()
45
-
46
- if (options.watch) {
47
- console.log('\nWatching for changes...')
48
- const watcher = chokidar.watch(await glob(config.extract.input), {
49
- ignored: /node_modules/,
50
- persistent: true,
51
- })
52
- watcher.on('change', path => {
53
- console.log(`\nFile changed: ${path}`)
54
- run()
55
- })
50
+ } catch (error) {
51
+ console.error('Error running extractor:', error)
52
+ process.exit(1)
56
53
  }
57
54
  })
58
55
 
@@ -43,10 +43,12 @@ export async function runExtractor (
43
43
  config: I18nextToolkitConfig,
44
44
  {
45
45
  isWatchMode = false,
46
- isDryRun = false
46
+ isDryRun = false,
47
+ syncPrimaryWithDefaults = false
47
48
  }: {
48
49
  isWatchMode?: boolean,
49
50
  isDryRun?: boolean,
51
+ syncPrimaryWithDefaults?: boolean,
50
52
  } = {},
51
53
  logger: Logger = new ConsoleLogger()
52
54
  ): Promise<boolean> {
@@ -67,7 +69,7 @@ export async function runExtractor (
67
69
  const { allKeys, objectKeys } = await findKeys(config, logger)
68
70
  spinner.text = `Found ${allKeys.size} unique keys. Updating translation files...`
69
71
 
70
- const results = await getTranslations(allKeys, objectKeys, config)
72
+ const results = await getTranslations(allKeys, objectKeys, config, { syncPrimaryWithDefaults })
71
73
 
72
74
  let anyFileUpdated = false
73
75
  for (const result of results) {
@@ -188,13 +190,13 @@ export async function processFile (
188
190
  * }
189
191
  * ```
190
192
  */
191
- export async function extract (config: I18nextToolkitConfig) {
193
+ export async function extract (config: I18nextToolkitConfig, { syncPrimaryWithDefaults = false }: { syncPrimaryWithDefaults?: boolean } = {}) {
192
194
  config.extract.primaryLanguage ||= config.locales[0] || 'en'
193
195
  config.extract.secondaryLanguages ||= config.locales.filter((l: string) => l !== config?.extract?.primaryLanguage)
194
196
  config.extract.functions ||= ['t', '*.t']
195
197
  config.extract.transComponents ||= ['Trans']
196
198
  const { allKeys, objectKeys } = await findKeys(config)
197
- return getTranslations(allKeys, objectKeys, config)
199
+ return getTranslations(allKeys, objectKeys, config, { syncPrimaryWithDefaults })
198
200
  }
199
201
 
200
202
  /**
@@ -108,7 +108,8 @@ function buildNewTranslationsForNs (
108
108
  locale: string,
109
109
  namespace: string,
110
110
  preservePatterns: RegExp[],
111
- objectKeys: Set<string>
111
+ objectKeys: Set<string>,
112
+ syncPrimaryWithDefaults: boolean = false
112
113
  ): Record<string, any> {
113
114
  const {
114
115
  keySeparator = '.',
@@ -233,7 +234,12 @@ function buildNewTranslationsForNs (
233
234
  valueToSet = resolveDefaultValue(emptyDefaultValue, key, namespace, locale)
234
235
  }
235
236
  } else {
236
- valueToSet = existingValue
237
+ // Check CLI flag for syncing primary language with code defaults
238
+ if (locale === primaryLanguage && syncPrimaryWithDefaults && defaultValue && defaultValue !== key) {
239
+ valueToSet = defaultValue
240
+ } else {
241
+ valueToSet = existingValue
242
+ }
237
243
  }
238
244
 
239
245
  setNestedValue(newTranslations, key, valueToSet, keySeparator ?? '.')
@@ -315,7 +321,8 @@ function buildNewTranslationsForNs (
315
321
  export async function getTranslations (
316
322
  keys: Map<string, ExtractedKey>,
317
323
  objectKeys: Set<string>,
318
- config: I18nextToolkitConfig
324
+ config: I18nextToolkitConfig,
325
+ { syncPrimaryWithDefaults = false }: { syncPrimaryWithDefaults?: boolean } = {}
319
326
  ): Promise<TranslationResult[]> {
320
327
  config.extract.primaryLanguage ||= config.locales[0] || 'en'
321
328
  config.extract.secondaryLanguages ||= config.locales.filter((l: string) => l !== config?.extract?.primaryLanguage)
@@ -359,7 +366,7 @@ export async function getTranslations (
359
366
  for (const ns of namespacesToProcess) {
360
367
  const nsKeys = keysByNS.get(ns) || []
361
368
  const existingTranslations = existingMergedFile[ns] || {}
362
- newMergedTranslations[ns] = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, ns, preservePatterns, objectKeys)
369
+ newMergedTranslations[ns] = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, ns, preservePatterns, objectKeys, syncPrimaryWithDefaults)
363
370
  }
364
371
 
365
372
  const oldContent = JSON.stringify(existingMergedFile, null, indentation)
@@ -383,7 +390,7 @@ export async function getTranslations (
383
390
  const outputPath = getOutputPath(config.extract.output, locale, ns)
384
391
  const fullPath = resolve(process.cwd(), outputPath)
385
392
  const existingTranslations = await loadTranslationFile(fullPath) || {}
386
- const newTranslations = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, ns, preservePatterns, objectKeys)
393
+ const newTranslations = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, ns, preservePatterns, objectKeys, syncPrimaryWithDefaults)
387
394
 
388
395
  const oldContent = JSON.stringify(existingTranslations, null, indentation)
389
396
  const newContent = JSON.stringify(newTranslations, null, indentation)
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, writeFile, access } from 'node:fs/promises'
2
- import { dirname, extname } from 'node:path'
2
+ import { dirname, extname, resolve } from 'node:path'
3
3
  import { createJiti } from 'jiti'
4
4
  import type { I18nextToolkitConfig } from '../types'
5
5
  import { getTsConfigAliases } from '../config'
@@ -89,41 +89,30 @@ export function getOutputPath (
89
89
  * @returns The parsed content of the file, or null if not found or failed to parse.
90
90
  */
91
91
  export async function loadTranslationFile (filePath: string): Promise<Record<string, any> | null> {
92
+ const fullPath = resolve(process.cwd(), filePath)
92
93
  try {
93
- // Check if file exists first
94
- await access(filePath)
94
+ await access(fullPath)
95
95
  } catch {
96
96
  return null // File doesn't exist
97
97
  }
98
98
 
99
99
  try {
100
- const ext = extname(filePath).toLowerCase()
100
+ const ext = extname(fullPath).toLowerCase()
101
101
 
102
102
  if (ext === '.json') {
103
- const content = await readFile(filePath, 'utf-8')
103
+ const content = await readFile(fullPath, 'utf-8')
104
104
  return JSON.parse(content)
105
105
  } else if (ext === '.ts' || ext === '.js') {
106
106
  // Load TypeScript path aliases for proper module resolution
107
107
  const aliases = await getTsConfigAliases()
108
108
 
109
- const jiti = createJiti(import.meta.url, {
109
+ const jiti = createJiti(process.cwd(), {
110
110
  alias: aliases,
111
111
  interopDefault: true,
112
112
  })
113
113
 
114
- const module = await jiti.import(filePath) as any
115
-
116
- // Handle different export patterns
117
- if (module && typeof module === 'object') {
118
- // If module.default exists, use it
119
- if ('default' in module && module.default !== undefined) {
120
- return module.default
121
- }
122
- // Otherwise, use the module itself (might be a CommonJS export)
123
- return module
124
- }
125
-
126
- return null
114
+ const module = await jiti.import(fullPath, { default: true }) as unknown
115
+ return module as Record<string, any> | null
127
116
  }
128
117
 
129
118
  return null // Unsupported file type
@@ -26,9 +26,10 @@ import { ASTVisitors } from './ast-visitors';
26
26
  * }
27
27
  * ```
28
28
  */
29
- export declare function runExtractor(config: I18nextToolkitConfig, { isWatchMode, isDryRun }?: {
29
+ export declare function runExtractor(config: I18nextToolkitConfig, { isWatchMode, isDryRun, syncPrimaryWithDefaults }?: {
30
30
  isWatchMode?: boolean;
31
31
  isDryRun?: boolean;
32
+ syncPrimaryWithDefaults?: boolean;
32
33
  }, logger?: Logger): Promise<boolean>;
33
34
  /**
34
35
  * Processes an individual source file for translation key extraction.
@@ -66,5 +67,7 @@ export declare function processFile(file: string, plugins: Plugin[], astVisitors
66
67
  * }
67
68
  * ```
68
69
  */
69
- export declare function extract(config: I18nextToolkitConfig): Promise<import("../../types").TranslationResult[]>;
70
+ export declare function extract(config: I18nextToolkitConfig, { syncPrimaryWithDefaults }?: {
71
+ syncPrimaryWithDefaults?: boolean;
72
+ }): Promise<import("../../types").TranslationResult[]>;
70
73
  //# sourceMappingURL=extractor.d.ts.map
@@ -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,EACjB,GAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACf,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,CAoCf;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAE,MAAM,EAAE,oBAAoB,sDAO1D"}
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,CAoCf;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAE,MAAM,EAAE,oBAAoB,EAAE,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,sDAO3I"}
@@ -28,5 +28,7 @@ import { TranslationResult, ExtractedKey, I18nextToolkitConfig } from '../../typ
28
28
  * // Results contain update status and new/existing translations for each locale.
29
29
  * ```
30
30
  */
31
- export declare function getTranslations(keys: Map<string, ExtractedKey>, objectKeys: Set<string>, config: I18nextToolkitConfig): Promise<TranslationResult[]>;
31
+ export declare function getTranslations(keys: Map<string, ExtractedKey>, objectKeys: Set<string>, config: I18nextToolkitConfig, { syncPrimaryWithDefaults }?: {
32
+ syncPrimaryWithDefaults?: boolean;
33
+ }): Promise<TranslationResult[]>;
32
34
  //# sourceMappingURL=translation-manager.d.ts.map
@@ -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;AA6RnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,GAC3B,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA8E9B"}
1
+ {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAmSnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA8E9B"}
@@ -1 +1 @@
1
- {"version":3,"file":"file-utils.d.ts","sourceRoot":"","sources":["../../src/utils/file-utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAGpD;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG5E;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,aAAa,CAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEnF;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,SAAS,GAAE,MAAW,GACrB,MAAM,CAIR;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,CA2ChG;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACzB,MAAM,GAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC,cAAc,CAAU,EAChE,WAAW,GAAE,MAAM,GAAG,MAAU,GAC/B,MAAM,CAgBR"}
1
+ {"version":3,"file":"file-utils.d.ts","sourceRoot":"","sources":["../../src/utils/file-utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAA;AAGpD;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG5E;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,aAAa,CAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEnF;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,SAAS,GAAE,MAAW,GACrB,MAAM,CAIR;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,CAgChG;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACzB,MAAM,GAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC,cAAc,CAAU,EAChE,WAAW,GAAE,MAAM,GAAG,MAAU,GAC/B,MAAM,CAgBR"}