i18next-cli 1.88.1 → 1.89.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 (46) hide show
  1. package/README.md +62 -9
  2. package/dist/cjs/cli.js +18 -3
  3. package/dist/cjs/extractor/core/translation-manager.js +9 -2
  4. package/dist/cjs/index.js +2 -1
  5. package/dist/cjs/init.js +3 -11
  6. package/dist/cjs/instrumenter/core/instrumenter.js +1114 -209
  7. package/dist/cjs/instrumenter/core/key-generator.js +19 -9
  8. package/dist/cjs/instrumenter/core/string-detector.js +106 -29
  9. package/dist/cjs/instrumenter/core/transformer.js +89 -31
  10. package/dist/cjs/localize/detect.js +2 -11
  11. package/dist/cjs/localize/localize.js +2 -1
  12. package/dist/cjs/utils/file-utils.js +48 -0
  13. package/dist/cjs/utils/jsx-attributes.js +3 -1
  14. package/dist/esm/cli.js +18 -3
  15. package/dist/esm/extractor/core/translation-manager.js +9 -2
  16. package/dist/esm/index.js +2 -1
  17. package/dist/esm/init.js +3 -11
  18. package/dist/esm/instrumenter/core/instrumenter.js +1117 -212
  19. package/dist/esm/instrumenter/core/key-generator.js +19 -9
  20. package/dist/esm/instrumenter/core/string-detector.js +107 -31
  21. package/dist/esm/instrumenter/core/transformer.js +89 -31
  22. package/dist/esm/localize/detect.js +3 -12
  23. package/dist/esm/localize/localize.js +2 -1
  24. package/dist/esm/utils/file-utils.js +49 -2
  25. package/dist/esm/utils/jsx-attributes.js +3 -1
  26. package/package.json +1 -1
  27. package/types/cli.d.ts.map +1 -1
  28. package/types/extractor/core/translation-manager.d.ts.map +1 -1
  29. package/types/index.d.ts +1 -1
  30. package/types/index.d.ts.map +1 -1
  31. package/types/init.d.ts.map +1 -1
  32. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  33. package/types/instrumenter/core/key-generator.d.ts +2 -0
  34. package/types/instrumenter/core/key-generator.d.ts.map +1 -1
  35. package/types/instrumenter/core/string-detector.d.ts +5 -1
  36. package/types/instrumenter/core/string-detector.d.ts.map +1 -1
  37. package/types/instrumenter/core/transformer.d.ts +10 -1
  38. package/types/instrumenter/core/transformer.d.ts.map +1 -1
  39. package/types/instrumenter/index.d.ts +1 -1
  40. package/types/instrumenter/index.d.ts.map +1 -1
  41. package/types/localize/detect.d.ts.map +1 -1
  42. package/types/types.d.ts +48 -1
  43. package/types/types.d.ts.map +1 -1
  44. package/types/utils/file-utils.d.ts +7 -0
  45. package/types/utils/file-utils.d.ts.map +1 -1
  46. package/types/utils/jsx-attributes.d.ts.map +1 -1
@@ -4,14 +4,16 @@ import { dirname, extname, join, relative, isAbsolute, resolve } from 'node:path
4
4
  import { parse } from '@swc/core';
5
5
  import { prompt } from '../../utils/prompt.js';
6
6
  import { styleText } from 'node:util';
7
- import { detectCandidate } from './string-detector.js';
7
+ import { detectCandidate, HTML_ENTITY_RE } from './string-detector.js';
8
8
  import { transformFile } from './transformer.js';
9
9
  import { createKeyRegistry, generateKeyFromContent } from './key-generator.js';
10
10
  import { createSpinnerLike } from '../../utils/wrap-ora.js';
11
11
  import { ConsoleLogger } from '../../utils/logger.js';
12
- import { importAliases, resolveElementAttributes, jsxElementName, ignoredAttributeSet } from '../../utils/jsx-attributes.js';
12
+ import { translatablePropertySet, importAliases, resolveElementAttributes, jsxElementName, ignoredAttributeSet, ignoredTags } from '../../utils/jsx-attributes.js';
13
13
  import { normalizeSpansToCharIndices, collectIgnoredLineRanges } from '../../extractor/parsers/ast-utils.js';
14
- import { getOutputPath } from '../../utils/file-utils.js';
14
+ import { readProjectDeps, getOutputPath } from '../../utils/file-utils.js';
15
+ import { findKeys } from '../../extractor/core/key-finder.js';
16
+ import { matchesFunctionPattern } from '../../extractor/utils/function-matcher.js';
15
17
  import { usesMessageFormat, toMessageFormatPlaceholders } from '../../utils/message-format.js';
16
18
 
17
19
  /**
@@ -39,6 +41,27 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
39
41
  let totalSkipped = 0;
40
42
  let totalLanguageChanges = 0;
41
43
  let usesI18nextT = false;
44
+ // The same warning for many files is printed once, with the files below it
45
+ const warnings = new Map();
46
+ const warnFor = (where, message) => {
47
+ warnings.set(message, [...(warnings.get(message) ?? []), where]);
48
+ };
49
+ let moduleScopeTotal = 0;
50
+ // The code imports i18next before it is instrumented: it is set up already, here or in a shared package
51
+ let i18nextInUse = false;
52
+ // Keys the code uses already: a new text gets another key, unless it is the same text, and no new key is
53
+ // the parent of nested ones (`tenants` beside `tenants.title` is a nesting conflict at extract)
54
+ // Best effort, without plugins (their hooks are for extract): a file it cannot read reserves nothing
55
+ const separator = config.extract.keySeparator ?? '.';
56
+ const existingKeys = await findKeys({ ...config, plugins: [] }, { info() { }, warn() { }, error() { } })
57
+ .then(found => found.allKeys, () => new Map());
58
+ for (const { key, defaultValue } of existingKeys.values()) {
59
+ const parent = separator ? key.split(separator)[0] : key;
60
+ if (parent !== key)
61
+ keyRegistry.reserve(parent);
62
+ else
63
+ keyRegistry.reserve(key, defaultValue ?? key);
64
+ }
42
65
  // Detect framework and language
43
66
  const hasReact = await isProjectUsingReact();
44
67
  const hasTypeScript = await isProjectUsingTypeScript();
@@ -69,18 +92,22 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
69
92
  if (loadResult === null)
70
93
  continue; // plugin says skip this file
71
94
  content = loadResult;
95
+ i18nextInUse ||= I18NEXT_IMPORT_RE.test(content);
72
96
  const scanResult = await scanFileForCandidates(content, file, config);
73
97
  let { candidates } = scanResult;
74
- const { components, languageChangeSites } = scanResult;
98
+ const { components, languageChangeSites, imports, memoHooks, pluralHelperImports } = scanResult;
75
99
  // Run instrumentOnResult plugin pipeline
76
100
  candidates = await runInstrumentOnResultPipeline(file, candidates, plugins, logger);
101
+ if (scanResult.ownTSkipped) {
102
+ totalCandidates += scanResult.ownTSkipped;
103
+ totalSkipped += scanResult.ownTSkipped;
104
+ warnFor(`${file} (${scanResult.ownTSkipped})`, 'Skipped the texts of components that declare a `t` of their own (not a translation function): rename it, then run instrument again.');
105
+ }
77
106
  if (scanResult.moduleScopeSkipped > 0) {
78
107
  totalCandidates += scanResult.moduleScopeSkipped;
79
108
  totalSkipped += scanResult.moduleScopeSkipped;
80
- logger.warn(`${file}: skipped ${scanResult.moduleScopeSkipped} module-scope string(s). ` +
81
- 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
82
- 'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
83
- 'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/');
109
+ moduleScopeTotal += scanResult.moduleScopeSkipped;
110
+ warnFor(`${file} (${scanResult.moduleScopeSkipped})`, MODULE_SCOPE_WARNING);
84
111
  }
85
112
  if (candidates.length === 0 && languageChangeSites.length === 0) {
86
113
  continue;
@@ -105,7 +132,7 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
105
132
  ]);
106
133
  switch (action) {
107
134
  case 'approve':
108
- candidate.key = generateKeyFromContent(candidate.content);
135
+ candidate.key = keyRegistry.add(generateKeyFromContent(keySourceOf(candidate)), candidate.content);
109
136
  break;
110
137
  case 'skip':
111
138
  candidate.skipReason = 'User skipped';
@@ -116,10 +143,11 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
116
143
  type: 'input',
117
144
  name: 'key',
118
145
  message: 'New key:',
119
- default: generateKeyFromContent(candidate.content)
146
+ default: generateKeyFromContent(keySourceOf(candidate))
120
147
  }
121
148
  ]);
122
149
  candidate.key = key;
150
+ keyRegistry.reserve(key, candidate.content);
123
151
  break;
124
152
  }
125
153
  case 'edit-value': {
@@ -132,7 +160,7 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
132
160
  }
133
161
  ]);
134
162
  candidate.content = value;
135
- candidate.key = generateKeyFromContent(value);
163
+ candidate.key = keyRegistry.add(generateKeyFromContent(value), value);
136
164
  break;
137
165
  }
138
166
  }
@@ -144,7 +172,7 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
144
172
  // Generate keys for approved candidates
145
173
  for (const candidate of approvedCandidates) {
146
174
  if (!candidate.key) {
147
- candidate.key = keyRegistry.add(generateKeyFromContent(candidate.content), candidate.content);
175
+ candidate.key = keyRegistry.add(generateKeyFromContent(keySourceOf(candidate)), candidate.content);
148
176
  }
149
177
  }
150
178
  // After key generation, so ICU/MF2 syntax does not end up in generated keys
@@ -158,7 +186,10 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
158
186
  config,
159
187
  components,
160
188
  namespace: targetNamespace,
161
- languageChangeSites
189
+ languageChangeSites,
190
+ imports,
191
+ memoHooks,
192
+ pluralHelperImports
162
193
  });
163
194
  if (!options.isDryRun && transformResult.modified) {
164
195
  // Write the transformed file
@@ -172,16 +203,15 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
172
203
  if (!usesI18nextT && approvedCandidates.some(c => !c.insideComponent && c.confidence >= 0.7)) {
173
204
  usesI18nextT = true;
174
205
  }
175
- // Log any warnings (e.g. i18next.t() in React files)
176
- if (transformResult.warnings?.length) {
177
- for (const warning of transformResult.warnings) {
178
- logger.warn(warning);
179
- }
206
+ // Collect warnings (e.g. i18next.t() in React files) and candidates that could not be rewritten
207
+ for (const warning of [...(transformResult.warnings ?? []), ...transformResult.errors]) {
208
+ warnFor(file, warning.startsWith(`${file}: `) ? warning.slice(file.length + 2) : warning);
180
209
  }
181
210
  results.push({
182
211
  file,
183
212
  candidates: approvedCandidates,
184
- result: transformResult
213
+ result: transformResult,
214
+ languageChangeSites
185
215
  });
186
216
  }
187
217
  else {
@@ -194,8 +224,15 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
194
224
  }
195
225
  const langChangeSuffix = totalLanguageChanges > 0 ? `, ${totalLanguageChanges} language-change site(s)` : '';
196
226
  spinner.succeed(styleText('bold', `Scanned complete: ${totalCandidates} candidates, ${totalTransformed} approved${langChangeSuffix}`));
227
+ for (const [message, where] of warnings) {
228
+ const head = message === MODULE_SCOPE_WARNING ? `Skipped ${moduleScopeTotal} module-scope string(s). ${message}` : message;
229
+ logger.warn(`${head}\n${where.map(w => ` ${w}`).join('\n')}`);
230
+ }
197
231
  // Generate i18n init file if needed and any transformations were made
198
- if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun) {
232
+ if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && i18nextInUse) {
233
+ logger.info('Your code imports i18next already, so it is set up somewhere: no i18n init file generated.');
234
+ }
235
+ if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !i18nextInUse) {
199
236
  const initFilePath = await ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT);
200
237
  if (initFilePath) {
201
238
  await injectI18nImportIntoEntryFile(initFilePath, logger);
@@ -216,6 +253,15 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
216
253
  throw error;
217
254
  }
218
255
  }
256
+ /** The text a key is made from: a <Trans> candidate's words, not its JSX source (`<a href=…>`). */
257
+ function keySourceOf(candidate) {
258
+ return candidate.transValue?.replace(/<\/?\d+>/g, '') ?? candidate.content;
259
+ }
260
+ /** An import of i18next or react-i18next (`.init()` alone is any library's: `Sentry.init()`). */
261
+ const I18NEXT_IMPORT_RE = /\bfrom\s*['"](?:i18next|react-i18next)['"]|\brequire\(\s*['"](?:i18next|react-i18next)['"]\s*\)/;
262
+ const MODULE_SCOPE_WARNING = 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
263
+ 'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
264
+ 'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/';
219
265
  /**
220
266
  * Scans a source file for hardcoded string candidates and React component boundaries.
221
267
  */
@@ -224,6 +270,10 @@ async function scanFileForCandidates(content, file, config) {
224
270
  const components = [];
225
271
  const languageChangeSites = [];
226
272
  let moduleScopeSkipped = 0;
273
+ let ownTSkipped = 0;
274
+ let imports;
275
+ const memoHooks = [];
276
+ let pluralHelperImports;
227
277
  const fileExt = extname(file).toLowerCase();
228
278
  const isTypeScriptFile = ['.ts', '.tsx', '.mts', '.cts'].includes(fileExt);
229
279
  const isTSX = fileExt === '.tsx';
@@ -271,6 +321,15 @@ async function scanFileForCandidates(content, file, config) {
271
321
  // indices — without the conversion every emoji / accented char / CJK char
272
322
  // shifts all subsequent offsets.
273
323
  normalizeSpansToCharIndices(ast, content);
324
+ imports = ast.body
325
+ .filter((item) => item.type === 'ImportDeclaration')
326
+ .map((item) => ({
327
+ source: item.source.value,
328
+ start: item.span.start,
329
+ end: item.span.end,
330
+ locals: (item.specifiers ?? []).map((spec) => spec.local?.value).filter(Boolean)
331
+ }));
332
+ collectMemoHooks(ast, memoHooks);
274
333
  // Detect React function component boundaries
275
334
  detectComponentBoundaries(ast, content, components);
276
335
  // Collect function spans so module-scope strings can be excluded below
@@ -282,11 +341,19 @@ async function scanFileForCandidates(content, file, config) {
282
341
  const jsx = attributeRules && !Array.isArray(attributeRules)
283
342
  ? { rules: attributeRules, aliases: importAliases(ast) }
284
343
  : undefined;
285
- visitNodeForStrings(ast, content, file, config, candidates, jsx);
286
- // Detect JSX interpolation patterns (merge adjacent text + expression children)
287
- detectJSXInterpolation(ast, content, file, config, candidates);
288
- // Detect plural conditional patterns (ternary chains checking count === 0/1/other)
289
- detectPluralPatterns(ast, content, file, config, candidates);
344
+ consoleOnlyNames.set(file, collectConsoleOnlyNames(ast));
345
+ fileDataStrings.set(file, collectDataStrings(ast));
346
+ try {
347
+ visitNodeForStrings(ast, content, file, config, candidates, jsx);
348
+ // Detect JSX interpolation patterns (merge adjacent text + expression children)
349
+ detectJSXInterpolation(ast, content, file, config, candidates);
350
+ // Detect plural conditional patterns (ternary chains checking count === 0/1/other)
351
+ detectPluralPatterns(ast, content, file, config, candidates);
352
+ }
353
+ finally {
354
+ consoleOnlyNames.delete(file);
355
+ fileDataStrings.delete(file);
356
+ }
290
357
  // Detect language-change call sites (e.g. updateSettings({ language: code }))
291
358
  detectLanguageChangeSites(ast, content, languageChangeSites);
292
359
  // Annotate candidates with their enclosing component (if any)
@@ -298,6 +365,15 @@ async function scanFileForCandidates(content, file, config) {
298
365
  }
299
366
  }
300
367
  }
368
+ // A component whose `t` is something else (`const [t, setT] = useState(0)`) keeps its texts: a t() call
369
+ // there would call that `t`
370
+ const ownT = new Set(components.filter(c => c.ownT).map(c => c.name));
371
+ if (ownT.size) {
372
+ const keep = candidates.filter(c => !c.insideComponent || !ownT.has(c.insideComponent));
373
+ ownTSkipped = candidates.length - keep.length;
374
+ candidates.length = 0;
375
+ candidates.push(...keep);
376
+ }
301
377
  // Drop module-scope candidates: wrapping them yields a t() call evaluated
302
378
  // once at import time — possibly before i18next is initialized, and never
303
379
  // re-evaluated on language change. See issue #278.
@@ -337,11 +413,27 @@ async function scanFileForCandidates(content, file, config) {
337
413
  candidates.length = 0;
338
414
  candidates.push(...keep);
339
415
  }
416
+ const helperNames = new Set(candidates.map(c => c.pluralHelper).filter((n) => !!n));
417
+ if (helperNames.size)
418
+ pluralHelperImports = findPluralHelperImports(ast, content, helperNames);
419
+ // Two candidates whose spans overlap cannot both be rewritten (a template literal in another one's `${}`):
420
+ // the outer one wins, the inner text stays in its interpolation value as written
421
+ const bySize = [...candidates].sort((a, b) => (b.endOffset - b.offset) - (a.endOffset - a.offset));
422
+ const kept = new Set();
423
+ for (const c of bySize) {
424
+ if (![...kept].some(k => c.offset < k.endOffset && k.offset < c.endOffset))
425
+ kept.add(c);
426
+ }
427
+ if (kept.size < candidates.length) {
428
+ const keep = candidates.filter(c => kept.has(c));
429
+ candidates.length = 0;
430
+ candidates.push(...keep);
431
+ }
340
432
  }
341
433
  catch (err) {
342
434
  // Silently skip files that can't be parsed
343
435
  }
344
- return { candidates, components, languageChangeSites, moduleScopeSkipped };
436
+ return { candidates, components, languageChangeSites, moduleScopeSkipped, ownTSkipped, imports, memoHooks, pluralHelperImports };
345
437
  }
