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