i18next-cli 1.88.1 → 1.90.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.
- package/README.md +104 -12
- package/dist/cjs/cli.js +25 -6
- package/dist/cjs/config.js +13 -12
- package/dist/cjs/extractor/core/extractor.js +1 -3
- package/dist/cjs/extractor/core/translation-manager.js +9 -2
- package/dist/cjs/heuristic-config.js +51 -6
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/init.js +8 -11
- package/dist/cjs/instrumenter/core/instrumenter.js +1372 -218
- package/dist/cjs/instrumenter/core/key-generator.js +20 -9
- package/dist/cjs/instrumenter/core/next-files.js +104 -0
- package/dist/cjs/instrumenter/core/string-detector.js +106 -29
- package/dist/cjs/instrumenter/core/transformer.js +165 -83
- package/dist/cjs/localize/agent-prompt.js +5 -2
- package/dist/cjs/localize/detect.js +3 -11
- package/dist/cjs/localize/localize.js +27 -5
- package/dist/cjs/utils/file-utils.js +48 -0
- package/dist/cjs/utils/jsx-attributes.js +3 -1
- package/dist/esm/cli.js +25 -6
- package/dist/esm/config.js +13 -12
- package/dist/esm/extractor/core/extractor.js +1 -3
- package/dist/esm/extractor/core/translation-manager.js +9 -2
- package/dist/esm/heuristic-config.js +52 -7
- package/dist/esm/index.js +2 -1
- package/dist/esm/init.js +8 -11
- package/dist/esm/instrumenter/core/instrumenter.js +1376 -222
- package/dist/esm/instrumenter/core/key-generator.js +20 -9
- package/dist/esm/instrumenter/core/next-files.js +101 -0
- package/dist/esm/instrumenter/core/string-detector.js +107 -31
- package/dist/esm/instrumenter/core/transformer.js +165 -83
- package/dist/esm/localize/agent-prompt.js +5 -2
- package/dist/esm/localize/detect.js +4 -12
- package/dist/esm/localize/localize.js +27 -5
- package/dist/esm/utils/file-utils.js +49 -2
- package/dist/esm/utils/jsx-attributes.js +3 -1
- package/package.json +1 -1
- package/types/cli.d.ts.map +1 -1
- package/types/config.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/heuristic-config.d.ts.map +1 -1
- package/types/index.d.ts +1 -1
- package/types/index.d.ts.map +1 -1
- package/types/init.d.ts.map +1 -1
- package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
- package/types/instrumenter/core/key-generator.d.ts +2 -0
- package/types/instrumenter/core/key-generator.d.ts.map +1 -1
- package/types/instrumenter/core/next-files.d.ts +25 -0
- package/types/instrumenter/core/next-files.d.ts.map +1 -0
- package/types/instrumenter/core/string-detector.d.ts +5 -1
- package/types/instrumenter/core/string-detector.d.ts.map +1 -1
- package/types/instrumenter/core/transformer.d.ts +16 -1
- package/types/instrumenter/core/transformer.d.ts.map +1 -1
- package/types/instrumenter/index.d.ts +1 -1
- package/types/instrumenter/index.d.ts.map +1 -1
- package/types/localize/agent-prompt.d.ts +1 -1
- package/types/localize/agent-prompt.d.ts.map +1 -1
- package/types/localize/detect.d.ts +2 -0
- package/types/localize/detect.d.ts.map +1 -1
- package/types/localize/localize.d.ts.map +1 -1
- package/types/types.d.ts +87 -1
- package/types/types.d.ts.map +1 -1
- package/types/utils/file-utils.d.ts +7 -0
- package/types/utils/file-utils.d.ts.map +1 -1
- package/types/utils/jsx-attributes.d.ts.map +1 -1
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
import { readFile, mkdir, writeFile, access } from 'node:fs/promises';
|
|
2
2
|
import { glob } from 'glob';
|
|
3
|
-
import { dirname, extname,
|
|
3
|
+
import { dirname, resolve, extname, isAbsolute, relative, join } 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';
|
|
17
|
+
import { classifyNextFiles, projectPath } from './next-files.js';
|
|
15
18
|
import { usesMessageFormat, toMessageFormatPlaceholders } from '../../utils/message-format.js';
|
|
16
19
|
|
|
17
20
|
/**
|
|
@@ -39,9 +42,44 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
39
42
|
let totalSkipped = 0;
|
|
40
43
|
let totalLanguageChanges = 0;
|
|
41
44
|
let usesI18nextT = false;
|
|
45
|
+
// The same warning for many files is printed once, with the files below it
|
|
46
|
+
const warnings = new Map();
|
|
47
|
+
const warnFor = (where, message) => {
|
|
48
|
+
warnings.set(message, [...(warnings.get(message) ?? []), where]);
|
|
49
|
+
};
|
|
50
|
+
let moduleScopeTotal = 0;
|
|
51
|
+
// The code imports i18next before it is instrumented: it is set up already, here or in a shared package
|
|
52
|
+
let i18nextInUse = false;
|
|
53
|
+
// Keys the code uses already: a new text gets another key, unless it is the same text, and no new key is
|
|
54
|
+
// the parent of nested ones (`tenants` beside `tenants.title` is a nesting conflict at extract)
|
|
55
|
+
// Best effort, without plugins (their hooks are for extract): a file it cannot read reserves nothing
|
|
56
|
+
const separator = config.extract.keySeparator ?? '.';
|
|
57
|
+
const existingKeys = await findKeys({ ...config, plugins: [] }, { info() { }, warn() { }, error() { } })
|
|
58
|
+
.then(found => found.allKeys, () => new Map());
|
|
59
|
+
for (const { key, defaultValue } of existingKeys.values()) {
|
|
60
|
+
const parent = separator ? key.split(separator)[0] : key;
|
|
61
|
+
if (parent !== key)
|
|
62
|
+
keyRegistry.reserve(parent);
|
|
63
|
+
else
|
|
64
|
+
keyRegistry.reserve(key, defaultValue ?? key);
|
|
65
|
+
}
|
|
42
66
|
// Detect framework and language
|
|
43
67
|
const hasReact = await isProjectUsingReact();
|
|
44
68
|
const hasTypeScript = await isProjectUsingTypeScript();
|
|
69
|
+
// A Next.js app gets next-i18next's calls: getT() in Server Components, useT() in Client Components,
|
|
70
|
+
// useTranslation() from next-i18next/pages in the Pages Router. Also one with i18next not set up at all,
|
|
71
|
+
// whose Server Components no plain react-i18next hook would work in; one with an i18next setup of its own
|
|
72
|
+
// keeps it.
|
|
73
|
+
const contents = new Map();
|
|
74
|
+
for (const file of sourceFiles)
|
|
75
|
+
contents.set(file, await readFile(file, 'utf-8'));
|
|
76
|
+
const deps = await readProjectDeps();
|
|
77
|
+
const code = [...contents.values()];
|
|
78
|
+
const nextI18next = !!deps['next-i18next'] || code.some(c => NEXT_I18NEXT_IMPORT_RE.test(c)) ||
|
|
79
|
+
(!!deps.next && !deps.i18next && !deps['react-i18next'] && !code.some(c => I18NEXT_IMPORT_RE.test(c)));
|
|
80
|
+
const nextFiles = nextI18next ? await classifyNextFiles(contents) : undefined;
|
|
81
|
+
const nextKinds = nextFiles?.kinds;
|
|
82
|
+
const serverModule = nextI18next ? findServerModule(contents) : undefined;
|
|
45
83
|
// Initialize plugins
|
|
46
84
|
const plugins = config.plugins || [];
|
|
47
85
|
await initializeInstrumentPlugins(plugins, { config, logger });
|
|
@@ -63,24 +101,34 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
63
101
|
}
|
|
64
102
|
for (const file of sourceFiles) {
|
|
65
103
|
try {
|
|
66
|
-
let content =
|
|
104
|
+
let content = contents.get(file);
|
|
67
105
|
// Run instrumentOnLoad plugin pipeline
|
|
68
106
|
const loadResult = await runInstrumentOnLoadPipeline(content, file, plugins, logger);
|
|
69
107
|
if (loadResult === null)
|
|
70
108
|
continue; // plugin says skip this file
|
|
71
109
|
content = loadResult;
|
|
72
|
-
|
|
110
|
+
i18nextInUse ||= I18NEXT_IMPORT_RE.test(content) || NEXT_I18NEXT_IMPORT_RE.test(content);
|
|
111
|
+
const nextKind = nextKinds?.get(file);
|
|
112
|
+
const scanResult = await scanFileForCandidates(content, file, config, nextKind);
|
|
73
113
|
let { candidates } = scanResult;
|
|
74
|
-
const { components, languageChangeSites } = scanResult;
|
|
114
|
+
const { components, languageChangeSites, imports, memoHooks, pluralHelperImports } = scanResult;
|
|
75
115
|
// Run instrumentOnResult plugin pipeline
|
|
76
116
|
candidates = await runInstrumentOnResultPipeline(file, candidates, plugins, logger);
|
|
117
|
+
if (scanResult.ownTSkipped) {
|
|
118
|
+
totalCandidates += scanResult.ownTSkipped;
|
|
119
|
+
totalSkipped += scanResult.ownTSkipped;
|
|
120
|
+
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.');
|
|
121
|
+
}
|
|
122
|
+
for (const { message, count, lines } of scanResult.dropped ?? []) {
|
|
123
|
+
totalCandidates += count;
|
|
124
|
+
totalSkipped += count;
|
|
125
|
+
warnFor(lines ? lines.map(line => `${file}:${line}`).join(', ') : `${file} (${count})`, message);
|
|
126
|
+
}
|
|
77
127
|
if (scanResult.moduleScopeSkipped > 0) {
|
|
78
128
|
totalCandidates += scanResult.moduleScopeSkipped;
|
|
79
129
|
totalSkipped += scanResult.moduleScopeSkipped;
|
|
80
|
-
|
|
81
|
-
|
|
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/');
|
|
130
|
+
moduleScopeTotal += scanResult.moduleScopeSkipped;
|
|
131
|
+
warnFor(`${file} (${scanResult.moduleScopeSkipped})`, MODULE_SCOPE_WARNING);
|
|
84
132
|
}
|
|
85
133
|
if (candidates.length === 0 && languageChangeSites.length === 0) {
|
|
86
134
|
continue;
|
|
@@ -105,7 +153,7 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
105
153
|
]);
|
|
106
154
|
switch (action) {
|
|
107
155
|
case 'approve':
|
|
108
|
-
candidate.key = generateKeyFromContent(candidate.content);
|
|
156
|
+
candidate.key = keyRegistry.add(generateKeyFromContent(keySourceOf(candidate)), candidate.content);
|
|
109
157
|
break;
|
|
110
158
|
case 'skip':
|
|
111
159
|
candidate.skipReason = 'User skipped';
|
|
@@ -116,10 +164,11 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
116
164
|
type: 'input',
|
|
117
165
|
name: 'key',
|
|
118
166
|
message: 'New key:',
|
|
119
|
-
default: generateKeyFromContent(candidate
|
|
167
|
+
default: generateKeyFromContent(keySourceOf(candidate))
|
|
120
168
|
}
|
|
121
169
|
]);
|
|
122
170
|
candidate.key = key;
|
|
171
|
+
keyRegistry.reserve(key, candidate.content);
|
|
123
172
|
break;
|
|
124
173
|
}
|
|
125
174
|
case 'edit-value': {
|
|
@@ -132,7 +181,7 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
132
181
|
}
|
|
133
182
|
]);
|
|
134
183
|
candidate.content = value;
|
|
135
|
-
candidate.key = generateKeyFromContent(value);
|
|
184
|
+
candidate.key = keyRegistry.add(generateKeyFromContent(value), value);
|
|
136
185
|
break;
|
|
137
186
|
}
|
|
138
187
|
}
|
|
@@ -144,7 +193,7 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
144
193
|
// Generate keys for approved candidates
|
|
145
194
|
for (const candidate of approvedCandidates) {
|
|
146
195
|
if (!candidate.key) {
|
|
147
|
-
candidate.key = keyRegistry.add(generateKeyFromContent(candidate
|
|
196
|
+
candidate.key = keyRegistry.add(generateKeyFromContent(keySourceOf(candidate)), candidate.content);
|
|
148
197
|
}
|
|
149
198
|
}
|
|
150
199
|
// After key generation, so ICU/MF2 syntax does not end up in generated keys
|
|
@@ -158,7 +207,11 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
158
207
|
config,
|
|
159
208
|
components,
|
|
160
209
|
namespace: targetNamespace,
|
|
161
|
-
languageChangeSites
|
|
210
|
+
languageChangeSites,
|
|
211
|
+
imports,
|
|
212
|
+
memoHooks,
|
|
213
|
+
pluralHelperImports,
|
|
214
|
+
next: nextKind && { kind: nextKind, serverModule: serverModuleFor(serverModule, file) }
|
|
162
215
|
});
|
|
163
216
|
if (!options.isDryRun && transformResult.modified) {
|
|
164
217
|
// Write the transformed file
|
|
@@ -172,16 +225,15 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
172
225
|
if (!usesI18nextT && approvedCandidates.some(c => !c.insideComponent && c.confidence >= 0.7)) {
|
|
173
226
|
usesI18nextT = true;
|
|
174
227
|
}
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
logger.warn(warning);
|
|
179
|
-
}
|
|
228
|
+
// Collect warnings (e.g. i18next.t() in React files) and candidates that could not be rewritten
|
|
229
|
+
for (const warning of [...(transformResult.warnings ?? []), ...transformResult.errors]) {
|
|
230
|
+
warnFor(file, warning.startsWith(`${file}: `) ? warning.slice(file.length + 2) : warning);
|
|
180
231
|
}
|
|
181
232
|
results.push({
|
|
182
233
|
file,
|
|
183
234
|
candidates: approvedCandidates,
|
|
184
|
-
result: transformResult
|
|
235
|
+
result: transformResult,
|
|
236
|
+
languageChangeSites
|
|
185
237
|
});
|
|
186
238
|
}
|
|
187
239
|
else {
|
|
@@ -194,8 +246,33 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
194
246
|
}
|
|
195
247
|
const langChangeSuffix = totalLanguageChanges > 0 ? `, ${totalLanguageChanges} language-change site(s)` : '';
|
|
196
248
|
spinner.succeed(styleText('bold', `Scanned complete: ${totalCandidates} candidates, ${totalTransformed} approved${langChangeSuffix}`));
|
|
249
|
+
for (const [message, where] of warnings) {
|
|
250
|
+
const head = message === MODULE_SCOPE_WARNING ? `Skipped ${moduleScopeTotal} module-scope string(s). ${message}` : message;
|
|
251
|
+
logger.warn(`${head}\n${where.map(w => ` ${w}`).join('\n')}`);
|
|
252
|
+
}
|
|
253
|
+
if (nextI18next && totalTransformed > 0) {
|
|
254
|
+
// next-i18next sets i18next up itself (its config, the proxy, the root layout or appWithTranslation)
|
|
255
|
+
// a page loads its namespaces itself, with serverSideTranslations() (or a helper it imports that calls it)
|
|
256
|
+
const loads = (file) => [file, ...nextFiles.imports.get(file) ?? []].some(f => contents.get(f).includes('serverSideTranslations'));
|
|
257
|
+
const pagesWithoutProps = results.filter(r => nextKinds?.get(r.file) === 'pages' && isPagesRoute(r.file) && !loads(r.file)).map(r => r.file);
|
|
258
|
+
if (pagesWithoutProps.length) {
|
|
259
|
+
logger.warn(`These pages need serverSideTranslations() in getStaticProps or getServerSideProps, or their texts render untranslated (https://github.com/i18next/next-i18next#pages-router-setup):\n${pagesWithoutProps.map(f => ` ${f}`).join('\n')}`);
|
|
260
|
+
}
|
|
261
|
+
if (!i18nextInUse && !await nextI18nextConfigured()) {
|
|
262
|
+
const kinds = new Set(results.map(r => nextKinds?.get(r.file)));
|
|
263
|
+
logger.info([
|
|
264
|
+
'The code now uses next-i18next. Set it up:',
|
|
265
|
+
` npm install next-i18next i18next react-i18next${config.extract.messageFormat === 'icu' ? ' i18next-icu intl-messageformat' : config.extract.messageFormat === 'mf2' ? ' i18next-mf2' : ''}`,
|
|
266
|
+
...(kinds.has('server') || kinds.has('client') ? [' App Router: i18n.config, proxy and root layout, https://github.com/i18next/next-i18next#app-router-setup (no [lng] folder: localeInPath: false)'] : []),
|
|
267
|
+
...(kinds.has('pages') ? [' Pages Router: next-i18next.config.js, appWithTranslation and serverSideTranslations, https://github.com/i18next/next-i18next#pages-router-setup'] : [])
|
|
268
|
+
].join('\n'));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
197
271
|
// Generate i18n init file if needed and any transformations were made
|
|
198
|
-
if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun) {
|
|
272
|
+
if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !nextI18next && i18nextInUse) {
|
|
273
|
+
logger.info('Your code imports i18next already, so it is set up somewhere: no i18n init file generated.');
|
|
274
|
+
}
|
|
275
|
+
if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !nextI18next && !i18nextInUse) {
|
|
199
276
|
const initFilePath = await ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT);
|
|
200
277
|
if (initFilePath) {
|
|
201
278
|
await injectI18nImportIntoEntryFile(initFilePath, logger);
|
|
@@ -216,14 +293,67 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
|
|
|
216
293
|
throw error;
|
|
217
294
|
}
|
|
218
295
|
}
|
|
296
|
+
/** The text a key is made from: a <Trans> candidate's words, not its JSX source (`<a href=…>`). */
|
|
297
|
+
function keySourceOf(candidate) {
|
|
298
|
+
return candidate.transValue?.replace(/<\/?\d+>/g, '') ?? candidate.content;
|
|
299
|
+
}
|
|
300
|
+
/** An import of next-i18next, which sets i18next up itself. */
|
|
301
|
+
const NEXT_I18NEXT_IMPORT_RE = /\bfrom\s*['"]next-i18next(?:\/[\w/]+)?['"]|\brequire\(\s*['"]next-i18next(?:\/[\w/]+)?['"]\s*\)/;
|
|
302
|
+
/**
|
|
303
|
+
* The module the app imports `getT` from when it is not `next-i18next/server` (`createServerI18next` in its
|
|
304
|
+
* own `i18n.server.ts`, so no init order matters): an alias as written, a relative one as an absolute path.
|
|
305
|
+
*/
|
|
306
|
+
function findServerModule(contents) {
|
|
307
|
+
for (const [file, code] of contents) {
|
|
308
|
+
for (const [, names, source] of code.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g)) {
|
|
309
|
+
if (!/\bgetT\b/.test(names) || source === 'next-i18next/server')
|
|
310
|
+
continue;
|
|
311
|
+
return source.startsWith('.') ? resolve(dirname(file), source) : source;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
/** The specifier a file imports `getT` with: `next-i18next/server`, the app's alias, or a path relative to it. */
|
|
317
|
+
function serverModuleFor(serverModule, file) {
|
|
318
|
+
if (!serverModule)
|
|
319
|
+
return 'next-i18next/server';
|
|
320
|
+
if (!isAbsolute(serverModule))
|
|
321
|
+
return serverModule;
|
|
322
|
+
const rel = relative(dirname(resolve(file)), serverModule).replace(/\\/g, '/').replace(/\.(?:tsx?|jsx?|mjs)$/, '');
|
|
323
|
+
return rel.startsWith('.') ? rel : `./${rel}`;
|
|
324
|
+
}
|
|
325
|
+
/** A page of the Pages Router (not `_app`, `_document`, `_error` or an API route), which loads its own translations. */
|
|
326
|
+
function isPagesRoute(file) {
|
|
327
|
+
const rel = projectPath(file);
|
|
328
|
+
return rel.startsWith('pages/') && !/^pages\/(?:_app|_document|_error|api\/)/.test(rel);
|
|
329
|
+
}
|
|
330
|
+
/** next-i18next has a config of its own already: `i18n.config.*` (App Router) or `next-i18next.config.*` (Pages Router). */
|
|
331
|
+
async function nextI18nextConfigured() {
|
|
332
|
+
const names = ['i18n.config', 'next-i18next.config'].flatMap(name => ['ts', 'js', 'mjs', 'cjs'].map(ext => `${name}.${ext}`));
|
|
333
|
+
for (const name of names) {
|
|
334
|
+
if (await fileExists(join(process.cwd(), name)) || await fileExists(join(process.cwd(), 'src', name)))
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
/** An import of i18next or react-i18next (`.init()` alone is any library's: `Sentry.init()`). */
|
|
340
|
+
const I18NEXT_IMPORT_RE = /\bfrom\s*['"](?:i18next|react-i18next)['"]|\brequire\(\s*['"](?:i18next|react-i18next)['"]\s*\)/;
|
|
341
|
+
const MODULE_SCOPE_WARNING = 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
|
|
342
|
+
'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
|
|
343
|
+
'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/';
|
|
219
344
|
/**
|
|
220
345
|
* Scans a source file for hardcoded string candidates and React component boundaries.
|
|
221
346
|
*/
|
|
222
|
-
async function scanFileForCandidates(content, file, config) {
|
|
347
|
+
async function scanFileForCandidates(content, file, config, nextKind) {
|
|
223
348
|
const candidates = [];
|
|
224
349
|
const components = [];
|
|
225
350
|
const languageChangeSites = [];
|
|
226
351
|
let moduleScopeSkipped = 0;
|
|
352
|
+
let ownTSkipped = 0;
|
|
353
|
+
let imports;
|
|
354
|
+
const memoHooks = [];
|
|
355
|
+
let pluralHelperImports;
|
|
356
|
+
const dropped = [];
|
|
227
357
|
const fileExt = extname(file).toLowerCase();
|
|
228
358
|
const isTypeScriptFile = ['.ts', '.tsx', '.mts', '.cts'].includes(fileExt);
|
|
229
359
|
const isTSX = fileExt === '.tsx';
|
|
@@ -271,22 +401,47 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
271
401
|
// indices — without the conversion every emoji / accented char / CJK char
|
|
272
402
|
// shifts all subsequent offsets.
|
|
273
403
|
normalizeSpansToCharIndices(ast, content);
|
|
404
|
+
imports = ast.body
|
|
405
|
+
.filter((item) => item.type === 'ImportDeclaration')
|
|
406
|
+
.map((item) => ({
|
|
407
|
+
source: item.source.value,
|
|
408
|
+
start: item.span.start,
|
|
409
|
+
end: item.span.end,
|
|
410
|
+
locals: (item.specifiers ?? []).map((spec) => spec.local?.value).filter(Boolean)
|
|
411
|
+
}));
|
|
412
|
+
collectMemoHooks(ast, memoHooks);
|
|
274
413
|
// Detect React function component boundaries
|
|
275
|
-
detectComponentBoundaries(ast, content, components);
|
|
414
|
+
detectComponentBoundaries(ast, content, components, nextKind === 'server');
|
|
276
415
|
// Collect function spans so module-scope strings can be excluded below
|
|
277
416
|
const functionSpans = [];
|
|
278
417
|
collectFunctionSpans(ast, functionSpans);
|
|
418
|
+
// Next.js reads the texts of `export const metadata` once; generateMetadata() can get them with getT()
|
|
419
|
+
if (nextKind === 'server' && !/\bgenerateMetadata\b/.test(content)) {
|
|
420
|
+
const metadata = metadataExport(ast, content);
|
|
421
|
+
if (metadata) {
|
|
422
|
+
components.push(metadata);
|
|
423
|
+
functionSpans.push({ start: metadata.bodyStart, end: metadata.bodyEnd });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
279
426
|
// Visit AST to find string literals; the object form of extract.acceptedAttributes
|
|
280
427
|
// sets which attributes hold text per JSX element
|
|
281
428
|
const attributeRules = config.extract.acceptedAttributes;
|
|
282
429
|
const jsx = attributeRules && !Array.isArray(attributeRules)
|
|
283
430
|
? { rules: attributeRules, aliases: importAliases(ast) }
|
|
284
431
|
: undefined;
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
432
|
+
consoleOnlyNames.set(file, collectConsoleOnlyNames(ast));
|
|
433
|
+
fileDataStrings.set(file, collectDataStrings(ast));
|
|
434
|
+
try {
|
|
435
|
+
visitNodeForStrings(ast, content, file, config, candidates, jsx);
|
|
436
|
+
// Detect JSX interpolation patterns (merge adjacent text + expression children)
|
|
437
|
+
detectJSXInterpolation(ast, content, file, config, candidates);
|
|
438
|
+
// Detect plural conditional patterns (ternary chains checking count === 0/1/other)
|
|
439
|
+
detectPluralPatterns(ast, content, file, config, candidates);
|
|
440
|
+
}
|
|
441
|
+
finally {
|
|
442
|
+
consoleOnlyNames.delete(file);
|
|
443
|
+
fileDataStrings.delete(file);
|
|
444
|
+
}
|
|
290
445
|
// Detect language-change call sites (e.g. updateSettings({ language: code }))
|
|
291
446
|
detectLanguageChangeSites(ast, content, languageChangeSites);
|
|
292
447
|
// Annotate candidates with their enclosing component (if any)
|
|
@@ -298,6 +453,15 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
298
453
|
}
|
|
299
454
|
}
|
|
300
455
|
}
|
|
456
|
+
// A component whose `t` is something else (`const [t, setT] = useState(0)`) keeps its texts: a t() call
|
|
457
|
+
// there would call that `t`
|
|
458
|
+
const ownT = new Set(components.filter(c => c.ownT).map(c => c.name));
|
|
459
|
+
if (ownT.size) {
|
|
460
|
+
const keep = candidates.filter(c => !c.insideComponent || !ownT.has(c.insideComponent));
|
|
461
|
+
ownTSkipped = candidates.length - keep.length;
|
|
462
|
+
candidates.length = 0;
|
|
463
|
+
candidates.push(...keep);
|
|
464
|
+
}
|
|
301
465
|
// Drop module-scope candidates: wrapping them yields a t() call evaluated
|
|
302
466
|
// once at import time — possibly before i18next is initialized, and never
|
|
303
467
|
// re-evaluated on language change. See issue #278.
|
|
@@ -308,6 +472,15 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
308
472
|
candidates.length = 0;
|
|
309
473
|
candidates.push(...keep);
|
|
310
474
|
}
|
|
475
|
+
if (nextKind) {
|
|
476
|
+
dropped.push(...dropForNextI18next(candidates, components, nextKind, isApiRoute(file), serverDirectiveSpans(ast)));
|
|
477
|
+
// next-i18next switches the language through the route or useChangeLanguage(): `i18n.changeLanguage()`
|
|
478
|
+
// would change the client instance alone. A call of that switch is no site at all.
|
|
479
|
+
const sites = languageChangeSites.filter(site => !/^(?:\w+\.)?changeLanguage\(/.test(content.slice(site.callStart, site.callEnd)));
|
|
480
|
+
if (sites.length)
|
|
481
|
+
dropped.push({ message: NEXT_LANGUAGE_CHANGE, count: sites.length, lines: sites.map(site => site.line) });
|
|
482
|
+
languageChangeSites.length = 0;
|
|
483
|
+
}
|
|
311
484
|
// Annotate language change sites with their enclosing component (if any)
|
|
312
485
|
for (const site of languageChangeSites) {
|
|
313
486
|
for (const comp of components) {
|
|
@@ -337,11 +510,131 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
337
510
|
candidates.length = 0;
|
|
338
511
|
candidates.push(...keep);
|
|
339
512
|
}
|
|
513
|
+
const helperNames = new Set(candidates.map(c => c.pluralHelper).filter((n) => !!n));
|
|
514
|
+
if (helperNames.size)
|
|
515
|
+
pluralHelperImports = findPluralHelperImports(ast, content, helperNames);
|
|
516
|
+
// Two candidates whose spans overlap cannot both be rewritten (a template literal in another one's `${}`):
|
|
517
|
+
// the outer one wins, the inner text stays in its interpolation value as written
|
|
518
|
+
const bySize = [...candidates].sort((a, b) => (b.endOffset - b.offset) - (a.endOffset - a.offset));
|
|
519
|
+
const kept = new Set();
|
|
520
|
+
for (const c of bySize) {
|
|
521
|
+
if (![...kept].some(k => c.offset < k.endOffset && k.offset < c.endOffset))
|
|
522
|
+
kept.add(c);
|
|
523
|
+
}
|
|
524
|
+
if (kept.size < candidates.length) {
|
|
525
|
+
const keep = candidates.filter(c => kept.has(c));
|
|
526
|
+
candidates.length = 0;
|
|
527
|
+
candidates.push(...keep);
|
|
528
|
+
}
|
|
340
529
|
}
|
|
341
530
|
catch (err) {
|
|
342
531
|
// Silently skip files that can't be parsed
|
|
343
532
|
}
|
|
344
|
-
return { candidates, components, languageChangeSites, moduleScopeSkipped };
|
|
533
|
+
return { candidates, components, languageChangeSites, moduleScopeSkipped, ownTSkipped, imports, memoHooks, pluralHelperImports, dropped };
|
|
534
|
+
}
|
|
535
|
+
/** `export const metadata = { title: '…' }` (with or without a type) as the scope of a generateMetadata() to be. */
|
|
536
|
+
function metadataExport(ast, content) {
|
|
537
|
+
for (const item of ast.body ?? []) {
|
|
538
|
+
const decl = item.type === 'ExportDeclaration' ? item.declaration : null;
|
|
539
|
+
const [declarator] = decl?.type === 'VariableDeclaration' && decl.declarations?.length === 1 ? decl.declarations : [];
|
|
540
|
+
if (declarator?.id?.value !== 'metadata' || declarator.init?.type !== 'ObjectExpression')
|
|
541
|
+
continue;
|
|
542
|
+
const annotation = declarator.id.typeAnnotation?.typeAnnotation;
|
|
543
|
+
return {
|
|
544
|
+
name: `metadata@${declarator.init.span.start}`,
|
|
545
|
+
bodyStart: declarator.init.span.start,
|
|
546
|
+
bodyEnd: declarator.init.span.end,
|
|
547
|
+
hasUseTranslation: false,
|
|
548
|
+
expressionBody: true,
|
|
549
|
+
isAsync: true,
|
|
550
|
+
metadataHead: {
|
|
551
|
+
start: decl.span.start,
|
|
552
|
+
end: declarator.init.span.start,
|
|
553
|
+
type: annotation?.span ? content.slice(annotation.span.start, annotation.span.end) : undefined
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
/** A route handler (`route.ts` under `app/`, a file under `pages/api/`): its texts are responses of an API, not of a page. */
|
|
560
|
+
function isApiRoute(file) {
|
|
561
|
+
const rel = projectPath(file);
|
|
562
|
+
return /^app\/(?:.*\/)?route\.[cm]?[jt]sx?$/.test(rel) || rel.startsWith('pages/api/');
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* The functions that run as Server Actions or cached (`'use server'`, `'use cache'` as their first statement), all
|
|
566
|
+
* of the file for such a directive at its top: they have no root params, so getT() there needs `{ lng }` passed in.
|
|
567
|
+
*/
|
|
568
|
+
function serverDirectiveSpans(ast) {
|
|
569
|
+
const directive = (stmts) => stmts.some((st) => st.type === 'ExpressionStatement' &&
|
|
570
|
+
st.expression?.type === 'StringLiteral' && /^use (?:server|cache)\b/.test(st.expression.value));
|
|
571
|
+
// the directive prologue: the string statements a body or module starts with
|
|
572
|
+
const leading = (stmts = []) => {
|
|
573
|
+
const end = stmts.findIndex((st) => st.type !== 'ExpressionStatement' || st.expression?.type !== 'StringLiteral');
|
|
574
|
+
return end < 0 ? stmts : stmts.slice(0, end);
|
|
575
|
+
};
|
|
576
|
+
if (directive(leading(ast.body)))
|
|
577
|
+
return [{ start: 0, end: Infinity }];
|
|
578
|
+
const spans = [];
|
|
579
|
+
const walk = (node) => {
|
|
580
|
+
if (!node || typeof node !== 'object')
|
|
581
|
+
return;
|
|
582
|
+
if (FUNCTION_LIKE.has(node.type) && isBlockBody(node.body) && directive(leading(node.body.stmts))) {
|
|
583
|
+
spans.push({ start: node.body.span.start, end: node.body.span.end });
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
for (const key in node) {
|
|
587
|
+
const value = node[key];
|
|
588
|
+
if (Array.isArray(value))
|
|
589
|
+
value.forEach(walk);
|
|
590
|
+
else if (value && typeof value === 'object' && key !== 'span')
|
|
591
|
+
walk(value);
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
walk(ast);
|
|
595
|
+
return spans;
|
|
596
|
+
}
|
|
597
|
+
const NEXT_API = 'Left API routes as they are: their texts are responses, not pages (getT() there needs { lng } from the request).';
|
|
598
|
+
const NEXT_DIRECTIVE = "Left Server Actions and cached functions ('use server', 'use cache') as they are: getT() there needs { lng } passed in.";
|
|
599
|
+
const NEXT_UNKNOWN = "Skipped the texts of files that no page or layout imports (as far as the imports resolve), so it is not known whether Server or Client Components render them: add 'use client' to a Client Component, then run instrument again.";
|
|
600
|
+
const NEXT_OUTSIDE = 'Skipped texts outside components: next-i18next has no global t(). Move them into a component (or, in a Server Component file, an async function), then run instrument again.';
|
|
601
|
+
const NEXT_SHARED = 'Skipped the texts of components that Server and Client Components both render, where neither getT() nor a hook works: give them a `t` prop (from getT() or useT() in the callers), then run instrument again.';
|
|
602
|
+
const NEXT_WRAPPED = 'Skipped the texts of Server Components wrapped in a call (memo, forwardRef), which cannot become async for getT().';
|
|
603
|
+
const NEXT_LANGUAGE_CHANGE = 'Language switches left as they are: next-i18next changes the language through the route (/de/…) or useChangeLanguage() from next-i18next/client. Wire these by hand.';
|
|
604
|
+
/**
|
|
605
|
+
* Takes out the candidates next-i18next cannot translate where they are: outside a component (no global `t`), in
|
|
606
|
+
* a component rendered on both sides without a `t` prop, a <Trans> there, in a Server Component that cannot
|
|
607
|
+
* become async. Returns what it dropped, by reason.
|
|
608
|
+
*/
|
|
609
|
+
function dropForNextI18next(candidates, components, kind, apiRoute, directiveSpans) {
|
|
610
|
+
const componentOf = (c) => components.find(comp => comp.name === c.insideComponent);
|
|
611
|
+
const reasonOf = (c) => {
|
|
612
|
+
if (apiRoute)
|
|
613
|
+
return NEXT_API;
|
|
614
|
+
if (directiveSpans.some(span => c.offset >= span.start && c.endOffset <= span.end))
|
|
615
|
+
return NEXT_DIRECTIVE;
|
|
616
|
+
const comp = componentOf(c);
|
|
617
|
+
// a <Trans> takes its `t` from the React context, in any render code of a Client Component
|
|
618
|
+
if (!comp)
|
|
619
|
+
return c.type === 'jsx-mixed' && (kind === 'client' || kind === 'pages') ? null : NEXT_OUTSIDE;
|
|
620
|
+
// with `t` and `i18n` props, a <Trans> takes them both and works on either side
|
|
621
|
+
if ((kind === 'shared' || kind === 'unknown') && (!comp.hasUseTranslation || (c.type === 'jsx-mixed' && !comp.i18nParam))) {
|
|
622
|
+
return kind === 'shared' ? NEXT_SHARED : NEXT_UNKNOWN;
|
|
623
|
+
}
|
|
624
|
+
if (kind === 'server' && comp.wrapped && !comp.hasUseTranslation)
|
|
625
|
+
return NEXT_WRAPPED;
|
|
626
|
+
return null;
|
|
627
|
+
};
|
|
628
|
+
const counts = new Map();
|
|
629
|
+
const keep = candidates.filter(c => {
|
|
630
|
+
const reason = reasonOf(c);
|
|
631
|
+
if (reason)
|
|
632
|
+
counts.set(reason, (counts.get(reason) ?? 0) + 1);
|
|
633
|
+
return !reason;
|
|
634
|
+
});
|
|
635
|
+
candidates.length = 0;
|
|
636
|
+
candidates.push(...keep);
|
|
637
|
+
return [...counts].map(([message, count]) => ({ message, count }));
|
|
345
638
|
}
|
|
346
639
|
/**
|
|
347
640
|
* Node types whose span delimits deferred (call-time) evaluation. A string
|
|
@@ -404,7 +697,7 @@ function lineOfOffset(content, offset) {
|
|
|
404
697
|
* - forwardRef wrappers: `const Greeting = React.forwardRef((props, ref) => { ... })`
|
|
405
698
|
* - memo wrappers: `const Greeting = React.memo(() => { ... })`
|
|
406
699
|
*/
|
|
407
|
-
function detectComponentBoundaries(node, content, components) {
|
|
700
|
+
function detectComponentBoundaries(node, content, components, serverFile = false) {
|
|
408
701
|
if (!node)
|
|
409
702
|
return;
|
|
410
703
|
// FunctionDeclaration with uppercase name
|
|
@@ -415,7 +708,8 @@ function detectComponentBoundaries(node, content, components) {
|
|
|
415
708
|
name: node.identifier.value,
|
|
416
709
|
bodyStart: body.span.start,
|
|
417
710
|
bodyEnd: body.span.end,
|
|
418
|
-
|
|
711
|
+
...tBinding(node, body),
|
|
712
|
+
...functionFacts(node)
|
|
419
713
|
});
|
|
420
714
|
}
|
|
421
715
|
}
|
|
@@ -433,7 +727,8 @@ function detectComponentBoundaries(node, content, components) {
|
|
|
433
727
|
name: node.identifier.value,
|
|
434
728
|
bodyStart: body.span.start,
|
|
435
729
|
bodyEnd: body.span.end,
|
|
436
|
-
|
|
730
|
+
...tBinding(node, body),
|
|
731
|
+
...functionFacts(node)
|
|
437
732
|
});
|
|
438
733
|
}
|
|
439
734
|
}
|
|
@@ -459,25 +754,59 @@ function detectComponentBoundaries(node, content, components) {
|
|
|
459
754
|
if (isWrapper && init.arguments?.length > 0) {
|
|
460
755
|
const arg = init.arguments[0]?.expression || init.arguments[0];
|
|
461
756
|
if (arg && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
|
|
462
|
-
addComponentFromFunctionNode(node.id.value, arg, content, components);
|
|
757
|
+
addComponentFromFunctionNode(node.id.value, arg, content, components, true);
|
|
463
758
|
}
|
|
464
759
|
}
|
|
465
760
|
}
|
|
466
761
|
}
|
|
467
762
|
}
|
|
763
|
+
// Not a component, but a function with a `t` of its own (`const { t } = await getT()` in `generateMetadata`,
|
|
764
|
+
// a custom hook), or in a Server Component file one that can await getT(): an async one, or the metadata
|
|
765
|
+
// functions Next.js awaits
|
|
766
|
+
if (FUNCTION_LIKE.has(node.type) && node.body?.span && !components.some(c => c.bodyStart === node.body.span.start)) {
|
|
767
|
+
const name = node.identifier?.value;
|
|
768
|
+
const ownHook = isBlockBody(node.body) && bindsT({}, node.body) === 'translation';
|
|
769
|
+
if (ownHook || (serverFile && (node.async || /^generate(?:Metadata|Viewport)$/.test(name ?? '')))) {
|
|
770
|
+
addComponentFromFunctionNode(`${name ?? 'function'}@${node.body.span.start}`, node, content, components, false, true);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
468
773
|
// Recurse into children
|
|
469
774
|
for (const key in node) {
|
|
470
775
|
const value = node[key];
|
|
471
776
|
if (value && typeof value === 'object') {
|
|
472
777
|
if (Array.isArray(value)) {
|
|
473
|
-
value.forEach(item => detectComponentBoundaries(item, content, components));
|
|
778
|
+
value.forEach(item => detectComponentBoundaries(item, content, components, serverFile));
|
|
474
779
|
}
|
|
475
780
|
else {
|
|
476
|
-
detectComponentBoundaries(value, content, components);
|
|
781
|
+
detectComponentBoundaries(value, content, components, serverFile);
|
|
477
782
|
}
|
|
478
783
|
}
|
|
479
784
|
}
|
|
480
785
|
}
|
|
786
|
+
const FUNCTION_LIKE = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
|
|
787
|
+
/** Where a function starts, whether it is async, and the translation hook it calls without taking `t`. */
|
|
788
|
+
function functionFacts(fnNode, wrapped = false) {
|
|
789
|
+
const facts = { start: fnNode.span?.start, isAsync: !!fnNode.async };
|
|
790
|
+
if (wrapped)
|
|
791
|
+
facts.wrapped = true;
|
|
792
|
+
if ((fnNode.params ?? []).some((p) => patternBinds(p, 'i18n')))
|
|
793
|
+
facts.i18nParam = true;
|
|
794
|
+
const returnType = fnNode.returnType?.typeAnnotation?.span;
|
|
795
|
+
if (returnType)
|
|
796
|
+
facts.returnType = { start: returnType.start, end: returnType.end };
|
|
797
|
+
for (const stmt of isBlockBody(fnNode.body) ? fnNode.body.stmts ?? [] : []) {
|
|
798
|
+
for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
|
|
799
|
+
const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
|
|
800
|
+
const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
|
|
801
|
+
const props = d.id?.type === 'ObjectPattern' ? d.id.properties ?? [] : [];
|
|
802
|
+
if (!hook || !HOOK_CALL_RE.test(hook) || !props.length || props.some((p) => p.type === 'RestElement'))
|
|
803
|
+
continue;
|
|
804
|
+
facts.hookPattern = { statement: stmt.span.start, first: props[0].span.start, last: props[props.length - 1].span.end, names: props.map((p) => p.key?.value).filter(Boolean) };
|
|
805
|
+
return facts;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
return facts;
|
|
809
|
+
}
|
|
481
810
|
/**
|
|
482
811
|
* swc >=1.16 types function bodies as 'FunctionBody'; older versions used 'BlockStatement'.
|
|
483
812
|
*/
|
|
@@ -488,17 +817,85 @@ function isBlockBody(body) {
|
|
|
488
817
|
* Helper: extracts a ComponentBoundary from an ArrowFunctionExpression or FunctionExpression
|
|
489
818
|
* that has a block body.
|
|
490
819
|
*/
|
|
491
|
-
function addComponentFromFunctionNode(name, fnNode, content, components) {
|
|
820
|
+
function addComponentFromFunctionNode(name, fnNode, content, components, wrapped = false, anyExpressionBody = false) {
|
|
492
821
|
const body = fnNode.body;
|
|
493
|
-
if (body
|
|
822
|
+
if (isBlockBody(body) && body.span) {
|
|
823
|
+
components.push({
|
|
824
|
+
name,
|
|
825
|
+
bodyStart: body.span.start,
|
|
826
|
+
bodyEnd: body.span.end,
|
|
827
|
+
...tBinding(fnNode, body),
|
|
828
|
+
...functionFacts(fnNode, wrapped)
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
else if ((isJSXExpression(body) || anyExpressionBody) && body?.span) {
|
|
832
|
+
// `const Hint = () => <p>…</p>`: a component too; its body becomes a block when it needs the hook
|
|
833
|
+
// (as does `async () => ({ title: … })`, a server function)
|
|
494
834
|
components.push({
|
|
495
835
|
name,
|
|
496
836
|
bodyStart: body.span.start,
|
|
497
837
|
bodyEnd: body.span.end,
|
|
498
|
-
|
|
838
|
+
...tBinding(fnNode, {}),
|
|
839
|
+
...functionFacts(fnNode, wrapped),
|
|
840
|
+
expressionBody: true
|
|
499
841
|
});
|
|
500
842
|
}
|
|
501
843
|
}
|
|
844
|
+
/** JSX, possibly in parentheses. */
|
|
845
|
+
function isJSXExpression(expr) {
|
|
846
|
+
if (expr?.type === 'ParenthesisExpression')
|
|
847
|
+
return isJSXExpression(expr.expression);
|
|
848
|
+
return expr?.type === 'JSXElement' || expr?.type === 'JSXFragment';
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* The `t` a component has already: `'translation'` for a parameter (`({ t })`, a prop passed down) or one
|
|
852
|
+
* destructured from a translation hook (`const { t } = useTranslation('ns')`, also re-exported or renamed:
|
|
853
|
+
* `useT`, `useAppTranslation`, `getTranslations`), `'other'` for any other `t` in its body
|
|
854
|
+
* (`const [t, setT] = useState(0)`), null for none. Another `const { t }` would be a redeclaration, and the
|
|
855
|
+
* `t()` calls would call the other `t`.
|
|
856
|
+
*/
|
|
857
|
+
function bindsT(fnNode, body) {
|
|
858
|
+
if ((fnNode.params ?? []).some((p) => patternBinds(p, 't')))
|
|
859
|
+
return 'translation';
|
|
860
|
+
for (const stmt of body.stmts ?? []) {
|
|
861
|
+
if (stmt.type === 'FunctionDeclaration' && stmt.identifier?.value === 't')
|
|
862
|
+
return 'other';
|
|
863
|
+
for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
|
|
864
|
+
if (!patternBinds(d.id, 't'))
|
|
865
|
+
continue;
|
|
866
|
+
const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
|
|
867
|
+
const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
|
|
868
|
+
// `const t = i18n.getFixedT(lng, 'footer')` is one too
|
|
869
|
+
if (d.id.type === 'Identifier' && hook === 'getFixedT')
|
|
870
|
+
return 'translation';
|
|
871
|
+
return d.id.type === 'ObjectPattern' && hook && TRANSLATION_HOOK_RE.test(hook) ? 'translation' : 'other';
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
/** The translation hooks a call to which can take `t` as well; an app's own `useRoleTranslations()` returns data. */
|
|
877
|
+
const HOOK_CALL_RE = /^(?:useTranslation|useT|getT)$/;
|
|
878
|
+
/** Names of the hooks and functions that give a translation `t`. */
|
|
879
|
+
const TRANSLATION_HOOK_RE = /^(?:use|get)\w*(?:Translation|T|I18n|Intl)\w*$/;
|
|
880
|
+
/** A component's `hasUseTranslation`, and `ownT` when its `t` is something else (see `bindsT`). */
|
|
881
|
+
function tBinding(fnNode, body) {
|
|
882
|
+
const kind = bindsT(fnNode, body);
|
|
883
|
+
return kind === 'other' ? { hasUseTranslation: true, ownT: true } : { hasUseTranslation: kind === 'translation' };
|
|
884
|
+
}
|
|
885
|
+
/** Whether a binding pattern (a parameter, a destructuring) binds `name`; defaults and renamed keys aside. */
|
|
886
|
+
function patternBinds(pat, name) {
|
|
887
|
+
switch (pat?.type) {
|
|
888
|
+
case 'Identifier': return pat.value === name;
|
|
889
|
+
case 'Parameter': return patternBinds(pat.pat, name);
|
|
890
|
+
case 'AssignmentPattern': return patternBinds(pat.left, name);
|
|
891
|
+
case 'RestElement': return patternBinds(pat.argument, name);
|
|
892
|
+
case 'ArrayPattern': return (pat.elements ?? []).some((e) => patternBinds(e, name));
|
|
893
|
+
case 'ObjectPattern': return (pat.properties ?? []).some((p) => p.type === 'KeyValuePatternProperty'
|
|
894
|
+
? patternBinds(p.value, name)
|
|
895
|
+
: p.type === 'AssignmentPatternProperty' ? p.key?.value === name : patternBinds(p.argument, name));
|
|
896
|
+
default: return false;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
502
899
|
// Non-translatable JSX attributes are defined in utils/jsx-attributes.ts
|
|
503
900
|
// and shared with the linter. The instrumenter uses `ignoredAttributeSet`
|
|
504
901
|
// to skip recursing into non-translatable attribute values.
|
|
@@ -506,22 +903,183 @@ function addComponentFromFunctionNode(name, fnNode, content, components) {
|
|
|
506
903
|
* Returns true when the AST node is a `t(...)` or `i18next.t(...)` call
|
|
507
904
|
* expression — i.e. code that was already instrumented.
|
|
508
905
|
*/
|
|
509
|
-
function isTranslationCall(node) {
|
|
906
|
+
function isTranslationCall(node, functions = []) {
|
|
907
|
+
const name = dottedName(node.callee);
|
|
908
|
+
if (!name)
|
|
909
|
+
return false;
|
|
910
|
+
// t(...), $t(...), i18next.t(...), props.t(...), this.$t(...), and the project's own (`extract.functions`)
|
|
911
|
+
return name === 't' || name === '$t' || /\.\$?t$/.test(name) || functions.some(fn => matchesFunctionPattern(name, fn));
|
|
912
|
+
}
|
|
913
|
+
/** A callee as a dotted name (`this.props.t`, `i18n.t`), or null for a computed one. */
|
|
914
|
+
function dottedName(callee) {
|
|
915
|
+
if (callee?.type === 'Identifier')
|
|
916
|
+
return callee.value;
|
|
917
|
+
if (callee?.type === 'ThisExpression')
|
|
918
|
+
return 'this';
|
|
919
|
+
if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
|
|
920
|
+
return null;
|
|
921
|
+
const object = dottedName(callee.object);
|
|
922
|
+
return object && `${object}.${callee.property.value}`;
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Methods whose string arguments are never text shown to a user: selectors, attribute and storage names,
|
|
926
|
+
* and the strings a text is searched for or compared with (translating `msg.includes('not found')` breaks it).
|
|
927
|
+
*/
|
|
928
|
+
const NON_TEXT_METHODS = new Set([
|
|
929
|
+
'querySelector', 'querySelectorAll', 'closest', 'matches', 'getElementById', 'getElementsByClassName',
|
|
930
|
+
'getElementsByTagName', 'getElementsByName', 'addEventListener', 'removeEventListener',
|
|
931
|
+
'getAttribute', 'hasAttribute', 'removeAttribute', 'getPropertyValue', 'setProperty', 'removeProperty',
|
|
932
|
+
'getItem', 'setItem', 'removeItem',
|
|
933
|
+
// analytics event and user names: a translated one splits the data by language
|
|
934
|
+
'track', 'trackEvent', 'logEvent', 'capture', 'captureMessage', 'captureException', 'identify',
|
|
935
|
+
// event names, and format patterns (`dayjs(d).format('DD MMM YYYY')`)
|
|
936
|
+
'emit', 'on', 'once', 'off', 'addListener', 'removeListener', 'format',
|
|
937
|
+
'indexOf', 'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'match', 'matchAll', 'search', 'replace',
|
|
938
|
+
'replaceAll', 'split', 'localeCompare'
|
|
939
|
+
]);
|
|
940
|
+
/**
|
|
941
|
+
* Functions whose string arguments are never text: `gtag('event', 'Sign Up Completed')`, `require('x')`,
|
|
942
|
+
* `RegExp('…')`, `format(date, 'yyyy-MM-dd')`.
|
|
943
|
+
*/
|
|
944
|
+
const NON_TEXT_FUNCTIONS = new Set(['gtag', 'require', 'RegExp', 'format']);
|
|
945
|
+
/** Objects whose method calls are logs or error reports, for developers whatever they say. */
|
|
946
|
+
const LOG_OBJECTS = /^(?:logger|log|Sentry|sentry|Bugsnag|bugsnag|Rollbar|rollbar|winston|pino)$/;
|
|
947
|
+
/** A call to one of `NON_TEXT_METHODS` or `NON_TEXT_FUNCTIONS` (`el.closest('button, a')`, `gtag(…)`). */
|
|
948
|
+
function isNonTextMethodCall(node) {
|
|
510
949
|
const callee = node.callee;
|
|
511
|
-
if (
|
|
950
|
+
if (callee?.type === 'Identifier')
|
|
951
|
+
return NON_TEXT_FUNCTIONS.has(callee.value);
|
|
952
|
+
if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
|
|
512
953
|
return false;
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
954
|
+
return NON_TEXT_METHODS.has(callee.property.value) || (callee.object?.type === 'Identifier' && LOG_OBJECTS.test(callee.object.value));
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* The names of a file's variables whose every use is inside a `console.*` call: a variable declared twice
|
|
958
|
+
* counts as one name, and any use elsewhere takes it out.
|
|
959
|
+
*/
|
|
960
|
+
function collectConsoleOnlyNames(ast) {
|
|
961
|
+
const declared = new Set();
|
|
962
|
+
const inConsole = new Set();
|
|
963
|
+
const elsewhere = new Set();
|
|
964
|
+
const walk = (node, inLog) => {
|
|
965
|
+
if (!node || typeof node !== 'object')
|
|
966
|
+
return;
|
|
967
|
+
if (Array.isArray(node)) {
|
|
968
|
+
node.forEach(n => walk(n, inLog));
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
if (node.type === 'VariableDeclarator') {
|
|
972
|
+
if (node.id?.type === 'Identifier')
|
|
973
|
+
declared.add(node.id.value);
|
|
974
|
+
else
|
|
975
|
+
walk(node.id, inLog);
|
|
976
|
+
walk(node.init, inLog);
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
if (node.type === 'MemberExpression') {
|
|
980
|
+
walk(node.object, inLog);
|
|
981
|
+
if (node.property?.type === 'Computed')
|
|
982
|
+
walk(node.property, inLog);
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
if (node.type === 'KeyValueProperty') {
|
|
986
|
+
walk(node.value, inLog);
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
if (node.type === 'Identifier')
|
|
990
|
+
(inLog ? inConsole : elsewhere).add(node.value);
|
|
991
|
+
const log = inLog || (node.type === 'CallExpression' && isConsoleCall(node));
|
|
992
|
+
for (const key in node)
|
|
993
|
+
if (key !== 'span')
|
|
994
|
+
walk(node[key], log);
|
|
995
|
+
};
|
|
996
|
+
walk(ast, false);
|
|
997
|
+
return new Set([...declared].filter(n => inConsole.has(n) && !elsewhere.has(n)));
|
|
998
|
+
}
|
|
999
|
+
/** Per file, the names `collectConsoleOnlyNames` found for its content (set by the scan, read by the visit). */
|
|
1000
|
+
const consoleOnlyNames = new Map();
|
|
1001
|
+
/** The property names whose value is text (`label`, `title`, …), lower-cased. */
|
|
1002
|
+
const translatablePropertyLowerSet = new Set([...translatablePropertySet].map(p => p.toLowerCase()));
|
|
1003
|
+
/** String literals a JSX element renders (see `markRendered`): text whatever their words. */
|
|
1004
|
+
const renderedStrings = new WeakSet();
|
|
1005
|
+
/** Marks the strings an expression rendered as a JSX child can produce: itself, a branch, a fallback. */
|
|
1006
|
+
function markRendered(expr) {
|
|
1007
|
+
if (!expr)
|
|
1008
|
+
return;
|
|
1009
|
+
if (expr.type === 'StringLiteral')
|
|
1010
|
+
renderedStrings.add(expr);
|
|
1011
|
+
else if (expr.type === 'ConditionalExpression') {
|
|
1012
|
+
markRendered(expr.consequent);
|
|
1013
|
+
markRendered(expr.alternate);
|
|
1014
|
+
}
|
|
1015
|
+
else if (expr.type === 'BinaryExpression' && LOGICAL_OPERATORS.has(expr.operator)) {
|
|
1016
|
+
// swc types `&&`, `||` and `??` as a BinaryExpression
|
|
1017
|
+
markRendered(expr.right);
|
|
1018
|
+
}
|
|
1019
|
+
else if (expr.type === 'ParenthesisExpression')
|
|
1020
|
+
markRendered(expr.expression);
|
|
1021
|
+
}
|
|
1022
|
+
/** Per file, the strings `collectDataStrings` found (set by the scan, read by the visit). */
|
|
1023
|
+
const fileDataStrings = new Map();
|
|
1024
|
+
/** Property and attribute names whose string value is data the code matches against. */
|
|
1025
|
+
const DATA_KEYS = new Set(['id', 'key', 'value', 'type', 'code', 'kind']);
|
|
1026
|
+
/** Names of lists whose strings are values to match (`order: ['2FA', 'no 2FA']`). */
|
|
1027
|
+
const DATA_LISTS = /^(?:order|ids|keys|values|types|kinds|codes)$/i;
|
|
1028
|
+
/**
|
|
1029
|
+
* The strings a file uses as data: compared (`=== 'no 2FA'`), a `case`, an object key, the value of an `id`,
|
|
1030
|
+
* `key`, `value`, `type`, `code` or `kind`, an entry of an `order`/`ids`/`values` list, or an argument of a
|
|
1031
|
+
* method that compares (`includes`). The same string as text elsewhere in that file is then data too: a
|
|
1032
|
+
* facet's `of()` returning `'no 2FA'` must keep matching `order: ['2FA', 'no 2FA']`.
|
|
1033
|
+
*/
|
|
1034
|
+
function collectDataStrings(ast) {
|
|
1035
|
+
const found = new Set();
|
|
1036
|
+
const add = (node) => { if (node?.type === 'StringLiteral')
|
|
1037
|
+
found.add(node.value); };
|
|
1038
|
+
const addList = (node) => { if (node?.type === 'ArrayExpression')
|
|
1039
|
+
for (const e of node.elements ?? [])
|
|
1040
|
+
add(e?.expression); };
|
|
1041
|
+
const walk = (node) => {
|
|
1042
|
+
if (!node || typeof node !== 'object')
|
|
1043
|
+
return;
|
|
1044
|
+
if (Array.isArray(node)) {
|
|
1045
|
+
node.forEach(walk);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
if (node.type === 'BinaryExpression' && COMPARISON_OPERATORS.has(node.operator)) {
|
|
1049
|
+
add(node.left);
|
|
1050
|
+
add(node.right);
|
|
1051
|
+
}
|
|
1052
|
+
if (node.type === 'SwitchCase')
|
|
1053
|
+
add(node.test);
|
|
1054
|
+
if (node.type === 'KeyValueProperty') {
|
|
1055
|
+
add(node.key);
|
|
1056
|
+
const name = propertyName(node.key);
|
|
1057
|
+
if (name && DATA_KEYS.has(name))
|
|
1058
|
+
add(node.value);
|
|
1059
|
+
if (name && DATA_LISTS.test(name))
|
|
1060
|
+
addList(node.value);
|
|
1061
|
+
}
|
|
1062
|
+
if (node.type === 'VariableDeclarator' && DATA_LISTS.test(node.id?.value ?? ''))
|
|
1063
|
+
addList(node.init);
|
|
1064
|
+
if (node.type === 'JSXAttribute' && DATA_KEYS.has(node.name?.value) && node.value?.type === 'StringLiteral')
|
|
1065
|
+
add(node.value);
|
|
1066
|
+
if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
|
|
1067
|
+
for (const arg of node.arguments ?? [])
|
|
1068
|
+
add(arg.expression);
|
|
1069
|
+
if (node.callee?.type === 'MemberExpression')
|
|
1070
|
+
addList(node.callee.object);
|
|
1071
|
+
}
|
|
1072
|
+
for (const key in node)
|
|
1073
|
+
if (key !== 'span')
|
|
1074
|
+
walk(node[key]);
|
|
1075
|
+
};
|
|
1076
|
+
walk(ast);
|
|
1077
|
+
return found;
|
|
1078
|
+
}
|
|
1079
|
+
/** `console.log(...)`, `console.warn(...)`: their arguments are for developers, however they are built. */
|
|
1080
|
+
function isConsoleCall(node) {
|
|
1081
|
+
const callee = node.callee;
|
|
1082
|
+
return callee?.type === 'MemberExpression' && callee.object?.type === 'Identifier' && callee.object.value === 'console';
|
|
525
1083
|
}
|
|
526
1084
|
/**
|
|
527
1085
|
* Recursively visits AST nodes to find string literals.
|
|
@@ -534,14 +1092,22 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
534
1092
|
if (node.type === 'JSXOpeningElement' && jsx) {
|
|
535
1093
|
jsx = { ...jsx, element: resolveElementAttributes(jsx.rules, jsxElementName(node.name, jsx.aliases)) };
|
|
536
1094
|
}
|
|
537
|
-
|
|
538
|
-
//
|
|
539
|
-
//
|
|
540
|
-
if (node.type === 'CallExpression' &&
|
|
1095
|
+
const visit = (child) => visitNodeForStrings(child, content, file, config, candidates, jsx);
|
|
1096
|
+
// Its string arguments are not text; what it is called on and the functions it gets may hold some
|
|
1097
|
+
// (`el.addEventListener('click', () => { status.textContent = 'Copied to clipboard' })`)
|
|
1098
|
+
if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
|
|
1099
|
+
visit(node.callee);
|
|
1100
|
+
for (const arg of node.arguments ?? [])
|
|
1101
|
+
visitTextHolders(arg.expression, content, file, config, candidates, jsx);
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
const parts = nonTextParts(node, file, config, true);
|
|
1105
|
+
if (parts === 'all')
|
|
541
1106
|
return;
|
|
542
|
-
|
|
543
|
-
|
|
1107
|
+
if (parts) {
|
|
1108
|
+
forEachChild(node, parts, visit);
|
|
544
1109
|
return;
|
|
1110
|
+
}
|
|
545
1111
|
// Skip non-translatable JSX attributes entirely (e.g. className={...})
|
|
546
1112
|
if (node.type === 'JSXAttribute') {
|
|
547
1113
|
const nameNode = node.name;
|
|
@@ -555,31 +1121,47 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
555
1121
|
}
|
|
556
1122
|
// A rule that adds an attribute on this element wins over the built-in skip list (e.g. `name`)
|
|
557
1123
|
const added = attrName != null && jsx?.element?.accepted.has(attrName.toLowerCase());
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
//
|
|
561
|
-
|
|
1124
|
+
// The value of an ignored attribute, or one a rule removed on this element, is not text; but the
|
|
1125
|
+
// elements and functions in it hold text as anywhere else (`action={<Button>change</Button>}`,
|
|
1126
|
+
// `onClick={() => setMessage('Copied')}`)
|
|
1127
|
+
const notText = !!attrName && ((ignoredAttributeSet.has(attrName) && !added) ||
|
|
1128
|
+
!!jsx?.element?.removed.has(attrName.toLowerCase()) ||
|
|
1129
|
+
// For hyphenated names (data-testid), also check with the raw text
|
|
1130
|
+
(attrName.includes(':') && ignoredAttributeSet.has(attrName.replace(':', '-'))));
|
|
1131
|
+
if (notText) {
|
|
1132
|
+
visitTextHolders(node.value, content, file, config, candidates, jsx);
|
|
562
1133
|
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
1134
|
}
|
|
569
1135
|
}
|
|
1136
|
+
// What a JSX element renders from an expression is text, a single word too: `{used ? <>…</> : 'Never used'}`,
|
|
1137
|
+
// `{busy && 'saving'}`, `{name || 'the organization'}`
|
|
1138
|
+
if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
|
|
1139
|
+
for (const child of node.children ?? [])
|
|
1140
|
+
if (child.type === 'JSXExpressionContainer')
|
|
1141
|
+
markRendered(child.expression);
|
|
1142
|
+
}
|
|
1143
|
+
// The two branches of a ternary are alternatives of one text: when one is text, a string on the other side
|
|
1144
|
+
// is too (`running ? 'Confirm all reviews' : 'stop'`, `n ? \`Pay invoice ${n}\` : 'Pay invoice'`)
|
|
1145
|
+
if (node.type === 'ConditionalExpression') {
|
|
1146
|
+
visit(node.test);
|
|
1147
|
+
visit(node.consequent);
|
|
1148
|
+
visit(node.alternate);
|
|
1149
|
+
const branches = [node.consequent, node.alternate];
|
|
1150
|
+
const found = (b) => candidates.some(c => c.offset === b?.span?.start && c.endOffset === b?.span?.end);
|
|
1151
|
+
branches.forEach((b, i) => {
|
|
1152
|
+
if (b?.type !== 'StringLiteral' || found(b) || !found(branches[1 - i]))
|
|
1153
|
+
return;
|
|
1154
|
+
const candidate = stringCandidate(b, content, file, config, jsx?.element?.accepted, true);
|
|
1155
|
+
if (candidate)
|
|
1156
|
+
candidates.push(candidate);
|
|
1157
|
+
});
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
570
1160
|
// Check if this is a string literal
|
|
571
1161
|
if (node.type === 'StringLiteral') {
|
|
572
|
-
const
|
|
573
|
-
if (
|
|
574
|
-
|
|
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
|
-
}
|
|
1162
|
+
const candidate = stringCandidate(node, content, file, config, jsx?.element?.accepted, renderedStrings.has(node));
|
|
1163
|
+
if (candidate)
|
|
1164
|
+
candidates.push(candidate);
|
|
583
1165
|
}
|
|
584
1166
|
// Template literals
|
|
585
1167
|
if (node.type === 'TemplateLiteral') {
|
|
@@ -601,18 +1183,26 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
601
1183
|
}
|
|
602
1184
|
}
|
|
603
1185
|
else if (quasis?.length > 1 && expressions?.length > 0 && node.span) {
|
|
604
|
-
// Template literal with interpolation, e.g. `${count}-day streak
|
|
605
|
-
const
|
|
606
|
-
|
|
1186
|
+
// Template literal with interpolation, e.g. `${count}-day streak`, possibly with a plural in it
|
|
1187
|
+
const plural = buildPluralTemplate(quasis, expressions, content);
|
|
1188
|
+
const result = plural
|
|
1189
|
+
? { text: plural.pluralForms.other, interpolations: plural.interpolations }
|
|
1190
|
+
: buildInterpolatedTemplate(quasis, expressions, content);
|
|
1191
|
+
if (result && hasWordsBesidePlaceholders(result.text)) {
|
|
607
1192
|
const trimmed = result.text.trim();
|
|
608
1193
|
if (trimmed) {
|
|
609
1194
|
const candidate = detectCandidate(trimmed, node.span.start, node.span.end, file, content, config);
|
|
610
1195
|
if (candidate) {
|
|
611
1196
|
candidate.content = trimmed;
|
|
612
1197
|
candidate.type = 'template-literal';
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
1198
|
+
if (result.interpolations.length)
|
|
1199
|
+
candidate.interpolations = result.interpolations;
|
|
1200
|
+
if (plural) {
|
|
1201
|
+
candidate.pluralForms = plural.pluralForms;
|
|
1202
|
+
candidate.pluralHelper = plural.pluralHelper;
|
|
1203
|
+
}
|
|
1204
|
+
// Template literals mixing text + expressions are likely user-facing, plurals always
|
|
1205
|
+
candidate.confidence = Math.min(1, candidate.confidence + (plural ? 0.3 : 0.15));
|
|
616
1206
|
if (node.span.start > 0 && content[node.span.start - 1] === '=') {
|
|
617
1207
|
candidate.type = 'jsx-attribute';
|
|
618
1208
|
}
|
|
@@ -633,7 +1223,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
633
1223
|
const trimmedStart = raw.indexOf(trimmed);
|
|
634
1224
|
const offset = node.span.start + trimmedStart;
|
|
635
1225
|
const endOffset = offset + trimmed.length;
|
|
636
|
-
const candidate = detectCandidate(trimmed, offset, endOffset, file, content, config);
|
|
1226
|
+
const candidate = detectCandidate(jsxTextValue(trimmed), offset, endOffset, file, content, config, undefined, true);
|
|
637
1227
|
if (candidate) {
|
|
638
1228
|
candidate.type = 'jsx-text';
|
|
639
1229
|
// JSXText is almost always user-visible content; boost confidence
|
|
@@ -658,6 +1248,183 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
658
1248
|
}
|
|
659
1249
|
}
|
|
660
1250
|
}
|
|
1251
|
+
/**
|
|
1252
|
+
* Whether a name says it holds a language model's input: a function or variable (not a component) whose
|
|
1253
|
+
* camelCase words include `prompt` and one of system, user, ai, llm, gpt, assistant, chat, model
|
|
1254
|
+
* (`getSystemPrompt`, `aiFixPrompt`, `userPromptBatch`). A bare `prompt` may ask the user something
|
|
1255
|
+
* (`deletePrompt`), and `EmailPrompt` or `UserPromptDialog` are components.
|
|
1256
|
+
*/
|
|
1257
|
+
function isModelPromptName(name) {
|
|
1258
|
+
if (!name || !/^[a-z]/.test(name))
|
|
1259
|
+
return false;
|
|
1260
|
+
const words = name.split(/(?=[A-Z])|_/).map(w => w.toLowerCase());
|
|
1261
|
+
return words.includes('prompt') && words.some(w => MODEL_WORDS.has(w));
|
|
1262
|
+
}
|
|
1263
|
+
const MODEL_WORDS = new Set(['system', 'user', 'ai', 'llm', 'gpt', 'assistant', 'chat', 'model']);
|
|
1264
|
+
/**
|
|
1265
|
+
* JSX text as React renders it: each line trimmed where it meets a line break, the lines joined by one space,
|
|
1266
|
+
* entities decoded (`can't` → `can't`). In a `t()` default the source form would show as written.
|
|
1267
|
+
*/
|
|
1268
|
+
function jsxTextValue(raw) {
|
|
1269
|
+
const lines = raw.split(/\r\n|\n|\r/);
|
|
1270
|
+
let lastNonEmpty = 0;
|
|
1271
|
+
lines.forEach((line, i) => { if (/[^ \t]/.test(line))
|
|
1272
|
+
lastNonEmpty = i; });
|
|
1273
|
+
let text = '';
|
|
1274
|
+
lines.forEach((line, i) => {
|
|
1275
|
+
let part = line.replace(/\t/g, ' ');
|
|
1276
|
+
if (i > 0)
|
|
1277
|
+
part = part.replace(/^ +/, '');
|
|
1278
|
+
if (i < lines.length - 1)
|
|
1279
|
+
part = part.replace(/ +$/, '');
|
|
1280
|
+
if (part)
|
|
1281
|
+
text += i < lastNonEmpty ? `${part} ` : part;
|
|
1282
|
+
});
|
|
1283
|
+
return text.replace(HTML_ENTITY_RE, entity => decodeEntity(entity));
|
|
1284
|
+
}
|
|
1285
|
+
const NAMED_ENTITIES = {
|
|
1286
|
+
amp: '&',
|
|
1287
|
+
lt: '<',
|
|
1288
|
+
gt: '>',
|
|
1289
|
+
quot: '"',
|
|
1290
|
+
apos: "'",
|
|
1291
|
+
nbsp: '\u00a0',
|
|
1292
|
+
ndash: '–',
|
|
1293
|
+
mdash: '—',
|
|
1294
|
+
hellip: '…',
|
|
1295
|
+
lsquo: '‘',
|
|
1296
|
+
rsquo: '’',
|
|
1297
|
+
ldquo: '“',
|
|
1298
|
+
rdquo: '”',
|
|
1299
|
+
laquo: '«',
|
|
1300
|
+
raquo: '»',
|
|
1301
|
+
middot: '·',
|
|
1302
|
+
bull: '•',
|
|
1303
|
+
times: '×',
|
|
1304
|
+
copy: '©',
|
|
1305
|
+
reg: '®',
|
|
1306
|
+
trade: '™',
|
|
1307
|
+
euro: '€',
|
|
1308
|
+
deg: '°'
|
|
1309
|
+
};
|
|
1310
|
+
/** One HTML character reference as its character; an unknown name stays as written. */
|
|
1311
|
+
function decodeEntity(entity) {
|
|
1312
|
+
const body = entity.slice(1, -1);
|
|
1313
|
+
if (body[0] === '#') {
|
|
1314
|
+
const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
|
|
1315
|
+
return Number.isFinite(code) && code <= 0x10FFFF ? String.fromCodePoint(code) : entity;
|
|
1316
|
+
}
|
|
1317
|
+
return NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()] ?? entity;
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* What of a node is never text, the same for every walker looking for text: `'all'` (a t() call, a console
|
|
1321
|
+
* call, a <Trans>, an icon, code, a prompt for a language model, a log line, an error or a pattern), the
|
|
1322
|
+
* child keys that are not (an object key, a member property, a compared operand, a `case` value, the strings
|
|
1323
|
+
* of a non-text call), or null (all of it may be). `withTextHolders` is for the walker that visits the
|
|
1324
|
+
* functions and elements passed to a non-text call itself.
|
|
1325
|
+
*/
|
|
1326
|
+
function nonTextParts(node, file, config, withTextHolders) {
|
|
1327
|
+
switch (node.type) {
|
|
1328
|
+
case 'CallExpression':
|
|
1329
|
+
// already instrumented (also its options on a second run), or for developers however it is built
|
|
1330
|
+
if (isTranslationCall(node, config.extract.functions) || isConsoleCall(node))
|
|
1331
|
+
return 'all';
|
|
1332
|
+
return !withTextHolders && isNonTextMethodCall(node) ? ['arguments'] : null;
|
|
1333
|
+
case 'NewExpression':
|
|
1334
|
+
// `new Error('…')` is for developers, `new RegExp('…')` a pattern
|
|
1335
|
+
return node.callee?.type === 'Identifier' && /^RegExp$|Error$/.test(node.callee.value) ? 'all' : null;
|
|
1336
|
+
case 'JSXElement': {
|
|
1337
|
+
if (isTransComponent(node, config.extract.transComponents) || isIconElement(node))
|
|
1338
|
+
return 'all';
|
|
1339
|
+
// what code, scripts and styles show (`ignoredTags`, as for lint); inside a sentence it stays in its <Trans>
|
|
1340
|
+
const tag = node.opening?.name?.type === 'Identifier' ? node.opening.name.value.toLowerCase() : null;
|
|
1341
|
+
return tag && (ignoredTags.includes(tag) || config.extract.ignoredTags?.some(t => t.toLowerCase() === tag)) ? 'all' : null;
|
|
1342
|
+
}
|
|
1343
|
+
case 'KeyValueProperty':
|
|
1344
|
+
// a key names something and is never text; a call there is even a syntax error (`{ 'a b': 1 }`)
|
|
1345
|
+
return isModelPromptName(propertyName(node.key)) ? 'all' : ['key'];
|
|
1346
|
+
case 'MemberExpression':
|
|
1347
|
+
return ['property'];
|
|
1348
|
+
case 'BinaryExpression':
|
|
1349
|
+
// the strings a value is compared with are data (`status === 'Active'`)
|
|
1350
|
+
if (!COMPARISON_OPERATORS.has(node.operator))
|
|
1351
|
+
return null;
|
|
1352
|
+
return ['left', 'right'].filter(k => node[k]?.type === 'StringLiteral' || node[k]?.type === 'TemplateLiteral');
|
|
1353
|
+
case 'SwitchCase':
|
|
1354
|
+
return ['test'];
|
|
1355
|
+
case 'FunctionDeclaration':
|
|
1356
|
+
// a prompt is the input of a language model: translating it changes what the model does
|
|
1357
|
+
return isModelPromptName(node.identifier?.value) ? 'all' : null;
|
|
1358
|
+
case 'VariableDeclarator':
|
|
1359
|
+
// a prompt, or a variable used only in console calls (a log line: `const took = …; console.log(took)`)
|
|
1360
|
+
return isModelPromptName(node.id?.value) ||
|
|
1361
|
+
(node.id?.type === 'Identifier' && consoleOnlyNames.get(file)?.has(node.id.value))
|
|
1362
|
+
? 'all'
|
|
1363
|
+
: null;
|
|
1364
|
+
default:
|
|
1365
|
+
return null;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
/** Calls `visit` for each child node, but not those under the keys `except`. */
|
|
1369
|
+
function forEachChild(node, except, visit) {
|
|
1370
|
+
if (except === 'all')
|
|
1371
|
+
return;
|
|
1372
|
+
for (const key in node) {
|
|
1373
|
+
if (key === 'span' || except?.includes(key))
|
|
1374
|
+
continue;
|
|
1375
|
+
const value = node[key];
|
|
1376
|
+
if (Array.isArray(value))
|
|
1377
|
+
value.forEach(item => item && typeof item === 'object' && visit(item));
|
|
1378
|
+
else if (value && typeof value === 'object')
|
|
1379
|
+
visit(value);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
/** A string literal as a candidate of enough confidence, or null; `textSlot` takes a single word as text. */
|
|
1383
|
+
function stringCandidate(stringNode, content, file, config, accepted, textSlot) {
|
|
1384
|
+
if (!stringNode.span || typeof stringNode.span.start !== 'number')
|
|
1385
|
+
return null;
|
|
1386
|
+
// the same string as data elsewhere in the file: translating it here breaks the match there (what a JSX
|
|
1387
|
+
// element renders and an attribute's value, `data-tip='overridden'`, are shown, never matched)
|
|
1388
|
+
// nor a text property's (`{ value: 'Weekly', label: 'Weekly' }`)
|
|
1389
|
+
const attributeValue = stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=';
|
|
1390
|
+
const property = /([\w]+)\s*:\s*$/.exec(content.slice(Math.max(0, stringNode.span.start - 40), stringNode.span.start))?.[1];
|
|
1391
|
+
const textProperty = !!property && translatablePropertyLowerSet.has(property.toLowerCase());
|
|
1392
|
+
if (fileDataStrings.get(file)?.has(stringNode.value) && !renderedStrings.has(stringNode) && !attributeValue && !textProperty)
|
|
1393
|
+
return null;
|
|
1394
|
+
const candidate = detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, accepted, textSlot);
|
|
1395
|
+
// in a text slot the place says it is text, whatever the words score
|
|
1396
|
+
if (candidate && textSlot)
|
|
1397
|
+
candidate.confidence = Math.max(candidate.confidence, 0.7);
|
|
1398
|
+
if (!candidate || candidate.confidence < 0.7)
|
|
1399
|
+
return null;
|
|
1400
|
+
// Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
|
|
1401
|
+
if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=')
|
|
1402
|
+
candidate.type = 'jsx-attribute';
|
|
1403
|
+
return candidate;
|
|
1404
|
+
}
|
|
1405
|
+
const LOGICAL_OPERATORS = new Set(['&&', '||', '??']);
|
|
1406
|
+
const COMPARISON_OPERATORS = new Set(['===', '!==', '==', '!=', 'in', 'instanceof']);
|
|
1407
|
+
/** The name of an object property's key (`label`, `'aria-label'`), or null for a computed one. */
|
|
1408
|
+
function propertyName(key) {
|
|
1409
|
+
return key?.type === 'Identifier' || key?.type === 'StringLiteral' ? key.value : null;
|
|
1410
|
+
}
|
|
1411
|
+
/** Visits the JSX elements and functions inside a value that is not text itself, and nothing else of it. */
|
|
1412
|
+
function visitTextHolders(node, ...rest) {
|
|
1413
|
+
if (!node || typeof node !== 'object')
|
|
1414
|
+
return;
|
|
1415
|
+
if (TEXT_HOLDERS.has(node.type)) {
|
|
1416
|
+
visitNodeForStrings(node, ...rest);
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
for (const key in node) {
|
|
1420
|
+
const value = node[key];
|
|
1421
|
+
if (Array.isArray(value))
|
|
1422
|
+
value.forEach(item => visitTextHolders(item, ...rest));
|
|
1423
|
+
else
|
|
1424
|
+
visitTextHolders(value, ...rest);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
const TEXT_HOLDERS = new Set(['JSXElement', 'JSXFragment', 'ArrowFunctionExpression', 'FunctionExpression']);
|
|
661
1428
|
// ─── Template-literal interpolation helpers ──────────────────────────────────
|
|
662
1429
|
/**
|
|
663
1430
|
* Builds a merged text with `{{var}}` placeholders from a template literal's
|
|
@@ -665,7 +1432,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
665
1432
|
*/
|
|
666
1433
|
function buildInterpolatedTemplate(quasis, expressions, content) {
|
|
667
1434
|
const interpolations = [];
|
|
668
|
-
const usedNames = new
|
|
1435
|
+
const usedNames = new Map();
|
|
669
1436
|
let text = '';
|
|
670
1437
|
for (let i = 0; i < quasis.length; i++) {
|
|
671
1438
|
const quasi = quasis[i];
|
|
@@ -675,38 +1442,169 @@ function buildInterpolatedTemplate(quasis, expressions, content) {
|
|
|
675
1442
|
if (!info)
|
|
676
1443
|
return null; // un-resolvable expression — bail
|
|
677
1444
|
text += `{{${info.name}}}`;
|
|
678
|
-
|
|
1445
|
+
if (!info.reused)
|
|
1446
|
+
interpolations.push(info);
|
|
679
1447
|
}
|
|
680
1448
|
}
|
|
681
1449
|
return interpolations.length > 0 ? { text, interpolations } : null;
|
|
682
1450
|
}
|
|
683
1451
|
/**
|
|
684
|
-
*
|
|
685
|
-
*
|
|
686
|
-
*
|
|
687
|
-
*
|
|
688
|
-
*
|
|
1452
|
+
* Whether a text with `{{placeholders}}` holds at least one word standing on its own, and is not a
|
|
1453
|
+
* kebab-case name. A word: two letters or more, not camelCase, punctuation around it, a placeholder only
|
|
1454
|
+
* after it (`review{{suffix}}.`), not before it nor joined by `_`, `.` or `-`. Ids, paths, keys, flags and
|
|
1455
|
+
* class names built in a template literal have none: `{{projectId}}-{{version}}`, `weight_{{code}}`,
|
|
1456
|
+
* `{{baseUrl}}/api/{{id}}`, `{{id}}.collapsed`, `{{metric}}Avg`, `nameField{{i}}`, `--ct {{cdnType}}`,
|
|
1457
|
+
* `locize-dropzone {{state}}`.
|
|
1458
|
+
*/
|
|
1459
|
+
function hasWordsBesidePlaceholders(text) {
|
|
1460
|
+
// a placeholder becomes one private-use character, neither letter nor punctuation
|
|
1461
|
+
const bare = text.replace(HTML_ENTITY_RE, ' ').replace(/\{\{[^}]*\}\}/g, '\uE000');
|
|
1462
|
+
if (/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(bare.replace(/\uE000/g, ' ').trim()))
|
|
1463
|
+
return false;
|
|
1464
|
+
return bare.split(/\s+/).some(token => {
|
|
1465
|
+
// (a name with digits in a later part counts: `next-i18next v{{version}}`)
|
|
1466
|
+
const word = /^[^\p{L}\p{N}\uE000_.-]*(\p{L}{2,}(?:['’-]\p{N}*\p{L}[\p{L}\p{N}]*)*)[^\p{L}\p{N}_]*$/u.exec(token)?.[1];
|
|
1467
|
+
// `zh-{{country}}`, `{{a}}/{{b}}`: a placeholder joined to the word by a separator makes an id, not a phrase
|
|
1468
|
+
if (/[-_./:#@=&?|\\]\uE000/.test(token))
|
|
1469
|
+
return false;
|
|
1470
|
+
// one Han, Kana or Hangul character is a word of its own (`共 {{n}} 条`)
|
|
1471
|
+
return (!!word && !/\p{Ll}\p{Lu}/u.test(word)) || /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Hangul}]/u.test(token);
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* A template literal one of whose expressions is a plural (a plural helper call or a `count === 1` ternary),
|
|
1476
|
+
* as one text per plural form: `${n(keys)} ${plural(keys, 'key', 'keys')} unused` → one: '{{keys}} key unused',
|
|
1477
|
+
* other: '{{keys}} keys unused', count: keys. An expression that is the count itself becomes `{{count}}`.
|
|
1478
|
+
*/
|
|
1479
|
+
function buildPluralTemplate(quasis, expressions, content) {
|
|
1480
|
+
const pluralIndex = expressions.findIndex(e => parsePluralExpression(e, content));
|
|
1481
|
+
if (pluralIndex < 0)
|
|
1482
|
+
return null;
|
|
1483
|
+
const plural = parsePluralExpression(expressions[pluralIndex], content);
|
|
1484
|
+
const usedNames = new Map();
|
|
1485
|
+
const interpolations = [];
|
|
1486
|
+
const formText = (form) => {
|
|
1487
|
+
let text = '';
|
|
1488
|
+
for (let i = 0; i < quasis.length; i++) {
|
|
1489
|
+
text += quasis[i].cooked ?? quasis[i].raw ?? '';
|
|
1490
|
+
if (i >= expressions.length)
|
|
1491
|
+
continue;
|
|
1492
|
+
if (i === pluralIndex) {
|
|
1493
|
+
text += form;
|
|
1494
|
+
continue;
|
|
1495
|
+
}
|
|
1496
|
+
const expression = content.slice(expressions[i].span.start, expressions[i].span.end);
|
|
1497
|
+
if (expression === plural.countExpression) {
|
|
1498
|
+
text += '{{count}}';
|
|
1499
|
+
continue;
|
|
1500
|
+
}
|
|
1501
|
+
const info = resolveExpressionName(expressions[i], content, usedNames);
|
|
1502
|
+
if (!info)
|
|
1503
|
+
return null;
|
|
1504
|
+
text += `{{${info.name}}}`;
|
|
1505
|
+
if (!info.reused)
|
|
1506
|
+
interpolations.push(info);
|
|
1507
|
+
}
|
|
1508
|
+
return text.trim();
|
|
1509
|
+
};
|
|
1510
|
+
const other = formText(plural.other);
|
|
1511
|
+
const one = plural.one !== undefined ? formText(plural.one) : undefined;
|
|
1512
|
+
const zero = plural.zero !== undefined ? formText(plural.zero) : undefined;
|
|
1513
|
+
if (!other || one === null || zero === null)
|
|
1514
|
+
return null;
|
|
1515
|
+
if (!mergeInterpolations(interpolations, plural.interpolations))
|
|
1516
|
+
return null;
|
|
1517
|
+
return { pluralForms: { countExpression: plural.countExpression, zero, one, other }, interpolations, pluralHelper: pluralHelperOf(expressions[pluralIndex]) };
|
|
1518
|
+
}
|
|
1519
|
+
/** The name of the plural helper a call expression calls (`plural(n, …)` → `plural`), or undefined. */
|
|
1520
|
+
function pluralHelperOf(expr) {
|
|
1521
|
+
return expr?.type === 'CallExpression' && expr.callee?.type === 'Identifier' ? expr.callee.value : undefined;
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Adds a plural's own placeholders (from its forms) to the text's; false when a name stands for two
|
|
1525
|
+
* different expressions.
|
|
1526
|
+
*/
|
|
1527
|
+
function mergeInterpolations(into, from = []) {
|
|
1528
|
+
for (const item of from) {
|
|
1529
|
+
const same = into.find(i => i.name === item.name);
|
|
1530
|
+
if (same && same.expression !== item.expression)
|
|
1531
|
+
return false;
|
|
1532
|
+
if (!same)
|
|
1533
|
+
into.push(item);
|
|
1534
|
+
}
|
|
1535
|
+
return true;
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* The name an expression's value says best what it is, or null:
|
|
1539
|
+
* - `Identifier` → itself (`count`); `MemberExpression` → its last property (`profile.name` → `name`)
|
|
1540
|
+
* - a formatter's call, by its argument: `format.date(user.lastLogin)` → `lastLogin`, `n(queue)` → `queue`,
|
|
1541
|
+
* `Math.floor(m / 60)` → `m` (a namespace or a formatter keeps the meaning of what it gets)
|
|
1542
|
+
* - a string method's call, by what it is called on: `input.value.trim()` → `value`
|
|
1543
|
+
* - any other call, by the function: `price(plan)` → `price`, `api.calculatePercentage(stats)` → `calculatePercentage`
|
|
1544
|
+
* - `a - b`, `a || b`, `(a)`, `a as T`, `a!` → the name of `a`
|
|
1545
|
+
*/
|
|
1546
|
+
function nameOfExpression(expr) {
|
|
1547
|
+
switch (expr?.type) {
|
|
1548
|
+
case 'Identifier': return expr.value;
|
|
1549
|
+
case 'MemberExpression':
|
|
1550
|
+
return !expr.computed && expr.property?.type === 'Identifier' ? expr.property.value : null;
|
|
1551
|
+
case 'CallExpression': {
|
|
1552
|
+
const callee = expr.callee;
|
|
1553
|
+
const argument = () => nameOfExpression(expr.arguments?.[0]?.expression);
|
|
1554
|
+
if (callee?.type === 'Identifier')
|
|
1555
|
+
return FORMATTER_RE.test(callee.value) ? argument() : callee.value;
|
|
1556
|
+
if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
|
|
1557
|
+
return null;
|
|
1558
|
+
const object = callee.object;
|
|
1559
|
+
const method = callee.property.value;
|
|
1560
|
+
if (object?.type === 'Identifier' && (/^[A-Z]/.test(object.value) || FORMATTER_NAMESPACE_RE.test(object.value)))
|
|
1561
|
+
return argument();
|
|
1562
|
+
// `date.toLocaleDateString()`, `terms.map(…).join(', ')`: still the value it is called on
|
|
1563
|
+
if (STRING_METHODS.has(method) || ARRAY_METHODS.has(method))
|
|
1564
|
+
return nameOfExpression(object);
|
|
1565
|
+
return method;
|
|
1566
|
+
}
|
|
1567
|
+
case 'BinaryExpression':
|
|
1568
|
+
// `name || email` (swc types `||`, `&&`, `??` as a BinaryExpression), `i + 1`: the value meant; any other
|
|
1569
|
+
// arithmetic is a new quantity (`segments * tokensPerSegment`), which no operand names
|
|
1570
|
+
if (LOGICAL_OPERATORS.has(expr.operator))
|
|
1571
|
+
return nameOfExpression(expr.left);
|
|
1572
|
+
if ((expr.operator === '+' || expr.operator === '-') && expr.right?.type === 'NumericLiteral')
|
|
1573
|
+
return nameOfExpression(expr.left);
|
|
1574
|
+
return null;
|
|
1575
|
+
case 'ParenthesisExpression':
|
|
1576
|
+
case 'TsAsExpression':
|
|
1577
|
+
case 'TsNonNullExpression':
|
|
1578
|
+
case 'TsSatisfiesExpression': return nameOfExpression(expr.expression);
|
|
1579
|
+
default: return null;
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
/** Names of formatter functions: their call shows the value they get (`n(queue)`, `formatDate(createdAt)`). */
|
|
1583
|
+
const FORMATTER_RE = /^(?:format\w*|fmt|formatter|n|num|number|money|percent)$/i;
|
|
1584
|
+
/** Names of formatting namespaces (`format.date(x)`); a capitalized one (`Math`, `Intl`) is one too. */
|
|
1585
|
+
const FORMATTER_NAMESPACE_RE = /^(?:format\w*|fmt|formatter|intl)$/i;
|
|
1586
|
+
/** Array methods whose result still holds what they are called on. */
|
|
1587
|
+
const ARRAY_METHODS = new Set(['map', 'filter', 'sort', 'slice', 'flat', 'flatMap', 'concat', 'reverse']);
|
|
1588
|
+
/**
|
|
1589
|
+
* Resolves a human-friendly interpolation name from an AST expression node (see `nameOfExpression`;
|
|
1590
|
+
* `val`, `val2`, ... when none). The same expression twice in one text gets one name (`reused`), so the
|
|
1591
|
+
* options name it once.
|
|
689
1592
|
*/
|
|
690
1593
|
function resolveExpressionName(expr, content, usedNames) {
|
|
691
1594
|
if (!expr?.span)
|
|
692
1595
|
return null;
|
|
693
1596
|
const expression = content.slice(expr.span.start, expr.span.end);
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
}
|
|
698
|
-
else if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier') {
|
|
699
|
-
baseName = expr.property.value;
|
|
700
|
-
}
|
|
701
|
-
else {
|
|
702
|
-
baseName = 'val';
|
|
1597
|
+
for (const [name, expr] of usedNames) {
|
|
1598
|
+
if (expr === expression)
|
|
1599
|
+
return { name, expression, reused: true };
|
|
703
1600
|
}
|
|
1601
|
+
const baseName = nameOfExpression(expr) ?? 'val';
|
|
704
1602
|
let name = baseName;
|
|
705
1603
|
let counter = 2;
|
|
706
1604
|
while (usedNames.has(name)) {
|
|
707
1605
|
name = `${baseName}${counter++}`;
|
|
708
1606
|
}
|
|
709
|
-
usedNames.
|
|
1607
|
+
usedNames.set(name, expression);
|
|
710
1608
|
return { name, expression };
|
|
711
1609
|
}
|
|
712
1610
|
// ─── JSX sibling interpolation merging ───────────────────────────────────────
|
|
@@ -720,8 +1618,9 @@ function resolveExpressionName(expr, content, usedNames) {
|
|
|
720
1618
|
function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
721
1619
|
if (!node)
|
|
722
1620
|
return;
|
|
723
|
-
//
|
|
724
|
-
|
|
1621
|
+
// Not text (a <Trans>, code, an icon, a prompt, a log line, a key, …): nothing to merge in it
|
|
1622
|
+
const parts = nonTextParts(node, file, config, false);
|
|
1623
|
+
if (parts === 'all')
|
|
725
1624
|
return;
|
|
726
1625
|
const children = (node.type === 'JSXElement' || node.type === 'JSXFragment') ? node.children : null;
|
|
727
1626
|
if (children?.length > 1) {
|
|
@@ -732,13 +1631,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
732
1631
|
if (child.type === 'JSXText') {
|
|
733
1632
|
currentRun.push(child);
|
|
734
1633
|
}
|
|
735
|
-
else if (child.type === 'JSXExpressionContainer' && isSimpleJSXExpression(child.expression)) {
|
|
1634
|
+
else if (child.type === 'JSXExpressionContainer' && (isSimpleJSXExpression(child.expression) || child.expression?.type === 'StringLiteral')) {
|
|
1635
|
+
// a simple expression, or literal text such as {' '}
|
|
736
1636
|
currentRun.push(child);
|
|
737
1637
|
}
|
|
738
|
-
else if (child.type === 'JSXExpressionContainer' &&
|
|
739
|
-
|
|
740
|
-
tryParsePluralTernary(child.expression, content)) {
|
|
741
|
-
// Plural ternary expression — include in the run for merged handling
|
|
1638
|
+
else if (child.type === 'JSXExpressionContainer' && parsePluralExpression(child.expression, content)) {
|
|
1639
|
+
// Plural ternary or plural helper call: part of the run, merged with it
|
|
742
1640
|
currentRun.push(child);
|
|
743
1641
|
}
|
|
744
1642
|
else if (child.type === 'JSXElement' && isSimpleJSXElement(child)) {
|
|
@@ -756,7 +1654,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
756
1654
|
if (currentRun.length > 0) {
|
|
757
1655
|
runs.push(currentRun);
|
|
758
1656
|
}
|
|
759
|
-
for (const
|
|
1657
|
+
for (const fullRun of runs) {
|
|
1658
|
+
// Whitespace at a run's edges stays in the source: a rewrite of it would drop a space the page shows
|
|
1659
|
+
// (`provider:{' '}<strong>…`)
|
|
1660
|
+
const run = trimRun(fullRun);
|
|
1661
|
+
if (!run.length)
|
|
1662
|
+
continue;
|
|
760
1663
|
const hasText = run.some(c => c.type === 'JSXText' && c.value?.trim());
|
|
761
1664
|
const hasExpr = run.some(c => c.type === 'JSXExpressionContainer');
|
|
762
1665
|
const hasElement = run.some(c => c.type === 'JSXElement');
|
|
@@ -769,9 +1672,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
769
1672
|
let pluralChild = null;
|
|
770
1673
|
let pluralData = null;
|
|
771
1674
|
for (const child of run) {
|
|
772
|
-
if (child.type === 'JSXExpressionContainer'
|
|
773
|
-
child.expression
|
|
774
|
-
const p = tryParsePluralTernary(child.expression, content);
|
|
1675
|
+
if (child.type === 'JSXExpressionContainer') {
|
|
1676
|
+
const p = parsePluralExpression(child.expression, content);
|
|
775
1677
|
if (p) {
|
|
776
1678
|
pluralChild = child;
|
|
777
1679
|
pluralData = p;
|
|
@@ -779,12 +1681,15 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
779
1681
|
}
|
|
780
1682
|
}
|
|
781
1683
|
}
|
|
1684
|
+
// A sentence with both an element and a plural stays in its parts: in a <Trans> the plural's forms would
|
|
1685
|
+
// end up untranslated in an interpolation, and a plural t() cannot hold the element
|
|
1686
|
+
if (hasElement && pluralChild)
|
|
1687
|
+
continue;
|
|
782
1688
|
if (hasElement) {
|
|
783
1689
|
// ── JSX sibling run with nested HTML elements → <Trans> ──
|
|
784
|
-
const spanStart = run
|
|
785
|
-
const spanEnd = run[run.length - 1].span.end;
|
|
1690
|
+
const [spanStart, spanEnd] = runSpan(run, content);
|
|
786
1691
|
// Build the translation string (with indexed tags) and text-only version (for scoring)
|
|
787
|
-
const usedNames = new
|
|
1692
|
+
const usedNames = new Map();
|
|
788
1693
|
const interpolations = [];
|
|
789
1694
|
let transValue = '';
|
|
790
1695
|
let textOnly = '';
|
|
@@ -794,9 +1699,19 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
794
1699
|
for (const child of run) {
|
|
795
1700
|
if (child.type === 'JSXText') {
|
|
796
1701
|
const raw = content.slice(child.span.start, child.span.end);
|
|
797
|
-
|
|
798
|
-
|
|
1702
|
+
const text = jsxTextValue(raw);
|
|
1703
|
+
transValue += text;
|
|
1704
|
+
textOnly += text;
|
|
799
1705
|
transContent += raw;
|
|
1706
|
+
// whitespace with a line break is no child of the element at all
|
|
1707
|
+
if (text)
|
|
1708
|
+
childIndex++;
|
|
1709
|
+
}
|
|
1710
|
+
else if (child.type === 'JSXExpressionContainer' && child.expression?.type === 'StringLiteral') {
|
|
1711
|
+
// {' '} and other literal text: part of the sentence, kept as written
|
|
1712
|
+
transValue += child.expression.value;
|
|
1713
|
+
textOnly += child.expression.value;
|
|
1714
|
+
transContent += content.slice(child.span.start, child.span.end);
|
|
800
1715
|
childIndex++;
|
|
801
1716
|
}
|
|
802
1717
|
else if (child.type === 'JSXExpressionContainer') {
|
|
@@ -810,7 +1725,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
810
1725
|
// In <Trans> children, simple expressions become {{ obj }} syntax
|
|
811
1726
|
const objExpr = info.name === info.expression ? info.name : `${info.name}: ${info.expression}`;
|
|
812
1727
|
transContent += `{{ ${objExpr} }}`;
|
|
813
|
-
|
|
1728
|
+
if (!info.reused)
|
|
1729
|
+
interpolations.push(info);
|
|
814
1730
|
childIndex++;
|
|
815
1731
|
}
|
|
816
1732
|
else if (child.type === 'JSXElement') {
|
|
@@ -853,12 +1769,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
853
1769
|
// ── JSX sibling run with embedded plural ternary ──
|
|
854
1770
|
const countExpr = pluralData.countExpression;
|
|
855
1771
|
// Resolve names for non-count, non-plural expressions
|
|
856
|
-
const usedNames = new
|
|
1772
|
+
const usedNames = new Map();
|
|
857
1773
|
const extraInterpolations = [];
|
|
858
1774
|
const exprNameMap = new Map();
|
|
859
1775
|
let valid = true;
|
|
860
1776
|
for (const child of run) {
|
|
861
|
-
if (child.type === 'JSXExpressionContainer' && child !== pluralChild) {
|
|
1777
|
+
if (child.type === 'JSXExpressionContainer' && child !== pluralChild && child.expression?.type !== 'StringLiteral') {
|
|
862
1778
|
const exprText = content.slice(child.expression.span.start, child.expression.span.end);
|
|
863
1779
|
if (exprText === countExpr) {
|
|
864
1780
|
exprNameMap.set(child, 'count');
|
|
@@ -870,11 +1786,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
870
1786
|
break;
|
|
871
1787
|
}
|
|
872
1788
|
exprNameMap.set(child, info.name);
|
|
873
|
-
|
|
1789
|
+
if (!info.reused)
|
|
1790
|
+
extraInterpolations.push(info);
|
|
874
1791
|
}
|
|
875
1792
|
}
|
|
876
1793
|
}
|
|
877
|
-
if (!valid)
|
|
1794
|
+
if (!valid || !mergeInterpolations(extraInterpolations, pluralData.interpolations))
|
|
878
1795
|
continue;
|
|
879
1796
|
// Build merged text for each plural form
|
|
880
1797
|
const forms = [
|
|
@@ -887,7 +1804,10 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
887
1804
|
let text = '';
|
|
888
1805
|
for (const child of run) {
|
|
889
1806
|
if (child.type === 'JSXText') {
|
|
890
|
-
text += content.slice(child.span.start, child.span.end);
|
|
1807
|
+
text += jsxTextValue(content.slice(child.span.start, child.span.end));
|
|
1808
|
+
}
|
|
1809
|
+
else if (child.expression?.type === 'StringLiteral') {
|
|
1810
|
+
text += child.expression.value;
|
|
891
1811
|
}
|
|
892
1812
|
else if (child === pluralChild) {
|
|
893
1813
|
const formText = form === 'zero'
|
|
@@ -904,8 +1824,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
904
1824
|
}
|
|
905
1825
|
formTexts[form] = text.trim();
|
|
906
1826
|
}
|
|
907
|
-
const spanStart = run
|
|
908
|
-
const spanEnd = run[run.length - 1].span.end;
|
|
1827
|
+
const [spanStart, spanEnd] = runSpan(run, content);
|
|
909
1828
|
const otherText = formTexts.other;
|
|
910
1829
|
if (!otherText)
|
|
911
1830
|
continue;
|
|
@@ -922,6 +1841,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
922
1841
|
if (extraInterpolations.length > 0) {
|
|
923
1842
|
candidate.interpolations = extraInterpolations;
|
|
924
1843
|
}
|
|
1844
|
+
candidate.pluralHelper = pluralHelperOf(pluralChild.expression);
|
|
925
1845
|
// Plural + JSX merge is always user-facing
|
|
926
1846
|
candidate.confidence = Math.min(1, candidate.confidence + 0.3);
|
|
927
1847
|
if (candidate.confidence >= 0.7) {
|
|
@@ -938,13 +1858,16 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
938
1858
|
else {
|
|
939
1859
|
// ── Original JSX sibling merging (text + expressions, no elements) ──
|
|
940
1860
|
// Build the interpolated text from the run
|
|
941
|
-
const usedNames = new
|
|
1861
|
+
const usedNames = new Map();
|
|
942
1862
|
const interpolations = [];
|
|
943
1863
|
let text = '';
|
|
944
1864
|
let valid = true;
|
|
945
1865
|
for (const child of run) {
|
|
946
1866
|
if (child.type === 'JSXText') {
|
|
947
|
-
text += content.slice(child.span.start, child.span.end);
|
|
1867
|
+
text += jsxTextValue(content.slice(child.span.start, child.span.end));
|
|
1868
|
+
}
|
|
1869
|
+
else if (child.expression?.type === 'StringLiteral') {
|
|
1870
|
+
text += child.expression.value;
|
|
948
1871
|
}
|
|
949
1872
|
else {
|
|
950
1873
|
const info = resolveExpressionName(child.expression, content, usedNames);
|
|
@@ -953,21 +1876,23 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
953
1876
|
break;
|
|
954
1877
|
}
|
|
955
1878
|
text += `{{${info.name}}}`;
|
|
956
|
-
|
|
1879
|
+
if (!info.reused)
|
|
1880
|
+
interpolations.push(info);
|
|
957
1881
|
}
|
|
958
1882
|
}
|
|
959
1883
|
if (!valid)
|
|
960
1884
|
continue;
|
|
961
1885
|
const trimmed = text.trim();
|
|
962
|
-
|
|
1886
|
+
const literalPiece = run.some(c => c.expression?.type === 'StringLiteral');
|
|
1887
|
+
if (!trimmed || (interpolations.length === 0 && !literalPiece) || !hasWordsBesidePlaceholders(trimmed))
|
|
963
1888
|
continue;
|
|
964
|
-
const spanStart = run
|
|
965
|
-
const spanEnd = run[run.length - 1].span.end;
|
|
1889
|
+
const [spanStart, spanEnd] = runSpan(run, content);
|
|
966
1890
|
const candidate = detectCandidate(trimmed, spanStart, spanEnd, file, content, config);
|
|
967
1891
|
if (candidate) {
|
|
968
1892
|
candidate.type = 'jsx-text';
|
|
969
1893
|
candidate.content = trimmed;
|
|
970
|
-
|
|
1894
|
+
if (interpolations.length)
|
|
1895
|
+
candidate.interpolations = interpolations;
|
|
971
1896
|
// Mixed text + expressions in JSX is almost always user-facing
|
|
972
1897
|
candidate.confidence = Math.min(1, candidate.confidence + 0.2);
|
|
973
1898
|
if (candidate.confidence >= 0.7) {
|
|
@@ -984,17 +1909,36 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
984
1909
|
}
|
|
985
1910
|
}
|
|
986
1911
|
// Recurse into children
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1912
|
+
forEachChild(node, parts, child => detectJSXInterpolation(child, content, file, config, candidates));
|
|
1913
|
+
}
|
|
1914
|
+
/** A run without the whitespace-only text, `{' '}` pieces and empty elements (`<hr />`, `<br />`) at its two ends. */
|
|
1915
|
+
function trimRun(run) {
|
|
1916
|
+
const blank = (c) => (c.type === 'JSXText' && !c.value?.trim()) ||
|
|
1917
|
+
(c.type === 'JSXExpressionContainer' && c.expression?.type === 'StringLiteral' && !c.expression.value.trim()) ||
|
|
1918
|
+
(c.type === 'JSXElement' && !c.children?.length);
|
|
1919
|
+
let start = 0;
|
|
1920
|
+
let end = run.length;
|
|
1921
|
+
while (start < end && blank(run[start]))
|
|
1922
|
+
start++;
|
|
1923
|
+
while (end > start && blank(run[end - 1]))
|
|
1924
|
+
end--;
|
|
1925
|
+
return run.slice(start, end);
|
|
1926
|
+
}
|
|
1927
|
+
/** Where a run's rewrite starts and ends: inside the whitespace of its first and last text. */
|
|
1928
|
+
function runSpan(run, content) {
|
|
1929
|
+
const first = run[0];
|
|
1930
|
+
const last = run[run.length - 1];
|
|
1931
|
+
let start = first.span.start;
|
|
1932
|
+
let end = last.span.end;
|
|
1933
|
+
if (first.type === 'JSXText') {
|
|
1934
|
+
const raw = content.slice(first.span.start, first.span.end);
|
|
1935
|
+
start += raw.length - raw.trimStart().length;
|
|
1936
|
+
}
|
|
1937
|
+
if (last.type === 'JSXText') {
|
|
1938
|
+
const raw = content.slice(last.span.start, last.span.end);
|
|
1939
|
+
end -= raw.length - raw.trimEnd().length;
|
|
1940
|
+
}
|
|
1941
|
+
return [start, end];
|
|
998
1942
|
}
|
|
999
1943
|
/**
|
|
1000
1944
|
* Returns true when the expression is a simple Identifier or non-computed
|
|
@@ -1007,36 +1951,77 @@ function isSimpleJSXExpression(expr) {
|
|
|
1007
1951
|
return true;
|
|
1008
1952
|
if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier')
|
|
1009
1953
|
return true;
|
|
1954
|
+
// A string or number made from one, inside a sentence as a placeholder (`up to {n.toLocaleString()} segments`,
|
|
1955
|
+
// `{Math.round(score * 100)}%`, `+ {total - shown} more`); any other call may return elements
|
|
1956
|
+
if (expr.type === 'ParenthesisExpression')
|
|
1957
|
+
return isSimpleJSXExpression(expr.expression);
|
|
1958
|
+
if (expr.type === 'NumericLiteral')
|
|
1959
|
+
return true;
|
|
1960
|
+
if (expr.type === 'BinaryExpression' && ARITHMETIC_OPERATORS.has(expr.operator)) {
|
|
1961
|
+
return isSimpleJSXExpression(expr.left) && isSimpleJSXExpression(expr.right);
|
|
1962
|
+
}
|
|
1963
|
+
// a choice between such values (`{young ? 3 : 2}`); a choice between strings is text of its own, which a
|
|
1964
|
+
// placeholder would leave untranslated
|
|
1965
|
+
if (expr.type === 'ConditionalExpression') {
|
|
1966
|
+
return [expr.consequent, expr.alternate].every(b => b?.type !== 'StringLiteral' && b?.type !== 'TemplateLiteral' && isSimpleJSXExpression(b));
|
|
1967
|
+
}
|
|
1968
|
+
// `format.date(x)`, `formatPrice(x)`: a formatter returns a string
|
|
1969
|
+
if (expr.type === 'CallExpression' && expr.callee?.type === 'Identifier')
|
|
1970
|
+
return /^format[A-Z]/.test(expr.callee.value);
|
|
1971
|
+
if (expr.type === 'CallExpression' && expr.callee?.type === 'MemberExpression' && expr.callee.property?.type === 'Identifier') {
|
|
1972
|
+
const object = expr.callee.object;
|
|
1973
|
+
const method = expr.callee.property.value;
|
|
1974
|
+
return STRING_METHODS.has(method) || /^format/.test(method) ||
|
|
1975
|
+
(object?.type === 'Identifier' && (object.value === 'Math' || object.value === 'Number' || /^(?:format|formatter|fmt|intl)$/i.test(object.value)));
|
|
1976
|
+
}
|
|
1010
1977
|
return false;
|
|
1011
1978
|
}
|
|
1979
|
+
const ARITHMETIC_OPERATORS = new Set(['-', '*', '/', '%']);
|
|
1980
|
+
/**
|
|
1981
|
+
* Methods that return a string whatever they are called on (`list.map(…).join(', ')`), so their call in JSX
|
|
1982
|
+
* text is a placeholder like a variable; not `slice`, which keeps an array of elements.
|
|
1983
|
+
*/
|
|
1984
|
+
const STRING_METHODS = new Set([
|
|
1985
|
+
'join', 'toString', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString', 'toFixed', 'toPrecision',
|
|
1986
|
+
'trim', 'toUpperCase', 'toLowerCase', 'padStart', 'padEnd', 'substring', 'replace', 'replaceAll'
|
|
1987
|
+
]);
|
|
1012
1988
|
/**
|
|
1013
1989
|
* Returns true when a JSXElement is "simple" enough to be included in a
|
|
1014
1990
|
* `<Trans>` JSX sibling run. Accepts:
|
|
1015
|
-
* - Self-closing elements (`<br />`, `<img />`)
|
|
1016
|
-
* -
|
|
1017
|
-
*
|
|
1018
|
-
*
|
|
1991
|
+
* - Self-closing HTML elements (`<br />`, `<img />`)
|
|
1992
|
+
* - HTML elements whose only children are `JSXText` nodes
|
|
1993
|
+
* - Components whose only children are text, a link in a sentence
|
|
1994
|
+
* (`Leave your <DialogLink to='/'>projects</DialogLink> first.`); a component
|
|
1995
|
+
* without text (`<Icon />`) breaks the run
|
|
1019
1996
|
*/
|
|
1020
1997
|
function isSimpleJSXElement(node) {
|
|
1021
|
-
if (node.type !== 'JSXElement')
|
|
1998
|
+
if (node.type !== 'JSXElement' || isIconElement(node))
|
|
1022
1999
|
return false;
|
|
1023
2000
|
const namePart = node.opening?.name;
|
|
1024
2001
|
if (!namePart)
|
|
1025
2002
|
return false;
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
if (namePart.type === '
|
|
1029
|
-
|
|
2003
|
+
const children = node.children || [];
|
|
2004
|
+
const textOnly = children.every((c) => c.type === 'JSXText');
|
|
2005
|
+
if (namePart.type === 'JSXMemberExpression') {
|
|
2006
|
+
const name = `${namePart.object?.value ?? ''}.${namePart.property?.value ?? ''}`;
|
|
2007
|
+
return INLINE_COMPONENT_RE.test(name) && children.length > 0 && textOnly;
|
|
1030
2008
|
}
|
|
1031
|
-
if (
|
|
2009
|
+
if (namePart.type !== 'Identifier')
|
|
1032
2010
|
return false;
|
|
2011
|
+
const tagName = namePart.value;
|
|
2012
|
+
if (tagName[0] !== tagName[0].toLowerCase())
|
|
2013
|
+
return INLINE_COMPONENT_RE.test(tagName) && children.some((c) => c.value?.trim()) && textOnly;
|
|
1033
2014
|
// Self-closing elements are simple
|
|
1034
2015
|
if (node.opening?.selfClosing)
|
|
1035
2016
|
return true;
|
|
1036
2017
|
// Elements with only text children (or empty) are simple
|
|
1037
|
-
|
|
1038
|
-
return children.length === 0 || children.every((c) => c.type === 'JSXText');
|
|
2018
|
+
return children.length === 0 || textOnly;
|
|
1039
2019
|
}
|
|
2020
|
+
/**
|
|
2021
|
+
* Components that stand inside a sentence: links and text styles (`DialogLink`, `Text.Strong`). A button or a
|
|
2022
|
+
* card next to a text is a piece of its own, not part of the sentence.
|
|
2023
|
+
*/
|
|
2024
|
+
const INLINE_COMPONENT_RE = /Link$|^Text\b|Text$|^(?:Strong|Em|B|I|Code|Mark|Highlight)$/;
|
|
1040
2025
|
/**
|
|
1041
2026
|
* Returns the text content of a simple JSXElement's children.
|
|
1042
2027
|
*/
|
|
@@ -1051,17 +2036,32 @@ function getJSXElementTextContent(node, content) {
|
|
|
1051
2036
|
* Returns true when a JSXElement is a `<Trans>` component
|
|
1052
2037
|
* (already instrumented content).
|
|
1053
2038
|
*/
|
|
1054
|
-
function isTransComponent(node) {
|
|
2039
|
+
function isTransComponent(node, transComponents = []) {
|
|
1055
2040
|
const opening = node.opening;
|
|
1056
2041
|
if (!opening)
|
|
1057
2042
|
return false;
|
|
1058
2043
|
const name = opening.name;
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
2044
|
+
// react-i18next's own: Trans, IcuTrans and their WithoutContext variants for Server Components
|
|
2045
|
+
if (name?.type === 'Identifier')
|
|
2046
|
+
return TRANS_RE.test(name.value) || transComponents.includes(name.value);
|
|
2047
|
+
if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier') {
|
|
2048
|
+
const object = name.object?.type === 'Identifier' ? name.object.value : '';
|
|
2049
|
+
return TRANS_RE.test(name.property.value) || transComponents.includes(`${object}.${name.property.value}`);
|
|
2050
|
+
}
|
|
1063
2051
|
return false;
|
|
1064
2052
|
}
|
|
2053
|
+
const TRANS_RE = /^(?:Icu)?Trans(?:WithoutContext)?$/;
|
|
2054
|
+
/**
|
|
2055
|
+
* An icon: an element whose name ends in `Icon`, or one with a Material icon class. Its text is a ligature
|
|
2056
|
+
* (`<Icon>delete</Icon>`, `<span className='material-icons'>search</span>`) that a translation would break.
|
|
2057
|
+
*/
|
|
2058
|
+
function isIconElement(node) {
|
|
2059
|
+
const name = node.opening?.name;
|
|
2060
|
+
const tag = name?.type === 'Identifier' ? name.value : name?.type === 'JSXMemberExpression' ? name.property?.value : '';
|
|
2061
|
+
if (/Icon$/.test(tag ?? ''))
|
|
2062
|
+
return true;
|
|
2063
|
+
return (node.opening?.attributes ?? []).some((a) => a.name?.value === 'className' && a.value?.type === 'StringLiteral' && /\bmaterial-(?:icons|symbols)/.test(a.value.value));
|
|
2064
|
+
}
|
|
1065
2065
|
// ─── Plural conditional pattern detection ────────────────────────────────────
|
|
1066
2066
|
/**
|
|
1067
2067
|
* Extracts the text value from a string literal or static template literal node.
|
|
@@ -1162,8 +2162,11 @@ function parseCountTest(test, content) {
|
|
|
1162
2162
|
function detectPluralPatterns(node, content, file, config, candidates) {
|
|
1163
2163
|
if (!node)
|
|
1164
2164
|
return;
|
|
1165
|
-
|
|
1166
|
-
|
|
2165
|
+
const parts = nonTextParts(node, file, config, false);
|
|
2166
|
+
if (parts === 'all')
|
|
2167
|
+
return;
|
|
2168
|
+
if (node.type === 'ConditionalExpression' || node.type === 'CallExpression') {
|
|
2169
|
+
const plural = parsePluralExpression(node, content);
|
|
1167
2170
|
if (plural) {
|
|
1168
2171
|
// Use the "other" form as the candidate content (with {{count}})
|
|
1169
2172
|
const spanStart = node.span.start;
|
|
@@ -1183,6 +2186,9 @@ function detectPluralPatterns(node, content, file, config, candidates) {
|
|
|
1183
2186
|
one: plural.one,
|
|
1184
2187
|
other: plural.other
|
|
1185
2188
|
};
|
|
2189
|
+
if (plural.interpolations)
|
|
2190
|
+
candidate.interpolations = plural.interpolations;
|
|
2191
|
+
candidate.pluralHelper = pluralHelperOf(node);
|
|
1186
2192
|
// Plural patterns are always user-facing text — boost confidence
|
|
1187
2193
|
candidate.confidence = Math.min(1, candidate.confidence + 0.3);
|
|
1188
2194
|
if (candidate.confidence >= 0.7) {
|
|
@@ -1200,20 +2206,77 @@ function detectPluralPatterns(node, content, file, config, candidates) {
|
|
|
1200
2206
|
}
|
|
1201
2207
|
}
|
|
1202
2208
|
// Recurse into children
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
2209
|
+
forEachChild(node, parts, child => detectPluralPatterns(child, content, file, config, candidates));
|
|
2210
|
+
}
|
|
2211
|
+
/** A plural helper call or a `count === 1` ternary as its plural forms, or null. */
|
|
2212
|
+
function parsePluralExpression(expr, content) {
|
|
2213
|
+
if (expr?.type === 'ConditionalExpression')
|
|
2214
|
+
return tryParsePluralTernary(expr, content);
|
|
2215
|
+
if (expr?.type === 'CallExpression')
|
|
2216
|
+
return tryParsePluralCall(expr, content);
|
|
2217
|
+
return null;
|
|
2218
|
+
}
|
|
2219
|
+
/** Names of plural helpers whose call reads `(count, one, other)`. */
|
|
2220
|
+
const PLURAL_HELPER_RE = /^(?:plural|pluralize|pluralise)$/i;
|
|
2221
|
+
/**
|
|
2222
|
+
* Attempts to parse a plural helper call into a plural pattern:
|
|
2223
|
+
* plural(count, '# file', '# files') → one: '{{count}} file', other: '{{count}} files'
|
|
2224
|
+
* pluralize(n, 'item', `${n} items`) → one: 'item', other: '{{count}} items'
|
|
2225
|
+
* `#` in a form stands for the number, as in ICU. Only a call whose two forms are text (a string, or a
|
|
2226
|
+
* template literal whose only expression is the count) and whose count is not a string.
|
|
2227
|
+
*/
|
|
2228
|
+
function tryParsePluralCall(node, content) {
|
|
2229
|
+
const callee = node.callee;
|
|
2230
|
+
const name = callee?.type === 'Identifier'
|
|
2231
|
+
? callee.value
|
|
2232
|
+
: callee?.type === 'MemberExpression' && !callee.computed && callee.property?.type === 'Identifier' ? callee.property.value : null;
|
|
2233
|
+
if (!name || !PLURAL_HELPER_RE.test(name))
|
|
2234
|
+
return null;
|
|
2235
|
+
const [count, one, other] = (node.arguments ?? []).map((a) => a?.spread ? null : a?.expression);
|
|
2236
|
+
if (!count?.span || !one || !other || count.type === 'StringLiteral' || count.type === 'TemplateLiteral')
|
|
2237
|
+
return null;
|
|
2238
|
+
const countExpression = content.slice(count.span.start, count.span.end);
|
|
2239
|
+
// A form's other expressions become placeholders, named once for both forms (`showing ${shown} of # user`)
|
|
2240
|
+
const usedNames = new Map();
|
|
2241
|
+
const interpolations = [];
|
|
2242
|
+
const formText = (form) => {
|
|
2243
|
+
const text = extractStaticText(form);
|
|
2244
|
+
if (text !== null)
|
|
2245
|
+
return text;
|
|
2246
|
+
if (form?.type !== 'TemplateLiteral')
|
|
2247
|
+
return null;
|
|
2248
|
+
let result = '';
|
|
2249
|
+
for (let i = 0; i < form.quasis.length; i++) {
|
|
2250
|
+
result += form.quasis[i].cooked ?? form.quasis[i].raw ?? '';
|
|
2251
|
+
const expr = form.expressions?.[i];
|
|
2252
|
+
if (!expr)
|
|
2253
|
+
continue;
|
|
2254
|
+
if (content.slice(expr.span.start, expr.span.end) === countExpression) {
|
|
2255
|
+
result += '{{count}}';
|
|
2256
|
+
continue;
|
|
1211
2257
|
}
|
|
2258
|
+
const info = resolveExpressionName(expr, content, usedNames);
|
|
2259
|
+
if (!info)
|
|
2260
|
+
return null;
|
|
2261
|
+
result += `{{${info.name}}}`;
|
|
2262
|
+
if (!info.reused)
|
|
2263
|
+
interpolations.push(info);
|
|
1212
2264
|
}
|
|
1213
|
-
|
|
2265
|
+
return result;
|
|
2266
|
+
};
|
|
2267
|
+
const oneText = formText(one);
|
|
2268
|
+
const otherText = formText(other);
|
|
2269
|
+
if (oneText === null || otherText === null)
|
|
2270
|
+
return null;
|
|
2271
|
+
return {
|
|
2272
|
+
countExpression,
|
|
2273
|
+
one: oneText.replace(/#/g, '{{count}}'),
|
|
2274
|
+
other: otherText.replace(/#/g, '{{count}}'),
|
|
2275
|
+
...(interpolations.length ? { interpolations } : {})
|
|
2276
|
+
};
|
|
1214
2277
|
}
|
|
1215
2278
|
/**
|
|
1216
|
-
*
|
|
2279
|
+
* Parses the shape of a `ConditionalExpression` tree into a plural pattern (see `tryParsePluralTernary`).
|
|
1217
2280
|
*
|
|
1218
2281
|
* Supported shapes:
|
|
1219
2282
|
* count === 0 ? zeroText : count === 1 ? oneText : otherText (3-way)
|
|
@@ -1221,7 +2284,7 @@ function detectPluralPatterns(node, content, file, config, candidates) {
|
|
|
1221
2284
|
*
|
|
1222
2285
|
* Returns `null` when the node doesn't match any recognised plural shape.
|
|
1223
2286
|
*/
|
|
1224
|
-
function
|
|
2287
|
+
function parsePluralTernaryShape(node, content) {
|
|
1225
2288
|
if (node?.type !== 'ConditionalExpression')
|
|
1226
2289
|
return null;
|
|
1227
2290
|
const outerTest = parseCountTest(node.test, content);
|
|
@@ -1260,6 +2323,23 @@ function tryParsePluralTernary(node, content) {
|
|
|
1260
2323
|
}
|
|
1261
2324
|
return null;
|
|
1262
2325
|
}
|
|
2326
|
+
/**
|
|
2327
|
+
* A ternary on `count === 1` is a plural only when its branches are text: `score === 1 ? 'var(--ok)' :
|
|
2328
|
+
* 'var(--warn)'` and `score === 1 ? 'item-full' : 'item-low'` pick a style.
|
|
2329
|
+
*/
|
|
2330
|
+
function tryParsePluralTernary(node, content) {
|
|
2331
|
+
const plural = parsePluralTernaryShape(node, content);
|
|
2332
|
+
if (!plural)
|
|
2333
|
+
return null;
|
|
2334
|
+
// Fragments merged with the text around them (`''`, `'s'`, `${n}`) are fine; a technical form is not
|
|
2335
|
+
const forms = [plural.zero, plural.one, plural.other].filter((f) => f !== undefined);
|
|
2336
|
+
const technical = forms.some(f => f.trim().length > 1 && detectsAsTechnical(f));
|
|
2337
|
+
return !technical && forms.some(f => /\p{L}/u.test(f.replace(/\{\{[^}]*\}\}/g, ''))) ? plural : null;
|
|
2338
|
+
}
|
|
2339
|
+
/** A form that the string detector skips as technical (a CSS value, a class name); a single word is text here. */
|
|
2340
|
+
function detectsAsTechnical(text) {
|
|
2341
|
+
return detectCandidate(text, 0, text.length, 'plural.js', text, { extract: { input: [], output: '' } }, undefined, true) === null;
|
|
2342
|
+
}
|
|
1263
2343
|
// ─── Language-change detection ───────────────────────────────────────────────
|
|
1264
2344
|
/**
|
|
1265
2345
|
* Property names that indicate a "language" value in an object literal.
|
|
@@ -1274,6 +2354,24 @@ const LANGUAGE_PROP_NAMES = new Set(['language', 'lang', 'locale', 'lng']);
|
|
|
1274
2354
|
* Examples: `setLanguage(code)`, `setLocale(lng)`, `changeLanguage(x)`
|
|
1275
2355
|
*/
|
|
1276
2356
|
const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale|Lng)$/i;
|
|
2357
|
+
/**
|
|
2358
|
+
* A variable or a property (`code`, `lang.code`, `e.target.value`): the injected `changeLanguage()` repeats
|
|
2359
|
+
* the expression, which must then give the same value without doing anything (`getDefault(…)` would run twice).
|
|
2360
|
+
*/
|
|
2361
|
+
function isPlainValue(expr) {
|
|
2362
|
+
if (expr?.type === 'Identifier')
|
|
2363
|
+
return true;
|
|
2364
|
+
return expr?.type === 'MemberExpression' && expr.property?.type === 'Identifier' && isPlainValue(expr.object);
|
|
2365
|
+
}
|
|
2366
|
+
/** Nodes whose statements are a list, where one more statement can go before another. */
|
|
2367
|
+
const STATEMENT_LISTS = new Set(['FunctionBody', 'BlockStatement', 'Module', 'Script', 'SwitchCase']);
|
|
2368
|
+
/**
|
|
2369
|
+
* Callees whose object argument holds the user's settings, so a language property there is the app's
|
|
2370
|
+
* language (`updateSettings({ language })`, `saveProfile({ locale })`, `setState({ locale })`). Elsewhere a
|
|
2371
|
+
* `language`/`lng` property is data (`fetchTranslations({ lng })`, `list.push({ lng })`), and hooks
|
|
2372
|
+
* (`useState({ lng: [] })`) never are.
|
|
2373
|
+
*/
|
|
2374
|
+
const SETTINGS_CALLEE_RE = /settings|preferences|prefs|profile|user|account|state|locale|language/i;
|
|
1277
2375
|
/**
|
|
1278
2376
|
* Walks the AST looking for call expressions that appear to change the
|
|
1279
2377
|
* application language. Detected sites will later be augmented with an
|
|
@@ -1289,11 +2387,18 @@ const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale
|
|
|
1289
2387
|
* `setLanguage(code)`
|
|
1290
2388
|
* `setLocale(lng)`
|
|
1291
2389
|
* `changeLanguage(selectedLng)`
|
|
2390
|
+
*
|
|
2391
|
+
* Only a call that is a statement of its own in a block or an arrow function's expression body: the
|
|
2392
|
+
* injected call goes before it, which would change any other place (`const x = setLocale(l)`,
|
|
2393
|
+
* `return save({ locale })`, `if (ok) setLocale(l)`).
|
|
1292
2394
|
*/
|
|
1293
|
-
function detectLanguageChangeSites(node, content, sites) {
|
|
2395
|
+
function detectLanguageChangeSites(node, content, sites, parent, grandparent) {
|
|
1294
2396
|
if (!node)
|
|
1295
2397
|
return;
|
|
1296
|
-
|
|
2398
|
+
const standsAlone = (parent?.type === 'ExpressionStatement' && parent.expression === node &&
|
|
2399
|
+
STATEMENT_LISTS.has(grandparent?.type)) ||
|
|
2400
|
+
(parent?.type === 'ArrowFunctionExpression' && parent.body === node);
|
|
2401
|
+
if (node.type === 'CallExpression' && node.span && standsAlone) {
|
|
1297
2402
|
const detected = tryParseLanguageChangeCall(node, content);
|
|
1298
2403
|
if (detected) {
|
|
1299
2404
|
// Check if changeLanguage() already exists nearby (e.g. same arrow body)
|
|
@@ -1324,14 +2429,89 @@ function detectLanguageChangeSites(node, content, sites) {
|
|
|
1324
2429
|
const value = node[key];
|
|
1325
2430
|
if (value && typeof value === 'object') {
|
|
1326
2431
|
if (Array.isArray(value)) {
|
|
1327
|
-
value.forEach(item => detectLanguageChangeSites(item, content, sites));
|
|
2432
|
+
value.forEach(item => detectLanguageChangeSites(item, content, sites, node, parent));
|
|
1328
2433
|
}
|
|
1329
2434
|
else {
|
|
1330
|
-
detectLanguageChangeSites(value, content, sites);
|
|
2435
|
+
detectLanguageChangeSites(value, content, sites, node, parent);
|
|
1331
2436
|
}
|
|
1332
2437
|
}
|
|
1333
2438
|
}
|
|
1334
2439
|
}
|
|
2440
|
+
/**
|
|
2441
|
+
* The imports of the plural helpers `names` (`import { plural, number } from './format'`), each with the
|
|
2442
|
+
* number of other identifiers naming it in the file and the text that removes its import.
|
|
2443
|
+
*/
|
|
2444
|
+
function findPluralHelperImports(ast, content, names) {
|
|
2445
|
+
const found = [];
|
|
2446
|
+
for (const decl of ast.body ?? []) {
|
|
2447
|
+
if (decl.type !== 'ImportDeclaration')
|
|
2448
|
+
continue;
|
|
2449
|
+
const specifiers = decl.specifiers ?? [];
|
|
2450
|
+
// `import fmt, { plural } from …` mixes a default with the braces: removing one of them takes more than a
|
|
2451
|
+
// specifier and a comma, so such an import stays
|
|
2452
|
+
const named = specifiers.every((spec) => spec.type === 'ImportSpecifier');
|
|
2453
|
+
specifiers.forEach((spec, i) => {
|
|
2454
|
+
const name = spec.local?.value;
|
|
2455
|
+
if (!names.has(name) || (!named && specifiers.length > 1))
|
|
2456
|
+
return;
|
|
2457
|
+
let [removeStart, removeEnd] = specifiers.length === 1
|
|
2458
|
+
? [decl.span.start, decl.span.end]
|
|
2459
|
+
: i < specifiers.length - 1
|
|
2460
|
+
? [spec.span.start, specifiers[i + 1].span.start]
|
|
2461
|
+
: [specifiers[i - 1].span.end, spec.span.end];
|
|
2462
|
+
if (specifiers.length === 1)
|
|
2463
|
+
removeEnd += /^\r?\n/.exec(content.slice(removeEnd))?.[0].length ?? 0;
|
|
2464
|
+
found.push({ name, references: 0, removeStart, removeEnd });
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
const count = (node) => {
|
|
2468
|
+
if (!node || typeof node !== 'object')
|
|
2469
|
+
return;
|
|
2470
|
+
if (node.type === 'ImportDeclaration')
|
|
2471
|
+
return;
|
|
2472
|
+
if (node.type === 'Identifier') {
|
|
2473
|
+
const helper = found.find(h => h.name === node.value);
|
|
2474
|
+
if (helper)
|
|
2475
|
+
helper.references++;
|
|
2476
|
+
}
|
|
2477
|
+
for (const key in node) {
|
|
2478
|
+
const value = node[key];
|
|
2479
|
+
if (Array.isArray(value))
|
|
2480
|
+
value.forEach(count);
|
|
2481
|
+
else if (value && typeof value === 'object')
|
|
2482
|
+
count(value);
|
|
2483
|
+
}
|
|
2484
|
+
};
|
|
2485
|
+
count(ast);
|
|
2486
|
+
return found;
|
|
2487
|
+
}
|
|
2488
|
+
/** The `useMemo`/`useCallback` calls with a callback and a dependency array (see `MemoHookSpan`). */
|
|
2489
|
+
function collectMemoHooks(node, hooks) {
|
|
2490
|
+
if (!node || typeof node !== 'object')
|
|
2491
|
+
return;
|
|
2492
|
+
if (node.type === 'CallExpression' && ['useMemo', 'useCallback'].includes(getCalleeName(node.callee) ?? '')) {
|
|
2493
|
+
const [callback, deps] = (node.arguments ?? []).map((a) => a?.expression);
|
|
2494
|
+
if (callback?.span && deps?.type === 'ArrayExpression' && deps.span) {
|
|
2495
|
+
const elements = (deps.elements ?? []).filter(Boolean).map((e) => e.expression);
|
|
2496
|
+
hooks.push({
|
|
2497
|
+
callbackStart: callback.span.start,
|
|
2498
|
+
callbackEnd: callback.span.end,
|
|
2499
|
+
insertAt: elements.length ? elements[elements.length - 1].span.end : deps.span.start + 1,
|
|
2500
|
+
hasDeps: elements.length > 0,
|
|
2501
|
+
hasT: elements.some((e) => e.type === 'Identifier' && e.value === 't')
|
|
2502
|
+
});
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
for (const key in node) {
|
|
2506
|
+
const value = node[key];
|
|
2507
|
+
if (value && typeof value === 'object') {
|
|
2508
|
+
if (Array.isArray(value))
|
|
2509
|
+
value.forEach(item => collectMemoHooks(item, hooks));
|
|
2510
|
+
else
|
|
2511
|
+
collectMemoHooks(value, hooks);
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
1335
2515
|
/**
|
|
1336
2516
|
* Inspects a single CallExpression node to determine if it is a language-change
|
|
1337
2517
|
* call. Returns the detected site data (without line/column) or `null`.
|
|
@@ -1348,10 +2528,10 @@ function tryParseLanguageChangeCall(node, content) {
|
|
|
1348
2528
|
if (objName === 'i18n' || objName === 'i18next')
|
|
1349
2529
|
return null;
|
|
1350
2530
|
}
|
|
1351
|
-
// ── Pattern 1: direct setter
|
|
2531
|
+
// ── Pattern 1: direct setter, setLanguage(expr), changeLocale(expr) etc. ──
|
|
1352
2532
|
if (calleeName && LANGUAGE_SETTER_RE.test(calleeName)) {
|
|
1353
2533
|
const firstArg = node.arguments[0]?.expression;
|
|
1354
|
-
if (firstArg?.span) {
|
|
2534
|
+
if (firstArg?.span && isPlainValue(firstArg)) {
|
|
1355
2535
|
const langExpr = content.slice(firstArg.span.start, firstArg.span.end);
|
|
1356
2536
|
// Skip if the argument is already an i18next.changeLanguage call
|
|
1357
2537
|
if (langExpr.includes('changeLanguage'))
|
|
@@ -1363,7 +2543,9 @@ function tryParseLanguageChangeCall(node, content) {
|
|
|
1363
2543
|
};
|
|
1364
2544
|
}
|
|
1365
2545
|
}
|
|
1366
|
-
// ── Pattern 2: object with language property
|
|
2546
|
+
// ── Pattern 2: object with language property, updateSettings({ language: expr }) ──
|
|
2547
|
+
if (!calleeName || /^use[A-Z]/.test(calleeName) || !SETTINGS_CALLEE_RE.test(calleeName))
|
|
2548
|
+
return null;
|
|
1367
2549
|
for (const arg of node.arguments) {
|
|
1368
2550
|
const expr = arg.expression ?? arg;
|
|
1369
2551
|
if (expr?.type !== 'ObjectExpression')
|
|
@@ -1383,8 +2565,8 @@ function tryParseLanguageChangeCall(node, content) {
|
|
|
1383
2565
|
const valNode = prop.value;
|
|
1384
2566
|
if (valNode?.span) {
|
|
1385
2567
|
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')
|
|
2568
|
+
// Skip if value is a static string (e.g. `{ language: 'en' }` in a config), or not a plain value
|
|
2569
|
+
if (valNode.type === 'StringLiteral' || !isPlainValue(valNode))
|
|
1388
2570
|
continue;
|
|
1389
2571
|
// Skip if already contains changeLanguage
|
|
1390
2572
|
if (langExpr.includes('changeLanguage'))
|
|
@@ -1418,7 +2600,11 @@ function getCalleeName(callee) {
|
|
|
1418
2600
|
* Gets the list of source files to instrument.
|
|
1419
2601
|
*/
|
|
1420
2602
|
async function getSourceFilesForInstrumentation(config) {
|
|
1421
|
-
|
|
2603
|
+
// Stories, mocks and fixtures hold sample data, not the app's texts
|
|
2604
|
+
const defaultIgnore = [
|
|
2605
|
+
'node_modules/**', 'dist/**', 'build/**', '.next/**',
|
|
2606
|
+
'**/*.{stories,story,storybook}.*', '**/__mocks__/**', '**/__fixtures__/**', '**/__tests__/**'
|
|
2607
|
+
];
|
|
1422
2608
|
const userIgnore = Array.isArray(config.extract.ignore)
|
|
1423
2609
|
? config.extract.ignore
|
|
1424
2610
|
: config.extract.ignore ? [config.extract.ignore] : [];
|
|
@@ -1433,16 +2619,8 @@ async function getSourceFilesForInstrumentation(config) {
|
|
|
1433
2619
|
* Checks if the project uses React.
|
|
1434
2620
|
*/
|
|
1435
2621
|
async function isProjectUsingReact() {
|
|
1436
|
-
|
|
1437
|
-
|
|
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
|
-
}
|
|
2622
|
+
const deps = await readProjectDeps();
|
|
2623
|
+
return !!deps.react || !!deps['react-i18next'];
|
|
1446
2624
|
}
|
|
1447
2625
|
/** Well-known frontend framework packages (presence → browser environment). */
|
|
1448
2626
|
const FRONTEND_FRAMEWORKS = [
|
|
@@ -1479,13 +2657,7 @@ const SERVER_FRAMEWORKS = [
|
|
|
1479
2657
|
*/
|
|
1480
2658
|
async function detectProjectEnvironment() {
|
|
1481
2659
|
try {
|
|
1482
|
-
const
|
|
1483
|
-
const raw = await readFile(packageJsonPath, 'utf-8');
|
|
1484
|
-
const packageJson = JSON.parse(raw);
|
|
1485
|
-
const allDeps = {
|
|
1486
|
-
...packageJson.dependencies,
|
|
1487
|
-
...packageJson.devDependencies
|
|
1488
|
-
};
|
|
2660
|
+
const allDeps = await readProjectDeps();
|
|
1489
2661
|
const has = (list) => list.some(dep => !!allDeps[dep]);
|
|
1490
2662
|
// 1. Edge / serverless (check first — these projects may also list a
|
|
1491
2663
|
// bundler or even a framework, but they have no filesystem)
|
|
@@ -1584,28 +2756,10 @@ function buildDynamicImportPath(outputTemplate, initDir) {
|
|
|
1584
2756
|
*/
|
|
1585
2757
|
async function ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT) {
|
|
1586
2758
|
const cwd = process.cwd();
|
|
1587
|
-
// Check for existing init files in common locations
|
|
2759
|
+
// Check for existing init files in common locations (an init elsewhere imports i18next, see runInstrumenter)
|
|
1588
2760
|
if (await findExistingI18nInitFile()) {
|
|
1589
2761
|
return null; // Init file already exists
|
|
1590
2762
|
}
|
|
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
2763
|
// Determine output location — prefer src/ if it exists
|
|
1610
2764
|
const srcExists = await fileExists(join(cwd, 'src'));
|
|
1611
2765
|
const initDir = srcExists ? join(cwd, 'src') : cwd;
|