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