i18next-cli 1.34.0 → 1.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/cli.js +271 -1
  3. package/dist/cjs/config.js +211 -1
  4. package/dist/cjs/extractor/core/ast-visitors.js +364 -1
  5. package/dist/cjs/extractor/core/extractor.js +245 -1
  6. package/dist/cjs/extractor/core/key-finder.js +132 -1
  7. package/dist/cjs/extractor/core/translation-manager.js +745 -1
  8. package/dist/cjs/extractor/parsers/ast-utils.js +85 -1
  9. package/dist/cjs/extractor/parsers/call-expression-handler.js +941 -1
  10. package/dist/cjs/extractor/parsers/comment-parser.js +375 -1
  11. package/dist/cjs/extractor/parsers/expression-resolver.js +362 -1
  12. package/dist/cjs/extractor/parsers/jsx-handler.js +492 -1
  13. package/dist/cjs/extractor/parsers/jsx-parser.js +355 -1
  14. package/dist/cjs/extractor/parsers/scope-manager.js +408 -1
  15. package/dist/cjs/extractor/plugin-manager.js +106 -1
  16. package/dist/cjs/heuristic-config.js +99 -1
  17. package/dist/cjs/index.js +28 -1
  18. package/dist/cjs/init.js +174 -1
  19. package/dist/cjs/linter.js +431 -1
  20. package/dist/cjs/locize.js +269 -1
  21. package/dist/cjs/migrator.js +196 -1
  22. package/dist/cjs/rename-key.js +354 -1
  23. package/dist/cjs/status.js +336 -1
  24. package/dist/cjs/syncer.js +120 -1
  25. package/dist/cjs/types-generator.js +165 -1
  26. package/dist/cjs/utils/default-value.js +43 -1
  27. package/dist/cjs/utils/file-utils.js +136 -1
  28. package/dist/cjs/utils/funnel-msg-tracker.js +75 -1
  29. package/dist/cjs/utils/logger.js +36 -1
  30. package/dist/cjs/utils/nested-object.js +124 -1
  31. package/dist/cjs/utils/validation.js +71 -1
  32. package/dist/esm/cli.js +269 -1
  33. package/dist/esm/config.js +206 -1
  34. package/dist/esm/extractor/core/ast-visitors.js +362 -1
  35. package/dist/esm/extractor/core/extractor.js +241 -1
  36. package/dist/esm/extractor/core/key-finder.js +130 -1
  37. package/dist/esm/extractor/core/translation-manager.js +743 -1
  38. package/dist/esm/extractor/parsers/ast-utils.js +80 -1
  39. package/dist/esm/extractor/parsers/call-expression-handler.js +939 -1
  40. package/dist/esm/extractor/parsers/comment-parser.js +373 -1
  41. package/dist/esm/extractor/parsers/expression-resolver.js +360 -1
  42. package/dist/esm/extractor/parsers/jsx-handler.js +490 -1
  43. package/dist/esm/extractor/parsers/jsx-parser.js +334 -1
  44. package/dist/esm/extractor/parsers/scope-manager.js +406 -1
  45. package/dist/esm/extractor/plugin-manager.js +103 -1
  46. package/dist/esm/heuristic-config.js +97 -1
  47. package/dist/esm/index.js +11 -1
  48. package/dist/esm/init.js +172 -1
  49. package/dist/esm/linter.js +425 -1
  50. package/dist/esm/locize.js +265 -1
  51. package/dist/esm/migrator.js +194 -1
  52. package/dist/esm/rename-key.js +352 -1
  53. package/dist/esm/status.js +334 -1
  54. package/dist/esm/syncer.js +118 -1
  55. package/dist/esm/types-generator.js +163 -1
  56. package/dist/esm/utils/default-value.js +41 -1
  57. package/dist/esm/utils/file-utils.js +131 -1
  58. package/dist/esm/utils/funnel-msg-tracker.js +72 -1
  59. package/dist/esm/utils/logger.js +34 -1
  60. package/dist/esm/utils/nested-object.js +120 -1
  61. package/dist/esm/utils/validation.js +68 -1
  62. package/package.json +2 -2
  63. package/types/locize.d.ts.map +1 -1
