i18next-cli 1.74.5 → 1.74.7

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.
@@ -3,6 +3,7 @@
3
3
  var pluralRules = require('../../utils/plural-rules.js');
4
4
  var jsxParser = require('./jsx-parser.js');
5
5
  var astUtils = require('./ast-utils.js');
6
+ var callExpressionHandler = require('./call-expression-handler.js');
6
7
 
7
8
  // Checks if a string looks like natural language (contains spaces, punctuation, etc.)
8
9
  const naturalLanguageChars = /[ ,?!;]/;
@@ -169,7 +170,22 @@ class JSXHandler {
169
170
  // If ns is not explicitly set on the component, try to find it from the key
170
171
  // or the `t` prop
171
172
  if (!extractedAttributes.ns) {
173
+ const tProp = node.opening.attributes?.find(attr => attr.type === 'JSXAttribute' &&
174
+ attr.name.type === 'Identifier' &&
175
+ attr.name.value === 't');
176
+ // Check if the prop value is an identifier (e.g., t={t})
177
+ const scopeInfo = tProp?.type === 'JSXAttribute' &&
178
+ tProp.value?.type === 'JSXExpressionContainer' &&
179
+ tProp.value.expression.type === 'Identifier'
180
+ ? getScopeInfo(tProp.value.expression.value)
181
+ : undefined;
182
+ // Trans leaves a selector key to the `t` prop, which routes it into the
183
+ // hook's other namespaces like t() does (react-i18next#1933)
184
+ const isSelector = !!extractedAttributes.keyExpression &&
185
+ astUtils.unwrapParens(extractedAttributes.keyExpression).type === 'ArrowFunctionExpression';
172
186
  extractedKeys = keysToProcess.map(key => {
187
+ if (isSelector)
188
+ key = callExpressionHandler.applySelectorNsRewrite(key, scopeInfo, this.config);
173
189
  const nsSeparator = this.config.extract.nsSeparator ?? ':';
174
190
  let ns;
175
191
  // If the key contains a namespace separator, it takes precedence
@@ -191,16 +207,8 @@ class JSXHandler {
191
207
  locations
192
208
  };
193
209
  });
194
- const tProp = node.opening.attributes?.find(attr => attr.type === 'JSXAttribute' &&
195
- attr.name.type === 'Identifier' &&
196
- attr.name.value === 't');
197
- // Check if the prop value is an identifier (e.g., t={t})
198
- if (tProp?.type === 'JSXAttribute' &&
199
- tProp.value?.type === 'JSXExpressionContainer' &&
200
- tProp.value.expression.type === 'Identifier') {
201
- const tIdentifier = tProp.value.expression.value;
202
- const scopeInfo = getScopeInfo(tIdentifier);
203
- if (scopeInfo?.defaultNs) {
210
+ if (scopeInfo) {
211
+ if (scopeInfo.defaultNs) {
204
212
  // One copy per namespace when the hook's ns was a conditional (#299)
205
213
  const scopeNamespaces = [scopeInfo.defaultNs, ...(scopeInfo.altNs ?? [])];
206
214
  extractedKeys = extractedKeys.flatMap(key => key.ns ? [key] : scopeNamespaces.map(ns => ({ ...key, ns })));
package/dist/esm/cli.js CHANGED
@@ -31,7 +31,7 @@ const program = new Command();
31
31
  program
32
32
  .name('i18next-cli')
33
33
  .description('A unified, high-performance i18next CLI.')
34
- .version('1.74.5') // This string is replaced with the actual version at build time by rollup
34
+ .version('1.74.7') // This string is replaced with the actual version at build time by rollup
35
35
  .addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
36
36
  // new: global config override option
37
37
  program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
@@ -1,7 +1,8 @@
1
1
  import { ScopeManager } from '../parsers/scope-manager.js';
2
- import { ExpressionResolver } from '../parsers/expression-resolver.js';
2
+ import { ExpressionResolver, nestedMembers } from '../parsers/expression-resolver.js';
3
3
  import { CallExpressionHandler } from '../parsers/call-expression-handler.js';
4
4
  import { JSXHandler } from '../parsers/jsx-handler.js';
5
+ import { unwrapParens } from '../parsers/ast-utils.js';
5
6
 
6
7
  /**
7
8
  * Array iteration methods whose callback we can bind, mapped to the position of
@@ -18,6 +19,24 @@ const ITERATION_METHODS = {
18
19
  reduce: 1,
19
20
  reduceRight: 1,
20
21
  };
22
+ // `FC<Props>` / `React.FC<Props>` / `FunctionComponent<Props>` → `Props`
23
+ const COMPONENT_TYPES = new Set(['FC', 'FunctionComponent', 'VFC', 'VoidFunctionComponent']);
24
+ function componentPropsType(type) {
25
+ if (type?.type !== 'TsTypeReference')
26
+ return undefined;
27
+ const name = type.typeName?.type === 'TsQualifiedName' ? type.typeName.right?.value : type.typeName?.value;
28
+ return COMPONENT_TYPES.has(name) ? type.typeParams?.params?.[0] : undefined;
29
+ }
30
+ // `memo(fn)` / `forwardRef(fn)` → `fn`, and which type argument types its props:
31
+ // `memo<Props>` → 0, `forwardRef<Ref, Props>` → 1
32
+ const PROPS_TYPE_ARG = { memo: 0, forwardRef: 1 };
33
+ function reactWrapper(node) {
34
+ if (node?.type !== 'CallExpression')
35
+ return undefined;
36
+ const name = node.callee?.type === 'MemberExpression' ? node.callee.property?.value : node.callee?.value;
37
+ const propsTypeIndex = PROPS_TYPE_ARG[name];
38
+ return propsTypeIndex === undefined ? undefined : { fn: unwrapParens(node.arguments?.[0]?.expression), propsTypeIndex };
39
+ }
21
40
  /**
22
41
  * AST visitor class that traverses JavaScript/TypeScript syntax trees to extract translation keys.
23
42
  *
@@ -54,6 +73,8 @@ class ASTVisitors {
54
73
  jsxHandler;
55
74
  currentFile = '';
56
75
  currentCode = '';
76
+ // `const C: React.FC<Props> = (props) => …` → the function → `Props`
77
+ componentPropsTypes = new WeakMap();
57
78
  /**
58
79
  * Creates a new AST visitor instance.
59
80
  *
@@ -259,11 +280,13 @@ class ASTVisitors {
259
280
  let ident;
260
281
  if (!p)
261
282
  continue;
283
+ // The props of `const C: React.FC<Props> = (props) => …` are typed by `Props`
284
+ const inheritedType = p === params[0] ? this.componentPropsTypes.get(node) : undefined;
262
285
  // Destructured object param: `function f({ size }: IProps)`.
263
286
  // Bind each destructured local name to its interface member's values.
264
287
  const pat = p.pat ?? p.pattern ?? p;
265
288
  if (pat.type === 'ObjectPattern') {
266
- const patType = pat.typeAnnotation?.typeAnnotation ?? pat.typeAnnotation;
289
+ const patType = pat.typeAnnotation?.typeAnnotation ?? pat.typeAnnotation ?? inheritedType;
267
290
  const members = this.expressionResolver.resolveTypeMembers(patType);
268
291
  for (const prop of (pat.properties ?? [])) {
269
292
  // `{ size }` / `{ size = 'all' }` → AssignmentPatternProperty (local name is the key)
@@ -287,12 +310,25 @@ class ASTVisitors {
287
310
  }
288
311
  // `({ t }: { t: TFunction<'ns'> })` → bind `t` to that namespace
289
312
  this.bindTFunctionParam(localName, this.getMemberTypeNode(patType, memberName), typeParamConstraints);
290
- if (!members?.[memberName])
313
+ if (members?.[memberName]) {
314
+ this.expressionResolver.setTemporaryVariable(localName, members[memberName]);
315
+ if (!paramTemporaries)
316
+ paramTemporaries = [];
317
+ paramTemporaries.push(localName);
291
318
  continue;
292
- this.expressionResolver.setTemporaryVariable(localName, members[memberName]);
293
- if (!paramTemporaries)
294
- paramTemporaries = [];
295
- paramTemporaries.push(localName);
319
+ }
320
+ // `({ Bar }: DeepObject)` → `Bar.status`; `({ items }: Props)` → `items.map(({ kind }) => …)`
321
+ const nested = nestedMembers(members, memberName);
322
+ if (!nested)
323
+ continue;
324
+ this.expressionResolver.setTemporaryObjectVariable(localName, nested);
325
+ this.expressionResolver.setArrayElementMembers(localName, nested);
326
+ if (!paramObjectTemporaries)
327
+ paramObjectTemporaries = [];
328
+ paramObjectTemporaries.push(localName);
329
+ if (!paramArrayTemporaries)
330
+ paramArrayTemporaries = [];
331
+ paramArrayTemporaries.push(localName);
296
332
  }
297
333
  continue;
298
334
  }
@@ -336,7 +372,7 @@ class ASTVisitors {
336
372
  paramDefaults.push(paramKey);
337
373
  }
338
374
  // Try to locate TypeScript type node carried on the identifier.
339
- const rawTypeAnn = (ident.typeAnnotation ?? p.typeAnnotation ?? (p.left && p.left.typeAnnotation));
375
+ const rawTypeAnn = (ident.typeAnnotation ?? p.typeAnnotation ?? (p.left && p.left.typeAnnotation) ?? inheritedType);
340
376
  let typeAnn;
341
377
  if (rawTypeAnn) {
342
378
  // SWC may wrap the actual TS type in a wrapper like TsTypeAnn / TsTypeAnnotation
@@ -395,12 +431,18 @@ class ASTVisitors {
395
431
  // --- VISIT LOGIC ---
396
432
  // Handle specific node types
397
433
  switch (node.type) {
398
- case 'VariableDeclarator':
434
+ case 'VariableDeclarator': {
399
435
  this.scopeManager.handleVariableDeclarator(node);
400
436
  // Capture simple variable initializers so the expressionResolver can
401
437
  // resolve identifiers / member expressions that reference them.
402
438
  this.expressionResolver.captureVariableDeclarator(node);
439
+ // `const C: React.FC<Props> = (props) => …` / `= memo((props) => …)`
440
+ const propsType = componentPropsType(node.id?.typeAnnotation?.typeAnnotation);
441
+ const init = unwrapParens(node.init);
442
+ if (propsType && init)
443
+ this.componentPropsTypes.set(reactWrapper(init)?.fn ?? init, propsType);
403
444
  break;
445
+ }
404
446
  case 'TSEnumDeclaration':
405
447
  case 'TsEnumDeclaration':
406
448
  case 'TsEnumDecl':
@@ -423,9 +465,15 @@ class ASTVisitors {
423
465
  case 'FnDecl':
424
466
  this.expressionResolver.captureFunctionDeclaration(node);
425
467
  break;
426
- case 'CallExpression':
468
+ case 'CallExpression': {
427
469
  this.callExpressionHandler.handleCallExpression(node, this.scopeManager.getVarFromScope.bind(this.scopeManager));
470
+ // `forwardRef<Ref, Props>((props, ref) => …)` / `memo<Props>((props) => …)`
471
+ const wrapper = reactWrapper(node);
472
+ const propsType = wrapper && node.typeArguments?.params?.[wrapper.propsTypeIndex];
473
+ if (propsType && wrapper.fn)
474
+ this.componentPropsTypes.set(wrapper.fn, propsType);
428
475
  break;
476
+ }
429
477
  case 'NewExpression':
430
478
  // Handle NewExpression similarly to CallExpression (e.g., new TranslatedError(...))
431
479
  // NewExpression has the same structure: callee and arguments
@@ -807,15 +855,11 @@ class ASTVisitors {
807
855
  const elementParamIndex = ITERATION_METHODS[prop.value];
808
856
  if (elementParamIndex === undefined)
809
857
  return undefined;
810
- // The object must be an identifier whose value is a known string array
811
858
  const obj = callee.object;
812
- // ── Case 1: KNOWN_ARRAY.map(x => ...) ─────────────────────────────────
813
- if (obj?.type === 'Identifier') {
814
- const values = this.expressionResolver.getVariableValues(obj.value);
815
- if (values && values.length > 0) {
816
- return this.extractCallbackParam(node, values, elementParamIndex);
817
- }
818
- }
859
+ // ── Case 1: KNOWN_ARRAY.map(x => ...) / ([1, 2] as const).map(x => ...)
860
+ const values = this.expressionResolver.arrayValuesOf(obj);
861
+ if (values?.length)
862
+ return this.extractCallbackParam(node, values, elementParamIndex);
819
863
  // ── Case 2: Object.keys(MAP).map(k => ...) ────────────────────────────
820
864
  // Object.values(MAP).map(v => ...)
821
865
  // callee.object is a CallExpression: Object.keys(...) / Object.values(...)
@@ -857,20 +901,18 @@ class ASTVisitors {
857
901
  */
858
902
  tryBindForOfLoop(node) {
859
903
  try {
860
- if (node.right?.type !== 'Identifier')
861
- return undefined;
862
- const source = node.right.value;
904
+ const source = node.right;
863
905
  const left = node.left;
864
906
  const pat = left?.type === 'VariableDeclaration' ? left.declarations?.[0]?.id : left;
865
907
  // `for (const unit of ['day', 'hour'] as const)`
866
908
  if (pat?.type === 'Identifier') {
867
- const values = this.expressionResolver.getVariableValues(source);
909
+ const values = this.expressionResolver.arrayValuesOf(source);
868
910
  if (values?.length) {
869
911
  this.expressionResolver.setTemporaryVariable(pat.value, values);
870
912
  return () => this.expressionResolver.deleteTemporaryVariable(pat.value);
871
913
  }
872
914
  // `for (const item of items)` so `item.unit` resolves
873
- const members = this.expressionResolver.getArrayElementMembers(source);
915
+ const members = this.expressionResolver.arrayMembersOf(source);
874
916
  if (members) {
875
917
  this.expressionResolver.setTemporaryObjectVariable(pat.value, members);
876
918
  return () => this.expressionResolver.deleteTemporaryObjectVariable(pat.value);
@@ -879,7 +921,7 @@ class ASTVisitors {
879
921
  }
880
922
  // `for (const { unit } of [{ unit: 'day' }, …] as const)`
881
923
  if (pat?.type === 'ObjectPattern') {
882
- const members = this.expressionResolver.getArrayElementMembers(source);
924
+ const members = this.expressionResolver.arrayMembersOf(source);
883
925
  if (!members)
884
926
  return undefined;
885
927
  const bound = [];
@@ -925,9 +967,7 @@ class ASTVisitors {
925
967
  const elementParamIndex = ITERATION_METHODS[prop.value];
926
968
  if (elementParamIndex === undefined)
927
969
  return undefined;
928
- if (callee.object?.type !== 'Identifier')
929
- return undefined;
930
- const members = this.expressionResolver.getArrayElementMembers(callee.object.value);
970
+ const members = this.expressionResolver.arrayMembersOf(callee.object);
931
971
  if (!members)
932
972
  return undefined;
933
973
  const callbackArg = node.arguments?.[0]?.expression;
@@ -9,6 +9,57 @@ const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
9
9
  // Used to prevent splitting keys like "Error message: not found" into namespace + key.
10
10
  const naturalLanguageChars = /[ ,?!;]/;
11
11
  const looksLikeNaturalLanguage = (s) => naturalLanguageChars.test(s);
12
+ /**
13
+ * Mirror i18next's runtime selector rule (v25.8.19 default, or
14
+ * `enableSelector: 'strict'` when `types.enableSelector === 'strict'`).
15
+ *
16
+ * **Default mode** — rewrite only when the hook was called with a multi-element
17
+ * namespace array and the path's first segment matches a *secondary* namespace.
18
+ * The primary is intentionally not rewritten (preserves #2405): its keys are
19
+ * exposed flat on `$`, so `$.primary.foo` means a literal sub-key.
20
+ *
21
+ * **Strict mode** — every namespace (primary included) is exposed only under
22
+ * its own key on `$`. So a leading segment matching *any* namespace in the
23
+ * scope's list — primary or secondary, single-ns or multi-ns — is rewritten.
24
+ * Mirrors `i18next/src/selector.js` strict branch.
25
+ *
26
+ * In strict mode we also accept a single-ns scope, falling back to
27
+ * `[scopeInfo.defaultNs]` when the scope didn't capture an explicit array
28
+ * (e.g. `useTranslation('only')`).
29
+ *
30
+ * Falls through to the input string when:
31
+ * - the call had no selector (string keys go through this path unchanged),
32
+ * - scope has no namespaces info,
33
+ * - first segment isn't in the scope's namespaces list, or
34
+ * - separators are configured off.
35
+ */
36
+ function applySelectorNsRewrite(key, scopeInfo, config) {
37
+ const strict = config.types?.enableSelector === 'strict';
38
+ // Resolve the effective namespace list for the rule:
39
+ // - default mode: only the explicitly-captured `namespaces` array, length ≥ 2
40
+ // - strict mode: same array if present; otherwise synthesize from `defaultNs`
41
+ const nsCaptured = scopeInfo?.namespaces;
42
+ const nsList = strict
43
+ ? (nsCaptured ?? (scopeInfo?.defaultNs ? [scopeInfo.defaultNs] : undefined))
44
+ : nsCaptured;
45
+ if (!nsList || nsList.length < (strict ? 1 : 2))
46
+ return key;
47
+ const keySeparator = config.extract.keySeparator;
48
+ const joiner = typeof keySeparator === 'string' ? keySeparator : '.';
49
+ const nsSeparator = config.extract.nsSeparator ?? ':';
50
+ if (keySeparator === false || !nsSeparator)
51
+ return key;
52
+ const firstSepAt = key.indexOf(joiner);
53
+ if (firstSepAt < 0)
54
+ return key;
55
+ const head = key.slice(0, firstSepAt);
56
+ // Default mode excludes the primary; strict mode includes it.
57
+ if (!strict && head === nsList[0])
58
+ return key;
59
+ if (!nsList.includes(head))
60
+ return key;
61
+ return `${head}${nsSeparator}${key.slice(firstSepAt + joiner.length)}`;
62
+ }
12
63
  class CallExpressionHandler {
13
64
  pluginContext;
14
65
  config;
@@ -591,7 +642,7 @@ class CallExpressionHandler {
591
642
  if (keys.length > 0) {
592
643
  for (const k of keys) {
593
644
  originalKeysToProcess.push(k);
594
- keysToProcess.push(this.applySelectorNsRewrite(k, scopeInfo));
645
+ keysToProcess.push(applySelectorNsRewrite(k, scopeInfo, this.config));
595
646
  }
596
647
  isSelectorAPI = true;
597
648
  }
@@ -625,57 +676,6 @@ class CallExpressionHandler {
625
676
  isSelectorAPI,
626
677
  };
627
678
  }
628
- /**
629
- * Mirror i18next's runtime selector rule (v25.8.19 default, or
630
- * `enableSelector: 'strict'` when `types.enableSelector === 'strict'`).
631
- *
632
- * **Default mode** — rewrite only when the hook was called with a multi-element
633
- * namespace array and the path's first segment matches a *secondary* namespace.
634
- * The primary is intentionally not rewritten (preserves #2405): its keys are
635
- * exposed flat on `$`, so `$.primary.foo` means a literal sub-key.
636
- *
637
- * **Strict mode** — every namespace (primary included) is exposed only under
638
- * its own key on `$`. So a leading segment matching *any* namespace in the
639
- * scope's list — primary or secondary, single-ns or multi-ns — is rewritten.
640
- * Mirrors `i18next/src/selector.js` strict branch.
641
- *
642
- * In strict mode we also accept a single-ns scope, falling back to
643
- * `[scopeInfo.defaultNs]` when the scope didn't capture an explicit array
644
- * (e.g. `useTranslation('only')`).
645
- *
646
- * Falls through to the input string when:
647
- * - the call had no selector (string keys go through this path unchanged),
648
- * - scope has no namespaces info,
649
- * - first segment isn't in the scope's namespaces list, or
650
- * - separators are configured off.
651
- */
652
- applySelectorNsRewrite(key, scopeInfo) {
653
- const strict = this.config.types?.enableSelector === 'strict';
654
- // Resolve the effective namespace list for the rule:
655
- // - default mode: only the explicitly-captured `namespaces` array, length ≥ 2
656
- // - strict mode: same array if present; otherwise synthesize from `defaultNs`
657
- const nsCaptured = scopeInfo?.namespaces;
658
- const nsList = strict
659
- ? (nsCaptured ?? (scopeInfo?.defaultNs ? [scopeInfo.defaultNs] : undefined))
660
- : nsCaptured;
661
- if (!nsList || nsList.length < (strict ? 1 : 2))
662
- return key;
663
- const keySeparator = this.config.extract.keySeparator;
664
- const joiner = typeof keySeparator === 'string' ? keySeparator : '.';
665
- const nsSeparator = this.config.extract.nsSeparator ?? ':';
666
- if (keySeparator === false || !nsSeparator)
667
- return key;
668
- const firstSepAt = key.indexOf(joiner);
669
- if (firstSepAt < 0)
670
- return key;
671
- const head = key.slice(0, firstSepAt);
672
- // Default mode excludes the primary; strict mode includes it.
673
- if (!strict && head === nsList[0])
674
- return key;
675
- if (!nsList.includes(head))
676
- return key;
677
- return `${head}${nsSeparator}${key.slice(firstSepAt + joiner.length)}`;
678
- }
679
679
  /**
680
680
  * Extracts translation key(s) from selector API arrow function.
681
681
  *
@@ -1048,4 +1048,4 @@ class CallExpressionHandler {
1048
1048
  }
1049
1049
  }
1050
1050
 
1051
- export { CallExpressionHandler };
1051
+ export { CallExpressionHandler, applySelectorNsRewrite };