i18next-cli 1.21.0 → 1.22.0

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +107 -0
  3. package/dist/cjs/cli.js +1 -1
  4. package/dist/cjs/extractor/core/ast-visitors.js +1 -1
  5. package/dist/cjs/extractor/core/extractor.js +1 -1
  6. package/dist/cjs/extractor/core/translation-manager.js +1 -1
  7. package/dist/cjs/extractor/parsers/call-expression-handler.js +1 -1
  8. package/dist/cjs/extractor/parsers/jsx-handler.js +1 -1
  9. package/dist/cjs/extractor/plugin-manager.js +1 -1
  10. package/dist/esm/cli.js +1 -1
  11. package/dist/esm/extractor/core/ast-visitors.js +1 -1
  12. package/dist/esm/extractor/core/extractor.js +1 -1
  13. package/dist/esm/extractor/core/translation-manager.js +1 -1
  14. package/dist/esm/extractor/parsers/call-expression-handler.js +1 -1
  15. package/dist/esm/extractor/parsers/jsx-handler.js +1 -1
  16. package/dist/esm/extractor/plugin-manager.js +1 -1
  17. package/package.json +1 -1
  18. package/src/cli.ts +1 -1
  19. package/src/extractor/core/ast-visitors.ts +48 -2
  20. package/src/extractor/core/extractor.ts +3 -0
  21. package/src/extractor/core/translation-manager.ts +4 -0
  22. package/src/extractor/parsers/call-expression-handler.ts +45 -2
  23. package/src/extractor/parsers/jsx-handler.ts +93 -19
  24. package/src/extractor/plugin-manager.ts +27 -3
  25. package/src/types.ts +7 -0
  26. package/types/extractor/core/ast-visitors.d.ts +23 -0
  27. package/types/extractor/core/ast-visitors.d.ts.map +1 -1
  28. package/types/extractor/core/extractor.d.ts.map +1 -1
  29. package/types/extractor/core/translation-manager.d.ts.map +1 -1
  30. package/types/extractor/parsers/call-expression-handler.d.ts +8 -1
  31. package/types/extractor/parsers/call-expression-handler.d.ts.map +1 -1
  32. package/types/extractor/parsers/jsx-handler.d.ts +9 -1
  33. package/types/extractor/parsers/jsx-handler.d.ts.map +1 -1
  34. package/types/extractor/plugin-manager.d.ts.map +1 -1
  35. package/types/types.d.ts +6 -0
  36. package/types/types.d.ts.map +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.22.0](https://github.com/i18next/i18next-cli/compare/v1.21.1...v1.22.0) - 2025-11-06
9
+
10
+ - **Plugin System:** Enhanced `ExtractedKey` type and plugin hooks to support location metadata tracking. Plugins can now access file paths, etc. for each extracted translation key via the `locations` array property. [#95](https://github.com/i18next/i18next-cli/issues/95)
11
+
12
+ ## [1.21.1](https://github.com/i18next/i18next-cli/compare/v1.21.0...v1.21.1) - 2025-11-05
13
+
14
+ - **Extractor (`--sync-primary`):** Fixed a bug where `<Trans i18nKey='namespace:key' />` components with namespaced keys were having their existing primary language translations overwritten with the full namespaced key string (e.g., `'translation:app.preservedTrans'`) when using the `--sync-primary` flag. The extractor now correctly identifies namespaced keys in defaultValue as derived (auto-generated) defaults rather than explicit developer-provided values, preserving existing translations when no explicit defaultValue is provided. This ensures that `<Trans>` components without explicit defaults behave consistently with `t()` calls under `--sync-primary`. [#92](https://github.com/i18next/i18next-cli/issues/92)
15
+
8
16
  ## [1.21.0](https://github.com/i18next/i18next-cli/compare/v1.20.4...v1.21.0) - 2025-11-05
9
17
 
10
18
  - **Extractor:** Enhanced `preservePatterns` with namespace pattern support. You can now preserve entire namespaces or namespace-specific key patterns using the namespace separator (e.g., `'assets:*'` to preserve all keys in the `assets` namespace, or `'common:button.*'` to preserve specific patterns within a namespace). This is particularly useful for managing translations that are handled externally, loaded dynamically, or constructed at runtime. Pattern matching respects the configured `nsSeparator` setting. [#90](https://github.com/i18next/i18next-cli/issues/90)
package/README.md CHANGED
@@ -581,6 +581,113 @@ export default defineConfig({
581
581
  });
582
582
  ```
583
583
 
584
+ ### Location Metadata Tracking
585
+
586
+ Track where each translation key is used in your codebase with a custom metadata plugin.
587
+
588
+ **Example Plugin Implementation:**
589
+
590
+ ```typescript
591
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
592
+ import { dirname } from 'node:path';
593
+ import type { Plugin } from 'i18next-cli';
594
+
595
+ interface LocationMetadataOptions {
596
+ /** Output path for the metadata file (default: 'locales/metadata.json') */
597
+ output?: string;
598
+ /** Include line and column numbers (default: true) */
599
+ includePosition?: boolean;
600
+ }
601
+
602
+ export const locationMetadataPlugin = (options: LocationMetadataOptions = {}): Plugin => {
603
+ const {
604
+ output = 'locales/metadata.json',
605
+ includePosition = true,
606
+ } = options;
607
+
608
+ return {
609
+ name: 'location-metadata',
610
+
611
+ async onEnd(keys) {
612
+ const metadata: Record<string, any> = {};
613
+
614
+ for (const [uniqueKey, extractedKey] of keys.entries()) {
615
+ const { key, ns, locations } = extractedKey;
616
+
617
+ // Skip keys without location data
618
+ if (!locations || locations.length === 0) {
619
+ continue;
620
+ }
621
+
622
+ // Format location data
623
+ const locationData = locations.map(loc => {
624
+ if (includePosition && loc.line !== undefined) {
625
+ return `${loc.file}:${loc.line}:${loc.column ?? 0}`;
626
+ }
627
+ return loc.file;
628
+ });
629
+
630
+ // Organize metadata
631
+ const namespace = ns || 'translation';
632
+ if (!metadata[namespace]) {
633
+ metadata[namespace] = {};
634
+ }
635
+ metadata[namespace][key] = locationData;
636
+ }
637
+
638
+ // Write metadata file
639
+ await mkdir(dirname(output), { recursive: true });
640
+ await writeFile(output, JSON.stringify(metadata, null, 2), 'utf-8');
641
+
642
+ console.log(`📍 Location metadata written to ${output}`);
643
+ }
644
+ };
645
+ };
646
+ ```
647
+
648
+ **Configuration:**
649
+
650
+ ```typescript
651
+ // i18next.config.ts
652
+ import { defineConfig } from 'i18next-cli';
653
+ import { locationMetadataPlugin } from './plugins/location-metadata.mjs';
654
+
655
+ export default defineConfig({
656
+ locales: ['en', 'de'],
657
+ extract: {
658
+ input: ['src/**/*.{ts,tsx}'],
659
+ output: 'locales/{{language}}/{{namespace}}.json',
660
+ },
661
+ plugins: [
662
+ locationMetadataPlugin({
663
+ output: 'locales/metadata.json'
664
+ })
665
+ ]
666
+ });
667
+ ```
668
+
669
+ **Example Output (`locales/metadata.json`):**
670
+
671
+ ```json
672
+ {
673
+ "translation": {
674
+ "app.title": [
675
+ "src/App.tsx:12:15",
676
+ "src/components/Header.tsx:8:22"
677
+ ],
678
+ "user.greeting": [
679
+ "src/pages/Profile.tsx:45:10"
680
+ ]
681
+ },
682
+ "common": {
683
+ "button.save": [
684
+ "src/components/SaveButton.tsx:18:7",
685
+ "src/forms/UserForm.tsx:92:5"
686
+ ]
687
+ }
688
+ }
689
+ ```
690
+
584
691
  ### Dynamic Key Preservation
585
692
 
586
693
  Use `preservePatterns` to maintain dynamically generated keys:
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.21.0"),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()))};
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.22.0"),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 e=require("../parsers/scope-manager.js"),s=require("../parsers/expression-resolver.js"),r=require("../parsers/call-expression-handler.js"),o=require("../parsers/jsx-handler.js");exports.ASTVisitors=class{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;constructor(a,i,t,n,l){this.pluginContext=i,this.config=a,this.logger=t,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e.ScopeManager(a),this.expressionResolver=l??new s.ExpressionResolver(this.hooks),this.callExpressionHandler=new r.CallExpressionHandler(a,i,t,this.expressionResolver),this.jsxHandler=new o.JSXHandler(a,i,this.expressionResolver)}visit(e){this.scopeManager.reset(),this.expressionResolver.resetFileSymbols(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let s=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),s=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"TSEnumDeclaration":case"TsEnumDeclaration":case"TsEnumDecl":this.expressionResolver.captureEnumDeclaration(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const s in e){if("span"===s)continue;const r=e[s];if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if(e&&e.id&&Array.isArray(e.members)&&this.expressionResolver.captureEnumDeclaration(e),"VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const s of e.declarations)s&&"object"==typeof s&&"VariableDeclarator"===s.type&&(this.scopeManager.handleVariableDeclarator(s),this.expressionResolver.captureVariableDeclarator(s))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of r)e&&"object"==typeof e&&this.walk(e)}else r&&"object"==typeof r&&this.walk(r)}s&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}};
1
+ "use strict";var e=require("../parsers/scope-manager.js"),r=require("../parsers/expression-resolver.js"),s=require("../parsers/call-expression-handler.js"),t=require("../parsers/jsx-handler.js");exports.ASTVisitors=class{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;currentFile="";currentCode="";constructor(o,a,i,n,l){this.pluginContext=a,this.config=o,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e.ScopeManager(o),this.expressionResolver=l??new r.ExpressionResolver(this.hooks),this.callExpressionHandler=new s.CallExpressionHandler(o,a,i,this.expressionResolver,()=>this.getCurrentFile(),()=>this.getCurrentCode()),this.jsxHandler=new t.JSXHandler(o,a,this.expressionResolver,()=>this.getCurrentFile(),()=>this.getCurrentCode())}visit(e){this.scopeManager.reset(),this.expressionResolver.resetFileSymbols(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let r=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),r=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"TSEnumDeclaration":case"TsEnumDeclaration":case"TsEnumDecl":this.expressionResolver.captureEnumDeclaration(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const r in e){if("span"===r)continue;const s=e[r];if(Array.isArray(s)){for(const e of s)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if(e&&e.id&&Array.isArray(e.members)&&this.expressionResolver.captureEnumDeclaration(e),"VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const r of e.declarations)r&&"object"==typeof r&&"VariableDeclarator"===r.type&&(this.scopeManager.handleVariableDeclarator(r),this.expressionResolver.captureVariableDeclarator(r))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of s)e&&"object"==typeof e&&this.walk(e)}else s&&"object"==typeof s&&this.walk(s)}r&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}setCurrentFile(e,r){this.currentFile=e,this.currentCode=r}getCurrentFile(){return this.currentFile}getCurrentCode(){return this.currentCode}};
@@ -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 p;try{p=await r.parse(l,{syntax:g?"typescript":"ecmascript",tsx:m,decorators:!0,dynamicImport:!0,comments:!0})}catch(e){if(".ts"!==d||m)throw new i.ExtractorError("Failed to process file",t,e);try{p=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.visit(p),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
+ "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 p;try{p=await r.parse(l,{syntax:g?"typescript":"ecmascript",tsx:m,decorators:!0,dynamicImport:!0,comments:!0})}catch(e){if(".ts"!==d||m)throw new i.ExtractorError("Failed to process file",t,e);try{p=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(p),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"),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${r}${e}`),i=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),i=s(t);if(a.isPlural&&i.isPlural){const e=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const t=a.isOrdinal?o:n,s=t.indexOf(a.form),r=t.indexOf(i.form);return-1!==s&&-1!==r?s-r:a.form.localeCompare(i.form)}const l=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===l?e.localeCompare(t,void 0,{sensitivity:"case"}):l});for(const r of i)s[r]=a(e[r],t);return s}function i(e,t,r,i,l,c=[],u=new Set,f=!1){const{keySeparator:d=".",sort:p=!0,removeUnusedKeys:g=!0,primaryLanguage:y,defaultValue:h="",pluralSeparator:x="_",contextSeparator:m="_"}=r.extract,O=new Set;let S=[],v=[];try{const e=new Intl.PluralRules(i,{type:"cardinal"}),t=new Intl.PluralRules(i,{type:"ordinal"});S=e.resolvedOptions().pluralCategories,v=t.resolvedOptions().pluralCategories,S.forEach(e=>O.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>O.add(`ordinal_${e}`))}catch(e){const t=y||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),r=new Intl.PluralRules(t,{type:"ordinal"});S=s.resolvedOptions().pluralCategories,v=r.resolvedOptions().pluralCategories,S.forEach(e=>O.add(e)),r.resolvedOptions().pluralCategories.forEach(e=>O.add(`ordinal_${e}`))}const N=r.extract.preservePatterns||[],$="string"==typeof r.extract.nsSeparator?r.extract.nsSeparator:":",w=e=>{if(c.some(t=>t.test(e)))return!0;for(const t of N)if("string"==typeof t){if(t.endsWith(`${$}*`)){const e=t.slice(0,-($.length+1));if("*"===e||l&&e===l)return!0}if(t.includes($)&&l){const[s,r]=t.split($);if(s===l){if(o(r).test(e))return!0}}}return!1},b=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if((e=>{if(c.some(t=>t.test(e)))return!0;for(const e of N)if("string"==typeof e&&e.endsWith(`${$}*`)){const t=e.slice(0,-($.length+1));if("*"===t||l&&t===l)return!0}return!1})(e))return!1;if(!t)return!0;const r=e.split(x);if(t&&1===r.length)return!0;if(1===S.length&&"other"===S[0]&&1===r.length)return!0;if(s&&r.includes("ordinal")){const e=r[r.length-1];return O.has(`ordinal_${e}`)}if(t){const e=r[r.length-1];return O.has(e)}return!0}),j=new Set;for(const e of b)if(e.isExpandedPlural){const t=String(e.key).split(x);t.length>=3&&"ordinal"===t[t.length-2]?j.add(t.slice(0,-2).join(x)):j.add(t.slice(0,-1).join(x))}let P=g?{}:JSON.parse(JSON.stringify(t));const k=s.getNestedKeys(t,d??".");for(const e of k)if(w(e)){const r=s.getNestedValue(t,e,d??".");s.setNestedValue(P,e,r,d??".")}if(g){const e=s.getNestedKeys(t,d??".");for(const r of e){const e=r.split(x);if("zero"===e[e.length-1]){const n=e.slice(0,-1).join(x);if(b.some(({key:e})=>e.split(x).slice(0,-1).join(x)===n)){const e=s.getNestedValue(t,r,d??".");s.setNestedValue(P,r,e,d??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:a,hasCount:c,isExpandedPlural:p,isOrdinal:g}of b){if(c&&!p){const t=String(e).split(x);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(x):t.length>=2&&(s=t.slice(0,-1).join(x)),j.has(s))continue}if(c&&!p){if(1===String(e).split(x).length&&i!==y){const a=e;if(j.has(a));else{const e=g?v:S;for(const c of e){const e=g?`${a}${x}ordinal${x}${c}`:`${a}${x}${c}`,u=s.getNestedValue(t,e,d??".");if(void 0===u){let t;t="string"==typeof o?o:n.resolveDefaultValue(h,String(a),l||r?.extract?.defaultNS||"translation",i,o),s.setNestedValue(P,e,t,d??".")}else s.setNestedValue(P,e,u,d??".")}}continue}}const O=s.getNestedValue(t,e,d??"."),N=!1===d||!b.some(t=>t.key!==e&&t.key.startsWith(`${e}${d}`)),$="object"==typeof O&&null!==O&&(u.has(e)||!o||o===e),w="object"==typeof O&&null!==O&&N&&!u.has(e)&&!$;if($){s.setNestedValue(P,e,O,d??".");continue}let k;if(void 0===O||w)if(i===y)if(f){const t=o&&(o===e||e!==o&&(e.startsWith(o+x)||e.startsWith(o+m)));k=o&&!t?o:n.resolveDefaultValue(h,e,l||r?.extract?.defaultNS||"translation",i,o)}else k=o||e;else k=n.resolveDefaultValue(h,e,l||r?.extract?.defaultNS||"translation",i,o);else if(i===y&&f){const t=o&&(o===e||e!==o&&(e.startsWith(o+x)||e.startsWith(o+m)));k=(e.includes(x)||e.includes(m))&&!a?O:o&&!t?o:O}else k=O;s.setNestedValue(P,e,k,d??".")}if(!0===p)return a(P,r);if("function"==typeof p){const e={},t=Object.keys(P),s=new Map;for(const e of b){const t=!1===d?e.key:e.key.split(d)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof p){const r=s.get(e),n=s.get(t);if(r&&n)return p(r,n)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=a(P[s],r);P=e}return P}exports.getTranslations=async function(s,n,a,{syncPrimaryWithDefaults:l=!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 n)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=[],y=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=r.getOutputPath(a.extract.output,s),c=e.resolve(process.cwd(),o),y=await r.loadTranslationFile(c)||{},h=Object.keys(y),x=!1!==a.extract.defaultNS&&h.some(e=>{const t=y[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...p.keys(),...h]):new Set([...p.keys(),d]);for(const e of x){const r=p.get(e)||[];if(e===d){const e=i(r,y,a,s,void 0,f,n,l);Object.assign(t,e)}else{const o=y[e]||{};t[e]=i(r,o,a,s,e,f,n,l)}}const m=JSON.stringify(y,null,u),O=JSON.stringify(t,null,u);g.push({path:c,updated:O!==m,newTranslations:t,existingTranslations:y})}else{const o=new Set(p.keys()),c=r.getOutputPath(a.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});for(const t of d)o.add(e.basename(t,e.extname(t)));for(const t of o){const o=p.get(t)||[],c=r.getOutputPath(a.extract.output,s,t),d=e.resolve(process.cwd(),c),y=await r.loadTranslationFile(d)||{},h=i(o,y,a,s,t,f,n,l),x=JSON.stringify(y,null,u),m=JSON.stringify(h,null,u);g.push({path:d,updated:m!==x,newTranslations:h,existingTranslations:y})}}}return g};
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){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},n=t?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],o=r.map(e=>`ordinal${n}${e}`),i=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of o)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of r)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},a=s(e),i=s(t);if(a.isPlural&&i.isPlural){const e=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const t=a.isOrdinal?o:r,s=t.indexOf(a.form),n=t.indexOf(i.form);return-1!==s&&-1!==n?s-n:a.form.localeCompare(i.form)}const l=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===l?e.localeCompare(t,void 0,{sensitivity:"case"}):l});for(const n of i)s[n]=a(e[n],t);return s}function i(e,t,n,i,l,c=[],u=new Set,f=!1){const{keySeparator:d=".",sort:p=!0,removeUnusedKeys:g=!0,primaryLanguage:y,defaultValue:h="",pluralSeparator:x="_",contextSeparator:m="_"}=n.extract,O=new Set;let S=[],v=[];try{const e=new Intl.PluralRules(i,{type:"cardinal"}),t=new Intl.PluralRules(i,{type:"ordinal"});S=e.resolvedOptions().pluralCategories,v=t.resolvedOptions().pluralCategories,S.forEach(e=>O.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>O.add(`ordinal_${e}`))}catch(e){const t=y||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});S=s.resolvedOptions().pluralCategories,v=n.resolvedOptions().pluralCategories,S.forEach(e=>O.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>O.add(`ordinal_${e}`))}const N=n.extract.preservePatterns||[],$="string"==typeof n.extract.nsSeparator?n.extract.nsSeparator:":",w=e=>{if(c.some(t=>t.test(e)))return!0;for(const t of N)if("string"==typeof t){if(t.endsWith(`${$}*`)){const e=t.slice(0,-($.length+1));if("*"===e||l&&e===l)return!0}if(t.includes($)&&l){const[s,n]=t.split($);if(s===l){if(o(n).test(e))return!0}}}return!1},b=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if((e=>{if(c.some(t=>t.test(e)))return!0;for(const e of N)if("string"==typeof e&&e.endsWith(`${$}*`)){const t=e.slice(0,-($.length+1));if("*"===t||l&&t===l)return!0}return!1})(e))return!1;if(!t)return!0;const n=e.split(x);if(t&&1===n.length)return!0;if(1===S.length&&"other"===S[0]&&1===n.length)return!0;if(s&&n.includes("ordinal")){const e=n[n.length-1];return O.has(`ordinal_${e}`)}if(t){const e=n[n.length-1];return O.has(e)}return!0}),j=new Set;for(const e of b)if(e.isExpandedPlural){const t=String(e.key).split(x);t.length>=3&&"ordinal"===t[t.length-2]?j.add(t.slice(0,-2).join(x)):j.add(t.slice(0,-1).join(x))}let P=g?{}:JSON.parse(JSON.stringify(t));const k=s.getNestedKeys(t,d??".");for(const e of k)if(w(e)){const n=s.getNestedValue(t,e,d??".");s.setNestedValue(P,e,n,d??".")}if(g){const e=s.getNestedKeys(t,d??".");for(const n of e){const e=n.split(x);if("zero"===e[e.length-1]){const r=e.slice(0,-1).join(x);if(b.some(({key:e})=>e.split(x).slice(0,-1).join(x)===r)){const e=s.getNestedValue(t,n,d??".");s.setNestedValue(P,n,e,d??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:a,hasCount:c,isExpandedPlural:p,isOrdinal:g}of b){if(c&&!p){const t=String(e).split(x);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(x):t.length>=2&&(s=t.slice(0,-1).join(x)),j.has(s))continue}if(c&&!p){if(1===String(e).split(x).length&&i!==y){const a=e;if(j.has(a));else{const e=g?v:S;for(const c of e){const e=g?`${a}${x}ordinal${x}${c}`:`${a}${x}${c}`,u=s.getNestedValue(t,e,d??".");if(void 0===u){let t;t="string"==typeof o?o:r.resolveDefaultValue(h,String(a),l||n?.extract?.defaultNS||"translation",i,o),s.setNestedValue(P,e,t,d??".")}else s.setNestedValue(P,e,u,d??".")}}continue}}const O=s.getNestedValue(t,e,d??"."),N=!1===d||!b.some(t=>t.key!==e&&t.key.startsWith(`${e}${d}`)),w="object"==typeof O&&null!==O&&(u.has(e)||!o||o===e),k="object"==typeof O&&null!==O&&N&&!u.has(e)&&!w;if(w){s.setNestedValue(P,e,O,d??".");continue}let V;if(void 0===O||k)if(i===y)if(f){const t=o&&(o===e||o.includes($)||e!==o&&(e.startsWith(o+x)||e.startsWith(o+m)));V=o&&!t?o:r.resolveDefaultValue(h,e,l||n?.extract?.defaultNS||"translation",i,o)}else V=o||e;else V=r.resolveDefaultValue(h,e,l||n?.extract?.defaultNS||"translation",i,o);else if(i===y&&f){const t=o&&(o===e||o.includes($)||e!==o&&(e.startsWith(o+x)||e.startsWith(o+m)));V=(e.includes(x)||e.includes(m))&&!a?O:o&&!t?o:O}else V=O;s.setNestedValue(P,e,V,d??".")}if(!0===p)return a(P,n);if("function"==typeof p){const e={},t=Object.keys(P),s=new Map;for(const e of b){const t=!1===d?e.key:e.key.split(d)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof p){const n=s.get(e),r=s.get(t);if(n&&r)return p(n,r)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=a(P[s],n);P=e}return P}exports.getTranslations=async function(s,r,a,{syncPrimaryWithDefaults:l=!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=[],y=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),y=await n.loadTranslationFile(c)||{},h=Object.keys(y),x=!1!==a.extract.defaultNS&&h.some(e=>{const t=y[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...p.keys(),...h]):new Set([...p.keys(),d]);for(const e of x){const n=p.get(e)||[];if(e===d){const e=i(n,y,a,s,void 0,f,r,l);Object.assign(t,e)}else{const o=y[e]||{};t[e]=i(n,o,a,s,e,f,r,l)}}const m=JSON.stringify(y,null,u),O=JSON.stringify(t,null,u);g.push({path:c,updated:O!==m,newTranslations:t,existingTranslations:y})}else{const o=new Set(p.keys()),c=n.getOutputPath(a.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});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),y=await n.loadTranslationFile(d)||{},h=i(o,y,a,s,t,f,r,l),x=JSON.stringify(y,null,u),m=JSON.stringify(h,null,u);g.push({path:d,updated:m!==x,newTranslations:h,existingTranslations:y})}}}return g};
@@ -1 +1 @@
1
- "use strict";var e=require("./ast-utils.js");exports.CallExpressionHandler=class{pluginContext;config;logger;expressionResolver;objectKeys=new Set;constructor(e,t,r,n){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n}handleCallExpression(t,r){const n=this.getFunctionName(t.callee);if(!n)return;const s=r(n),o=this.config.extract.functions||["t","*.t"];let i=void 0!==s;if(!i)for(const e of o)if(e.startsWith("*.")){if(n.endsWith(e.substring(1))){i=!0;break}}else if(e===n){i=!0;break}if(!i||0===t.arguments.length)return;const{keysToProcess:l,isSelectorAPI:a}=this.handleCallExpressionArgument(t,0);if(0===l.length)return;let u=!1;const p=this.config.extract.pluralSeparator??"_";for(let e=0;e<l.length;e++)l[e].endsWith(`${p}ordinal`)&&(u=!0,l[e]=l[e].slice(0,-8));let f,c;if(t.arguments.length>1){const r=t.arguments[1].expression;"ObjectExpression"===r.type?c=r:"StringLiteral"===r.type?f=r.value:"TemplateLiteral"===r.type&&e.isSimpleTemplateLiteral(r)&&(f=r.quasis[0].cooked)}if(t.arguments.length>2){const e=t.arguments[2].expression;"ObjectExpression"===e.type&&(c=e)}const y=c?e.getObjectPropValue(c,"defaultValue"):void 0,g="string"==typeof y?y:f,h=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},d="string"==typeof g||h(c),x=h(c),k=Boolean(x||"string"==typeof g&&!("string"==typeof(v=g)&&/{{\s*count\s*}}/.test(v)));var v;for(let t=0;t<l.length;t++){let r,n=l[t];if(c){const t=e.getObjectPropValue(c,"ns");"string"==typeof t&&(r=t)}const o=this.config.extract.nsSeparator??":";if(!r&&o&&n.includes(o)){const e=n.split(o);if(r=e.shift(),n=e.join(o),!n||""===n.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${r}${o}'`);continue}}!r&&s?.defaultNs&&(r=s.defaultNs),r||(r=this.config.extract.defaultNS);let i=n;if(s?.keyPrefix){const e=this.config.extract.keySeparator??".";if(i=!1!==e?s.keyPrefix.endsWith(e)?`${s.keyPrefix}${n}`:`${s.keyPrefix}${e}${n}`:`${s.keyPrefix}${n}`,!1!==e){if(i.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${i}' (keyPrefix: '${s.keyPrefix}', key: '${n}')`);continue}}}const p=t===l.length-1&&g||n;if(c){const t=e.getObjectProperty(c,"context"),n=[];if("StringLiteral"===t?.value?.type||"NumericLiteral"===t?.value.type||"BooleanLiteral"===t?.value.type){const e=`${t.value.value}`,s=this.config.extract.contextSeparator??"_";""!==e&&n.push({key:`${i}${s}${e}`,ns:r,defaultValue:p,explicitDefault:d})}else if(t?.value){const e=this.expressionResolver.resolvePossibleContextStringValues(t.value),s=this.config.extract.contextSeparator??"_";e.length>0&&(e.forEach(e=>{n.push({key:`${i}${s}${e}`,ns:r,defaultValue:p,explicitDefault:d})}),n.push({key:i,ns:r,defaultValue:p,explicitDefault:d}))}const s=e=>{if(e){if("KeyValueProperty"===e.type&&e.key){if("Identifier"===e.key.type)return e.key.value;if("StringLiteral"===e.key.type)return e.key.value}return"KeyValueProperty"===e.type&&e.value&&"Identifier"===e.value.type?e.key&&"Identifier"===e.key.type?e.key.value:void 0:"ShorthandProperty"!==e.type&&"Identifier"!==e.type||!e.value?e.key&&"string"==typeof e.key?e.key:void 0:e.value}},o=(()=>{if(!c||!Array.isArray(c.properties))return!1;for(const e of c.properties){if("count"===s(e))return!0}return!1})(),l=(()=>{if(!c||!Array.isArray(c.properties))return!1;for(const e of c.properties){if("ordinal"===s(e))return!("KeyValueProperty"!==e.type||!e.value||"BooleanLiteral"!==e.value.type)&&Boolean(e.value.value)}return!1})();if(o||u){try{const e=u?"ordinal":"cardinal",t=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let s=!1;try{const r=new Intl.PluralRules(t,{type:e}).resolvedOptions().pluralCategories;1===r.length&&"other"===r[0]&&(s=!0)}catch{}if(!s){const t=new Set;for(const r of this.config.locales)try{new Intl.PluralRules(r,{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}catch{new Intl.PluralRules("en",{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}const r=Array.from(t).sort();1===r.length&&"other"===r[0]&&(s=!0)}if(s){if(n.length>0)for(const e of n)this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,hasCount:!0,isOrdinal:u});else this.pluginContext.addKey({key:i,ns:r,defaultValue:p,hasCount:!0,isOrdinal:u});continue}}catch(e){}this.config.extract.disablePlurals?n.length>0?n.forEach(this.pluginContext.addKey):this.pluginContext.addKey({key:i,ns:r,defaultValue:p,explicitDefault:d}):this.handlePluralKeys(i,r,c,l||u,g,k);continue}if(n.length>0){n.forEach(this.pluginContext.addKey);continue}!0===e.getObjectPropValue(c,"returnObjects")&&this.objectKeys.add(i)}a&&this.objectKeys.add(i),this.pluginContext.addKey({key:i,ns:r,defaultValue:p,explicitDefault:d})}}handleCallExpressionArgument(e,t){const r=e.arguments[t].expression,n=[];let s=!1;if("ArrowFunctionExpression"===r.type){const e=this.extractKeyFromSelector(r);e&&(n.push(e),s=!0)}else if("ArrayExpression"===r.type)for(const e of r.elements)e?.expression&&n.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else n.push(...this.expressionResolver.resolvePossibleKeyStringValues(r));return{keysToProcess:n.filter(e=>!!e),isSelectorAPI:s}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let r=t;const n=[];for(;"MemberExpression"===r.type;){const e=r.property;if("Identifier"===e.type)n.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;n.unshift(e.expression.value)}r=r.object}if(n.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return n.join(t)}return null}handlePluralKeys(t,r,n,s,o,i){try{const l=s?"ordinal":"cardinal",a=new Set;for(const e of this.config.locales)try{const t=new Intl.PluralRules(e,{type:l});t.resolvedOptions().pluralCategories.forEach(e=>a.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:l});t.resolvedOptions().pluralCategories.forEach(e=>a.add(e))}const u=Array.from(a).sort(),p=this.config.extract.pluralSeparator??"_",f=e.getObjectPropValue(n,"defaultValue"),c=e.getObjectPropValue(n,`defaultValue${p}other`),y=e.getObjectPropValue(n,`defaultValue${p}ordinal${p}other`),g=e.getObjectProperty(n,"context"),h=[];if(g?.value){const e=this.expressionResolver.resolvePossibleContextStringValues(g.value);if(e.length>0)if("StringLiteral"===g.value.type)for(const r of e)r.length>0&&h.push({key:t,context:r});else{for(const r of e)r.length>0&&h.push({key:t,context:r});!1!==this.config.extract?.generateBasePluralForms&&h.push({key:t})}else h.push({key:t})}else h.push({key:t});const d=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let x=!1;try{const e=new Intl.PluralRules(d,{type:l}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(x=!0)}catch{x=!1}if(x||1===u.length&&"other"===u[0]){for(const{key:t,context:l}of h){const a=e.getObjectPropValue(n,`defaultValue${p}other`);let u;u="string"==typeof a?a:"string"==typeof f?f:"string"==typeof o?o:l?`${t}_${l}`:t;const c=this.config.extract.contextSeparator??"_",y=l?`${t}${c}${l}`:t;this.pluginContext.addKey({key:y,ns:r,defaultValue:u,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(i||"string"==typeof a)})}return}for(const{key:t,context:l}of h)for(const a of u){const u=s?`defaultValue${p}ordinal${p}${a}`:`defaultValue${p}${a}`,g=e.getObjectPropValue(n,u);let h,d;if(h="string"==typeof g?g:"one"===a&&"string"==typeof f?f:"one"===a&&"string"==typeof o?o:s&&"string"==typeof y?y:s||"string"!=typeof c?"string"==typeof f?f:"string"==typeof o?o:t:c,l){const e=this.config.extract.contextSeparator??"_";d=s?`${t}${e}${l}${p}ordinal${p}${a}`:`${t}${e}${l}${p}${a}`}else d=s?`${t}${p}ordinal${p}${a}`:`${t}${p}${a}`;this.pluginContext.addKey({key:d,ns:r,defaultValue:h,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(i||"string"==typeof g||"string"==typeof c)})}}catch(s){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const i=o||e.getObjectPropValue(n,"defaultValue");this.pluginContext.addKey({key:t,ns:r,defaultValue:"string"==typeof i?i:t})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let r=e;for(;"MemberExpression"===r.type;){if("Identifier"!==r.property.type)return null;t.unshift(r.property.value),r=r.object}if("ThisExpression"===r.type)t.unshift("this");else{if("Identifier"!==r.type)return null;t.unshift(r.value)}return t.join(".")}return null}};
1
+ "use strict";var e=require("./ast-utils.js");exports.CallExpressionHandler=class{pluginContext;config;logger;expressionResolver;objectKeys=new Set;getCurrentFile;getCurrentCode;constructor(e,t,r,n,o,i){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n,this.getCurrentFile=o,this.getCurrentCode=i}getLocationFromSpan(e){if(!e||"number"!=typeof e.start)return;const t=this.getCurrentCode(),r=e.start,n=t.substring(0,r).split("\n");return{line:n.length,column:n[n.length-1].length}}handleCallExpression(t,r){const n=this.getFunctionName(t.callee);if(!n)return;const o=r(n),i=this.config.extract.functions||["t","*.t"];let s=void 0!==o;if(!s)for(const e of i)if(e.startsWith("*.")){if(n.endsWith(e.substring(1))){s=!0;break}}else if(e===n){s=!0;break}if(!s||0===t.arguments.length)return;const{keysToProcess:l,isSelectorAPI:a}=this.handleCallExpressionArgument(t,0);if(0===l.length)return;let u=!1;const p=this.config.extract.pluralSeparator??"_";for(let e=0;e<l.length;e++)l[e].endsWith(`${p}ordinal`)&&(u=!0,l[e]=l[e].slice(0,-8));let c,f;if(t.arguments.length>1){const r=t.arguments[1].expression;"ObjectExpression"===r.type?f=r:"StringLiteral"===r.type?c=r.value:"TemplateLiteral"===r.type&&e.isSimpleTemplateLiteral(r)&&(c=r.quasis[0].cooked)}if(t.arguments.length>2){const e=t.arguments[2].expression;"ObjectExpression"===e.type&&(f=e)}const y=f?e.getObjectPropValue(f,"defaultValue"):void 0,g="string"==typeof y?y:c,h=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},d="string"==typeof g||h(f),x=h(f),k=Boolean(x||"string"==typeof g&&!("string"==typeof(v=g)&&/{{\s*count\s*}}/.test(v)));var v;for(let r=0;r<l.length;r++){let n,i=l[r];if(f){const t=e.getObjectPropValue(f,"ns");"string"==typeof t&&(n=t)}const s=this.config.extract.nsSeparator??":";if(!n&&s&&i.includes(s)){const e=i.split(s);if(n=e.shift(),i=e.join(s),!i||""===i.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${n}${s}'`);continue}}!n&&o?.defaultNs&&(n=o.defaultNs),n||(n=this.config.extract.defaultNS);let p=i;if(o?.keyPrefix){const e=this.config.extract.keySeparator??".";if(p=!1!==e?o.keyPrefix.endsWith(e)?`${o.keyPrefix}${i}`:`${o.keyPrefix}${e}${i}`:`${o.keyPrefix}${i}`,!1!==e){if(p.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${p}' (keyPrefix: '${o.keyPrefix}', key: '${i}')`);continue}}}const c=r===l.length-1&&g||i;if(f){const t=e.getObjectProperty(f,"context"),r=[];if("StringLiteral"===t?.value?.type||"NumericLiteral"===t?.value.type||"BooleanLiteral"===t?.value.type){const e=`${t.value.value}`,o=this.config.extract.contextSeparator??"_";""!==e&&r.push({key:`${p}${o}${e}`,ns:n,defaultValue:c,explicitDefault:d})}else if(t?.value){const e=this.expressionResolver.resolvePossibleContextStringValues(t.value),o=this.config.extract.contextSeparator??"_";e.length>0&&(e.forEach(e=>{r.push({key:`${p}${o}${e}`,ns:n,defaultValue:c,explicitDefault:d})}),r.push({key:p,ns:n,defaultValue:c,explicitDefault:d}))}const o=e=>{if(e){if("KeyValueProperty"===e.type&&e.key){if("Identifier"===e.key.type)return e.key.value;if("StringLiteral"===e.key.type)return e.key.value}return"KeyValueProperty"===e.type&&e.value&&"Identifier"===e.value.type?e.key&&"Identifier"===e.key.type?e.key.value:void 0:"ShorthandProperty"!==e.type&&"Identifier"!==e.type||!e.value?e.key&&"string"==typeof e.key?e.key:void 0:e.value}},i=(()=>{if(!f||!Array.isArray(f.properties))return!1;for(const e of f.properties){if("count"===o(e))return!0}return!1})(),s=(()=>{if(!f||!Array.isArray(f.properties))return!1;for(const e of f.properties){if("ordinal"===o(e))return!("KeyValueProperty"!==e.type||!e.value||"BooleanLiteral"!==e.value.type)&&Boolean(e.value.value)}return!1})();if(i||u){try{const e=u?"ordinal":"cardinal",t=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let o=!1;try{const r=new Intl.PluralRules(t,{type:e}).resolvedOptions().pluralCategories;1===r.length&&"other"===r[0]&&(o=!0)}catch{}if(!o){const t=new Set;for(const r of this.config.locales)try{new Intl.PluralRules(r,{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}catch{new Intl.PluralRules("en",{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}const r=Array.from(t).sort();1===r.length&&"other"===r[0]&&(o=!0)}if(o){if(r.length>0)for(const e of r)this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,hasCount:!0,isOrdinal:u});else this.pluginContext.addKey({key:p,ns:n,defaultValue:c,hasCount:!0,isOrdinal:u});continue}}catch(e){}this.config.extract.disablePlurals?r.length>0?r.forEach(this.pluginContext.addKey):this.pluginContext.addKey({key:p,ns:n,defaultValue:c,explicitDefault:d}):this.handlePluralKeys(p,n,f,s||u,g,k);continue}if(r.length>0){r.forEach(this.pluginContext.addKey);continue}!0===e.getObjectPropValue(f,"returnObjects")&&this.objectKeys.add(p)}a&&this.objectKeys.add(p);{const e=t.span?this.getLocationFromSpan(t.span):void 0;this.pluginContext.addKey({key:p,ns:n,defaultValue:c,explicitDefault:d,locations:e?[{file:this.getCurrentFile(),line:e.line,column:e.column}]:void 0})}}}handleCallExpressionArgument(e,t){const r=e.arguments[t].expression,n=[];let o=!1;if("ArrowFunctionExpression"===r.type){const e=this.extractKeyFromSelector(r);e&&(n.push(e),o=!0)}else if("ArrayExpression"===r.type)for(const e of r.elements)e?.expression&&n.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else n.push(...this.expressionResolver.resolvePossibleKeyStringValues(r));return{keysToProcess:n.filter(e=>!!e),isSelectorAPI:o}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let r=t;const n=[];for(;"MemberExpression"===r.type;){const e=r.property;if("Identifier"===e.type)n.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;n.unshift(e.expression.value)}r=r.object}if(n.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return n.join(t)}return null}handlePluralKeys(t,r,n,o,i,s){try{const l=o?"ordinal":"cardinal",a=new Set;for(const e of this.config.locales)try{const t=new Intl.PluralRules(e,{type:l});t.resolvedOptions().pluralCategories.forEach(e=>a.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:l});t.resolvedOptions().pluralCategories.forEach(e=>a.add(e))}const u=Array.from(a).sort(),p=this.config.extract.pluralSeparator??"_",c=e.getObjectPropValue(n,"defaultValue"),f=e.getObjectPropValue(n,`defaultValue${p}other`),y=e.getObjectPropValue(n,`defaultValue${p}ordinal${p}other`),g=e.getObjectProperty(n,"context"),h=[];if(g?.value){const e=this.expressionResolver.resolvePossibleContextStringValues(g.value);if(e.length>0)if("StringLiteral"===g.value.type)for(const r of e)r.length>0&&h.push({key:t,context:r});else{for(const r of e)r.length>0&&h.push({key:t,context:r});!1!==this.config.extract?.generateBasePluralForms&&h.push({key:t})}else h.push({key:t})}else h.push({key:t});const d=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let x=!1;try{const e=new Intl.PluralRules(d,{type:l}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(x=!0)}catch{x=!1}if(x||1===u.length&&"other"===u[0]){for(const{key:t,context:l}of h){const a=e.getObjectPropValue(n,`defaultValue${p}other`);let u;u="string"==typeof a?a:"string"==typeof c?c:"string"==typeof i?i:l?`${t}_${l}`:t;const f=this.config.extract.contextSeparator??"_",y=l?`${t}${f}${l}`:t;this.pluginContext.addKey({key:y,ns:r,defaultValue:u,hasCount:!0,isOrdinal:o,explicitDefault:Boolean(s||"string"==typeof a)})}return}for(const{key:t,context:l}of h)for(const a of u){const u=o?`defaultValue${p}ordinal${p}${a}`:`defaultValue${p}${a}`,g=e.getObjectPropValue(n,u);let h,d;if(h="string"==typeof g?g:"one"===a&&"string"==typeof c?c:"one"===a&&"string"==typeof i?i:o&&"string"==typeof y?y:o||"string"!=typeof f?"string"==typeof c?c:"string"==typeof i?i:t:f,l){const e=this.config.extract.contextSeparator??"_";d=o?`${t}${e}${l}${p}ordinal${p}${a}`:`${t}${e}${l}${p}${a}`}else d=o?`${t}${p}ordinal${p}${a}`:`${t}${p}${a}`;this.pluginContext.addKey({key:d,ns:r,defaultValue:h,hasCount:!0,isOrdinal:o,explicitDefault:Boolean(s||"string"==typeof g||"string"==typeof f)})}}catch(o){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=i||e.getObjectPropValue(n,"defaultValue");this.pluginContext.addKey({key:t,ns:r,defaultValue:"string"==typeof s?s:t})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let r=e;for(;"MemberExpression"===r.type;){if("Identifier"!==r.property.type)return null;t.unshift(r.property.value),r=r.object}if("ThisExpression"===r.type)t.unshift("this");else{if("Identifier"!==r.type)return null;t.unshift(r.value)}return t.join(".")}return null}};
@@ -1 +1 @@
1
- "use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.JSXHandler=class{config;pluginContext;expressionResolver;constructor(e,t,n){this.config=e,this.pluginContext=t,this.expressionResolver=n}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e.extractFromTransComponent(t,this.config),a=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);a.push(...e)}else a.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:l,defaultValue:o,hasCount:r,isOrdinal:u,serializedChildren:f}=s;if(s.ns){const{ns:t}=s;e=a.map(e=>({key:e,ns:t,defaultValue:o||f,hasCount:r,isOrdinal:u}))}else{e=a.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:o||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,a=this.expressionResolver.resolvePossibleContextStringValues(i),o=this.config.extract.contextSeparator??"_";if(a.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l));for(const t of a)for(const n of e){const e=`${n.key}${o}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,l,n.explicitDefault)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:a,defaultValue:i}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:a,defaultValue:i});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}}}generatePluralKeysForTrans(e,n,s,a,i,l){try{const o=a?"ordinal":"cardinal",r=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:o}).resolvedOptions().pluralCategories,u=this.config.extract.pluralSeparator??"_";let f,d;if(i&&(f=t.getObjectPropValue(i,`defaultValue${u}other`),d=t.getObjectPropValue(i,`defaultValue${u}ordinal${u}other`)),1===r.length&&"other"===r[0]){const o=i?t.getObjectPropValue(i,`defaultValue${u}other`):void 0,r="string"==typeof o?o:"string"==typeof n?n:e;return void this.pluginContext.addKey({key:e,ns:s,defaultValue:r,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof o||"string"==typeof f)})}for(const o of r){const r=a?`defaultValue${u}ordinal${u}${o}`:`defaultValue${u}${o}`,p=i?t.getObjectPropValue(i,r):void 0;let c;c="string"==typeof p?p:"one"===o&&"string"==typeof n?n:a&&"string"==typeof d?d:a||"string"!=typeof f?"string"==typeof n?n:e:f;const y=a?`${e}${u}ordinal${u}${o}`:`${e}${u}${o}`;this.pluginContext.addKey({key:y,ns:s,defaultValue:c,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof p||"string"==typeof f)})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}};
1
+ "use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.JSXHandler=class{config;pluginContext;expressionResolver;getCurrentFile;getCurrentCode;constructor(e,t,n,s,o){this.config=e,this.pluginContext=t,this.expressionResolver=n,this.getCurrentFile=s,this.getCurrentCode=o}getLocationFromSpan(e){if(!e||"number"!=typeof e.start)return;const t=this.getCurrentCode(),n=e.start,s=t.substring(0,n).split("\n");return{line:s.length,column:s[s.length-1].length}}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e.extractFromTransComponent(t,this.config),o=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);o.push(...e)}else o.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:a,defaultValue:l,hasCount:r,isOrdinal:u,serializedChildren:f}=s,c=t.span?this.getLocationFromSpan(t.span):void 0,d=c?[{file:this.getCurrentFile(),line:c.line,column:c.column}]:void 0;if(s.ns){const{ns:t}=s;e=o.map(e=>({key:e,ns:t,defaultValue:l||f,hasCount:r,isOrdinal:u,locations:d}))}else{e=o.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:l||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault,locations:d}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue,locations:t.locations})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue,locations:t.locations})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,o=this.expressionResolver.resolvePossibleContextStringValues(i),l=this.config.extract.contextSeparator??"_";if(o.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,a,void 0,e.locations));for(const t of o)for(const n of e){const e=`${n.key}${l}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,a,n.explicitDefault,n.locations)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,a,e.explicitDefault,e.locations))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:o,defaultValue:i,locations:a}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:o,defaultValue:i,locations:a});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,a,e.explicitDefault,e.locations))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}}}generatePluralKeysForTrans(e,n,s,o,i,a,l){try{const r=o?"ordinal":"cardinal",u=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:r}).resolvedOptions().pluralCategories,f=this.config.extract.pluralSeparator??"_";let c,d;if(i&&(c=t.getObjectPropValue(i,`defaultValue${f}other`),d=t.getObjectPropValue(i,`defaultValue${f}ordinal${f}other`)),1===u.length&&"other"===u[0]){const r=i?t.getObjectPropValue(i,`defaultValue${f}other`):void 0,u="string"==typeof r?r:"string"==typeof n?n:e;return void this.pluginContext.addKey({key:e,ns:s,defaultValue:u,hasCount:!0,isOrdinal:o,explicitDefault:Boolean(a||"string"==typeof r||"string"==typeof c),locations:l})}for(const r of u){const u=o?`defaultValue${f}ordinal${f}${r}`:`defaultValue${f}${r}`,p=i?t.getObjectPropValue(i,u):void 0;let g;g="string"==typeof p?p:"one"===r&&"string"==typeof n?n:o&&"string"==typeof d?d:o||"string"!=typeof c?"string"==typeof n?n:e:c;const y=o?`${e}${f}ordinal${f}${r}`:`${e}${f}${r}`;this.pluginContext.addKey({key:y,ns:s,defaultValue:g,hasCount:!0,isOrdinal:o,explicitDefault:Boolean(a||"string"==typeof p||"string"==typeof c),locations:l})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n,locations:l})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}};
@@ -1 +1 @@
1
- "use strict";exports.createPluginContext=function(t,e,a,n){return{addKey:e=>{const n=!1===e.ns?void 0:e.ns,s=n??a.extract?.defaultNS??"translation",l=void 0===n,i=`${String(s)}:${e.key}`,u=e.defaultValue??e.key,o=t.get(i);if(o){const n=o.defaultValue===o.key||o.hasCount&&o.defaultValue&&o.key.includes("_")&&o.key.startsWith(o.defaultValue),r=u===e.key;n&&!r&&t.set(i,{...e,ns:s||a.extract?.defaultNS||"translation",nsIsImplicit:l,defaultValue:u})}else t.set(i,{...e,ns:s||a.extract?.defaultNS||"translation",nsIsImplicit:l,defaultValue:u})},config:Object.freeze({...a,plugins:[...e]}),logger:n,getVarFromScope:()=>{}}},exports.initializePlugins=async function(t){for(const e of t)await(e.setup?.())};
1
+ "use strict";exports.createPluginContext=function(t,e,a,n){return{addKey:e=>{const n=!1===e.ns?void 0:e.ns,s=n??a.extract?.defaultNS??"translation",l=void 0===n,o=`${String(s)}:${e.key}`,i=e.defaultValue??e.key,u=t.get(o);if(u){const n=u.defaultValue===u.key||u.hasCount&&u.defaultValue&&u.key.includes("_")&&u.key.startsWith(u.defaultValue),c=i===e.key;e.locations&&(u.locations=[...u.locations||[],...e.locations]),n&&!c&&t.set(o,{...e,ns:s||a.extract?.defaultNS||"translation",nsIsImplicit:l,defaultValue:i,locations:u.locations})}else t.set(o,{...e,ns:s||a.extract?.defaultNS||"translation",nsIsImplicit:l,defaultValue:i})},config:Object.freeze({...a,plugins:[...e]}),logger:n,getVarFromScope:()=>{}}},exports.initializePlugins=async function(t){for(const e of t)await(e.setup?.())};
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.21.0"),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()))};
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.22.0"),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{ScopeManager as e}from"../parsers/scope-manager.js";import{ExpressionResolver as s}from"../parsers/expression-resolver.js";import{CallExpressionHandler as r}from"../parsers/call-expression-handler.js";import{JSXHandler as o}from"../parsers/jsx-handler.js";class a{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;constructor(a,t,i,n,l){this.pluginContext=t,this.config=a,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e(a),this.expressionResolver=l??new s(this.hooks),this.callExpressionHandler=new r(a,t,i,this.expressionResolver),this.jsxHandler=new o(a,t,this.expressionResolver)}visit(e){this.scopeManager.reset(),this.expressionResolver.resetFileSymbols(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let s=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),s=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"TSEnumDeclaration":case"TsEnumDeclaration":case"TsEnumDecl":this.expressionResolver.captureEnumDeclaration(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const s in e){if("span"===s)continue;const r=e[s];if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if(e&&e.id&&Array.isArray(e.members)&&this.expressionResolver.captureEnumDeclaration(e),"VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const s of e.declarations)s&&"object"==typeof s&&"VariableDeclarator"===s.type&&(this.scopeManager.handleVariableDeclarator(s),this.expressionResolver.captureVariableDeclarator(s))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of r)e&&"object"==typeof e&&this.walk(e)}else r&&"object"==typeof r&&this.walk(r)}s&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}}export{a as ASTVisitors};
1
+ import{ScopeManager as e}from"../parsers/scope-manager.js";import{ExpressionResolver as r}from"../parsers/expression-resolver.js";import{CallExpressionHandler as s}from"../parsers/call-expression-handler.js";import{JSXHandler as t}from"../parsers/jsx-handler.js";class o{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;currentFile="";currentCode="";constructor(o,a,i,n,l){this.pluginContext=a,this.config=o,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e(o),this.expressionResolver=l??new r(this.hooks),this.callExpressionHandler=new s(o,a,i,this.expressionResolver,()=>this.getCurrentFile(),()=>this.getCurrentCode()),this.jsxHandler=new t(o,a,this.expressionResolver,()=>this.getCurrentFile(),()=>this.getCurrentCode())}visit(e){this.scopeManager.reset(),this.expressionResolver.resetFileSymbols(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let r=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),r=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"TSEnumDeclaration":case"TsEnumDeclaration":case"TsEnumDecl":this.expressionResolver.captureEnumDeclaration(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const r in e){if("span"===r)continue;const s=e[r];if(Array.isArray(s)){for(const e of s)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if(e&&e.id&&Array.isArray(e.members)&&this.expressionResolver.captureEnumDeclaration(e),"VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const r of e.declarations)r&&"object"==typeof r&&"VariableDeclarator"===r.type&&(this.scopeManager.handleVariableDeclarator(r),this.expressionResolver.captureVariableDeclarator(r))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of s)e&&"object"==typeof e&&this.walk(e)}else s&&"object"==typeof s&&this.walk(s)}r&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}setCurrentFile(e,r){this.currentFile=e,this.currentCode=r}getCurrentFile(){return this.currentFile}getCurrentCode(){return this.currentCode}}export{o as ASTVisitors};
@@ -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 d;try{d=await e(l,{syntax:u?"typescript":"ecmascript",tsx:y,decorators:!0,dynamicImport:!0,comments:!0})}catch(a){if(".ts"!==m||y)throw new f("Failed to process file",t,a);try{d=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.visit(d),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
+ 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 d;try{d=await e(l,{syntax:u?"typescript":"ecmascript",tsx:y,decorators:!0,dynamicImport:!0,comments:!0})}catch(a){if(".ts"!==m||y)throw new f("Failed to process file",t,a);try{d=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(d),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){if("object"!=typeof t||null===t||Array.isArray(t))return t;const n={},r=e?.extract?.pluralSeparator??"_",s=["zero","one","two","few","many","other"],o=s.map(t=>`ordinal${r}${t}`),i=Object.keys(t).sort((t,e)=>{const n=t=>{for(const e of o)if(t.endsWith(`${r}${e}`)){return{base:t.slice(0,-(r.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of s)if(t.endsWith(`${r}${e}`)){return{base:t.slice(0,-(r.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},i=n(t),a=n(e);if(i.isPlural&&a.isPlural){const t=i.base.localeCompare(a.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(i.isOrdinal!==a.isOrdinal)return i.isOrdinal?1:-1;const e=i.isOrdinal?o:s,n=e.indexOf(i.form),r=e.indexOf(a.form);return-1!==n&&-1!==r?n-r:i.form.localeCompare(a.form)}const l=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===l?t.localeCompare(e,void 0,{sensitivity:"case"}):l});for(const r of i)n[r]=u(t[r],e);return n}function p(t,e,n,r,a,l=[],p=new Set,d=!1){const{keySeparator:g=".",sort:y=!0,removeUnusedKeys:h=!0,primaryLanguage:m,defaultValue:x="",pluralSeparator:S="_",contextSeparator:O="_"}=n.extract,$=new Set;let v=[],w=[];try{const t=new Intl.PluralRules(r,{type:"cardinal"}),e=new Intl.PluralRules(r,{type:"ordinal"});v=t.resolvedOptions().pluralCategories,w=e.resolvedOptions().pluralCategories,v.forEach(t=>$.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>$.add(`ordinal_${t}`))}catch(t){const e=m||"en",n=new Intl.PluralRules(e,{type:"cardinal"}),r=new Intl.PluralRules(e,{type:"ordinal"});v=n.resolvedOptions().pluralCategories,w=r.resolvedOptions().pluralCategories,v.forEach(t=>$.add(t)),r.resolvedOptions().pluralCategories.forEach(t=>$.add(`ordinal_${t}`))}const b=n.extract.preservePatterns||[],j="string"==typeof n.extract.nsSeparator?n.extract.nsSeparator:":",k=t=>{if(l.some(e=>e.test(t)))return!0;for(const e of b)if("string"==typeof e){if(e.endsWith(`${j}*`)){const t=e.slice(0,-(j.length+1));if("*"===t||a&&t===a)return!0}if(e.includes(j)&&a){const[n,r]=e.split(j);if(n===a){if(f(r).test(t))return!0}}}return!1},P=t.filter(({key:t,hasCount:e,isOrdinal:n})=>{if((t=>{if(l.some(e=>e.test(t)))return!0;for(const t of b)if("string"==typeof t&&t.endsWith(`${j}*`)){const e=t.slice(0,-(j.length+1));if("*"===e||a&&e===a)return!0}return!1})(t))return!1;if(!e)return!0;const r=t.split(S);if(e&&1===r.length)return!0;if(1===v.length&&"other"===v[0]&&1===r.length)return!0;if(n&&r.includes("ordinal")){const t=r[r.length-1];return $.has(`ordinal_${t}`)}if(e){const t=r[r.length-1];return $.has(t)}return!0}),C=new Set;for(const t of P)if(t.isExpandedPlural){const e=String(t.key).split(S);e.length>=3&&"ordinal"===e[e.length-2]?C.add(e.slice(0,-2).join(S)):C.add(e.slice(0,-1).join(S))}let N=h?{}:JSON.parse(JSON.stringify(e));const _=s(e,g??".");for(const t of _)if(k(t)){const n=o(e,t,g??".");i(N,t,n,g??".")}if(h){const t=s(e,g??".");for(const n of t){const t=n.split(S);if("zero"===t[t.length-1]){const r=t.slice(0,-1).join(S);if(P.some(({key:t})=>t.split(S).slice(0,-1).join(S)===r)){const t=o(e,n,g??".");i(N,n,t,g??".")}}}}for(const{key:t,defaultValue:s,explicitDefault:l,hasCount:f,isExpandedPlural:u,isOrdinal:y}of P){if(f&&!u){const e=String(t).split(S);let n=t;if(e.length>=3&&"ordinal"===e[e.length-2]?n=e.slice(0,-2).join(S):e.length>=2&&(n=e.slice(0,-1).join(S)),C.has(n))continue}if(f&&!u){if(1===String(t).split(S).length&&r!==m){const l=t;if(C.has(l));else{const t=y?w:v;for(const f of t){const t=y?`${l}${S}ordinal${S}${f}`:`${l}${S}${f}`,u=o(e,t,g??".");if(void 0===u){let e;e="string"==typeof s?s:c(x,String(l),a||n?.extract?.defaultNS||"translation",r,s),i(N,t,e,g??".")}else i(N,t,u,g??".")}}continue}}const h=o(e,t,g??"."),$=!1===g||!P.some(e=>e.key!==t&&e.key.startsWith(`${t}${g}`)),b="object"==typeof h&&null!==h&&(p.has(t)||!s||s===t),j="object"==typeof h&&null!==h&&$&&!p.has(t)&&!b;if(b){i(N,t,h,g??".");continue}let k;if(void 0===h||j)if(r===m)if(d){const e=s&&(s===t||t!==s&&(t.startsWith(s+S)||t.startsWith(s+O)));k=s&&!e?s:c(x,t,a||n?.extract?.defaultNS||"translation",r,s)}else k=s||t;else k=c(x,t,a||n?.extract?.defaultNS||"translation",r,s);else if(r===m&&d){const e=s&&(s===t||t!==s&&(t.startsWith(s+S)||t.startsWith(s+O)));k=(t.includes(S)||t.includes(O))&&!l?h:s&&!e?s:h}else k=h;i(N,t,k,g??".")}if(!0===y)return u(N,n);if("function"==typeof y){const t={},e=Object.keys(N),r=new Map;for(const t of P){const e=!1===g?t.key:t.key.split(g)[0];r.has(e)||r.set(e,t)}e.sort((t,e)=>{if("function"==typeof y){const n=r.get(t),s=r.get(e);if(n&&s)return y(n,s)}return t.localeCompare(e,void 0,{sensitivity:"base"})});for(const r of e)t[r]=u(N[r],n);N=t}return N}async function d(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||[]],d=i.extract.indentation??2;for(const t of o)u.push(`${t}.*`);const g=u.map(f),y="__no_namespace__",h=new Map;for(const t of s.values()){const e=t.nsIsImplicit&&!1===i.extract.defaultNS?y:String(t.ns??i.extract.defaultNS??"translation");h.has(e)||h.set(e,[]),h.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([...h.keys(),...u]):new Set([...h.keys(),y]);for(const t of x){const n=h.get(t)||[];if(t===y){const t=p(n,f,i,s,void 0,g,o,c);Object.assign(e,t)}else{const r=f[t]||{};e[t]=p(n,r,i,s,t,g,o,c)}}const S=JSON.stringify(f,null,d),O=JSON.stringify(e,null,d);m.push({path:r,updated:O!==S,newTranslations:e,existingTranslations:f})}else{const f=new Set(h.keys()),u=a(i.extract.output,s,"*").replace(/\\/g,"/"),y=await r(u,{ignore:x});for(const t of y)f.add(e(t,n(t)));for(const e of f){const n=h.get(e)||[],r=a(i.extract.output,s,e),f=t(process.cwd(),r),u=await l(f)||{},y=p(n,u,i,s,e,g,o,c),x=JSON.stringify(u,null,d),S=JSON.stringify(y,null,d);m.push({path:f,updated:S!==x,newTranslations:y,existingTranslations:u})}}}return m}export{d as getTranslations};
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){if("object"!=typeof t||null===t||Array.isArray(t))return t;const n={},r=e?.extract?.pluralSeparator??"_",s=["zero","one","two","few","many","other"],o=s.map(t=>`ordinal${r}${t}`),i=Object.keys(t).sort((t,e)=>{const n=t=>{for(const e of o)if(t.endsWith(`${r}${e}`)){return{base:t.slice(0,-(r.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of s)if(t.endsWith(`${r}${e}`)){return{base:t.slice(0,-(r.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},i=n(t),a=n(e);if(i.isPlural&&a.isPlural){const t=i.base.localeCompare(a.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(i.isOrdinal!==a.isOrdinal)return i.isOrdinal?1:-1;const e=i.isOrdinal?o:s,n=e.indexOf(i.form),r=e.indexOf(a.form);return-1!==n&&-1!==r?n-r:i.form.localeCompare(a.form)}const l=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===l?t.localeCompare(e,void 0,{sensitivity:"case"}):l});for(const r of i)n[r]=u(t[r],e);return n}function p(t,e,n,r,a,l=[],p=new Set,d=!1){const{keySeparator:g=".",sort:y=!0,removeUnusedKeys:h=!0,primaryLanguage:m,defaultValue:x="",pluralSeparator:S="_",contextSeparator:O="_"}=n.extract,$=new Set;let v=[],w=[];try{const t=new Intl.PluralRules(r,{type:"cardinal"}),e=new Intl.PluralRules(r,{type:"ordinal"});v=t.resolvedOptions().pluralCategories,w=e.resolvedOptions().pluralCategories,v.forEach(t=>$.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>$.add(`ordinal_${t}`))}catch(t){const e=m||"en",n=new Intl.PluralRules(e,{type:"cardinal"}),r=new Intl.PluralRules(e,{type:"ordinal"});v=n.resolvedOptions().pluralCategories,w=r.resolvedOptions().pluralCategories,v.forEach(t=>$.add(t)),r.resolvedOptions().pluralCategories.forEach(t=>$.add(`ordinal_${t}`))}const b=n.extract.preservePatterns||[],j="string"==typeof n.extract.nsSeparator?n.extract.nsSeparator:":",k=t=>{if(l.some(e=>e.test(t)))return!0;for(const e of b)if("string"==typeof e){if(e.endsWith(`${j}*`)){const t=e.slice(0,-(j.length+1));if("*"===t||a&&t===a)return!0}if(e.includes(j)&&a){const[n,r]=e.split(j);if(n===a){if(f(r).test(t))return!0}}}return!1},P=t.filter(({key:t,hasCount:e,isOrdinal:n})=>{if((t=>{if(l.some(e=>e.test(t)))return!0;for(const t of b)if("string"==typeof t&&t.endsWith(`${j}*`)){const e=t.slice(0,-(j.length+1));if("*"===e||a&&e===a)return!0}return!1})(t))return!1;if(!e)return!0;const r=t.split(S);if(e&&1===r.length)return!0;if(1===v.length&&"other"===v[0]&&1===r.length)return!0;if(n&&r.includes("ordinal")){const t=r[r.length-1];return $.has(`ordinal_${t}`)}if(e){const t=r[r.length-1];return $.has(t)}return!0}),C=new Set;for(const t of P)if(t.isExpandedPlural){const e=String(t.key).split(S);e.length>=3&&"ordinal"===e[e.length-2]?C.add(e.slice(0,-2).join(S)):C.add(e.slice(0,-1).join(S))}let N=h?{}:JSON.parse(JSON.stringify(e));const _=s(e,g??".");for(const t of _)if(k(t)){const n=o(e,t,g??".");i(N,t,n,g??".")}if(h){const t=s(e,g??".");for(const n of t){const t=n.split(S);if("zero"===t[t.length-1]){const r=t.slice(0,-1).join(S);if(P.some(({key:t})=>t.split(S).slice(0,-1).join(S)===r)){const t=o(e,n,g??".");i(N,n,t,g??".")}}}}for(const{key:t,defaultValue:s,explicitDefault:l,hasCount:f,isExpandedPlural:u,isOrdinal:y}of P){if(f&&!u){const e=String(t).split(S);let n=t;if(e.length>=3&&"ordinal"===e[e.length-2]?n=e.slice(0,-2).join(S):e.length>=2&&(n=e.slice(0,-1).join(S)),C.has(n))continue}if(f&&!u){if(1===String(t).split(S).length&&r!==m){const l=t;if(C.has(l));else{const t=y?w:v;for(const f of t){const t=y?`${l}${S}ordinal${S}${f}`:`${l}${S}${f}`,u=o(e,t,g??".");if(void 0===u){let e;e="string"==typeof s?s:c(x,String(l),a||n?.extract?.defaultNS||"translation",r,s),i(N,t,e,g??".")}else i(N,t,u,g??".")}}continue}}const h=o(e,t,g??"."),$=!1===g||!P.some(e=>e.key!==t&&e.key.startsWith(`${t}${g}`)),b="object"==typeof h&&null!==h&&(p.has(t)||!s||s===t),k="object"==typeof h&&null!==h&&$&&!p.has(t)&&!b;if(b){i(N,t,h,g??".");continue}let _;if(void 0===h||k)if(r===m)if(d){const e=s&&(s===t||s.includes(j)||t!==s&&(t.startsWith(s+S)||t.startsWith(s+O)));_=s&&!e?s:c(x,t,a||n?.extract?.defaultNS||"translation",r,s)}else _=s||t;else _=c(x,t,a||n?.extract?.defaultNS||"translation",r,s);else if(r===m&&d){const e=s&&(s===t||s.includes(j)||t!==s&&(t.startsWith(s+S)||t.startsWith(s+O)));_=(t.includes(S)||t.includes(O))&&!l?h:s&&!e?s:h}else _=h;i(N,t,_,g??".")}if(!0===y)return u(N,n);if("function"==typeof y){const t={},e=Object.keys(N),r=new Map;for(const t of P){const e=!1===g?t.key:t.key.split(g)[0];r.has(e)||r.set(e,t)}e.sort((t,e)=>{if("function"==typeof y){const n=r.get(t),s=r.get(e);if(n&&s)return y(n,s)}return t.localeCompare(e,void 0,{sensitivity:"base"})});for(const r of e)t[r]=u(N[r],n);N=t}return N}async function d(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||[]],d=i.extract.indentation??2;for(const t of o)u.push(`${t}.*`);const g=u.map(f),y="__no_namespace__",h=new Map;for(const t of s.values()){const e=t.nsIsImplicit&&!1===i.extract.defaultNS?y:String(t.ns??i.extract.defaultNS??"translation");h.has(e)||h.set(e,[]),h.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([...h.keys(),...u]):new Set([...h.keys(),y]);for(const t of x){const n=h.get(t)||[];if(t===y){const t=p(n,f,i,s,void 0,g,o,c);Object.assign(e,t)}else{const r=f[t]||{};e[t]=p(n,r,i,s,t,g,o,c)}}const S=JSON.stringify(f,null,d),O=JSON.stringify(e,null,d);m.push({path:r,updated:O!==S,newTranslations:e,existingTranslations:f})}else{const f=new Set(h.keys()),u=a(i.extract.output,s,"*").replace(/\\/g,"/"),y=await r(u,{ignore:x});for(const t of y)f.add(e(t,n(t)));for(const e of f){const n=h.get(e)||[],r=a(i.extract.output,s,e),f=t(process.cwd(),r),u=await l(f)||{},y=p(n,u,i,s,e,g,o,c),x=JSON.stringify(u,null,d),S=JSON.stringify(y,null,d);m.push({path:f,updated:S!==x,newTranslations:y,existingTranslations:u})}}}return m}export{d as getTranslations};
@@ -1 +1 @@
1
- import{isSimpleTemplateLiteral as e,getObjectPropValue as t,getObjectProperty as r}from"./ast-utils.js";class n{pluginContext;config;logger;expressionResolver;objectKeys=new Set;constructor(e,t,r,n){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n}handleCallExpression(n,s){const i=this.getFunctionName(n.callee);if(!i)return;const o=s(i),l=this.config.extract.functions||["t","*.t"];let a=void 0!==o;if(!a)for(const e of l)if(e.startsWith("*.")){if(i.endsWith(e.substring(1))){a=!0;break}}else if(e===i){a=!0;break}if(!a||0===n.arguments.length)return;const{keysToProcess:u,isSelectorAPI:f}=this.handleCallExpressionArgument(n,0);if(0===u.length)return;let p=!1;const c=this.config.extract.pluralSeparator??"_";for(let e=0;e<u.length;e++)u[e].endsWith(`${c}ordinal`)&&(p=!0,u[e]=u[e].slice(0,-8));let y,g;if(n.arguments.length>1){const t=n.arguments[1].expression;"ObjectExpression"===t.type?g=t:"StringLiteral"===t.type?y=t.value:"TemplateLiteral"===t.type&&e(t)&&(y=t.quasis[0].cooked)}if(n.arguments.length>2){const e=n.arguments[2].expression;"ObjectExpression"===e.type&&(g=e)}const h=g?t(g,"defaultValue"):void 0,d="string"==typeof h?h:y,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},k="string"==typeof d||x(g),v=x(g),$=Boolean(v||"string"==typeof d&&!("string"==typeof(m=d)&&/{{\s*count\s*}}/.test(m)));var m;for(let e=0;e<u.length;e++){let n,s=u[e];if(g){const e=t(g,"ns");"string"==typeof e&&(n=e)}const i=this.config.extract.nsSeparator??":";if(!n&&i&&s.includes(i)){const e=s.split(i);if(n=e.shift(),s=e.join(i),!s||""===s.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${n}${i}'`);continue}}!n&&o?.defaultNs&&(n=o.defaultNs),n||(n=this.config.extract.defaultNS);let l=s;if(o?.keyPrefix){const e=this.config.extract.keySeparator??".";if(l=!1!==e?o.keyPrefix.endsWith(e)?`${o.keyPrefix}${s}`:`${o.keyPrefix}${e}${s}`:`${o.keyPrefix}${s}`,!1!==e){if(l.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${l}' (keyPrefix: '${o.keyPrefix}', key: '${s}')`);continue}}}const a=e===u.length-1&&d||s;if(g){const e=r(g,"context"),s=[];if("StringLiteral"===e?.value?.type||"NumericLiteral"===e?.value.type||"BooleanLiteral"===e?.value.type){const t=`${e.value.value}`,r=this.config.extract.contextSeparator??"_";""!==t&&s.push({key:`${l}${r}${t}`,ns:n,defaultValue:a,explicitDefault:k})}else if(e?.value){const t=this.expressionResolver.resolvePossibleContextStringValues(e.value),r=this.config.extract.contextSeparator??"_";t.length>0&&(t.forEach(e=>{s.push({key:`${l}${r}${e}`,ns:n,defaultValue:a,explicitDefault:k})}),s.push({key:l,ns:n,defaultValue:a,explicitDefault:k}))}const i=e=>{if(e){if("KeyValueProperty"===e.type&&e.key){if("Identifier"===e.key.type)return e.key.value;if("StringLiteral"===e.key.type)return e.key.value}return"KeyValueProperty"===e.type&&e.value&&"Identifier"===e.value.type?e.key&&"Identifier"===e.key.type?e.key.value:void 0:"ShorthandProperty"!==e.type&&"Identifier"!==e.type||!e.value?e.key&&"string"==typeof e.key?e.key:void 0:e.value}},o=(()=>{if(!g||!Array.isArray(g.properties))return!1;for(const e of g.properties){if("count"===i(e))return!0}return!1})(),u=(()=>{if(!g||!Array.isArray(g.properties))return!1;for(const e of g.properties){if("ordinal"===i(e))return!("KeyValueProperty"!==e.type||!e.value||"BooleanLiteral"!==e.value.type)&&Boolean(e.value.value)}return!1})();if(o||p){try{const e=p?"ordinal":"cardinal",t=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let r=!1;try{const n=new Intl.PluralRules(t,{type:e}).resolvedOptions().pluralCategories;1===n.length&&"other"===n[0]&&(r=!0)}catch{}if(!r){const t=new Set;for(const r of this.config.locales)try{new Intl.PluralRules(r,{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}catch{new Intl.PluralRules("en",{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}const n=Array.from(t).sort();1===n.length&&"other"===n[0]&&(r=!0)}if(r){if(s.length>0)for(const e of s)this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,hasCount:!0,isOrdinal:p});else this.pluginContext.addKey({key:l,ns:n,defaultValue:a,hasCount:!0,isOrdinal:p});continue}}catch(e){}this.config.extract.disablePlurals?s.length>0?s.forEach(this.pluginContext.addKey):this.pluginContext.addKey({key:l,ns:n,defaultValue:a,explicitDefault:k}):this.handlePluralKeys(l,n,g,u||p,d,$);continue}if(s.length>0){s.forEach(this.pluginContext.addKey);continue}!0===t(g,"returnObjects")&&this.objectKeys.add(l)}f&&this.objectKeys.add(l),this.pluginContext.addKey({key:l,ns:n,defaultValue:a,explicitDefault:k})}}handleCallExpressionArgument(e,t){const r=e.arguments[t].expression,n=[];let s=!1;if("ArrowFunctionExpression"===r.type){const e=this.extractKeyFromSelector(r);e&&(n.push(e),s=!0)}else if("ArrayExpression"===r.type)for(const e of r.elements)e?.expression&&n.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else n.push(...this.expressionResolver.resolvePossibleKeyStringValues(r));return{keysToProcess:n.filter(e=>!!e),isSelectorAPI:s}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let r=t;const n=[];for(;"MemberExpression"===r.type;){const e=r.property;if("Identifier"===e.type)n.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;n.unshift(e.expression.value)}r=r.object}if(n.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return n.join(t)}return null}handlePluralKeys(e,n,s,i,o,l){try{const a=i?"ordinal":"cardinal",u=new Set;for(const e of this.config.locales)try{const t=new Intl.PluralRules(e,{type:a});t.resolvedOptions().pluralCategories.forEach(e=>u.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:a});t.resolvedOptions().pluralCategories.forEach(e=>u.add(e))}const f=Array.from(u).sort(),p=this.config.extract.pluralSeparator??"_",c=t(s,"defaultValue"),y=t(s,`defaultValue${p}other`),g=t(s,`defaultValue${p}ordinal${p}other`),h=r(s,"context"),d=[];if(h?.value){const t=this.expressionResolver.resolvePossibleContextStringValues(h.value);if(t.length>0)if("StringLiteral"===h.value.type)for(const r of t)r.length>0&&d.push({key:e,context:r});else{for(const r of t)r.length>0&&d.push({key:e,context:r});!1!==this.config.extract?.generateBasePluralForms&&d.push({key:e})}else d.push({key:e})}else d.push({key:e});const x=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let k=!1;try{const e=new Intl.PluralRules(x,{type:a}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(k=!0)}catch{k=!1}if(k||1===f.length&&"other"===f[0]){for(const{key:e,context:r}of d){const a=t(s,`defaultValue${p}other`);let u;u="string"==typeof a?a:"string"==typeof c?c:"string"==typeof o?o:r?`${e}_${r}`:e;const f=this.config.extract.contextSeparator??"_",y=r?`${e}${f}${r}`:e;this.pluginContext.addKey({key:y,ns:n,defaultValue:u,hasCount:!0,isOrdinal:i,explicitDefault:Boolean(l||"string"==typeof a)})}return}for(const{key:e,context:r}of d)for(const a of f){const u=t(s,i?`defaultValue${p}ordinal${p}${a}`:`defaultValue${p}${a}`);let f,h;if(f="string"==typeof u?u:"one"===a&&"string"==typeof c?c:"one"===a&&"string"==typeof o?o:i&&"string"==typeof g?g:i||"string"!=typeof y?"string"==typeof c?c:"string"==typeof o?o:e:y,r){const t=this.config.extract.contextSeparator??"_";h=i?`${e}${t}${r}${p}ordinal${p}${a}`:`${e}${t}${r}${p}${a}`}else h=i?`${e}${p}ordinal${p}${a}`:`${e}${p}${a}`;this.pluginContext.addKey({key:h,ns:n,defaultValue:f,hasCount:!0,isOrdinal:i,explicitDefault:Boolean(l||"string"==typeof u||"string"==typeof y)})}}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const i=o||t(s,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof i?i:e})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let r=e;for(;"MemberExpression"===r.type;){if("Identifier"!==r.property.type)return null;t.unshift(r.property.value),r=r.object}if("ThisExpression"===r.type)t.unshift("this");else{if("Identifier"!==r.type)return null;t.unshift(r.value)}return t.join(".")}return null}}export{n as CallExpressionHandler};
1
+ import{isSimpleTemplateLiteral as e,getObjectPropValue as t,getObjectProperty as r}from"./ast-utils.js";class n{pluginContext;config;logger;expressionResolver;objectKeys=new Set;getCurrentFile;getCurrentCode;constructor(e,t,r,n,i,s){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n,this.getCurrentFile=i,this.getCurrentCode=s}getLocationFromSpan(e){if(!e||"number"!=typeof e.start)return;const t=this.getCurrentCode(),r=e.start,n=t.substring(0,r).split("\n");return{line:n.length,column:n[n.length-1].length}}handleCallExpression(n,i){const s=this.getFunctionName(n.callee);if(!s)return;const o=i(s),l=this.config.extract.functions||["t","*.t"];let a=void 0!==o;if(!a)for(const e of l)if(e.startsWith("*.")){if(s.endsWith(e.substring(1))){a=!0;break}}else if(e===s){a=!0;break}if(!a||0===n.arguments.length)return;const{keysToProcess:u,isSelectorAPI:f}=this.handleCallExpressionArgument(n,0);if(0===u.length)return;let p=!1;const c=this.config.extract.pluralSeparator??"_";for(let e=0;e<u.length;e++)u[e].endsWith(`${c}ordinal`)&&(p=!0,u[e]=u[e].slice(0,-8));let y,g;if(n.arguments.length>1){const t=n.arguments[1].expression;"ObjectExpression"===t.type?g=t:"StringLiteral"===t.type?y=t.value:"TemplateLiteral"===t.type&&e(t)&&(y=t.quasis[0].cooked)}if(n.arguments.length>2){const e=n.arguments[2].expression;"ObjectExpression"===e.type&&(g=e)}const h=g?t(g,"defaultValue"):void 0,d="string"==typeof h?h:y,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},k="string"==typeof d||x(g),v=x(g),$=Boolean(v||"string"==typeof d&&!("string"==typeof(m=d)&&/{{\s*count\s*}}/.test(m)));var m;for(let e=0;e<u.length;e++){let i,s=u[e];if(g){const e=t(g,"ns");"string"==typeof e&&(i=e)}const l=this.config.extract.nsSeparator??":";if(!i&&l&&s.includes(l)){const e=s.split(l);if(i=e.shift(),s=e.join(l),!s||""===s.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${i}${l}'`);continue}}!i&&o?.defaultNs&&(i=o.defaultNs),i||(i=this.config.extract.defaultNS);let a=s;if(o?.keyPrefix){const e=this.config.extract.keySeparator??".";if(a=!1!==e?o.keyPrefix.endsWith(e)?`${o.keyPrefix}${s}`:`${o.keyPrefix}${e}${s}`:`${o.keyPrefix}${s}`,!1!==e){if(a.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${a}' (keyPrefix: '${o.keyPrefix}', key: '${s}')`);continue}}}const c=e===u.length-1&&d||s;if(g){const e=r(g,"context"),n=[];if("StringLiteral"===e?.value?.type||"NumericLiteral"===e?.value.type||"BooleanLiteral"===e?.value.type){const t=`${e.value.value}`,r=this.config.extract.contextSeparator??"_";""!==t&&n.push({key:`${a}${r}${t}`,ns:i,defaultValue:c,explicitDefault:k})}else if(e?.value){const t=this.expressionResolver.resolvePossibleContextStringValues(e.value),r=this.config.extract.contextSeparator??"_";t.length>0&&(t.forEach(e=>{n.push({key:`${a}${r}${e}`,ns:i,defaultValue:c,explicitDefault:k})}),n.push({key:a,ns:i,defaultValue:c,explicitDefault:k}))}const s=e=>{if(e){if("KeyValueProperty"===e.type&&e.key){if("Identifier"===e.key.type)return e.key.value;if("StringLiteral"===e.key.type)return e.key.value}return"KeyValueProperty"===e.type&&e.value&&"Identifier"===e.value.type?e.key&&"Identifier"===e.key.type?e.key.value:void 0:"ShorthandProperty"!==e.type&&"Identifier"!==e.type||!e.value?e.key&&"string"==typeof e.key?e.key:void 0:e.value}},o=(()=>{if(!g||!Array.isArray(g.properties))return!1;for(const e of g.properties){if("count"===s(e))return!0}return!1})(),l=(()=>{if(!g||!Array.isArray(g.properties))return!1;for(const e of g.properties){if("ordinal"===s(e))return!("KeyValueProperty"!==e.type||!e.value||"BooleanLiteral"!==e.value.type)&&Boolean(e.value.value)}return!1})();if(o||p){try{const e=p?"ordinal":"cardinal",t=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let r=!1;try{const n=new Intl.PluralRules(t,{type:e}).resolvedOptions().pluralCategories;1===n.length&&"other"===n[0]&&(r=!0)}catch{}if(!r){const t=new Set;for(const r of this.config.locales)try{new Intl.PluralRules(r,{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}catch{new Intl.PluralRules("en",{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}const n=Array.from(t).sort();1===n.length&&"other"===n[0]&&(r=!0)}if(r){if(n.length>0)for(const e of n)this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,hasCount:!0,isOrdinal:p});else this.pluginContext.addKey({key:a,ns:i,defaultValue:c,hasCount:!0,isOrdinal:p});continue}}catch(e){}this.config.extract.disablePlurals?n.length>0?n.forEach(this.pluginContext.addKey):this.pluginContext.addKey({key:a,ns:i,defaultValue:c,explicitDefault:k}):this.handlePluralKeys(a,i,g,l||p,d,$);continue}if(n.length>0){n.forEach(this.pluginContext.addKey);continue}!0===t(g,"returnObjects")&&this.objectKeys.add(a)}f&&this.objectKeys.add(a);{const e=n.span?this.getLocationFromSpan(n.span):void 0;this.pluginContext.addKey({key:a,ns:i,defaultValue:c,explicitDefault:k,locations:e?[{file:this.getCurrentFile(),line:e.line,column:e.column}]:void 0})}}}handleCallExpressionArgument(e,t){const r=e.arguments[t].expression,n=[];let i=!1;if("ArrowFunctionExpression"===r.type){const e=this.extractKeyFromSelector(r);e&&(n.push(e),i=!0)}else if("ArrayExpression"===r.type)for(const e of r.elements)e?.expression&&n.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else n.push(...this.expressionResolver.resolvePossibleKeyStringValues(r));return{keysToProcess:n.filter(e=>!!e),isSelectorAPI:i}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let r=t;const n=[];for(;"MemberExpression"===r.type;){const e=r.property;if("Identifier"===e.type)n.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;n.unshift(e.expression.value)}r=r.object}if(n.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return n.join(t)}return null}handlePluralKeys(e,n,i,s,o,l){try{const a=s?"ordinal":"cardinal",u=new Set;for(const e of this.config.locales)try{const t=new Intl.PluralRules(e,{type:a});t.resolvedOptions().pluralCategories.forEach(e=>u.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:a});t.resolvedOptions().pluralCategories.forEach(e=>u.add(e))}const f=Array.from(u).sort(),p=this.config.extract.pluralSeparator??"_",c=t(i,"defaultValue"),y=t(i,`defaultValue${p}other`),g=t(i,`defaultValue${p}ordinal${p}other`),h=r(i,"context"),d=[];if(h?.value){const t=this.expressionResolver.resolvePossibleContextStringValues(h.value);if(t.length>0)if("StringLiteral"===h.value.type)for(const r of t)r.length>0&&d.push({key:e,context:r});else{for(const r of t)r.length>0&&d.push({key:e,context:r});!1!==this.config.extract?.generateBasePluralForms&&d.push({key:e})}else d.push({key:e})}else d.push({key:e});const x=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let k=!1;try{const e=new Intl.PluralRules(x,{type:a}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(k=!0)}catch{k=!1}if(k||1===f.length&&"other"===f[0]){for(const{key:e,context:r}of d){const a=t(i,`defaultValue${p}other`);let u;u="string"==typeof a?a:"string"==typeof c?c:"string"==typeof o?o:r?`${e}_${r}`:e;const f=this.config.extract.contextSeparator??"_",y=r?`${e}${f}${r}`:e;this.pluginContext.addKey({key:y,ns:n,defaultValue:u,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(l||"string"==typeof a)})}return}for(const{key:e,context:r}of d)for(const a of f){const u=t(i,s?`defaultValue${p}ordinal${p}${a}`:`defaultValue${p}${a}`);let f,h;if(f="string"==typeof u?u:"one"===a&&"string"==typeof c?c:"one"===a&&"string"==typeof o?o:s&&"string"==typeof g?g:s||"string"!=typeof y?"string"==typeof c?c:"string"==typeof o?o:e:y,r){const t=this.config.extract.contextSeparator??"_";h=s?`${e}${t}${r}${p}ordinal${p}${a}`:`${e}${t}${r}${p}${a}`}else h=s?`${e}${p}ordinal${p}${a}`:`${e}${p}${a}`;this.pluginContext.addKey({key:h,ns:n,defaultValue:f,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(l||"string"==typeof u||"string"==typeof y)})}}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=o||t(i,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let r=e;for(;"MemberExpression"===r.type;){if("Identifier"!==r.property.type)return null;t.unshift(r.property.value),r=r.object}if("ThisExpression"===r.type)t.unshift("this");else{if("Identifier"!==r.type)return null;t.unshift(r.value)}return t.join(".")}return null}}export{n as CallExpressionHandler};
@@ -1 +1 @@
1
- import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t}from"./ast-utils.js";class n{config;pluginContext;expressionResolver;constructor(e,t,n){this.config=e,this.pluginContext=t,this.expressionResolver=n}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e(t,this.config),a=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);a.push(...e)}else a.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:l,defaultValue:o,hasCount:r,isOrdinal:u,serializedChildren:f}=s;if(s.ns){const{ns:t}=s;e=a.map(e=>({key:e,ns:t,defaultValue:o||f,hasCount:r,isOrdinal:u}))}else{e=a.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:o||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,a=this.expressionResolver.resolvePossibleContextStringValues(i),o=this.config.extract.contextSeparator??"_";if(a.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l));for(const t of a)for(const n of e){const e=`${n.key}${o}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,l,n.explicitDefault)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:a,defaultValue:i}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:a,defaultValue:i});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}}}generatePluralKeysForTrans(e,n,s,a,i,l){try{const o=a?"ordinal":"cardinal",r=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:o}).resolvedOptions().pluralCategories,u=this.config.extract.pluralSeparator??"_";let f,d;if(i&&(f=t(i,`defaultValue${u}other`),d=t(i,`defaultValue${u}ordinal${u}other`)),1===r.length&&"other"===r[0]){const o=i?t(i,`defaultValue${u}other`):void 0,r="string"==typeof o?o:"string"==typeof n?n:e;return void this.pluginContext.addKey({key:e,ns:s,defaultValue:r,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof o||"string"==typeof f)})}for(const o of r){const r=i?t(i,a?`defaultValue${u}ordinal${u}${o}`:`defaultValue${u}${o}`):void 0;let p;p="string"==typeof r?r:"one"===o&&"string"==typeof n?n:a&&"string"==typeof d?d:a||"string"!=typeof f?"string"==typeof n?n:e:f;const c=a?`${e}${u}ordinal${u}${o}`:`${e}${u}${o}`;this.pluginContext.addKey({key:c,ns:s,defaultValue:p,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof r||"string"==typeof f)})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}}export{n as JSXHandler};
1
+ import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t}from"./ast-utils.js";class n{config;pluginContext;expressionResolver;getCurrentFile;getCurrentCode;constructor(e,t,n,s,o){this.config=e,this.pluginContext=t,this.expressionResolver=n,this.getCurrentFile=s,this.getCurrentCode=o}getLocationFromSpan(e){if(!e||"number"!=typeof e.start)return;const t=this.getCurrentCode(),n=e.start,s=t.substring(0,n).split("\n");return{line:s.length,column:s[s.length-1].length}}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e(t,this.config),o=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);o.push(...e)}else o.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:a,defaultValue:l,hasCount:r,isOrdinal:u,serializedChildren:f}=s,c=t.span?this.getLocationFromSpan(t.span):void 0,d=c?[{file:this.getCurrentFile(),line:c.line,column:c.column}]:void 0;if(s.ns){const{ns:t}=s;e=o.map(e=>({key:e,ns:t,defaultValue:l||f,hasCount:r,isOrdinal:u,locations:d}))}else{e=o.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:l||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault,locations:d}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue,locations:t.locations})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue,locations:t.locations})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,o=this.expressionResolver.resolvePossibleContextStringValues(i),l=this.config.extract.contextSeparator??"_";if(o.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,a,void 0,e.locations));for(const t of o)for(const n of e){const e=`${n.key}${l}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,a,n.explicitDefault,n.locations)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,a,e.explicitDefault,e.locations))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:o,defaultValue:i,locations:a}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:o,defaultValue:i,locations:a});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,a,e.explicitDefault,e.locations))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,locations:e.locations})})}}}generatePluralKeysForTrans(e,n,s,o,i,a,l){try{const r=o?"ordinal":"cardinal",u=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:r}).resolvedOptions().pluralCategories,f=this.config.extract.pluralSeparator??"_";let c,d;if(i&&(c=t(i,`defaultValue${f}other`),d=t(i,`defaultValue${f}ordinal${f}other`)),1===u.length&&"other"===u[0]){const r=i?t(i,`defaultValue${f}other`):void 0,u="string"==typeof r?r:"string"==typeof n?n:e;return void this.pluginContext.addKey({key:e,ns:s,defaultValue:u,hasCount:!0,isOrdinal:o,explicitDefault:Boolean(a||"string"==typeof r||"string"==typeof c),locations:l})}for(const r of u){const u=i?t(i,o?`defaultValue${f}ordinal${f}${r}`:`defaultValue${f}${r}`):void 0;let p;p="string"==typeof u?u:"one"===r&&"string"==typeof n?n:o&&"string"==typeof d?d:o||"string"!=typeof c?"string"==typeof n?n:e:c;const y=o?`${e}${f}ordinal${f}${r}`:`${e}${f}${r}`;this.pluginContext.addKey({key:y,ns:s,defaultValue:p,hasCount:!0,isOrdinal:o,explicitDefault:Boolean(a||"string"==typeof u||"string"==typeof c),locations:l})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n,locations:l})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}}export{n as JSXHandler};
@@ -1 +1 @@
1
- async function t(t){for(const e of t)await(e.setup?.())}function e(t,e,a,n){return{addKey:e=>{const n=!1===e.ns?void 0:e.ns,l=n??a.extract?.defaultNS??"translation",s=void 0===n,u=`${String(l)}:${e.key}`,i=e.defaultValue??e.key,o=t.get(u);if(o){const n=o.defaultValue===o.key||o.hasCount&&o.defaultValue&&o.key.includes("_")&&o.key.startsWith(o.defaultValue),f=i===e.key;n&&!f&&t.set(u,{...e,ns:l||a.extract?.defaultNS||"translation",nsIsImplicit:s,defaultValue:i})}else t.set(u,{...e,ns:l||a.extract?.defaultNS||"translation",nsIsImplicit:s,defaultValue:i})},config:Object.freeze({...a,plugins:[...e]}),logger:n,getVarFromScope:()=>{}}}export{e as createPluginContext,t as initializePlugins};
1
+ async function t(t){for(const e of t)await(e.setup?.())}function e(t,e,a,n){return{addKey:e=>{const n=!1===e.ns?void 0:e.ns,l=n??a.extract?.defaultNS??"translation",o=void 0===n,s=`${String(l)}:${e.key}`,i=e.defaultValue??e.key,u=t.get(s);if(u){const n=u.defaultValue===u.key||u.hasCount&&u.defaultValue&&u.key.includes("_")&&u.key.startsWith(u.defaultValue),c=i===e.key;e.locations&&(u.locations=[...u.locations||[],...e.locations]),n&&!c&&t.set(s,{...e,ns:l||a.extract?.defaultNS||"translation",nsIsImplicit:o,defaultValue:i,locations:u.locations})}else t.set(s,{...e,ns:l||a.extract?.defaultNS||"translation",nsIsImplicit:o,defaultValue:i})},config:Object.freeze({...a,plugins:[...e]}),logger:n,getVarFromScope:()=>{}}}export{e as createPluginContext,t as initializePlugins};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.21.0",
3
+ "version": "1.22.0",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {
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.21.0')
25
+ .version('1.22.0')
26
26
 
27
27
  // new: global config override option
28
28
  program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')