@@ -1 +1,941 @@
1
- "use strict";var e=require("./ast-utils.js");const t=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");exports.CallExpressionHandler=class{pluginContext;config;logger;expressionResolver;objectKeys=new Set;getCurrentFile;getCurrentCode;lastSearchIndex=0;constructor(e,t,n,r,s,i){this.config=e,this.pluginContext=t,this.logger=n,this.expressionResolver=r,this.getCurrentFile=s,this.getCurrentCode=i}resetSearchIndex(){this.lastSearchIndex=0}getLocationFromNode(e){const t=this.getCurrentCode();let n;if("CallExpression"===e.type&&e.arguments.length>0){const t=e.arguments[0].expression;"StringLiteral"===t.type?n=t.raw??`'${t.value}'`:"TemplateLiteral"===t.type?n="`":"ArrowFunctionExpression"===t.type&&(n="=>")}if(!n)return;const r=t.indexOf(n,this.lastSearchIndex);if(-1===r)return;this.lastSearchIndex=r+n.length;const s=t.substring(0,r).split("\n");return{line:s.length,column:s[s.length-1].length}}handleCallExpression(n,r){const s=this.getFunctionName(n.callee);if(!s)return;const i=r(s),o=this.config.extract.functions||["t","*.t"];let l=void 0!==i;if(!l)for(const e of o)if(e.startsWith("*.")){if(s.endsWith(e.substring(1))){l=!0;break}}else if(e===s){l=!0;break}if(!l||0===n.arguments.length)return;const{keysToProcess:a,isSelectorAPI:c}=this.handleCallExpressionArgument(n,0);if(0===a.length)return;let u=!1;const f=this.config.extract.pluralSeparator??"_";for(let e=0;e<a.length;e++)a[e].endsWith(`${f}ordinal`)&&(u=!0,a[e]=a[e].slice(0,-8));let p,y;if(n.arguments.length>1){const t=n.arguments[1].expression;"ObjectExpression"===t.type?y=t:"StringLiteral"===t.type?p=t.value:"TemplateLiteral"===t.type&&e.isSimpleTemplateLiteral(t)&&(p=t.quasis[0].cooked)}if(n.arguments.length>2){const e=n.arguments[2].expression;"ObjectExpression"===e.type&&(y=e)}const g=y?e.getObjectPropValue(y,"defaultValue"):void 0,h="string"==typeof g?g:p,d=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},x="string"==typeof h||d(y),$=d(y),k=Boolean($||"string"==typeof h&&!(e=>{if("string"!=typeof e)return!1;const n=this.config.extract.interpolationPrefix??"{{",r=this.config.extract.interpolationSuffix??"}}";return new RegExp(`${t(n)}\\s*count\\s*${t(r)}`).test(e)})(h));for(let t=0;t<a.length;t++){const r=a[t];let s,o=a[t];if(y){const t=e.getObjectPropValue(y,"ns");"string"==typeof t&&(s=t)}const l=this.config.extract.nsSeparator??":";if(!s&&l&&o.includes(l)){const e=o.split(l);if(s=e.shift(),o=e.join(l),!o||""===o.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${s}${l}'`);continue}}!s&&i?.defaultNs&&(s=i.defaultNs),s||(s=this.config.extract.defaultNS);let f=o;if(i?.keyPrefix){const e=this.config.extract.keySeparator??".";if(f=!1!==e?i.keyPrefix.endsWith(e)?`${i.keyPrefix}${o}`:`${i.keyPrefix}${e}${o}`:`${i.keyPrefix}${o}`,!1!==e){if(f.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${f}' (keyPrefix: '${i.keyPrefix}', key: '${o}')`);continue}}}const p=t===a.length-1?"string"==typeof h?h:l&&r.includes(l||":")?r:o:o;if(y){const t=e.getObjectPropValueExpression(y,"context"),n=[];if("StringLiteral"===t?.type||"NumericLiteral"===t?.type||"BooleanLiteral"===t?.type){const e=`${t.value}`,r=this.config.extract.contextSeparator??"_";""!==e&&n.push({key:`${f}${r}${e}`,ns:s,defaultValue:p,explicitDefault:x})}else if(t){const e=this.expressionResolver.resolvePossibleContextStringValues(t),r=this.config.extract.contextSeparator??"_";e.length>0&&e.forEach(e=>{n.push({key:`${f}${r}${e}`,ns:s,defaultValue:p,explicitDefault:x})}),n.push({key:f,ns:s,defaultValue:p,explicitDefault:x,keyAcceptingContext:f})}const r=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(!y||!Array.isArray(y.properties))return!1;for(const e of y.properties){if("count"===r(e))return!0}return!1})(),o=(()=>{if(!y||!Array.isArray(y.properties))return!1;for(const e of y.properties){if("ordinal"===r(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 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 n of this.config.locales)try{new Intl.PluralRules(n,{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:u});else this.pluginContext.addKey({key:f,ns:s,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:f,ns:s,defaultValue:p,explicitDefault:x}):this.handlePluralKeys(f,s,y,o||u,h,k);continue}if(n.length>0){n.forEach(this.pluginContext.addKey);continue}!0===e.getObjectPropValue(y,"returnObjects")&&this.objectKeys.add(f)}c&&this.objectKeys.add(f);{const e=this.getLocationFromNode(n);this.pluginContext.addKey({key:f,ns:s,defaultValue:p,explicitDefault:x,locations:e?[{file:this.getCurrentFile(),line:e.line,column:e.column}]:void 0}),this.extractNestedKeys(f,s)}"string"==typeof h&&this.extractNestedKeys(h,s)}}extractNestedKeys(e,n){if(!e||"string"!=typeof e)return;const r=this.config.extract.nestingPrefix??"$t(",s=this.config.extract.nestingSuffix??")",i=t(r),o=t(s),l=new RegExp(`${i}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${o}`,"g");let a;for(;null!==(a=l.exec(e));)a[1]&&this.processNestedContent(a[1],void 0)}processNestedContent(e,n){let r=e,s="";const i=this.config.extract.nestingOptionsSeparator??",";if(e.indexOf(i)<0)r=e.trim();else{const n=new RegExp(`${t(i)}[ ]*{`),o=e.split(n);if(o.length>1)r=o[0].trim(),s=`{${o.slice(1).join(i+" {")}`;else{const t=e.indexOf(i);r=e.substring(0,t).trim(),s=e.substring(t+1).trim()}}if((r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))&&(r=r.slice(1,-1)),!r)return;let o;const l=this.config.extract.nsSeparator??":";if(l&&r.includes(l)){const e=r.split(l);if(o=e.shift(),r=e.join(l),!r||""===r.trim())return}else o=this.config.extract.defaultNS;let a,c=!1;if(s){/['"]?count['"]?\s*:/.test(s)&&(c=!0);const e=/['"]?context['"]?\s*:\s*(['"])(.*?)\1/.exec(s);e&&(a=e[2])}c||void 0!==a?this.generateNestedPluralKeys(r,o,c,a):this.pluginContext.addKey({key:r,ns:o})}generateNestedPluralKeys(e,t,n,r){try{const s="cardinal";if(!n&&void 0!==r)return this.pluginContext.addKey({key:e,ns:t}),void this.pluginContext.addKey({key:`${e}_${r}`,ns:t});const i=new Set,o=this.config.locales||["en"];for(const e of o)try{const t=new Intl.PluralRules(e,{type:s});t.resolvedOptions().pluralCategories.forEach(e=>i.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:s});t.resolvedOptions().pluralCategories.forEach(e=>i.add(e))}const l=Array.from(i).sort(),a=this.config.extract.pluralSeparator??"_",c=this.config.extract.contextSeparator??"_",u=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let f=!1;try{const e=new Intl.PluralRules(u,{type:s}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(f=!0)}catch{f=!1}const p=f||1===l.length&&"other"===l[0],y=[];if(void 0!==r?y.push({key:e,context:r}):y.push({key:e}),p){for(const{key:e,context:n}of y){const r=n?`${e}${c}${n}`:e;this.pluginContext.addKey({key:r,ns:t,hasCount:!0})}return}for(const{key:e,context:n}of y)for(const r of l){let s;s=n?`${e}${c}${n}${a}${r}`:`${e}${a}${r}`,this.pluginContext.addKey({key:s,ns:t,hasCount:!0})}}catch(n){this.pluginContext.addKey({key:e,ns:t})}}handleCallExpressionArgument(e,t){const n=e.arguments[t].expression,r=[];let s=!1;if("ArrowFunctionExpression"===n.type){const e=this.extractKeyFromSelector(n);e&&(r.push(e),s=!0)}else if("ArrayExpression"===n.type)for(const e of n.elements)e?.expression&&r.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else r.push(...this.expressionResolver.resolvePossibleKeyStringValues(n));return{keysToProcess:r.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 n=t;const r=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)r.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;r.unshift(e.expression.value)}n=n.object}if(r.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return r.join(t)}return null}handlePluralKeys(t,n,r,s,i,o){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 c=Array.from(a).sort(),u=this.config.extract.pluralSeparator??"_",f=e.getObjectPropValue(r,"defaultValue"),p=e.getObjectPropValue(r,`defaultValue${u}other`),y=e.getObjectPropValue(r,`defaultValue${u}ordinal${u}other`),g=e.getObjectPropValueExpression(r,"context"),h=[];if(g){const e=this.expressionResolver.resolvePossibleContextStringValues(g);if(e.length>0)if("StringLiteral"===g.type)for(const n of e)n.length>0&&h.push({key:t,context:n});else{for(const n of e)n.length>0&&h.push({key:t,context:n});!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===c.length&&"other"===c[0]){for(const{key:t,context:l}of h){const a=e.getObjectPropValue(r,`defaultValue${u}other`);let c;c="string"==typeof a?a:"string"==typeof f?f:"string"==typeof i?i:l?`${t}_${l}`:t;const p=this.config.extract.contextSeparator??"_",y=l?`${t}${p}${l}`:t;this.pluginContext.addKey({key:y,ns:n,defaultValue:c,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(o||"string"==typeof a)})}return}for(const{key:l,context:a}of h)for(const g of c){const c=s?`defaultValue${u}ordinal${u}${g}`:`defaultValue${u}${g}`,h=e.getObjectPropValue(r,c);let d,x;if(d="string"==typeof h?h:"one"===g&&"string"==typeof f?f:"one"===g&&"string"==typeof i?i:s&&"string"==typeof y?y:s||"string"!=typeof p?"string"==typeof f?f:"string"==typeof i?i:l:p,a){const e=this.config.extract.contextSeparator??"_";x=s?`${l}${e}${a}${u}ordinal${u}${g}`:`${l}${e}${a}${u}${g}`}else x=s?`${l}${u}ordinal${u}${g}`:`${l}${u}${g}`;this.pluginContext.addKey({key:x,ns:n,defaultValue:d,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(o||"string"==typeof h||"string"==typeof p),keyAcceptingContext:void 0!==a?t:void 0})}}catch(s){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const o=i||e.getObjectPropValue(r,"defaultValue");this.pluginContext.addKey({key:t,ns:n,defaultValue:"string"==typeof o?o:t})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}};
1
+ 'use strict';
2
+
3
+ var astUtils = require('./ast-utils.js');
4
+
5
+ // Helper to escape regex characters
6
+ const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
7
+ class CallExpressionHandler {
8
+ pluginContext;
9
+ config;
10
+ logger;
11
+ expressionResolver;
12
+ objectKeys = new Set();
13
+ getCurrentFile;
14
+ getCurrentCode;
15
+ lastSearchIndex = 0;
16
+ constructor(config, pluginContext, logger, expressionResolver, getCurrentFile, getCurrentCode) {
17
+ this.config = config;
18
+ this.pluginContext = pluginContext;
19
+ this.logger = logger;
20
+ this.expressionResolver = expressionResolver;
21
+ this.getCurrentFile = getCurrentFile;
22
+ this.getCurrentCode = getCurrentCode;
23
+ }
24
+ /**
25
+ * Reset the search index when starting to process a new file.
26
+ * This should be called before processing each file.
27
+ */
28
+ resetSearchIndex() {
29
+ this.lastSearchIndex = 0;
30
+ }
31
+ /**
32
+ * Helper method to calculate line and column from a position in the code.
33
+ * Uses string searching instead of SWC span offsets to avoid accumulation bugs.
34
+ */
35
+ getLocationFromNode(node) {
36
+ const code = this.getCurrentCode();
37
+ // Extract searchable text from the node
38
+ // For CallExpression, we can search for the key argument
39
+ let searchText;
40
+ if (node.type === 'CallExpression' && node.arguments.length > 0) {
41
+ const firstArg = node.arguments[0].expression;
42
+ if (firstArg.type === 'StringLiteral') {
43
+ // Search for the string literal including quotes
44
+ searchText = firstArg.raw ?? `'${firstArg.value}'`;
45
+ }
46
+ else if (firstArg.type === 'TemplateLiteral') {
47
+ // For template literals, search for the backtick
48
+ searchText = '`';
49
+ }
50
+ else if (firstArg.type === 'ArrowFunctionExpression') {
51
+ searchText = '=>';
52
+ }
53
+ }
54
+ if (!searchText)
55
+ return undefined;
56
+ // Search for the text starting from last known position
57
+ const position = code.indexOf(searchText, this.lastSearchIndex);
58
+ if (position === -1) {
59
+ // Not found - might be a parsing issue, skip location tracking
60
+ return undefined;
61
+ }
62
+ // Update last search position for next search
63
+ this.lastSearchIndex = position + searchText.length;
64
+ // Calculate line and column from the position
65
+ const upToPosition = code.substring(0, position);
66
+ const lines = upToPosition.split('\n');
67
+ return {
68
+ line: lines.length,
69
+ column: lines[lines.length - 1].length
70
+ };
71
+ }
72
+ /**
73
+ * Processes function call expressions to extract translation keys.
74
+ *
75
+ * This is the core extraction method that handles:
76
+ * - Standard t() calls with string literals
77
+ * - Selector API calls with arrow functions: `t($ => $.path.to.key)`
78
+ * - Namespace resolution from multiple sources
79
+ * - Default value extraction from various argument patterns
80
+ * - Pluralization and context handling
81
+ * - Key prefix application from scope
82
+ *
83
+ * @param node - Call expression node to process
84
+ * @param getScopeInfo - Function to retrieve scope information for variables
85
+ */
86
+ handleCallExpression(node, getScopeInfo) {
87
+ const functionName = this.getFunctionName(node.callee);
88
+ if (!functionName)
89
+ return;
90
+ // The scope lookup will only work for simple identifiers, which is okay for this fix.
91
+ const scopeInfo = getScopeInfo(functionName);
92
+ const configuredFunctions = this.config.extract.functions || ['t', '*.t'];
93
+ let isFunctionToParse = scopeInfo !== undefined; // A scoped variable (from useTranslation, etc.) is always parsed.
94
+ if (!isFunctionToParse) {
95
+ for (const pattern of configuredFunctions) {
96
+ if (pattern.startsWith('*.')) {
97
+ // Handle wildcard suffix (e.g., '*.t' matches 'i18n.t')
98
+ if (functionName.endsWith(pattern.substring(1))) {
99
+ isFunctionToParse = true;
100
+ break;
101
+ }
102
+ }
103
+ else {
104
+ // Handle exact match
105
+ if (pattern === functionName) {
106
+ isFunctionToParse = true;
107
+ break;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ if (!isFunctionToParse || node.arguments.length === 0)
113
+ return;
114
+ const { keysToProcess, isSelectorAPI } = this.handleCallExpressionArgument(node, 0);
115
+ if (keysToProcess.length === 0)
116
+ return;
117
+ let isOrdinalByKey = false;
118
+ const pluralSeparator = this.config.extract.pluralSeparator ?? '_';
119
+ for (let i = 0; i < keysToProcess.length; i++) {
120
+ if (keysToProcess[i].endsWith(`${pluralSeparator}ordinal`)) {
121
+ isOrdinalByKey = true;
122
+ // Normalize the key by stripping the suffix
123
+ keysToProcess[i] = keysToProcess[i].slice(0, -8);
124
+ }
125
+ }
126
+ let defaultValue;
127
+ let options;
128
+ if (node.arguments.length > 1) {
129
+ const arg2 = node.arguments[1].expression;
130
+ if (arg2.type === 'ObjectExpression') {
131
+ options = arg2;
132
+ }
133
+ else if (arg2.type === 'StringLiteral') {
134
+ defaultValue = arg2.value;
135
+ }
136
+ else if (arg2.type === 'TemplateLiteral' && astUtils.isSimpleTemplateLiteral(arg2)) {
137
+ defaultValue = arg2.quasis[0].cooked;
138
+ }
139
+ }
140
+ if (node.arguments.length > 2) {
141
+ const arg3 = node.arguments[2].expression;
142
+ if (arg3.type === 'ObjectExpression') {
143
+ options = arg3;
144
+ }
145
+ }
146
+ const defaultValueFromOptions = options ? astUtils.getObjectPropValue(options, 'defaultValue') : undefined;
147
+ const finalDefaultValue = (typeof defaultValueFromOptions === 'string' ? defaultValueFromOptions : defaultValue);
148
+ // Helper: detect if options object contains any defaultValue* properties
149
+ const optionsHasDefaultProps = (opts) => {
150
+ if (!opts || !Array.isArray(opts.properties))
151
+ return false;
152
+ for (const p of opts.properties) {
153
+ if (p && p.type === 'KeyValueProperty' && p.key) {
154
+ const keyName = (p.key.type === 'Identifier' && p.key.value) || (p.key.type === 'StringLiteral' && p.key.value);
155
+ if (typeof keyName === 'string' && keyName.startsWith('defaultValue'))
156
+ return true;
157
+ }
158
+ }
159
+ return false;
160
+ };
161
+ // explicit for base key when a string default was provided OR explicit plural defaults are present
162
+ const explicitDefaultForBase = typeof finalDefaultValue === 'string' || optionsHasDefaultProps(options);
163
+ // detect if options contain plural-specific defaultValue_* props
164
+ const explicitPluralDefaultsInOptions = optionsHasDefaultProps(options);
165
+ // If a base default string exists, consider it explicit for plural VARIANTS only when
166
+ // it does NOT contain a count interpolation like '{{count}}' — templates with count
167
+ // are often the runtime interpolation form and should NOT overwrite existing variant forms.
168
+ const containsCountPlaceholder = (s) => {
169
+ if (typeof s !== 'string')
170
+ return false;
171
+ const ip = this.config.extract.interpolationPrefix ?? '{{';
172
+ const is = this.config.extract.interpolationSuffix ?? '}}';
173
+ const re = new RegExp(`${escapeRegex(ip)}\\s*count\\s*${escapeRegex(is)}`);
174
+ return re.test(s);
175
+ };
176
+ const explicitPluralForVariants = Boolean(explicitPluralDefaultsInOptions || (typeof finalDefaultValue === 'string' && !containsCountPlaceholder(finalDefaultValue)));
177
+ // Loop through each key found (could be one or more) and process it
178
+ for (let i = 0; i < keysToProcess.length; i++) {
179
+ const originalKey = keysToProcess[i]; // preserve original (possibly namespaced) form
180
+ let key = keysToProcess[i];
181
+ let ns;
182
+ // Determine namespace (explicit ns > ns:key > scope ns > default)
183
+ // See https://www.i18next.com/overview/api#getfixedt
184
+ if (options) {
185
+ const nsVal = astUtils.getObjectPropValue(options, 'ns');
186
+ if (typeof nsVal === 'string')
187
+ ns = nsVal;
188
+ }
189
+ const nsSeparator = this.config.extract.nsSeparator ?? ':';
190
+ if (!ns && nsSeparator && key.includes(nsSeparator)) {
191
+ const parts = key.split(nsSeparator);
192
+ ns = parts.shift();
193
+ key = parts.join(nsSeparator);
194
+ if (!key || key.trim() === '') {
195
+ this.logger.warn(`Skipping key that became empty after namespace removal: '${ns}${nsSeparator}'`);
196
+ continue;
197
+ }
198
+ }
199
+ if (!ns && scopeInfo?.defaultNs)
200
+ ns = scopeInfo.defaultNs;
201
+ if (!ns)
202
+ ns = this.config.extract.defaultNS;
203
+ let finalKey = key;
204
+ // Apply keyPrefix AFTER namespace extraction
205
+ if (scopeInfo?.keyPrefix) {
206
+ const keySeparator = this.config.extract.keySeparator ?? '.';
207
+ // Apply keyPrefix - handle case where keyPrefix already ends with separator
208
+ if (keySeparator !== false) {
209
+ if (scopeInfo.keyPrefix.endsWith(keySeparator)) {
210
+ finalKey = `${scopeInfo.keyPrefix}${key}`;
211
+ }
212
+ else {
213
+ finalKey = `${scopeInfo.keyPrefix}${keySeparator}${key}`;
214
+ }
215
+ }
216
+ else {
217
+ finalKey = `${scopeInfo.keyPrefix}${key}`;
218
+ }
219
+ // Validate keyPrefix combinations that create problematic keys
220
+ if (keySeparator !== false) {
221
+ // Check for patterns that would create empty segments in the nested key structure
222
+ const segments = finalKey.split(keySeparator);
223
+ const hasEmptySegment = segments.some(segment => segment.trim() === '');
224
+ if (hasEmptySegment) {
225
+ this.logger.warn(`Skipping key with empty segments: '${finalKey}' (keyPrefix: '${scopeInfo.keyPrefix}', key: '${key}')`);
226
+ continue;
227
+ }
228
+ }
229
+ }
230
+ const isLastKey = i === keysToProcess.length - 1;
231
+ // Use the original (possibly namespaced) key as the default when no explicit
232
+ // default was provided and the source key contained a namespace prefix.
233
+ const dv = isLastKey
234
+ ? (typeof finalDefaultValue === 'string'
235
+ ? finalDefaultValue
236
+ : (nsSeparator && originalKey.includes(nsSeparator || ':') ? originalKey : key))
237
+ : key;
238
+ // Handle plurals, context, and returnObjects
239
+ if (options) {
240
+ const contextPropValue = astUtils.getObjectPropValueExpression(options, 'context');
241
+ const keysWithContext = [];
242
+ // 1. Handle Context
243
+ if (contextPropValue?.type === 'StringLiteral' || contextPropValue?.type === 'NumericLiteral' || contextPropValue?.type === 'BooleanLiteral') {
244
+ // If the context is static, we don't need to add the base key
245
+ const contextValue = `${contextPropValue.value}`;
246
+ const contextSeparator = this.config.extract.contextSeparator ?? '_';
247
+ // Ignore context: ''
248
+ if (contextValue !== '') {
249
+ keysWithContext.push({ key: `${finalKey}${contextSeparator}${contextValue}`, ns, defaultValue: dv, explicitDefault: explicitDefaultForBase });
250
+ }
251
+ }
252
+ else if (contextPropValue) {
253
+ const contextValues = this.expressionResolver.resolvePossibleContextStringValues(contextPropValue);
254
+ const contextSeparator = this.config.extract.contextSeparator ?? '_';
255
+ if (contextValues.length > 0) {
256
+ contextValues.forEach(context => {
257
+ keysWithContext.push({ key: `${finalKey}${contextSeparator}${context}`, ns, defaultValue: dv, explicitDefault: explicitDefaultForBase });
258
+ });
259
+ }
260
+ // For dynamic context, also add the base key as a fallback
261
+ keysWithContext.push({
262
+ key: finalKey,
263
+ ns,
264
+ defaultValue: dv,
265
+ explicitDefault: explicitDefaultForBase,
266
+ keyAcceptingContext: finalKey
267
+ });
268
+ }
269
+ // 2. Handle Plurals
270
+ // Robust detection for `{ count }`, `{ count: x }`, `{ 'count': x }` etc.
271
+ // Support KeyValueProperty and common shorthand forms that SWC may emit.
272
+ const propNameFromNode = (p) => {
273
+ if (!p)
274
+ return undefined;
275
+ // Standard key:value property
276
+ if (p.type === 'KeyValueProperty' && p.key) {
277
+ if (p.key.type === 'Identifier')
278
+ return p.key.value;
279
+ if (p.key.type === 'StringLiteral')
280
+ return p.key.value;
281
+ }
282
+ // SWC may represent shorthand properties differently (no explicit key node).
283
+ // Try common shapes: property with `value` being an Identifier (shorthand).
284
+ if (p.type === 'KeyValueProperty' && p.value && p.value.type === 'Identifier') {
285
+ // e.g. { count: count } - already covered above, but keep safe fallback
286
+ return p.key && p.key.type === 'Identifier' ? p.key.value : undefined;
287
+ }
288
+ // Some AST variants use 'ShorthandProperty' or keep the Identifier directly.
289
+ if ((p.type === 'ShorthandProperty' || p.type === 'Identifier') && p.value) {
290
+ return p.value;
291
+ }
292
+ // Fallback: if node has an 'id' or 'key' string value
293
+ if (p.key && typeof p.key === 'string')
294
+ return p.key;
295
+ return undefined;
296
+ };
297
+ const hasCount = (() => {
298
+ if (!options || !Array.isArray(options.properties))
299
+ return false;
300
+ for (const p of options.properties) {
301
+ const name = propNameFromNode(p);
302
+ if (name === 'count')
303
+ return true;
304
+ }
305
+ return false;
306
+ })();
307
+ const isOrdinalByOption = (() => {
308
+ if (!options || !Array.isArray(options.properties))
309
+ return false;
310
+ for (const p of options.properties) {
311
+ const name = propNameFromNode(p);
312
+ if (name === 'ordinal') {
313
+ // If it's a key:value pair with a BooleanLiteral true, respect it.
314
+ if (p.type === 'KeyValueProperty' && p.value && p.value.type === 'BooleanLiteral') {
315
+ return Boolean(p.value.value);
316
+ }
317
+ // shorthand `ordinal` without explicit true -> treat as false
318
+ return false;
319
+ }
320
+ }
321
+ return false;
322
+ })();
323
+ if (hasCount || isOrdinalByKey) {
324
+ // QUICK PATH: If ALL target locales only have the "other" category,
325
+ // emit base/context keys directly (avoid generating *_other). This
326
+ // mirrors the special-case in handlePluralKeys but is placed here as a
327
+ // defensive guard to ensure keys are always emitted.
328
+ try {
329
+ const typeForCheck = isOrdinalByKey ? 'ordinal' : 'cardinal';
330
+ // Prefer the configured primaryLanguage as the deciding signal for
331
+ // "single-other" languages (ja/zh/ko). Fall back to union of locales.
332
+ const primaryLang = this.config.extract?.primaryLanguage || (Array.isArray(this.config.locales) ? this.config.locales[0] : undefined) || 'en';
333
+ let isSingleOther = false;
334
+ try {
335
+ const primaryCategories = new Intl.PluralRules(primaryLang, { type: typeForCheck }).resolvedOptions().pluralCategories;
336
+ if (primaryCategories.length === 1 && primaryCategories[0] === 'other') {
337
+ isSingleOther = true;
338
+ }
339
+ }
340
+ catch {
341
+ // ignore and fall back to union-of-locales check below
342
+ }
343
+ if (!isSingleOther) {
344
+ const allPluralCategoriesCheck = new Set();
345
+ for (const locale of this.config.locales) {
346
+ try {
347
+ const rules = new Intl.PluralRules(locale, { type: typeForCheck });
348
+ rules.resolvedOptions().pluralCategories.forEach(c => allPluralCategoriesCheck.add(c));
349
+ }
350
+ catch {
351
+ new Intl.PluralRules('en', { type: typeForCheck }).resolvedOptions().pluralCategories.forEach(c => allPluralCategoriesCheck.add(c));
352
+ }
353
+ }
354
+ const pluralCategoriesCheck = Array.from(allPluralCategoriesCheck).sort();
355
+ if (pluralCategoriesCheck.length === 1 && pluralCategoriesCheck[0] === 'other') {
356
+ isSingleOther = true;
357
+ }
358
+ }
359
+ if (isSingleOther) {
360
+ // Emit only base/context keys (no _other) and skip the heavy plural path.
361
+ if (keysWithContext.length > 0) {
362
+ for (const k of keysWithContext) {
363
+ this.pluginContext.addKey({
364
+ key: k.key,
365
+ ns: k.ns,
366
+ defaultValue: k.defaultValue,
367
+ hasCount: true,
368
+ isOrdinal: isOrdinalByKey
369
+ });
370
+ }
371
+ }
372
+ else {
373
+ this.pluginContext.addKey({
374
+ key: finalKey,
375
+ ns,
376
+ defaultValue: dv,
377
+ hasCount: true,
378
+ isOrdinal: isOrdinalByKey
379
+ });
380
+ }
381
+ continue;
382
+ }
383
+ }
384
+ catch (e) {
385
+ // Ignore Intl failures here and fall through to normal logic
386
+ }
387
+ // Check if plurals are disabled
388
+ if (this.config.extract.disablePlurals) {
389
+ // When plurals are disabled, treat count as a regular option (for interpolation only)
390
+ // Still handle context normally
391
+ if (keysWithContext.length > 0) {
392
+ keysWithContext.forEach(this.pluginContext.addKey);
393
+ }
394
+ else {
395
+ this.pluginContext.addKey({ key: finalKey, ns, defaultValue: dv, explicitDefault: explicitDefaultForBase });
396
+ }
397
+ }
398
+ else {
399
+ // Original plural handling logic when plurals are enabled
400
+ // Always pass the base key to handlePluralKeys - it will handle context internally.
401
+ // Pass explicitDefaultForBase so that when a call-site provided an explicit
402
+ // base default (e.g. t('key', 'Default', { count })), plural variant keys
403
+ // are treated as explicit and may be synced to that default.
404
+ this.handlePluralKeys(finalKey, ns, options, isOrdinalByOption || isOrdinalByKey, finalDefaultValue, explicitPluralForVariants);
405
+ }
406
+ continue; // This key is fully handled
407
+ }
408
+ if (keysWithContext.length > 0) {
409
+ keysWithContext.forEach(this.pluginContext.addKey);
410
+ continue; // This key is now fully handled
411
+ }
412
+ // 3. Handle returnObjects
413
+ if (astUtils.getObjectPropValue(options, 'returnObjects') === true) {
414
+ this.objectKeys.add(finalKey);
415
+ // Fall through to add the base key itself
416
+ }
417
+ }
418
+ // 4. Handle selector API as implicit returnObjects
419
+ if (isSelectorAPI) {
420
+ this.objectKeys.add(finalKey);
421
+ // Fall through to add the base key itself
422
+ }
423
+ // 5. Default case: Add the simple key
424
+ {
425
+ // ✅ Use the helper method to find location by searching the code
426
+ const location = this.getLocationFromNode(node);
427
+ this.pluginContext.addKey({
428
+ key: finalKey,
429
+ ns,
430
+ defaultValue: dv,
431
+ explicitDefault: explicitDefaultForBase,
432
+ locations: location
433
+ ? [{
434
+ file: this.getCurrentFile(),
435
+ line: location.line,
436
+ column: location.column
437
+ }]
438
+ : undefined
439
+ });
440
+ // Check for nested translations in the key itself
441
+ this.extractNestedKeys(finalKey, ns);
442
+ }
443
+ // Check for nested translations in the default value
444
+ if (typeof finalDefaultValue === 'string') {
445
+ this.extractNestedKeys(finalDefaultValue, ns);
446
+ }
447
+ }
448
+ }
449
+ /**
450
+ * Scans a string for nested translations like $t(key, options) and extracts them.
451
+ */
452
+ extractNestedKeys(text, ns) {
453
+ if (!text || typeof text !== 'string')
454
+ return;
455
+ const prefix = this.config.extract.nestingPrefix ?? '$t(';
456
+ const suffix = this.config.extract.nestingSuffix ?? ')';
457
+ const escapedPrefix = escapeRegex(prefix);
458
+ const escapedSuffix = escapeRegex(suffix);
459
+ // Regex adapted from i18next Interpolator.js
460
+ // Matches nested calls like $t(key) or $t(key, { options })
461
+ // It handles balanced parentheses to some extent and quoted strings
462
+ const nestingRegexp = new RegExp(`${escapedPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${escapedSuffix}`, 'g');
463
+ let match;
464
+ while ((match = nestingRegexp.exec(text)) !== null) {
465
+ if (match[1]) {
466
+ // Do NOT trust the outer `ns` blindly — compute namespace from the nested key itself
467
+ // inside processNestedContent. Pass `undefined` so processNestedContent resolves ns
468
+ // deterministically (either from key "ns:key" or from defaultNS).
469
+ this.processNestedContent(match[1], undefined);
470
+ }
471
+ }
472
+ }
473
+ processNestedContent(content, ns) {
474
+ let key = content;
475
+ let optionsString = '';
476
+ const separator = this.config.extract.nestingOptionsSeparator ?? ',';
477
+ // Logic adapted from i18next Interpolator.js handleHasOptions
478
+ if (content.indexOf(separator) < 0) {
479
+ key = content.trim();
480
+ }
481
+ else {
482
+ // Split by separator, but be careful about objects
483
+ // i18next does: const c = key.split(new RegExp(`${sep}[ ]*{`));
484
+ // This assumes options start with {
485
+ const sepRegex = new RegExp(`${escapeRegex(separator)}[ ]*{`);
486
+ const parts = content.split(sepRegex);
487
+ if (parts.length > 1) {
488
+ key = parts[0].trim();
489
+ // Reconstruct the options part: add back the '{' that was consumed by split
490
+ optionsString = `{${parts.slice(1).join(separator + ' {')}`;
491
+ }
492
+ else {
493
+ // Fallback for simple split if no object pattern found
494
+ const sepIdx = content.indexOf(separator);
495
+ key = content.substring(0, sepIdx).trim();
496
+ optionsString = content.substring(sepIdx + 1).trim();
497
+ }
498
+ }
499
+ // Remove quotes from key if present
500
+ if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith('"') && key.endsWith('"'))) {
501
+ key = key.slice(1, -1);
502
+ }
503
+ if (!key)
504
+ return;
505
+ // Resolve namespace for the nested key:
506
+ // If nested key contains nsSeparator (e.g. "ns:key"), extract namespace,
507
+ // otherwise use configured defaultNS.
508
+ let nestedNs;
509
+ const nsSeparator = this.config.extract.nsSeparator ?? ':';
510
+ if (nsSeparator && key.includes(nsSeparator)) {
511
+ const parts = key.split(nsSeparator);
512
+ nestedNs = parts.shift();
513
+ key = parts.join(nsSeparator);
514
+ if (!key || key.trim() === '')
515
+ return;
516
+ }
517
+ else {
518
+ nestedNs = this.config.extract.defaultNS;
519
+ }
520
+ let hasCount = false;
521
+ let context;
522
+ if (optionsString) {
523
+ // Simple regex check for count and context in the options string
524
+ // This is an approximation since we don't have a full JSON parser here that handles JS objects perfectly
525
+ // but it should cover most static cases.
526
+ // Check for count: ...
527
+ if (/['"]?count['"]?\s*:/.test(optionsString)) {
528
+ hasCount = true;
529
+ }
530
+ // Check for context: ...
531
+ const contextMatch = /['"]?context['"]?\s*:\s*(['"])(.*?)\1/.exec(optionsString);
532
+ if (contextMatch) {
533
+ context = contextMatch[2];
534
+ }
535
+ }
536
+ if (hasCount || context !== undefined) {
537
+ this.generateNestedPluralKeys(key, nestedNs, hasCount, context);
538
+ }
539
+ else {
540
+ this.pluginContext.addKey({ key, ns: nestedNs });
541
+ }
542
+ }
543
+ generateNestedPluralKeys(key, ns, hasCount, context) {
544
+ try {
545
+ const type = 'cardinal';
546
+ // If only context, no plural
547
+ if (!hasCount && context !== undefined) {
548
+ this.pluginContext.addKey({ key, ns });
549
+ this.pluginContext.addKey({ key: `${key}_${context}`, ns });
550
+ return;
551
+ }
552
+ // If hasCount, generate plurals
553
+ const allPluralCategories = new Set();
554
+ const locales = this.config.locales || ['en'];
555
+ for (const locale of locales) {
556
+ try {
557
+ const pluralRules = new Intl.PluralRules(locale, { type });
558
+ const categories = pluralRules.resolvedOptions().pluralCategories;
559
+ categories.forEach(cat => allPluralCategories.add(cat));
560
+ }
561
+ catch (e) {
562
+ const englishRules = new Intl.PluralRules('en', { type });
563
+ const categories = englishRules.resolvedOptions().pluralCategories;
564
+ categories.forEach(cat => allPluralCategories.add(cat));
565
+ }
566
+ }
567
+ const pluralCategories = Array.from(allPluralCategories).sort();
568
+ const pluralSeparator = this.config.extract.pluralSeparator ?? '_';
569
+ const contextSeparator = this.config.extract.contextSeparator ?? '_';
570
+ const primaryLang = this.config.extract?.primaryLanguage || (Array.isArray(this.config.locales) ? this.config.locales[0] : undefined) || 'en';
571
+ let primaryIsSingleOther = false;
572
+ try {
573
+ const primaryCats = new Intl.PluralRules(primaryLang, { type }).resolvedOptions().pluralCategories;
574
+ if (primaryCats.length === 1 && primaryCats[0] === 'other')
575
+ primaryIsSingleOther = true;
576
+ }
577
+ catch {
578
+ primaryIsSingleOther = false;
579
+ }
580
+ const isSingleOther = primaryIsSingleOther || (pluralCategories.length === 1 && pluralCategories[0] === 'other');
581
+ const keysToGenerate = [];
582
+ if (context !== undefined) {
583
+ keysToGenerate.push({ key, context });
584
+ }
585
+ else {
586
+ keysToGenerate.push({ key });
587
+ }
588
+ if (isSingleOther) {
589
+ for (const { key: baseKey, context } of keysToGenerate) {
590
+ const finalKey = context ? `${baseKey}${contextSeparator}${context}` : baseKey;
591
+ this.pluginContext.addKey({ key: finalKey, ns, hasCount: true });
592
+ }
593
+ return;
594
+ }
595
+ for (const { key: baseKey, context } of keysToGenerate) {
596
+ for (const category of pluralCategories) {
597
+ let finalKey;
598
+ if (context) {
599
+ finalKey = `${baseKey}${contextSeparator}${context}${pluralSeparator}${category}`;
600
+ }
601
+ else {
602
+ finalKey = `${baseKey}${pluralSeparator}${category}`;
603
+ }
604
+ this.pluginContext.addKey({ key: finalKey, ns, hasCount: true });
605
+ }
606
+ }
607
+ }
608
+ catch (e) {
609
+ this.pluginContext.addKey({ key, ns });
610
+ }
611
+ }
612
+ /**
613
+ * Processed a call expression to extract keys from the specified argument.
614
+ *
615
+ * @param node - The call expression node
616
+ * @param argIndex - The index of the argument to process
617
+ * @returns An object containing the keys to process and a flag indicating if the selector API is used
618
+ */
619
+ handleCallExpressionArgument(node, argIndex) {
620
+ const firstArg = node.arguments[argIndex].expression;
621
+ const keysToProcess = [];
622
+ let isSelectorAPI = false;
623
+ if (firstArg.type === 'ArrowFunctionExpression') {
624
+ const key = this.extractKeyFromSelector(firstArg);
625
+ if (key) {
626
+ keysToProcess.push(key);
627
+ isSelectorAPI = true;
628
+ }
629
+ }
630
+ else if (firstArg.type === 'ArrayExpression') {
631
+ for (const element of firstArg.elements) {
632
+ if (element?.expression) {
633
+ keysToProcess.push(...this.expressionResolver.resolvePossibleKeyStringValues(element.expression));
634
+ }
635
+ }
636
+ }
637
+ else {
638
+ keysToProcess.push(...this.expressionResolver.resolvePossibleKeyStringValues(firstArg));
639
+ }
640
+ return {
641
+ keysToProcess: keysToProcess.filter((key) => !!key),
642
+ isSelectorAPI,
643
+ };
644
+ }
645
+ /**
646
+ * Extracts translation key from selector API arrow function.
647
+ *
648
+ * Processes selector expressions like:
649
+ * - `$ => $.path.to.key` → 'path.to.key'
650
+ * - `$ => $.app['title'].main` → 'app.title.main'
651
+ * - `$ => { return $.nested.key; }` → 'nested.key'
652
+ *
653
+ * Handles both dot notation and bracket notation, respecting
654
+ * the configured key separator or flat key structure.
655
+ *
656
+ * @param node - Arrow function expression from selector call
657
+ * @returns Extracted key path or null if not statically analyzable
658
+ */
659
+ extractKeyFromSelector(node) {
660
+ let body = node.body;
661
+ // Handle block bodies, e.g., $ => { return $.key; }
662
+ if (body.type === 'BlockStatement') {
663
+ const returnStmt = body.stmts.find(s => s.type === 'ReturnStatement');
664
+ if (returnStmt?.type === 'ReturnStatement' && returnStmt.argument) {
665
+ body = returnStmt.argument;
666
+ }
667
+ else {
668
+ return null;
669
+ }
670
+ }
671
+ let current = body;
672
+ const parts = [];
673
+ // Recursively walk down MemberExpressions
674
+ while (current.type === 'MemberExpression') {
675
+ const prop = current.property;
676
+ if (prop.type === 'Identifier') {
677
+ // This handles dot notation: .key
678
+ parts.unshift(prop.value);
679
+ }
680
+ else if (prop.type === 'Computed' && prop.expression.type === 'StringLiteral') {
681
+ // This handles bracket notation: ['key']
682
+ parts.unshift(prop.expression.value);
683
+ }
684
+ else {
685
+ // This is a dynamic property like [myVar] or a private name, which we cannot resolve.
686
+ return null;
687
+ }
688
+ current = current.object;
689
+ }
690
+ if (parts.length > 0) {
691
+ const keySeparator = this.config.extract.keySeparator;
692
+ const joiner = typeof keySeparator === 'string' ? keySeparator : '.';
693
+ return parts.join(joiner);
694
+ }
695
+ return null;
696
+ }
697
+ /**
698
+ * Generates plural form keys based on the primary language's plural rules.
699
+ *
700
+ * Uses Intl.PluralRules to determine the correct plural categories
701
+ * for the configured primary language and generates suffixed keys
702
+ * for each category (e.g., 'item_one', 'item_other').
703
+ *
704
+ * @param key - Base key name for pluralization
705
+ * @param ns - Namespace for the keys
706
+ * @param options - object expression options
707
+ * @param isOrdinal - isOrdinal flag
708
+ */
709
+ handlePluralKeys(key, ns, options, isOrdinal, defaultValueFromCall, explicitDefaultFromSource) {
710
+ try {
711
+ const type = isOrdinal ? 'ordinal' : 'cardinal';
712
+ // Generate plural forms for ALL target languages to ensure we have all necessary keys
713
+ const allPluralCategories = new Set();
714
+ for (const locale of this.config.locales) {
715
+ try {
716
+ const pluralRules = new Intl.PluralRules(locale, { type });
717
+ const categories = pluralRules.resolvedOptions().pluralCategories;
718
+ categories.forEach(cat => allPluralCategories.add(cat));
719
+ }
720
+ catch (e) {
721
+ // If a locale is invalid, fall back to English rules
722
+ const englishRules = new Intl.PluralRules('en', { type });
723
+ const categories = englishRules.resolvedOptions().pluralCategories;
724
+ categories.forEach(cat => allPluralCategories.add(cat));
725
+ }
726
+ }
727
+ const pluralCategories = Array.from(allPluralCategories).sort();
728
+ const pluralSeparator = this.config.extract.pluralSeparator ?? '_';
729
+ // Get all possible default values once at the start
730
+ const defaultValue = astUtils.getObjectPropValue(options, 'defaultValue');
731
+ const otherDefault = astUtils.getObjectPropValue(options, `defaultValue${pluralSeparator}other`);
732
+ const ordinalOtherDefault = astUtils.getObjectPropValue(options, `defaultValue${pluralSeparator}ordinal${pluralSeparator}other`);
733
+ // Handle context - both static and dynamic
734
+ const contextPropValue = astUtils.getObjectPropValueExpression(options, 'context');
735
+ const keysToGenerate = [];
736
+ if (contextPropValue) {
737
+ // Handle dynamic context by resolving all possible values
738
+ const contextValues = this.expressionResolver.resolvePossibleContextStringValues(contextPropValue);
739
+ if (contextValues.length > 0) {
740
+ // For static context (string literal), only generate context variants
741
+ if (contextPropValue.type === 'StringLiteral') {
742
+ // Only generate context-specific plural forms, no base forms
743
+ for (const contextValue of contextValues) {
744
+ if (contextValue.length > 0) {
745
+ keysToGenerate.push({ key, context: contextValue });
746
+ }
747
+ }
748
+ }
749
+ else {
750
+ // For dynamic context, generate context variants AND base forms
751
+ for (const contextValue of contextValues) {
752
+ if (contextValue.length > 0) {
753
+ keysToGenerate.push({ key, context: contextValue });
754
+ }
755
+ }
756
+ // Only generate base plural forms if generateBasePluralForms is not disabled
757
+ const shouldGenerateBaseForms = this.config.extract?.generateBasePluralForms !== false;
758
+ if (shouldGenerateBaseForms) {
759
+ keysToGenerate.push({ key });
760
+ }
761
+ }
762
+ }
763
+ else {
764
+ // Couldn't resolve context, fall back to base key only
765
+ keysToGenerate.push({ key });
766
+ }
767
+ }
768
+ else {
769
+ // No context, always generate base plural forms
770
+ keysToGenerate.push({ key });
771
+ }
772
+ // If the only plural category across configured locales is "other",
773
+ // prefer the base key (no "_other" suffix) as it's more natural for languages
774
+ // with no grammatical plural forms (ja/zh/ko).
775
+ // Prefer the configured primaryLanguage as signal for single-"other" languages.
776
+ // If primaryLanguage indicates single-"other", treat as that case; otherwise
777
+ // fall back to earlier union-of-locales check that produced `pluralCategories`.
778
+ const primaryLang = this.config.extract?.primaryLanguage || (Array.isArray(this.config.locales) ? this.config.locales[0] : undefined) || 'en';
779
+ let primaryIsSingleOther = false;
780
+ try {
781
+ const primaryCats = new Intl.PluralRules(primaryLang, { type }).resolvedOptions().pluralCategories;
782
+ if (primaryCats.length === 1 && primaryCats[0] === 'other')
783
+ primaryIsSingleOther = true;
784
+ }
785
+ catch {
786
+ primaryIsSingleOther = false;
787
+ }
788
+ if (primaryIsSingleOther || (pluralCategories.length === 1 && pluralCategories[0] === 'other')) {
789
+ for (const { key: baseKey, context } of keysToGenerate) {
790
+ const specificOther = astUtils.getObjectPropValue(options, `defaultValue${pluralSeparator}other`);
791
+ // Final default resolution:
792
+ // 1) plural-specific defaultValue_other
793
+ // 2) general defaultValue (from options)
794
+ // 3) defaultValueFromCall (string arg)
795
+ // 4) fallback to key (or context-key for context variants)
796
+ let finalDefaultValue;
797
+ if (typeof specificOther === 'string') {
798
+ finalDefaultValue = specificOther;
799
+ }
800
+ else if (typeof defaultValue === 'string') {
801
+ finalDefaultValue = defaultValue;
802
+ }
803
+ else if (typeof defaultValueFromCall === 'string') {
804
+ finalDefaultValue = defaultValueFromCall;
805
+ }
806
+ else {
807
+ finalDefaultValue = context ? `${baseKey}_${context}` : baseKey;
808
+ }
809
+ const ctxSep = this.config.extract.contextSeparator ?? '_';
810
+ const finalKey = context ? `${baseKey}${ctxSep}${context}` : baseKey;
811
+ this.pluginContext.addKey({
812
+ key: finalKey,
813
+ ns,
814
+ defaultValue: finalDefaultValue,
815
+ hasCount: true,
816
+ isOrdinal,
817
+ explicitDefault: Boolean(explicitDefaultFromSource || typeof specificOther === 'string')
818
+ });
819
+ }
820
+ return;
821
+ }
822
+ // Generate plural forms for each key variant
823
+ for (const { key: baseKey, context } of keysToGenerate) {
824
+ for (const category of pluralCategories) {
825
+ // 1. Look for the most specific default value
826
+ const specificDefaultKey = isOrdinal ? `defaultValue${pluralSeparator}ordinal${pluralSeparator}${category}` : `defaultValue${pluralSeparator}${category}`;
827
+ const specificDefault = astUtils.getObjectPropValue(options, specificDefaultKey);
828
+ // 2. Determine the final default value using the ORIGINAL fallback chain with corrections
829
+ let finalDefaultValue;
830
+ if (typeof specificDefault === 'string') {
831
+ // Most specific: defaultValue_one, defaultValue_ordinal_other, etc.
832
+ finalDefaultValue = specificDefault;
833
+ }
834
+ else if (category === 'one' && typeof defaultValue === 'string') {
835
+ // For "one" category, prefer the general defaultValue
836
+ finalDefaultValue = defaultValue;
837
+ }
838
+ else if (category === 'one' && typeof defaultValueFromCall === 'string') {
839
+ // For "one" category, also consider defaultValueFromCall
840
+ finalDefaultValue = defaultValueFromCall;
841
+ }
842
+ else if (isOrdinal && typeof ordinalOtherDefault === 'string') {
843
+ // For ordinals (non-one categories), fall back to ordinal_other
844
+ finalDefaultValue = ordinalOtherDefault;
845
+ }
846
+ else if (!isOrdinal && typeof otherDefault === 'string') {
847
+ // For cardinals (non-one categories), fall back to _other
848
+ finalDefaultValue = otherDefault;
849
+ }
850
+ else if (typeof defaultValue === 'string') {
851
+ // General defaultValue as fallback
852
+ finalDefaultValue = defaultValue;
853
+ }
854
+ else if (typeof defaultValueFromCall === 'string') {
855
+ // defaultValueFromCall as fallback
856
+ finalDefaultValue = defaultValueFromCall;
857
+ }
858
+ else {
859
+ // Final fallback to the base key itself
860
+ finalDefaultValue = baseKey;
861
+ }
862
+ // 3. Construct the final plural key
863
+ let finalKey;
864
+ if (context) {
865
+ const contextSeparator = this.config.extract.contextSeparator ?? '_';
866
+ finalKey = isOrdinal
867
+ ? `${baseKey}${contextSeparator}${context}${pluralSeparator}ordinal${pluralSeparator}${category}`
868
+ : `${baseKey}${contextSeparator}${context}${pluralSeparator}${category}`;
869
+ }
870
+ else {
871
+ finalKey = isOrdinal
872
+ ? `${baseKey}${pluralSeparator}ordinal${pluralSeparator}${category}`
873
+ : `${baseKey}${pluralSeparator}${category}`;
874
+ }
875
+ this.pluginContext.addKey({
876
+ key: finalKey,
877
+ ns,
878
+ defaultValue: finalDefaultValue,
879
+ hasCount: true,
880
+ isOrdinal,
881
+ // Only treat plural/context variant as explicit when:
882
+ // - the extractor marked the source as explicitly providing plural defaults
883
+ // - OR a plural-specific default was provided in the options (specificDefault/otherDefault)
884
+ // Do NOT treat the presence of a general base defaultValueFromCall as making variants explicit.
885
+ explicitDefault: Boolean(explicitDefaultFromSource || typeof specificDefault === 'string' || typeof otherDefault === 'string'),
886
+ // If this is a context variant, track the base key (without context or plural suffixes)
887
+ keyAcceptingContext: context !== undefined ? key : undefined
888
+ });
889
+ }
890
+ }
891
+ }
892
+ catch (e) {
893
+ this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);
894
+ // Fallback to a simple key if Intl API fails
895
+ const defaultValue = defaultValueFromCall || astUtils.getObjectPropValue(options, 'defaultValue');
896
+ this.pluginContext.addKey({ key, ns, defaultValue: typeof defaultValue === 'string' ? defaultValue : key });
897
+ }
898
+ }
899
+ /**
900
+ * Serializes a callee node (Identifier or MemberExpression) into a string.
901
+ *
902
+ * Produces a dotted name for simple callees that can be used for scope lookups
903
+ * or configuration matching.
904
+ *
905
+ * @param callee - The CallExpression callee node to serialize
906
+ * @returns A dotted string name for supported callees, or null when the callee
907
+ * is a computed/unsupported expression.
908
+ */
909
+ getFunctionName(callee) {
910
+ if (callee.type === 'Identifier') {
911
+ return callee.value;
912
+ }
913
+ if (callee.type === 'MemberExpression') {
914
+ const parts = [];
915
+ let current = callee;
916
+ while (current.type === 'MemberExpression') {
917
+ if (current.property.type === 'Identifier') {
918
+ parts.unshift(current.property.value);
919
+ }
920
+ else {
921
+ return null; // Cannot handle computed properties like i18n['t']
922
+ }
923
+ current = current.object;
924
+ }
925
+ // Handle `this` as the base of the expression (e.g., this._i18n.t)
926
+ if (current.type === 'ThisExpression') {
927
+ parts.unshift('this');
928
+ }
929
+ else if (current.type === 'Identifier') {
930
+ parts.unshift(current.value);
931
+ }
932
+ else {
933
+ return null; // Base of the expression is not a simple identifier
934
+ }
935
+ return parts.join('.');
936
+ }
937
+ return null;
938
+ }
939
+ }
940
+
941
+ exports.CallExpressionHandler = CallExpressionHandler;