346
438
  /**
347
439
  * Node types whose span delimits deferred (call-time) evaluation. A string
@@ -415,7 +507,7 @@ function detectComponentBoundaries(node, content, components) {
415
507
  name: node.identifier.value,
416
508
  bodyStart: body.span.start,
417
509
  bodyEnd: body.span.end,
418
- hasUseTranslation: content.slice(body.span.start, body.span.end).includes('useTranslation')
510
+ ...tBinding(node, body)
419
511
  });
420
512
  }
421
513
  }
@@ -433,7 +525,7 @@ function detectComponentBoundaries(node, content, components) {
433
525
  name: node.identifier.value,
434
526
  bodyStart: body.span.start,
435
527
  bodyEnd: body.span.end,
436
- hasUseTranslation: content.slice(body.span.start, body.span.end).includes('useTranslation')
528
+ ...tBinding(node, body)
437
529
  });
438
530
  }
439
531
  }
@@ -490,14 +582,74 @@ function isBlockBody(body) {
490
582
  */
491
583
  function addComponentFromFunctionNode(name, fnNode, content, components) {
492
584
  const body = fnNode.body;
493
- if (body?.type === 'BlockStatement' && body.span) {
585
+ if (isBlockBody(body) && body.span) {
494
586
  components.push({
495
587
  name,
496
588
  bodyStart: body.span.start,
497
589
  bodyEnd: body.span.end,
498
- hasUseTranslation: content.slice(body.span.start, body.span.end).includes('useTranslation')
590
+ ...tBinding(fnNode, body)
499
591
  });
500
592
  }
593
+ else if (isJSXExpression(body) && body.span) {
594
+ // `const Hint = () => <p>…</p>`: a component too; its body becomes a block when it needs the hook
595
+ components.push({
596
+ name,
597
+ bodyStart: body.span.start,
598
+ bodyEnd: body.span.end,
599
+ ...tBinding(fnNode, {}),
600
+ expressionBody: true
601
+ });
602
+ }
603
+ }
604
+ /** JSX, possibly in parentheses. */
605
+ function isJSXExpression(expr) {
606
+ if (expr?.type === 'ParenthesisExpression')
607
+ return isJSXExpression(expr.expression);
608
+ return expr?.type === 'JSXElement' || expr?.type === 'JSXFragment';
609
+ }
610
+ /**
611
+ * The `t` a component has already: `'translation'` for a parameter (`({ t })`, a prop passed down) or one
612
+ * destructured from a translation hook (`const { t } = useTranslation('ns')`, also re-exported or renamed:
613
+ * `useT`, `useAppTranslation`, `getTranslations`), `'other'` for any other `t` in its body
614
+ * (`const [t, setT] = useState(0)`), null for none. Another `const { t }` would be a redeclaration, and the
615
+ * `t()` calls would call the other `t`.
616
+ */
617
+ function bindsT(fnNode, body) {
618
+ if ((fnNode.params ?? []).some((p) => patternBinds(p, 't')))
619
+ return 'translation';
620
+ for (const stmt of body.stmts ?? []) {
621
+ if (stmt.type === 'FunctionDeclaration' && stmt.identifier?.value === 't')
622
+ return 'other';
623
+ for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
624
+ if (!patternBinds(d.id, 't'))
625
+ continue;
626
+ const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
627
+ const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
628
+ return d.id.type === 'ObjectPattern' && hook && TRANSLATION_HOOK_RE.test(hook) ? 'translation' : 'other';
629
+ }
630
+ }
631
+ return null;
632
+ }
633
+ /** Names of the hooks and functions that give a translation `t`. */
634
+ const TRANSLATION_HOOK_RE = /^(?:use|get)\w*(?:Translation|T|I18n|Intl)\w*$/;
635
+ /** A component's `hasUseTranslation`, and `ownT` when its `t` is something else (see `bindsT`). */
636
+ function tBinding(fnNode, body) {
637
+ const kind = bindsT(fnNode, body);
638
+ return kind === 'other' ? { hasUseTranslation: true, ownT: true } : { hasUseTranslation: kind === 'translation' };
639
+ }
640
+ /** Whether a binding pattern (a parameter, a destructuring) binds `name`; defaults and renamed keys aside. */
641
+ function patternBinds(pat, name) {
642
+ switch (pat?.type) {
643
+ case 'Identifier': return pat.value === name;
644
+ case 'Parameter': return patternBinds(pat.pat, name);
645
+ case 'AssignmentPattern': return patternBinds(pat.left, name);
646
+ case 'RestElement': return patternBinds(pat.argument, name);
647
+ case 'ArrayPattern': return (pat.elements ?? []).some((e) => patternBinds(e, name));
648
+ case 'ObjectPattern': return (pat.properties ?? []).some((p) => p.type === 'KeyValuePatternProperty'
649
+ ? patternBinds(p.value, name)
650
+ : p.type === 'AssignmentPatternProperty' ? p.key?.value === name : patternBinds(p.argument, name));
651
+ default: return false;
652
+ }
501
653
  }
502
654
  // Non-translatable JSX attributes are defined in utils/jsx-attributes.ts
503
655
  // and shared with the linter. The instrumenter uses `ignoredAttributeSet`
@@ -506,22 +658,183 @@ function addComponentFromFunctionNode(name, fnNode, content, components) {
506
658
  * Returns true when the AST node is a `t(...)` or `i18next.t(...)` call
507
659
  * expression — i.e. code that was already instrumented.
508
660
  */
509
- function isTranslationCall(node) {
661
+ function isTranslationCall(node, functions = []) {
662
+ const name = dottedName(node.callee);
663
+ if (!name)
664
+ return false;
665
+ // t(...), $t(...), i18next.t(...), props.t(...), this.$t(...), and the project's own (`extract.functions`)
666
+ return name === 't' || name === '$t' || /\.\$?t$/.test(name) || functions.some(fn => matchesFunctionPattern(name, fn));
667
+ }
668
+ /** A callee as a dotted name (`this.props.t`, `i18n.t`), or null for a computed one. */
669
+ function dottedName(callee) {
670
+ if (callee?.type === 'Identifier')
671
+ return callee.value;
672
+ if (callee?.type === 'ThisExpression')
673
+ return 'this';
674
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
675
+ return null;
676
+ const object = dottedName(callee.object);
677
+ return object && `${object}.${callee.property.value}`;
678
+ }
679
+ /**
680
+ * Methods whose string arguments are never text shown to a user: selectors, attribute and storage names,
681
+ * and the strings a text is searched for or compared with (translating `msg.includes('not found')` breaks it).
682
+ */
683
+ const NON_TEXT_METHODS = new Set([
684
+ 'querySelector', 'querySelectorAll', 'closest', 'matches', 'getElementById', 'getElementsByClassName',
685
+ 'getElementsByTagName', 'getElementsByName', 'addEventListener', 'removeEventListener',
686
+ 'getAttribute', 'hasAttribute', 'removeAttribute', 'getPropertyValue', 'setProperty', 'removeProperty',
687
+ 'getItem', 'setItem', 'removeItem',
688
+ // analytics event and user names: a translated one splits the data by language
689
+ 'track', 'trackEvent', 'logEvent', 'capture', 'captureMessage', 'captureException', 'identify',
690
+ // event names, and format patterns (`dayjs(d).format('DD MMM YYYY')`)
691
+ 'emit', 'on', 'once', 'off', 'addListener', 'removeListener', 'format',
692
+ 'indexOf', 'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'match', 'matchAll', 'search', 'replace',
693
+ 'replaceAll', 'split', 'localeCompare'
694
+ ]);
695
+ /**
696
+ * Functions whose string arguments are never text: `gtag('event', 'Sign Up Completed')`, `require('x')`,
697
+ * `RegExp('…')`, `format(date, 'yyyy-MM-dd')`.
698
+ */
699
+ const NON_TEXT_FUNCTIONS = new Set(['gtag', 'require', 'RegExp', 'format']);
700
+ /** Objects whose method calls are logs or error reports, for developers whatever they say. */
701
+ const LOG_OBJECTS = /^(?:logger|log|Sentry|sentry|Bugsnag|bugsnag|Rollbar|rollbar|winston|pino)$/;
702
+ /** A call to one of `NON_TEXT_METHODS` or `NON_TEXT_FUNCTIONS` (`el.closest('button, a')`, `gtag(…)`). */
703
+ function isNonTextMethodCall(node) {
510
704
  const callee = node.callee;
511
- if (!callee)
705
+ if (callee?.type === 'Identifier')
706
+ return NON_TEXT_FUNCTIONS.has(callee.value);
707
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
512
708
  return false;
513
- // t(...)
514
- if (callee.type === 'Identifier' && callee.value === 't')
515
- return true;
516
- // i18next.t(...)
517
- if (callee.type === 'MemberExpression' &&
518
- !callee.computed &&
519
- callee.property?.type === 'Identifier' &&
520
- callee.property.value === 't' &&
521
- callee.object?.type === 'Identifier' &&
522
- callee.object.value === 'i18next')
523
- return true;
524
- return false;
709
+ return NON_TEXT_METHODS.has(callee.property.value) || (callee.object?.type === 'Identifier' && LOG_OBJECTS.test(callee.object.value));
710
+ }
711
+ /**
712
+ * The names of a file's variables whose every use is inside a `console.*` call: a variable declared twice
713
+ * counts as one name, and any use elsewhere takes it out.
714
+ */
715
+ function collectConsoleOnlyNames(ast) {
716
+ const declared = new Set();
717
+ const inConsole = new Set();
718
+ const elsewhere = new Set();
719
+ const walk = (node, inLog) => {
720
+ if (!node || typeof node !== 'object')
721
+ return;
722
+ if (Array.isArray(node)) {
723
+ node.forEach(n => walk(n, inLog));
724
+ return;
725
+ }
726
+ if (node.type === 'VariableDeclarator') {
727
+ if (node.id?.type === 'Identifier')
728
+ declared.add(node.id.value);
729
+ else
730
+ walk(node.id, inLog);
731
+ walk(node.init, inLog);
732
+ return;
733
+ }
734
+ if (node.type === 'MemberExpression') {
735
+ walk(node.object, inLog);
736
+ if (node.property?.type === 'Computed')
737
+ walk(node.property, inLog);
738
+ return;
739
+ }
740
+ if (node.type === 'KeyValueProperty') {
741
+ walk(node.value, inLog);
742
+ return;
743
+ }
744
+ if (node.type === 'Identifier')
745
+ (inLog ? inConsole : elsewhere).add(node.value);
746
+ const log = inLog || (node.type === 'CallExpression' && isConsoleCall(node));
747
+ for (const key in node)
748
+ if (key !== 'span')
749
+ walk(node[key], log);
750
+ };
751
+ walk(ast, false);
752
+ return new Set([...declared].filter(n => inConsole.has(n) && !elsewhere.has(n)));
753
+ }
754
+ /** Per file, the names `collectConsoleOnlyNames` found for its content (set by the scan, read by the visit). */
755
+ const consoleOnlyNames = new Map();
756
+ /** The property names whose value is text (`label`, `title`, …), lower-cased. */
757
+ const translatablePropertyLowerSet = new Set([...translatablePropertySet].map(p => p.toLowerCase()));
758
+ /** String literals a JSX element renders (see `markRendered`): text whatever their words. */
759
+ const renderedStrings = new WeakSet();
760
+ /** Marks the strings an expression rendered as a JSX child can produce: itself, a branch, a fallback. */
761
+ function markRendered(expr) {
762
+ if (!expr)
763
+ return;
764
+ if (expr.type === 'StringLiteral')
765
+ renderedStrings.add(expr);
766
+ else if (expr.type === 'ConditionalExpression') {
767
+ markRendered(expr.consequent);
768
+ markRendered(expr.alternate);
769
+ }
770
+ else if (expr.type === 'BinaryExpression' && LOGICAL_OPERATORS.has(expr.operator)) {
771
+ // swc types `&&`, `||` and `??` as a BinaryExpression
772
+ markRendered(expr.right);
773
+ }
774
+ else if (expr.type === 'ParenthesisExpression')
775
+ markRendered(expr.expression);
776
+ }
777
+ /** Per file, the strings `collectDataStrings` found (set by the scan, read by the visit). */
778
+ const fileDataStrings = new Map();
779
+ /** Property and attribute names whose string value is data the code matches against. */
780
+ const DATA_KEYS = new Set(['id', 'key', 'value', 'type', 'code', 'kind']);
781
+ /** Names of lists whose strings are values to match (`order: ['2FA', 'no 2FA']`). */
782
+ const DATA_LISTS = /^(?:order|ids|keys|values|types|kinds|codes)$/i;
783
+ /**
784
+ * The strings a file uses as data: compared (`=== 'no 2FA'`), a `case`, an object key, the value of an `id`,
785
+ * `key`, `value`, `type`, `code` or `kind`, an entry of an `order`/`ids`/`values` list, or an argument of a
786
+ * method that compares (`includes`). The same string as text elsewhere in that file is then data too: a
787
+ * facet's `of()` returning `'no 2FA'` must keep matching `order: ['2FA', 'no 2FA']`.
788
+ */
789
+ function collectDataStrings(ast) {
790
+ const found = new Set();
791
+ const add = (node) => { if (node?.type === 'StringLiteral')
792
+ found.add(node.value); };
793
+ const addList = (node) => { if (node?.type === 'ArrayExpression')
794
+ for (const e of node.elements ?? [])
795
+ add(e?.expression); };
796
+ const walk = (node) => {
797
+ if (!node || typeof node !== 'object')
798
+ return;
799
+ if (Array.isArray(node)) {
800
+ node.forEach(walk);
801
+ return;
802
+ }
803
+ if (node.type === 'BinaryExpression' && COMPARISON_OPERATORS.has(node.operator)) {
804
+ add(node.left);
805
+ add(node.right);
806
+ }
807
+ if (node.type === 'SwitchCase')
808
+ add(node.test);
809
+ if (node.type === 'KeyValueProperty') {
810
+ add(node.key);
811
+ const name = propertyName(node.key);
812
+ if (name && DATA_KEYS.has(name))
813
+ add(node.value);
814
+ if (name && DATA_LISTS.test(name))
815
+ addList(node.value);
816
+ }
817
+ if (node.type === 'VariableDeclarator' && DATA_LISTS.test(node.id?.value ?? ''))
818
+ addList(node.init);
819
+ if (node.type === 'JSXAttribute' && DATA_KEYS.has(node.name?.value) && node.value?.type === 'StringLiteral')
820
+ add(node.value);
821
+ if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
822
+ for (const arg of node.arguments ?? [])
823
+ add(arg.expression);
824
+ if (node.callee?.type === 'MemberExpression')
825
+ addList(node.callee.object);
826
+ }
827
+ for (const key in node)
828
+ if (key !== 'span')
829
+ walk(node[key]);
830
+ };
831
+ walk(ast);
832
+ return found;
833
+ }
834
+ /** `console.log(...)`, `console.warn(...)`: their arguments are for developers, however they are built. */
835
+ function isConsoleCall(node) {
836
+ const callee = node.callee;
837
+ return callee?.type === 'MemberExpression' && callee.object?.type === 'Identifier' && callee.object.value === 'console';
525
838
  }
526
839
  /**
527
840
  * Recursively visits AST nodes to find string literals.
@@ -534,14 +847,22 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
534
847
  if (node.type === 'JSXOpeningElement' && jsx) {
535
848
  jsx = { ...jsx, element: resolveElementAttributes(jsx.rules, jsxElementName(node.name, jsx.aliases)) };
536
849
  }
537
- // Skip already-instrumented t() / i18next.t() calls entirely so that
538
- // strings inside the options object (defaultValue_one, etc.) are not
539
- // picked up as new candidates on a second run.
540
- if (node.type === 'CallExpression' && isTranslationCall(node))
850
+ const visit = (child) => visitNodeForStrings(child, content, file, config, candidates, jsx);
851
+ // Its string arguments are not text; what it is called on and the functions it gets may hold some
852
+ // (`el.addEventListener('click', () => { status.textContent = 'Copied to clipboard' })`)
853
+ if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
854
+ visit(node.callee);
855
+ for (const arg of node.arguments ?? [])
856
+ visitTextHolders(arg.expression, content, file, config, candidates, jsx);
541
857
  return;
542
- // Skip <Trans> elements (already instrumented)
543
- if (node.type === 'JSXElement' && isTransComponent(node))
858
+ }
859
+ const parts = nonTextParts(node, file, config, true);
860
+ if (parts === 'all')
861
+ return;
862
+ if (parts) {
863
+ forEachChild(node, parts, visit);
544
864
  return;
865
+ }
545
866
  // Skip non-translatable JSX attributes entirely (e.g. className={...})
546
867
  if (node.type === 'JSXAttribute') {
547
868
  const nameNode = node.name;
@@ -555,31 +876,47 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
555
876
  }
556
877
  // A rule that adds an attribute on this element wins over the built-in skip list (e.g. `name`)
557
878
  const added = attrName != null && jsx?.element?.accepted.has(attrName.toLowerCase());
558
- if (attrName && ignoredAttributeSet.has(attrName) && !added)
559
- return;
560
- // A rule removed this attribute on this element: its value is not text, skip it entirely
561
- if (attrName && jsx?.element?.removed.has(attrName.toLowerCase()))
879
+ // The value of an ignored attribute, or one a rule removed on this element, is not text; but the
880
+ // elements and functions in it hold text as anywhere else (`action={<Button>change</Button>}`,
881
+ // `onClick={() => setMessage('Copied')}`)
882
+ const notText = !!attrName && ((ignoredAttributeSet.has(attrName) && !added) ||
883
+ !!jsx?.element?.removed.has(attrName.toLowerCase()) ||
884
+ // For hyphenated names (data-testid), also check with the raw text
885
+ (attrName.includes(':') && ignoredAttributeSet.has(attrName.replace(':', '-'))));
886
+ if (notText) {
887
+ visitTextHolders(node.value, content, file, config, candidates, jsx);
562
888
  return;
563
- // For hyphenated names (data-testid), also check with the raw text
564
- if (attrName?.includes(':')) {
565
- const hyphenated = attrName.replace(':', '-');
566
- if (ignoredAttributeSet.has(hyphenated))
567
- return;
568
889
  }
569
890
  }
891
+ // What a JSX element renders from an expression is text, a single word too: `{used ? <>…</> : 'Never used'}`,
892
+ // `{busy && 'saving'}`, `{name || 'the organization'}`
893
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
894
+ for (const child of node.children ?? [])
895
+ if (child.type === 'JSXExpressionContainer')
896
+ markRendered(child.expression);
897
+ }
898
+ // The two branches of a ternary are alternatives of one text: when one is text, a string on the other side
899
+ // is too (`running ? 'Confirm all reviews' : 'stop'`, `n ? \`Pay invoice ${n}\` : 'Pay invoice'`)
900
+ if (node.type === 'ConditionalExpression') {
901
+ visit(node.test);
902
+ visit(node.consequent);
903
+ visit(node.alternate);
904
+ const branches = [node.consequent, node.alternate];
905
+ const found = (b) => candidates.some(c => c.offset === b?.span?.start && c.endOffset === b?.span?.end);
906
+ branches.forEach((b, i) => {
907
+ if (b?.type !== 'StringLiteral' || found(b) || !found(branches[1 - i]))
908
+ return;
909
+ const candidate = stringCandidate(b, content, file, config, jsx?.element?.accepted, true);
910
+ if (candidate)
911
+ candidates.push(candidate);
912
+ });
913
+ return;
914
+ }
570
915
  // Check if this is a string literal
571
916
  if (node.type === 'StringLiteral') {
572
- const stringNode = node;
573
- if (stringNode.span && typeof stringNode.span.start === 'number') {
574
- const candidate = detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, jsx?.element?.accepted);
575
- if (candidate && candidate.confidence >= 0.7) {
576
- // Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
577
- if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=') {
578
- candidate.type = 'jsx-attribute';
579
- }
580
- candidates.push(candidate);
581
- }
582
- }
917
+ const candidate = stringCandidate(node, content, file, config, jsx?.element?.accepted, renderedStrings.has(node));
918
+ if (candidate)
919
+ candidates.push(candidate);
583
920
  }
584
921
  // Template literals
585
922
  if (node.type === 'TemplateLiteral') {
@@ -601,18 +938,26 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
601
938
  }
602
939
  }
603
940
  else if (quasis?.length > 1 && expressions?.length > 0 && node.span) {
604
- // Template literal with interpolation, e.g. `${count}-day streak`
605
- const result = buildInterpolatedTemplate(quasis, expressions, content);
606
- if (result) {
941
+ // Template literal with interpolation, e.g. `${count}-day streak`, possibly with a plural in it
942
+ const plural = buildPluralTemplate(quasis, expressions, content);
943
+ const result = plural
944
+ ? { text: plural.pluralForms.other, interpolations: plural.interpolations }
945
+ : buildInterpolatedTemplate(quasis, expressions, content);
946
+ if (result && hasWordsBesidePlaceholders(result.text)) {
607
947
  const trimmed = result.text.trim();
608
948
  if (trimmed) {
609
949
  const candidate = detectCandidate(trimmed, node.span.start, node.span.end, file, content, config);
610
950
  if (candidate) {
611
951
  candidate.content = trimmed;
612
952
  candidate.type = 'template-literal';
613
- candidate.interpolations = result.interpolations;
614
- // Template literals mixing text + expressions are likely user-facing
615
- candidate.confidence = Math.min(1, candidate.confidence + 0.15);
953
+ if (result.interpolations.length)
954
+ candidate.interpolations = result.interpolations;
955
+ if (plural) {
956
+ candidate.pluralForms = plural.pluralForms;
957
+ candidate.pluralHelper = plural.pluralHelper;
958
+ }
959
+ // Template literals mixing text + expressions are likely user-facing, plurals always
960
+ candidate.confidence = Math.min(1, candidate.confidence + (plural ? 0.3 : 0.15));
616
961
  if (node.span.start > 0 && content[node.span.start - 1] === '=') {
617
962
  candidate.type = 'jsx-attribute';
618
963
  }
@@ -633,7 +978,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
633
978
  const trimmedStart = raw.indexOf(trimmed);
634
979
  const offset = node.span.start + trimmedStart;
635
980
  const endOffset = offset + trimmed.length;
636
- const candidate = detectCandidate(trimmed, offset, endOffset, file, content, config);
981
+ const candidate = detectCandidate(jsxTextValue(trimmed), offset, endOffset, file, content, config, undefined, true);
637
982
  if (candidate) {
638
983
  candidate.type = 'jsx-text';
639
984
  // JSXText is almost always user-visible content; boost confidence
@@ -658,6 +1003,183 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
658
1003
  }
659
1004
  }
660
1005
  }
1006
+ /**
1007
+ * Whether a name says it holds a language model's input: a function or variable (not a component) whose
1008
+ * camelCase words include `prompt` and one of system, user, ai, llm, gpt, assistant, chat, model
1009
+ * (`getSystemPrompt`, `aiFixPrompt`, `userPromptBatch`). A bare `prompt` may ask the user something
1010
+ * (`deletePrompt`), and `EmailPrompt` or `UserPromptDialog` are components.
1011
+ */
1012
+ function isModelPromptName(name) {
1013
+ if (!name || !/^[a-z]/.test(name))
1014
+ return false;
1015
+ const words = name.split(/(?=[A-Z])|_/).map(w => w.toLowerCase());
1016
+ return words.includes('prompt') && words.some(w => MODEL_WORDS.has(w));
1017
+ }
1018
+ const MODEL_WORDS = new Set(['system', 'user', 'ai', 'llm', 'gpt', 'assistant', 'chat', 'model']);
1019
+ /**
1020
+ * JSX text as React renders it: each line trimmed where it meets a line break, the lines joined by one space,
1021
+ * entities decoded (`can&apos;t` → `can't`). In a `t()` default the source form would show as written.
1022
+ */
1023
+ function jsxTextValue(raw) {
1024
+ const lines = raw.split(/\r\n|\n|\r/);
1025
+ let lastNonEmpty = 0;
1026
+ lines.forEach((line, i) => { if (/[^ \t]/.test(line))
1027
+ lastNonEmpty = i; });
1028
+ let text = '';
1029
+ lines.forEach((line, i) => {
1030
+ let part = line.replace(/\t/g, ' ');
1031
+ if (i > 0)
1032
+ part = part.replace(/^ +/, '');
1033
+ if (i < lines.length - 1)
1034
+ part = part.replace(/ +$/, '');
1035
+ if (part)
1036
+ text += i < lastNonEmpty ? `${part} ` : part;
1037
+ });
1038
+ return text.replace(HTML_ENTITY_RE, entity => decodeEntity(entity));
1039
+ }
1040
+ const NAMED_ENTITIES = {
1041
+ amp: '&',
1042
+ lt: '<',
1043
+ gt: '>',
1044
+ quot: '"',
1045
+ apos: "'",
1046
+ nbsp: '\u00a0',
1047
+ ndash: '–',
1048
+ mdash: '—',
1049
+ hellip: '…',
1050
+ lsquo: '‘',
1051
+ rsquo: '’',
1052
+ ldquo: '“',
1053
+ rdquo: '”',
1054
+ laquo: '«',
1055
+ raquo: '»',
1056
+ middot: '·',
1057
+ bull: '•',
1058
+ times: '×',
1059
+ copy: '©',
1060
+ reg: '®',
1061
+ trade: '™',
1062
+ euro: '€',
1063
+ deg: '°'
1064
+ };
1065
+ /** One HTML character reference as its character; an unknown name stays as written. */
1066
+ function decodeEntity(entity) {
1067
+ const body = entity.slice(1, -1);
1068
+ if (body[0] === '#') {
1069
+ const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1070
+ return Number.isFinite(code) && code <= 0x10FFFF ? String.fromCodePoint(code) : entity;
1071
+ }
1072
+ return NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()] ?? entity;
1073
+ }
1074
+ /**
1075
+ * What of a node is never text, the same for every walker looking for text: `'all'` (a t() call, a console
1076
+ * call, a <Trans>, an icon, code, a prompt for a language model, a log line, an error or a pattern), the
1077
+ * child keys that are not (an object key, a member property, a compared operand, a `case` value, the strings
1078
+ * of a non-text call), or null (all of it may be). `withTextHolders` is for the walker that visits the
1079
+ * functions and elements passed to a non-text call itself.
1080
+ */
1081
+ function nonTextParts(node, file, config, withTextHolders) {
1082
+ switch (node.type) {
1083
+ case 'CallExpression':
1084
+ // already instrumented (also its options on a second run), or for developers however it is built
1085
+ if (isTranslationCall(node, config.extract.functions) || isConsoleCall(node))
1086
+ return 'all';
1087
+ return !withTextHolders && isNonTextMethodCall(node) ? ['arguments'] : null;
1088
+ case 'NewExpression':
1089
+ // `new Error('…')` is for developers, `new RegExp('…')` a pattern
1090
+ return node.callee?.type === 'Identifier' && /^RegExp$|Error$/.test(node.callee.value) ? 'all' : null;
1091
+ case 'JSXElement': {
1092
+ if (isTransComponent(node, config.extract.transComponents) || isIconElement(node))
1093
+ return 'all';
1094
+ // what code, scripts and styles show (`ignoredTags`, as for lint); inside a sentence it stays in its <Trans>
1095
+ const tag = node.opening?.name?.type === 'Identifier' ? node.opening.name.value.toLowerCase() : null;
1096
+ return tag && (ignoredTags.includes(tag) || config.extract.ignoredTags?.some(t => t.toLowerCase() === tag)) ? 'all' : null;
1097
+ }
1098
+ case 'KeyValueProperty':
1099
+ // a key names something and is never text; a call there is even a syntax error (`{ 'a b': 1 }`)
1100
+ return isModelPromptName(propertyName(node.key)) ? 'all' : ['key'];
1101
+ case 'MemberExpression':
1102
+ return ['property'];
1103
+ case 'BinaryExpression':
1104
+ // the strings a value is compared with are data (`status === 'Active'`)
1105
+ if (!COMPARISON_OPERATORS.has(node.operator))
1106
+ return null;
1107
+ return ['left', 'right'].filter(k => node[k]?.type === 'StringLiteral' || node[k]?.type === 'TemplateLiteral');
1108
+ case 'SwitchCase':
1109
+ return ['test'];
1110
+ case 'FunctionDeclaration':
1111
+ // a prompt is the input of a language model: translating it changes what the model does
1112
+ return isModelPromptName(node.identifier?.value) ? 'all' : null;
1113
+ case 'VariableDeclarator':
1114
+ // a prompt, or a variable used only in console calls (a log line: `const took = …; console.log(took)`)
1115
+ return isModelPromptName(node.id?.value) ||
1116
+ (node.id?.type === 'Identifier' && consoleOnlyNames.get(file)?.has(node.id.value))
1117
+ ? 'all'
1118
+ : null;
1119
+ default:
1120
+ return null;
1121
+ }
1122
+ }
1123
+ /** Calls `visit` for each child node, but not those under the keys `except`. */
1124
+ function forEachChild(node, except, visit) {
1125
+ if (except === 'all')
1126
+ return;
1127
+ for (const key in node) {
1128
+ if (key === 'span' || except?.includes(key))
1129
+ continue;
1130
+ const value = node[key];
1131
+ if (Array.isArray(value))
1132
+ value.forEach(item => item && typeof item === 'object' && visit(item));
1133
+ else if (value && typeof value === 'object')
1134
+ visit(value);
1135
+ }
1136
+ }
1137
+ /** A string literal as a candidate of enough confidence, or null; `textSlot` takes a single word as text. */
1138
+ function stringCandidate(stringNode, content, file, config, accepted, textSlot) {
1139
+ if (!stringNode.span || typeof stringNode.span.start !== 'number')
1140
+ return null;
1141
+ // the same string as data elsewhere in the file: translating it here breaks the match there (what a JSX
1142
+ // element renders and an attribute's value, `data-tip='overridden'`, are shown, never matched)
1143
+ // nor a text property's (`{ value: 'Weekly', label: 'Weekly' }`)
1144
+ const attributeValue = stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=';
1145
+ const property = /([\w]+)\s*:\s*$/.exec(content.slice(Math.max(0, stringNode.span.start - 40), stringNode.span.start))?.[1];
1146
+ const textProperty = !!property && translatablePropertyLowerSet.has(property.toLowerCase());
1147
+ if (fileDataStrings.get(file)?.has(stringNode.value) && !renderedStrings.has(stringNode) && !attributeValue && !textProperty)
1148
+ return null;
1149
+ const candidate = detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, accepted, textSlot);
1150
+ // in a text slot the place says it is text, whatever the words score
1151
+ if (candidate && textSlot)
1152
+ candidate.confidence = Math.max(candidate.confidence, 0.7);
1153
+ if (!candidate || candidate.confidence < 0.7)
1154
+ return null;
1155
+ // Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
1156
+ if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=')
1157
+ candidate.type = 'jsx-attribute';
1158
+ return candidate;
1159
+ }
1160
+ const LOGICAL_OPERATORS = new Set(['&&', '||', '??']);
1161
+ const COMPARISON_OPERATORS = new Set(['===', '!==', '==', '!=', 'in', 'instanceof']);
1162
+ /** The name of an object property's key (`label`, `'aria-label'`), or null for a computed one. */
1163
+ function propertyName(key) {
1164
+ return key?.type === 'Identifier' || key?.type === 'StringLiteral' ? key.value : null;
1165
+ }
1166
+ /** Visits the JSX elements and functions inside a value that is not text itself, and nothing else of it. */
1167
+ function visitTextHolders(node, ...rest) {
1168
+ if (!node || typeof node !== 'object')
1169
+ return;
1170
+ if (TEXT_HOLDERS.has(node.type)) {
1171
+ visitNodeForStrings(node, ...rest);
1172
+ return;
1173
+ }
1174
+ for (const key in node) {
1175
+ const value = node[key];
1176
+ if (Array.isArray(value))
1177
+ value.forEach(item => visitTextHolders(item, ...rest));
1178
+ else
1179
+ visitTextHolders(value, ...rest);
1180
+ }
1181
+ }
1182
+ const TEXT_HOLDERS = new Set(['JSXElement', 'JSXFragment', 'ArrowFunctionExpression', 'FunctionExpression']);
661
1183
  // ─── Template-literal interpolation helpers ──────────────────────────────────
662
1184
  /**
663
1185
  * Builds a merged text with `{{var}}` placeholders from a template literal's
@@ -665,7 +1187,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
665
1187
  */
666
1188
  function buildInterpolatedTemplate(quasis, expressions, content) {
667
1189
  const interpolations = [];
668
- const usedNames = new Set();
1190
+ const usedNames = new Map();
669
1191
  let text = '';
670
1192
  for (let i = 0; i < quasis.length; i++) {
671
1193
  const quasi = quasis[i];
@@ -675,38 +1197,168 @@ function buildInterpolatedTemplate(quasis, expressions, content) {
675
1197
  if (!info)
676
1198
  return null; // un-resolvable expression — bail
677
1199
  text += `{{${info.name}}}`;
678
- interpolations.push(info);
1200
+ if (!info.reused)
1201
+ interpolations.push(info);
679
1202
  }
680
1203
  }
681
1204
  return interpolations.length > 0 ? { text, interpolations } : null;
682
1205
  }
683
1206
  /**
684
- * Resolves a human-friendly interpolation name from an AST expression node.
685
- *
686
- * - `Identifier` → uses the identifier value (`count`)
687
- * - `MemberExpression` → uses the deepest property name (`profile.name` → `name`)
688
- * - anything else → generated placeholder (`val`, `val2`, ...)
1207
+ * Whether a text with `{{placeholders}}` holds at least one word standing on its own, and is not a
1208
+ * kebab-case name. A word: two letters or more, not camelCase, punctuation around it, a placeholder only
1209
+ * after it (`review{{suffix}}.`), not before it nor joined by `_`, `.` or `-`. Ids, paths, keys, flags and
1210
+ * class names built in a template literal have none: `{{projectId}}-{{version}}`, `weight_{{code}}`,
1211
+ * `{{baseUrl}}/api/{{id}}`, `{{id}}.collapsed`, `{{metric}}Avg`, `nameField{{i}}`, `--ct {{cdnType}}`,
1212
+ * `locize-dropzone {{state}}`.
1213
+ */
1214
+ function hasWordsBesidePlaceholders(text) {
1215
+ // a placeholder becomes one private-use character, neither letter nor punctuation
1216
+ const bare = text.replace(HTML_ENTITY_RE, ' ').replace(/\{\{[^}]*\}\}/g, '\uE000');
1217
+ if (/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(bare.replace(/\uE000/g, ' ').trim()))
1218
+ return false;
1219
+ return bare.split(/\s+/).some(token => {
1220
+ const word = /^[^\p{L}\p{N}\uE000_.-]*(\p{L}{2,}(?:['’-]\p{L}+)*)[^\p{L}\p{N}_]*$/u.exec(token)?.[1];
1221
+ // `zh-{{country}}`, `{{a}}/{{b}}`: a placeholder joined to the word by a separator makes an id, not a phrase
1222
+ if (/[-_./:#@=&?|\\]\uE000/.test(token))
1223
+ return false;
1224
+ // one Han, Kana or Hangul character is a word of its own (`共 {{n}} 条`)
1225
+ return (!!word && !/\p{Ll}\p{Lu}/u.test(word)) || /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Hangul}]/u.test(token);
1226
+ });
1227
+ }
1228
+ /**
1229
+ * A template literal one of whose expressions is a plural (a plural helper call or a `count === 1` ternary),
1230
+ * as one text per plural form: `${n(keys)} ${plural(keys, 'key', 'keys')} unused` → one: '{{keys}} key unused',
1231
+ * other: '{{keys}} keys unused', count: keys. An expression that is the count itself becomes `{{count}}`.
1232
+ */
1233
+ function buildPluralTemplate(quasis, expressions, content) {
1234
+ const pluralIndex = expressions.findIndex(e => parsePluralExpression(e, content));
1235
+ if (pluralIndex < 0)
1236
+ return null;
1237
+ const plural = parsePluralExpression(expressions[pluralIndex], content);
1238
+ const usedNames = new Map();
1239
+ const interpolations = [];
1240
+ const formText = (form) => {
1241
+ let text = '';
1242
+ for (let i = 0; i < quasis.length; i++) {
1243
+ text += quasis[i].cooked ?? quasis[i].raw ?? '';
1244
+ if (i >= expressions.length)
1245
+ continue;
1246
+ if (i === pluralIndex) {
1247
+ text += form;
1248
+ continue;
1249
+ }
1250
+ const expression = content.slice(expressions[i].span.start, expressions[i].span.end);
1251
+ if (expression === plural.countExpression) {
1252
+ text += '{{count}}';
1253
+ continue;
1254
+ }
1255
+ const info = resolveExpressionName(expressions[i], content, usedNames);
1256
+ if (!info)
1257
+ return null;
1258
+ text += `{{${info.name}}}`;
1259
+ if (!info.reused)
1260
+ interpolations.push(info);
1261
+ }
1262
+ return text.trim();
1263
+ };
1264
+ const other = formText(plural.other);
1265
+ const one = plural.one !== undefined ? formText(plural.one) : undefined;
1266
+ const zero = plural.zero !== undefined ? formText(plural.zero) : undefined;
1267
+ if (!other || one === null || zero === null)
1268
+ return null;
1269
+ if (!mergeInterpolations(interpolations, plural.interpolations))
1270
+ return null;
1271
+ return { pluralForms: { countExpression: plural.countExpression, zero, one, other }, interpolations, pluralHelper: pluralHelperOf(expressions[pluralIndex]) };
1272
+ }
1273
+ /** The name of the plural helper a call expression calls (`plural(n, …)` → `plural`), or undefined. */
1274
+ function pluralHelperOf(expr) {
1275
+ return expr?.type === 'CallExpression' && expr.callee?.type === 'Identifier' ? expr.callee.value : undefined;
1276
+ }
1277
+ /**
1278
+ * Adds a plural's own placeholders (from its forms) to the text's; false when a name stands for two
1279
+ * different expressions.
1280
+ */
1281
+ function mergeInterpolations(into, from = []) {
1282
+ for (const item of from) {
1283
+ const same = into.find(i => i.name === item.name);
1284
+ if (same && same.expression !== item.expression)
1285
+ return false;
1286
+ if (!same)
1287
+ into.push(item);
1288
+ }
1289
+ return true;
1290
+ }
1291
+ /**
1292
+ * The name an expression's value says best what it is, or null:
1293
+ * - `Identifier` → itself (`count`); `MemberExpression` → its last property (`profile.name` → `name`)
1294
+ * - a formatter's call, by its argument: `format.date(user.lastLogin)` → `lastLogin`, `n(queue)` → `queue`,
1295
+ * `Math.floor(m / 60)` → `m` (a namespace or a formatter keeps the meaning of what it gets)
1296
+ * - a string method's call, by what it is called on: `input.value.trim()` → `value`
1297
+ * - any other call, by the function: `price(plan)` → `price`, `api.calculatePercentage(stats)` → `calculatePercentage`
1298
+ * - `a - b`, `a || b`, `(a)`, `a as T`, `a!` → the name of `a`
1299
+ */
1300
+ function nameOfExpression(expr) {
1301
+ switch (expr?.type) {
1302
+ case 'Identifier': return expr.value;
1303
+ case 'MemberExpression':
1304
+ return !expr.computed && expr.property?.type === 'Identifier' ? expr.property.value : null;
1305
+ case 'CallExpression': {
1306
+ const callee = expr.callee;
1307
+ const argument = () => nameOfExpression(expr.arguments?.[0]?.expression);
1308
+ if (callee?.type === 'Identifier')
1309
+ return FORMATTER_RE.test(callee.value) ? argument() : callee.value;
1310
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
1311
+ return null;
1312
+ const object = callee.object;
1313
+ const method = callee.property.value;
1314
+ if (object?.type === 'Identifier' && (/^[A-Z]/.test(object.value) || FORMATTER_NAMESPACE_RE.test(object.value)))
1315
+ return argument();
1316
+ // `date.toLocaleDateString()`, `terms.map(…).join(', ')`: still the value it is called on
1317
+ if (STRING_METHODS.has(method) || ARRAY_METHODS.has(method))
1318
+ return nameOfExpression(object);
1319
+ return method;
1320
+ }
1321
+ case 'BinaryExpression':
1322
+ // `name || email` (swc types `||`, `&&`, `??` as a BinaryExpression), `i + 1`: the value meant; any other
1323
+ // arithmetic is a new quantity (`segments * tokensPerSegment`), which no operand names
1324
+ if (LOGICAL_OPERATORS.has(expr.operator))
1325
+ return nameOfExpression(expr.left);
1326
+ if ((expr.operator === '+' || expr.operator === '-') && expr.right?.type === 'NumericLiteral')
1327
+ return nameOfExpression(expr.left);
1328
+ return null;
1329
+ case 'ParenthesisExpression':
1330
+ case 'TsAsExpression':
1331
+ case 'TsNonNullExpression':
1332
+ case 'TsSatisfiesExpression': return nameOfExpression(expr.expression);
1333
+ default: return null;
1334
+ }
1335
+ }
1336
+ /** Names of formatter functions: their call shows the value they get (`n(queue)`, `formatDate(createdAt)`). */
1337
+ const FORMATTER_RE = /^(?:format\w*|fmt|formatter|n|num|number|money|percent)$/i;
1338
+ /** Names of formatting namespaces (`format.date(x)`); a capitalized one (`Math`, `Intl`) is one too. */
1339
+ const FORMATTER_NAMESPACE_RE = /^(?:format\w*|fmt|formatter|intl)$/i;
1340
+ /** Array methods whose result still holds what they are called on. */
1341
+ const ARRAY_METHODS = new Set(['map', 'filter', 'sort', 'slice', 'flat', 'flatMap', 'concat', 'reverse']);
1342
+ /**
1343
+ * Resolves a human-friendly interpolation name from an AST expression node (see `nameOfExpression`;
1344
+ * `val`, `val2`, ... when none). The same expression twice in one text gets one name (`reused`), so the
1345
+ * options name it once.
689
1346
  */
690
1347
  function resolveExpressionName(expr, content, usedNames) {
691
1348
  if (!expr?.span)
692
1349
  return null;
693
1350
  const expression = content.slice(expr.span.start, expr.span.end);
694
- let baseName;
695
- if (expr.type === 'Identifier') {
696
- baseName = expr.value;
697
- }
698
- else if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier') {
699
- baseName = expr.property.value;
700
- }
701
- else {
702
- baseName = 'val';
1351
+ for (const [name, expr] of usedNames) {
1352
+ if (expr === expression)
1353
+ return { name, expression, reused: true };
703
1354
  }
1355
+ const baseName = nameOfExpression(expr) ?? 'val';
704
1356
  let name = baseName;
705
1357
  let counter = 2;
706
1358
  while (usedNames.has(name)) {
707
1359
  name = `${baseName}${counter++}`;
708
1360
  }
709
- usedNames.add(name);
1361
+ usedNames.set(name, expression);
710
1362
  return { name, expression };
711
1363
  }
712
1364
  // ─── JSX sibling interpolation merging ───────────────────────────────────────
@@ -720,8 +1372,9 @@ function resolveExpressionName(expr, content, usedNames) {
720
1372
  function detectJSXInterpolation(node, content, file, config, candidates) {
721
1373
  if (!node)
722
1374
  return;
723
- // Skip <Trans> elements (already instrumented)
724
- if (node.type === 'JSXElement' && isTransComponent(node))
1375
+ // Not text (a <Trans>, code, an icon, a prompt, a log line, a key, …): nothing to merge in it
1376
+ const parts = nonTextParts(node, file, config, false);
1377
+ if (parts === 'all')
725
1378
  return;
726
1379
  const children = (node.type === 'JSXElement' || node.type === 'JSXFragment') ? node.children : null;
727
1380
  if (children?.length > 1) {
@@ -732,13 +1385,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
732
1385
  if (child.type === 'JSXText') {
733
1386
  currentRun.push(child);
734
1387
  }
735
- else if (child.type === 'JSXExpressionContainer' && isSimpleJSXExpression(child.expression)) {
1388
+ else if (child.type === 'JSXExpressionContainer' && (isSimpleJSXExpression(child.expression) || child.expression?.type === 'StringLiteral')) {
1389
+ // a simple expression, or literal text such as {' '}
736
1390
  currentRun.push(child);
737
1391
  }
738
- else if (child.type === 'JSXExpressionContainer' &&
739
- child.expression?.type === 'ConditionalExpression' &&
740
- tryParsePluralTernary(child.expression, content)) {
741
- // Plural ternary expression — include in the run for merged handling
1392
+ else if (child.type === 'JSXExpressionContainer' && parsePluralExpression(child.expression, content)) {
1393
+ // Plural ternary or plural helper call: part of the run, merged with it
742
1394
  currentRun.push(child);
743
1395
  }
744
1396
  else if (child.type === 'JSXElement' && isSimpleJSXElement(child)) {
@@ -756,7 +1408,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
756
1408
  if (currentRun.length > 0) {
757
1409
  runs.push(currentRun);
758
1410
  }
759
- for (const run of runs) {
1411
+ for (const fullRun of runs) {
1412
+ // Whitespace at a run's edges stays in the source: a rewrite of it would drop a space the page shows
1413
+ // (`provider:{' '}<strong>…`)
1414
+ const run = trimRun(fullRun);
1415
+ if (!run.length)
1416
+ continue;
760
1417
  const hasText = run.some(c => c.type === 'JSXText' && c.value?.trim());
761
1418
  const hasExpr = run.some(c => c.type === 'JSXExpressionContainer');
762
1419
  const hasElement = run.some(c => c.type === 'JSXElement');
@@ -769,9 +1426,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
769
1426
  let pluralChild = null;
770
1427
  let pluralData = null;
771
1428
  for (const child of run) {
772
- if (child.type === 'JSXExpressionContainer' &&
773
- child.expression?.type === 'ConditionalExpression') {
774
- const p = tryParsePluralTernary(child.expression, content);
1429
+ if (child.type === 'JSXExpressionContainer') {
1430
+ const p = parsePluralExpression(child.expression, content);
775
1431
  if (p) {
776
1432
  pluralChild = child;
777
1433
  pluralData = p;
@@ -779,12 +1435,15 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
779
1435
  }
780
1436
  }
781
1437
  }
1438
+ // A sentence with both an element and a plural stays in its parts: in a <Trans> the plural's forms would
1439
+ // end up untranslated in an interpolation, and a plural t() cannot hold the element
1440
+ if (hasElement && pluralChild)
1441
+ continue;
782
1442
  if (hasElement) {
783
1443
  // ── JSX sibling run with nested HTML elements → <Trans> ──
784
- const spanStart = run[0].span.start;
785
- const spanEnd = run[run.length - 1].span.end;
1444
+ const [spanStart, spanEnd] = runSpan(run, content);
786
1445
  // Build the translation string (with indexed tags) and text-only version (for scoring)
787
- const usedNames = new Set();
1446
+ const usedNames = new Map();
788
1447
  const interpolations = [];
789
1448
  let transValue = '';
790
1449
  let textOnly = '';
@@ -794,9 +1453,19 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
794
1453
  for (const child of run) {
795
1454
  if (child.type === 'JSXText') {
796
1455
  const raw = content.slice(child.span.start, child.span.end);
797
- transValue += raw;
798
- textOnly += raw;
1456
+ const text = jsxTextValue(raw);
1457
+ transValue += text;
1458
+ textOnly += text;
799
1459
  transContent += raw;
1460
+ // whitespace with a line break is no child of the element at all
1461
+ if (text)
1462
+ childIndex++;
1463
+ }
1464
+ else if (child.type === 'JSXExpressionContainer' && child.expression?.type === 'StringLiteral') {
1465
+ // {' '} and other literal text: part of the sentence, kept as written
1466
+ transValue += child.expression.value;
1467
+ textOnly += child.expression.value;
1468
+ transContent += content.slice(child.span.start, child.span.end);
800
1469
  childIndex++;
801
1470
  }
802
1471
  else if (child.type === 'JSXExpressionContainer') {
@@ -810,7 +1479,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
810
1479
  // In <Trans> children, simple expressions become {{ obj }} syntax
811
1480
  const objExpr = info.name === info.expression ? info.name : `${info.name}: ${info.expression}`;
812
1481
  transContent += `{{ ${objExpr} }}`;
813
- interpolations.push(info);
1482
+ if (!info.reused)
1483
+ interpolations.push(info);
814
1484
  childIndex++;
815
1485
  }
816
1486
  else if (child.type === 'JSXElement') {
@@ -853,12 +1523,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
853
1523
  // ── JSX sibling run with embedded plural ternary ──
854
1524
  const countExpr = pluralData.countExpression;
855
1525
  // Resolve names for non-count, non-plural expressions
856
- const usedNames = new Set();
1526
+ const usedNames = new Map();
857
1527
  const extraInterpolations = [];
858
1528
  const exprNameMap = new Map();
859
1529
  let valid = true;
860
1530
  for (const child of run) {
861
- if (child.type === 'JSXExpressionContainer' && child !== pluralChild) {
1531
+ if (child.type === 'JSXExpressionContainer' && child !== pluralChild && child.expression?.type !== 'StringLiteral') {
862
1532
  const exprText = content.slice(child.expression.span.start, child.expression.span.end);
863
1533
  if (exprText === countExpr) {
864
1534
  exprNameMap.set(child, 'count');
@@ -870,11 +1540,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
870
1540
  break;
871
1541
  }
872
1542
  exprNameMap.set(child, info.name);
873
- extraInterpolations.push(info);
1543
+ if (!info.reused)
1544
+ extraInterpolations.push(info);
874
1545
  }
875
1546
  }
876
1547
  }
877
- if (!valid)
1548
+ if (!valid || !mergeInterpolations(extraInterpolations, pluralData.interpolations))
878
1549
  continue;
879
1550
  // Build merged text for each plural form
880
1551
  const forms = [
@@ -887,7 +1558,10 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
887
1558
  let text = '';
888
1559
  for (const child of run) {
889
1560
  if (child.type === 'JSXText') {
890
- text += content.slice(child.span.start, child.span.end);
1561
+ text += jsxTextValue(content.slice(child.span.start, child.span.end));
1562
+ }
1563
+ else if (child.expression?.type === 'StringLiteral') {
1564
+ text += child.expression.value;
891
1565
  }
892
1566
  else if (child === pluralChild) {
893
1567
  const formText = form === 'zero'
@@ -904,8 +1578,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
904
1578
  }
905
1579
  formTexts[form] = text.trim();
906
1580
  }
907
- const spanStart = run[0].span.start;
908
- const spanEnd = run[run.length - 1].span.end;
1581
+ const [spanStart, spanEnd] = runSpan(run, content);
909
1582
  const otherText = formTexts.other;
910
1583
  if (!otherText)
911
1584
  continue;
@@ -922,6 +1595,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
922
1595
  if (extraInterpolations.length > 0) {
923
1596
  candidate.interpolations = extraInterpolations;
924
1597
  }
1598
+ candidate.pluralHelper = pluralHelperOf(pluralChild.expression);
925
1599
  // Plural + JSX merge is always user-facing
926
1600
  candidate.confidence = Math.min(1, candidate.confidence + 0.3);
927
1601
  if (candidate.confidence >= 0.7) {
@@ -938,13 +1612,16 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
938
1612
  else {
939
1613
  // ── Original JSX sibling merging (text + expressions, no elements) ──
940
1614
  // Build the interpolated text from the run
941
- const usedNames = new Set();
1615
+ const usedNames = new Map();
942
1616
  const interpolations = [];
943
1617
  let text = '';
944
1618
  let valid = true;
945
1619
  for (const child of run) {
946
1620
  if (child.type === 'JSXText') {
947
- text += content.slice(child.span.start, child.span.end);
1621
+ text += jsxTextValue(content.slice(child.span.start, child.span.end));
1622
+ }
1623
+ else if (child.expression?.type === 'StringLiteral') {
1624
+ text += child.expression.value;
948
1625
  }
949
1626
  else {
950
1627
  const info = resolveExpressionName(child.expression, content, usedNames);
@@ -953,21 +1630,23 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
953
1630
  break;
954
1631
  }
955
1632
  text += `{{${info.name}}}`;
956
- interpolations.push(info);
1633
+ if (!info.reused)
1634
+ interpolations.push(info);
957
1635
  }
958
1636
  }
959
1637
  if (!valid)
960
1638
  continue;
961
1639
  const trimmed = text.trim();
962
- if (!trimmed || interpolations.length === 0)
1640
+ const literalPiece = run.some(c => c.expression?.type === 'StringLiteral');
1641
+ if (!trimmed || (interpolations.length === 0 && !literalPiece) || !hasWordsBesidePlaceholders(trimmed))
963
1642
  continue;
964
- const spanStart = run[0].span.start;
965
- const spanEnd = run[run.length - 1].span.end;
1643
+ const [spanStart, spanEnd] = runSpan(run, content);
966
1644
  const candidate = detectCandidate(trimmed, spanStart, spanEnd, file, content, config);
967
1645
  if (candidate) {
968
1646
  candidate.type = 'jsx-text';
969
1647
  candidate.content = trimmed;
970
- candidate.interpolations = interpolations;
1648
+ if (interpolations.length)
1649
+ candidate.interpolations = interpolations;
971
1650
  // Mixed text + expressions in JSX is almost always user-facing
972
1651
  candidate.confidence = Math.min(1, candidate.confidence + 0.2);
973
1652
  if (candidate.confidence >= 0.7) {
@@ -984,17 +1663,35 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
984
1663
  }
985
1664
  }
986
1665
  // Recurse into children
987
- for (const key in node) {
988
- const value = node[key];
989
- if (value && typeof value === 'object') {
990
- if (Array.isArray(value)) {
991
- value.forEach(item => detectJSXInterpolation(item, content, file, config, candidates));
992
- }
993
- else {
994
- detectJSXInterpolation(value, content, file, config, candidates);
995
- }
996
- }
997
- }
1666
+ forEachChild(node, parts, child => detectJSXInterpolation(child, content, file, config, candidates));
1667
+ }
1668
+ /** A run without the whitespace-only text and `{' '}` pieces at its two ends. */
1669
+ function trimRun(run) {
1670
+ const blank = (c) => (c.type === 'JSXText' && !c.value?.trim()) ||
1671
+ (c.type === 'JSXExpressionContainer' && c.expression?.type === 'StringLiteral' && !c.expression.value.trim());
1672
+ let start = 0;
1673
+ let end = run.length;
1674
+ while (start < end && blank(run[start]))
1675
+ start++;
1676
+ while (end > start && blank(run[end - 1]))
1677
+ end--;
1678
+ return run.slice(start, end);
1679
+ }
1680
+ /** Where a run's rewrite starts and ends: inside the whitespace of its first and last text. */
1681
+ function runSpan(run, content) {
1682
+ const first = run[0];
1683
+ const last = run[run.length - 1];
1684
+ let start = first.span.start;
1685
+ let end = last.span.end;
1686
+ if (first.type === 'JSXText') {
1687
+ const raw = content.slice(first.span.start, first.span.end);
1688
+ start += raw.length - raw.trimStart().length;
1689
+ }
1690
+ if (last.type === 'JSXText') {
1691
+ const raw = content.slice(last.span.start, last.span.end);
1692
+ end -= raw.length - raw.trimEnd().length;
1693
+ }
1694
+ return [start, end];
998
1695
  }
999
1696
  /**
1000
1697
  * Returns true when the expression is a simple Identifier or non-computed
@@ -1007,36 +1704,77 @@ function isSimpleJSXExpression(expr) {
1007
1704
  return true;
1008
1705
  if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier')
1009
1706
  return true;
1707
+ // A string or number made from one, inside a sentence as a placeholder (`up to {n.toLocaleString()} segments`,
1708
+ // `{Math.round(score * 100)}%`, `+ {total - shown} more`); any other call may return elements
1709
+ if (expr.type === 'ParenthesisExpression')
1710
+ return isSimpleJSXExpression(expr.expression);
1711
+ if (expr.type === 'NumericLiteral')
1712
+ return true;
1713
+ if (expr.type === 'BinaryExpression' && ARITHMETIC_OPERATORS.has(expr.operator)) {
1714
+ return isSimpleJSXExpression(expr.left) && isSimpleJSXExpression(expr.right);
1715
+ }
1716
+ // a choice between such values (`{young ? 3 : 2}`); a choice between strings is text of its own, which a
1717
+ // placeholder would leave untranslated
1718
+ if (expr.type === 'ConditionalExpression') {
1719
+ return [expr.consequent, expr.alternate].every(b => b?.type !== 'StringLiteral' && b?.type !== 'TemplateLiteral' && isSimpleJSXExpression(b));
1720
+ }
1721
+ // `format.date(x)`, `formatPrice(x)`: a formatter returns a string
1722
+ if (expr.type === 'CallExpression' && expr.callee?.type === 'Identifier')
1723
+ return /^format[A-Z]/.test(expr.callee.value);
1724
+ if (expr.type === 'CallExpression' && expr.callee?.type === 'MemberExpression' && expr.callee.property?.type === 'Identifier') {
1725
+ const object = expr.callee.object;
1726
+ const method = expr.callee.property.value;
1727
+ return STRING_METHODS.has(method) || /^format/.test(method) ||
1728
+ (object?.type === 'Identifier' && (object.value === 'Math' || object.value === 'Number' || /^(?:format|formatter|fmt|intl)$/i.test(object.value)));
1729
+ }
1010
1730
  return false;
1011
1731
  }
1732
+ const ARITHMETIC_OPERATORS = new Set(['-', '*', '/', '%']);
1733
+ /**
1734
+ * Methods that return a string whatever they are called on (`list.map(…).join(', ')`), so their call in JSX
1735
+ * text is a placeholder like a variable; not `slice`, which keeps an array of elements.
1736
+ */
1737
+ const STRING_METHODS = new Set([
1738
+ 'join', 'toString', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString', 'toFixed', 'toPrecision',
1739
+ 'trim', 'toUpperCase', 'toLowerCase', 'padStart', 'padEnd', 'substring', 'replace', 'replaceAll'
1740
+ ]);
1012
1741
  /**
1013
1742
  * Returns true when a JSXElement is "simple" enough to be included in a
1014
1743
  * `<Trans>` JSX sibling run. Accepts:
1015
- * - Self-closing elements (`<br />`, `<img />`)
1016
- * - Elements whose only children are `JSXText` nodes
1017
- * Only HTML-like elements (lowercase tag name) are accepted; React
1018
- * components (uppercase, e.g. `<Button />`) break the run.
1744
+ * - Self-closing HTML elements (`<br />`, `<img />`)
1745
+ * - HTML elements whose only children are `JSXText` nodes
1746
+ * - Components whose only children are text, a link in a sentence
1747
+ * (`Leave your <DialogLink to='/'>projects</DialogLink> first.`); a component
1748
+ * without text (`<Icon />`) breaks the run
1019
1749
  */
1020
1750
  function isSimpleJSXElement(node) {
1021
- if (node.type !== 'JSXElement')
1751
+ if (node.type !== 'JSXElement' || isIconElement(node))
1022
1752
  return false;
1023
1753
  const namePart = node.opening?.name;
1024
1754
  if (!namePart)
1025
1755
  return false;
1026
- // Only include HTML-like elements (lowercase first char)
1027
- let tagName = null;
1028
- if (namePart.type === 'Identifier') {
1029
- tagName = namePart.value;
1756
+ const children = node.children || [];
1757
+ const textOnly = children.every((c) => c.type === 'JSXText');
1758
+ if (namePart.type === 'JSXMemberExpression') {
1759
+ const name = `${namePart.object?.value ?? ''}.${namePart.property?.value ?? ''}`;
1760
+ return INLINE_COMPONENT_RE.test(name) && children.length > 0 && textOnly;
1030
1761
  }
1031
- if (!tagName || tagName[0] !== tagName[0].toLowerCase())
1762
+ if (namePart.type !== 'Identifier')
1032
1763
  return false;
1764
+ const tagName = namePart.value;
1765
+ if (tagName[0] !== tagName[0].toLowerCase())
1766
+ return INLINE_COMPONENT_RE.test(tagName) && children.some((c) => c.value?.trim()) && textOnly;
1033
1767
  // Self-closing elements are simple
1034
1768
  if (node.opening?.selfClosing)
1035
1769
  return true;
1036
1770
  // Elements with only text children (or empty) are simple
1037
- const children = node.children || [];
1038
- return children.length === 0 || children.every((c) => c.type === 'JSXText');
1771
+ return children.length === 0 || textOnly;
1039
1772
  }
1773
+ /**
1774
+ * Components that stand inside a sentence: links and text styles (`DialogLink`, `Text.Strong`). A button or a
1775
+ * card next to a text is a piece of its own, not part of the sentence.
1776
+ */
1777
+ const INLINE_COMPONENT_RE = /Link$|^Text\b|Text$|^(?:Strong|Em|B|I|Code|Mark|Highlight)$/;
1040
1778
  /**
1041
1779
  * Returns the text content of a simple JSXElement's children.
1042
1780
  */
@@ -1051,17 +1789,30 @@ function getJSXElementTextContent(node, content) {
1051
1789
  * Returns true when a JSXElement is a `<Trans>` component
1052
1790
  * (already instrumented content).
1053
1791
  */
1054
- function isTransComponent(node) {
1792
+ function isTransComponent(node, transComponents = []) {
1055
1793
  const opening = node.opening;
1056
1794
  if (!opening)
1057
1795
  return false;
1058
1796
  const name = opening.name;
1059
- if (name?.type === 'Identifier' && name.value === 'Trans')
1060
- return true;
1061
- if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier' && name.property.value === 'Trans')
1062
- return true;
1797
+ if (name?.type === 'Identifier')
1798
+ return name.value === 'Trans' || transComponents.includes(name.value);
1799
+ if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier') {
1800
+ const object = name.object?.type === 'Identifier' ? name.object.value : '';
1801
+ return name.property.value === 'Trans' || transComponents.includes(`${object}.${name.property.value}`);
1802
+ }
1063
1803
  return false;
1064
1804
  }
1805
+ /**
1806
+ * An icon: an element whose name ends in `Icon`, or one with a Material icon class. Its text is a ligature
1807
+ * (`<Icon>delete</Icon>`, `<span className='material-icons'>search</span>`) that a translation would break.
1808
+ */
1809
+ function isIconElement(node) {
1810
+ const name = node.opening?.name;
1811
+ const tag = name?.type === 'Identifier' ? name.value : name?.type === 'JSXMemberExpression' ? name.property?.value : '';
1812
+ if (/Icon$/.test(tag ?? ''))
1813
+ return true;
1814
+ return (node.opening?.attributes ?? []).some((a) => a.name?.value === 'className' && a.value?.type === 'StringLiteral' && /\bmaterial-(?:icons|symbols)/.test(a.value.value));
1815
+ }
1065
1816
  // ─── Plural conditional pattern detection ────────────────────────────────────
1066
1817
  /**
1067
1818
  * Extracts the text value from a string literal or static template literal node.
@@ -1162,8 +1913,11 @@ function parseCountTest(test, content) {
1162
1913
  function detectPluralPatterns(node, content, file, config, candidates) {
1163
1914
  if (!node)
1164
1915
  return;
1165
- if (node.type === 'ConditionalExpression') {
1166
- const plural = tryParsePluralTernary(node, content);
1916
+ const parts = nonTextParts(node, file, config, false);
1917
+ if (parts === 'all')
1918
+ return;
1919
+ if (node.type === 'ConditionalExpression' || node.type === 'CallExpression') {
1920
+ const plural = parsePluralExpression(node, content);
1167
1921
  if (plural) {
1168
1922
  // Use the "other" form as the candidate content (with {{count}})
1169
1923
  const spanStart = node.span.start;
@@ -1183,6 +1937,9 @@ function detectPluralPatterns(node, content, file, config, candidates) {
1183
1937
  one: plural.one,
1184
1938
  other: plural.other
1185
1939
  };
1940
+ if (plural.interpolations)
1941
+ candidate.interpolations = plural.interpolations;
1942
+ candidate.pluralHelper = pluralHelperOf(node);
1186
1943
  // Plural patterns are always user-facing text — boost confidence
1187
1944
  candidate.confidence = Math.min(1, candidate.confidence + 0.3);
1188
1945
  if (candidate.confidence >= 0.7) {
@@ -1200,20 +1957,77 @@ function detectPluralPatterns(node, content, file, config, candidates) {
1200
1957
  }
1201
1958
  }
1202
1959
  // Recurse into children
1203
- for (const key in node) {
1204
- const value = node[key];
1205
- if (value && typeof value === 'object') {
1206
- if (Array.isArray(value)) {
1207
- value.forEach(item => detectPluralPatterns(item, content, file, config, candidates));
1208
- }
1209
- else {
1210
- detectPluralPatterns(value, content, file, config, candidates);
1960
+ forEachChild(node, parts, child => detectPluralPatterns(child, content, file, config, candidates));
1961
+ }
1962
+ /** A plural helper call or a `count === 1` ternary as its plural forms, or null. */
1963
+ function parsePluralExpression(expr, content) {
1964
+ if (expr?.type === 'ConditionalExpression')
1965
+ return tryParsePluralTernary(expr, content);
1966
+ if (expr?.type === 'CallExpression')
1967
+ return tryParsePluralCall(expr, content);
1968
+ return null;
1969
+ }
1970
+ /** Names of plural helpers whose call reads `(count, one, other)`. */
1971
+ const PLURAL_HELPER_RE = /^(?:plural|pluralize|pluralise)$/i;
1972
+ /**
1973
+ * Attempts to parse a plural helper call into a plural pattern:
1974
+ * plural(count, '# file', '# files') → one: '{{count}} file', other: '{{count}} files'
1975
+ * pluralize(n, 'item', `${n} items`) → one: 'item', other: '{{count}} items'
1976
+ * `#` in a form stands for the number, as in ICU. Only a call whose two forms are text (a string, or a
1977
+ * template literal whose only expression is the count) and whose count is not a string.
1978
+ */
1979
+ function tryParsePluralCall(node, content) {
1980
+ const callee = node.callee;
1981
+ const name = callee?.type === 'Identifier'
1982
+ ? callee.value
1983
+ : callee?.type === 'MemberExpression' && !callee.computed && callee.property?.type === 'Identifier' ? callee.property.value : null;
1984
+ if (!name || !PLURAL_HELPER_RE.test(name))
1985
+ return null;
1986
+ const [count, one, other] = (node.arguments ?? []).map((a) => a?.spread ? null : a?.expression);
1987
+ if (!count?.span || !one || !other || count.type === 'StringLiteral' || count.type === 'TemplateLiteral')
1988
+ return null;
1989
+ const countExpression = content.slice(count.span.start, count.span.end);
1990
+ // A form's other expressions become placeholders, named once for both forms (`showing ${shown} of # user`)
1991
+ const usedNames = new Map();
1992
+ const interpolations = [];
1993
+ const formText = (form) => {
1994
+ const text = extractStaticText(form);
1995
+ if (text !== null)
1996
+ return text;
1997
+ if (form?.type !== 'TemplateLiteral')
1998
+ return null;
1999
+ let result = '';
2000
+ for (let i = 0; i < form.quasis.length; i++) {
2001
+ result += form.quasis[i].cooked ?? form.quasis[i].raw ?? '';
2002
+ const expr = form.expressions?.[i];
2003
+ if (!expr)
2004
+ continue;
2005
+ if (content.slice(expr.span.start, expr.span.end) === countExpression) {
2006
+ result += '{{count}}';
2007
+ continue;
1211
2008
  }
2009
+ const info = resolveExpressionName(expr, content, usedNames);
2010
+ if (!info)
2011
+ return null;
2012
+ result += `{{${info.name}}}`;
2013
+ if (!info.reused)
2014
+ interpolations.push(info);
1212
2015
  }
1213
- }
2016
+ return result;
2017
+ };
2018
+ const oneText = formText(one);
2019
+ const otherText = formText(other);
2020
+ if (oneText === null || otherText === null)
2021
+ return null;
2022
+ return {
2023
+ countExpression,
2024
+ one: oneText.replace(/#/g, '{{count}}'),
2025
+ other: otherText.replace(/#/g, '{{count}}'),
2026
+ ...(interpolations.length ? { interpolations } : {})
2027
+ };
1214
2028
  }
1215
2029
  /**
1216
- * Attempts to parse a `ConditionalExpression` tree into a plural pattern.
2030
+ * Parses the shape of a `ConditionalExpression` tree into a plural pattern (see `tryParsePluralTernary`).
1217
2031
  *
1218
2032
  * Supported shapes:
1219
2033
  * count === 0 ? zeroText : count === 1 ? oneText : otherText (3-way)
@@ -1221,7 +2035,7 @@ function detectPluralPatterns(node, content, file, config, candidates) {
1221
2035
  *
1222
2036
  * Returns `null` when the node doesn't match any recognised plural shape.
1223
2037
  */
1224
- function tryParsePluralTernary(node, content) {
2038
+ function parsePluralTernaryShape(node, content) {
1225
2039
  if (node?.type !== 'ConditionalExpression')
1226
2040
  return null;
1227
2041
  const outerTest = parseCountTest(node.test, content);
@@ -1260,6 +2074,23 @@ function tryParsePluralTernary(node, content) {
1260
2074
  }
1261
2075
  return null;
1262
2076
  }
2077
+ /**
2078
+ * A ternary on `count === 1` is a plural only when its branches are text: `score === 1 ? 'var(--ok)' :
2079
+ * 'var(--warn)'` and `score === 1 ? 'item-full' : 'item-low'` pick a style.
2080
+ */
2081
+ function tryParsePluralTernary(node, content) {
2082
+ const plural = parsePluralTernaryShape(node, content);
2083
+ if (!plural)
2084
+ return null;
2085
+ // Fragments merged with the text around them (`''`, `'s'`, `${n}`) are fine; a technical form is not
2086
+ const forms = [plural.zero, plural.one, plural.other].filter((f) => f !== undefined);
2087
+ const technical = forms.some(f => f.trim().length > 1 && detectsAsTechnical(f));
2088
+ return !technical && forms.some(f => /\p{L}/u.test(f.replace(/\{\{[^}]*\}\}/g, ''))) ? plural : null;
2089
+ }
2090
+ /** A form that the string detector skips as technical (a CSS value, a class name); a single word is text here. */
2091
+ function detectsAsTechnical(text) {
2092
+ return detectCandidate(text, 0, text.length, 'plural.js', text, { extract: { input: [], output: '' } }, undefined, true) === null;
2093
+ }
1263
2094
  // ─── Language-change detection ───────────────────────────────────────────────
1264
2095
  /**
1265
2096
  * Property names that indicate a "language" value in an object literal.
@@ -1274,6 +2105,24 @@ const LANGUAGE_PROP_NAMES = new Set(['language', 'lang', 'locale', 'lng']);
1274
2105
  * Examples: `setLanguage(code)`, `setLocale(lng)`, `changeLanguage(x)`
1275
2106
  */
1276
2107
  const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale|Lng)$/i;
2108
+ /**
2109
+ * A variable or a property (`code`, `lang.code`, `e.target.value`): the injected `changeLanguage()` repeats
2110
+ * the expression, which must then give the same value without doing anything (`getDefault(…)` would run twice).
2111
+ */
2112
+ function isPlainValue(expr) {
2113
+ if (expr?.type === 'Identifier')
2114
+ return true;
2115
+ return expr?.type === 'MemberExpression' && expr.property?.type === 'Identifier' && isPlainValue(expr.object);
2116
+ }
2117
+ /** Nodes whose statements are a list, where one more statement can go before another. */
2118
+ const STATEMENT_LISTS = new Set(['FunctionBody', 'BlockStatement', 'Module', 'Script', 'SwitchCase']);
2119
+ /**
2120
+ * Callees whose object argument holds the user's settings, so a language property there is the app's
2121
+ * language (`updateSettings({ language })`, `saveProfile({ locale })`, `setState({ locale })`). Elsewhere a
2122
+ * `language`/`lng` property is data (`fetchTranslations({ lng })`, `list.push({ lng })`), and hooks
2123
+ * (`useState({ lng: [] })`) never are.
2124
+ */
2125
+ const SETTINGS_CALLEE_RE = /settings|preferences|prefs|profile|user|account|state|locale|language/i;
1277
2126
  /**
1278
2127
  * Walks the AST looking for call expressions that appear to change the
1279
2128
  * application language. Detected sites will later be augmented with an
@@ -1289,11 +2138,18 @@ const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale
1289
2138
  * `setLanguage(code)`
1290
2139
  * `setLocale(lng)`
1291
2140
  * `changeLanguage(selectedLng)`
2141
+ *
2142
+ * Only a call that is a statement of its own in a block or an arrow function's expression body: the
2143
+ * injected call goes before it, which would change any other place (`const x = setLocale(l)`,
2144
+ * `return save({ locale })`, `if (ok) setLocale(l)`).
1292
2145
  */
1293
- function detectLanguageChangeSites(node, content, sites) {
2146
+ function detectLanguageChangeSites(node, content, sites, parent, grandparent) {
1294
2147
  if (!node)
1295
2148
  return;
1296
- if (node.type === 'CallExpression' && node.span) {
2149
+ const standsAlone = (parent?.type === 'ExpressionStatement' && parent.expression === node &&
2150
+ STATEMENT_LISTS.has(grandparent?.type)) ||
2151
+ (parent?.type === 'ArrowFunctionExpression' && parent.body === node);
2152
+ if (node.type === 'CallExpression' && node.span && standsAlone) {
1297
2153
  const detected = tryParseLanguageChangeCall(node, content);
1298
2154
  if (detected) {
1299
2155
  // Check if changeLanguage() already exists nearby (e.g. same arrow body)
@@ -1324,14 +2180,89 @@ function detectLanguageChangeSites(node, content, sites) {
1324
2180
  const value = node[key];
1325
2181
  if (value && typeof value === 'object') {
1326
2182
  if (Array.isArray(value)) {
1327
- value.forEach(item => detectLanguageChangeSites(item, content, sites));
2183
+ value.forEach(item => detectLanguageChangeSites(item, content, sites, node, parent));
1328
2184
  }
1329
2185
  else {
1330
- detectLanguageChangeSites(value, content, sites);
2186
+ detectLanguageChangeSites(value, content, sites, node, parent);
1331
2187
  }
1332
2188
  }
1333
2189
  }
1334
2190
  }
2191
+ /**
2192
+ * The imports of the plural helpers `names` (`import { plural, number } from './format'`), each with the
2193
+ * number of other identifiers naming it in the file and the text that removes its import.
2194
+ */
2195
+ function findPluralHelperImports(ast, content, names) {
2196
+ const found = [];
2197
+ for (const decl of ast.body ?? []) {
2198
+ if (decl.type !== 'ImportDeclaration')
2199
+ continue;
2200
+ const specifiers = decl.specifiers ?? [];
2201
+ // `import fmt, { plural } from …` mixes a default with the braces: removing one of them takes more than a
2202
+ // specifier and a comma, so such an import stays
2203
+ const named = specifiers.every((spec) => spec.type === 'ImportSpecifier');
2204
+ specifiers.forEach((spec, i) => {
2205
+ const name = spec.local?.value;
2206
+ if (!names.has(name) || (!named && specifiers.length > 1))
2207
+ return;
2208
+ let [removeStart, removeEnd] = specifiers.length === 1
2209
+ ? [decl.span.start, decl.span.end]
2210
+ : i < specifiers.length - 1
2211
+ ? [spec.span.start, specifiers[i + 1].span.start]
2212
+ : [specifiers[i - 1].span.end, spec.span.end];
2213
+ if (specifiers.length === 1)
2214
+ removeEnd += /^\r?\n/.exec(content.slice(removeEnd))?.[0].length ?? 0;
2215
+ found.push({ name, references: 0, removeStart, removeEnd });
2216
+ });
2217
+ }
2218
+ const count = (node) => {
2219
+ if (!node || typeof node !== 'object')
2220
+ return;
2221
+ if (node.type === 'ImportDeclaration')
2222
+ return;
2223
+ if (node.type === 'Identifier') {
2224
+ const helper = found.find(h => h.name === node.value);
2225
+ if (helper)
2226
+ helper.references++;
2227
+ }
2228
+ for (const key in node) {
2229
+ const value = node[key];
2230
+ if (Array.isArray(value))
2231
+ value.forEach(count);
2232
+ else if (value && typeof value === 'object')
2233
+ count(value);
2234
+ }
2235
+ };
2236
+ count(ast);
2237
+ return found;
2238
+ }
2239
+ /** The `useMemo`/`useCallback` calls with a callback and a dependency array (see `MemoHookSpan`). */
2240
+ function collectMemoHooks(node, hooks) {
2241
+ if (!node || typeof node !== 'object')
2242
+ return;
2243
+ if (node.type === 'CallExpression' && ['useMemo', 'useCallback'].includes(getCalleeName(node.callee) ?? '')) {
2244
+ const [callback, deps] = (node.arguments ?? []).map((a) => a?.expression);
2245
+ if (callback?.span && deps?.type === 'ArrayExpression' && deps.span) {
2246
+ const elements = (deps.elements ?? []).filter(Boolean).map((e) => e.expression);
2247
+ hooks.push({
2248
+ callbackStart: callback.span.start,
2249
+ callbackEnd: callback.span.end,
2250
+ insertAt: elements.length ? elements[elements.length - 1].span.end : deps.span.start + 1,
2251
+ hasDeps: elements.length > 0,
2252
+ hasT: elements.some((e) => e.type === 'Identifier' && e.value === 't')
2253
+ });
2254
+ }
2255
+ }
2256
+ for (const key in node) {
2257
+ const value = node[key];
2258
+ if (value && typeof value === 'object') {
2259
+ if (Array.isArray(value))
2260
+ value.forEach(item => collectMemoHooks(item, hooks));
2261
+ else
2262
+ collectMemoHooks(value, hooks);
2263
+ }
2264
+ }
2265
+ }
1335
2266
  /**
1336
2267
  * Inspects a single CallExpression node to determine if it is a language-change
1337
2268
  * call. Returns the detected site data (without line/column) or `null`.
@@ -1348,10 +2279,10 @@ function tryParseLanguageChangeCall(node, content) {
1348
2279
  if (objName === 'i18n' || objName === 'i18next')
1349
2280
  return null;
1350
2281
  }
1351
- // ── Pattern 1: direct setter — setLanguage(expr), changeLocale(expr) etc. ──
2282
+ // ── Pattern 1: direct setter, setLanguage(expr), changeLocale(expr) etc. ──
1352
2283
  if (calleeName && LANGUAGE_SETTER_RE.test(calleeName)) {
1353
2284
  const firstArg = node.arguments[0]?.expression;
1354
- if (firstArg?.span) {
2285
+ if (firstArg?.span && isPlainValue(firstArg)) {
1355
2286
  const langExpr = content.slice(firstArg.span.start, firstArg.span.end);
1356
2287
  // Skip if the argument is already an i18next.changeLanguage call
1357
2288
  if (langExpr.includes('changeLanguage'))
@@ -1363,7 +2294,9 @@ function tryParseLanguageChangeCall(node, content) {
1363
2294
  };
1364
2295
  }
1365
2296
  }
1366
- // ── Pattern 2: object with language property — fn({ language: expr }) ──
2297
+ // ── Pattern 2: object with language property, updateSettings({ language: expr }) ──
2298
+ if (!calleeName || /^use[A-Z]/.test(calleeName) || !SETTINGS_CALLEE_RE.test(calleeName))
2299
+ return null;
1367
2300
  for (const arg of node.arguments) {
1368
2301
  const expr = arg.expression ?? arg;
1369
2302
  if (expr?.type !== 'ObjectExpression')
@@ -1383,8 +2316,8 @@ function tryParseLanguageChangeCall(node, content) {
1383
2316
  const valNode = prop.value;
1384
2317
  if (valNode?.span) {
1385
2318
  const langExpr = content.slice(valNode.span.start, valNode.span.end);
1386
- // Skip if value is a static string (e.g. `{ language: 'en' }` in a config)
1387
- if (valNode.type === 'StringLiteral')
2319
+ // Skip if value is a static string (e.g. `{ language: 'en' }` in a config), or not a plain value
2320
+ if (valNode.type === 'StringLiteral' || !isPlainValue(valNode))
1388
2321
  continue;
1389
2322
  // Skip if already contains changeLanguage
1390
2323
  if (langExpr.includes('changeLanguage'))
@@ -1418,7 +2351,11 @@ function getCalleeName(callee) {
1418
2351
  * Gets the list of source files to instrument.
1419
2352
  */
1420
2353
  async function getSourceFilesForInstrumentation(config) {
1421
- const defaultIgnore = ['node_modules/**', 'dist/**', 'build/**', '.next/**'];
2354
+ // Stories, mocks and fixtures hold sample data, not the app's texts
2355
+ const defaultIgnore = [
2356
+ 'node_modules/**', 'dist/**', 'build/**', '.next/**',
2357
+ '**/*.{stories,story,storybook}.*', '**/__mocks__/**', '**/__fixtures__/**', '**/__tests__/**'
2358
+ ];
1422
2359
  const userIgnore = Array.isArray(config.extract.ignore)
1423
2360
  ? config.extract.ignore
1424
2361
  : config.extract.ignore ? [config.extract.ignore] : [];
@@ -1433,16 +2370,8 @@ async function getSourceFilesForInstrumentation(config) {
1433
2370
  * Checks if the project uses React.
1434
2371
  */
1435
2372
  async function isProjectUsingReact() {
1436
- try {
1437
- const packageJsonPath = process.cwd() + '/package.json';
1438
- const content = await readFile(packageJsonPath, 'utf-8');
1439
- const packageJson = JSON.parse(content);
1440
- const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
1441
- return !!deps.react || !!deps['react-i18next'];
1442
- }
1443
- catch {
1444
- return false;
1445
- }
2373
+ const deps = await readProjectDeps();
2374
+ return !!deps.react || !!deps['react-i18next'];
1446
2375
  }
1447
2376
  /** Well-known frontend framework packages (presence → browser environment). */
1448
2377
  const FRONTEND_FRAMEWORKS = [
@@ -1479,13 +2408,7 @@ const SERVER_FRAMEWORKS = [
1479
2408
  */
1480
2409
  async function detectProjectEnvironment() {
1481
2410
  try {
1482
- const packageJsonPath = process.cwd() + '/package.json';
1483
- const raw = await readFile(packageJsonPath, 'utf-8');
1484
- const packageJson = JSON.parse(raw);
1485
- const allDeps = {
1486
- ...packageJson.dependencies,
1487
- ...packageJson.devDependencies
1488
- };
2411
+ const allDeps = await readProjectDeps();
1489
2412
  const has = (list) => list.some(dep => !!allDeps[dep]);
1490
2413
  // 1. Edge / serverless (check first — these projects may also list a
1491
2414
  // bundler or even a framework, but they have no filesystem)
@@ -1584,28 +2507,10 @@ function buildDynamicImportPath(outputTemplate, initDir) {
1584
2507
  */
1585
2508
  async function ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT) {
1586
2509
  const cwd = process.cwd();
1587
- // Check for existing init files in common locations
2510
+ // Check for existing init files in common locations (an init elsewhere imports i18next, see runInstrumenter)
1588
2511
  if (await findExistingI18nInitFile()) {
1589
2512
  return null; // Init file already exists
1590
2513
  }
1591
- // Check if i18next.init() is called anywhere in the source
1592
- try {
1593
- const sourceFiles = await getSourceFilesForInstrumentation(config);
1594
- for (const file of sourceFiles) {
1595
- try {
1596
- const content = await readFile(file, 'utf-8');
1597
- if (content.includes('i18next.init') || content.includes('.init(') || content.includes('i18n.init')) {
1598
- return null; // Init is already present somewhere
1599
- }
1600
- }
1601
- catch {
1602
- // Skip unreadable files
1603
- }
1604
- }
1605
- }
1606
- catch {
1607
- // Skip if file scanning fails
1608
- }
1609
2514
  // Determine output location — prefer src/ if it exists
1610
2515
  const srcExists = await fileExists(join(cwd, 'src'));
1611
2516
  const initDir = srcExists ? join(cwd, 'src') : cwd;