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
|
@@ -7,6 +7,18 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
7
7
|
|
|
8
8
|
var MagicString__default = /*#__PURE__*/_interopDefault(MagicString);
|
|
9
9
|
|
|
10
|
+
/** The hook a component gets `t` from, and where `useTranslation`/`useT`/`getT` and `Trans` are imported from. */
|
|
11
|
+
function bindingsFor(next) {
|
|
12
|
+
switch (next?.kind) {
|
|
13
|
+
case 'server': return { hook: 'getT', hookModule: next.serverModule, transModule: 'react-i18next/TransWithoutContext', call: args => `await getT(${args})` };
|
|
14
|
+
// its `t` is a prop: no hook; a <Trans> without context works on both sides
|
|
15
|
+
case 'shared':
|
|
16
|
+
case 'unknown': return { hook: 'useT', hookModule: 'next-i18next/client', transModule: 'react-i18next/TransWithoutContext', call: args => `useT(${args})` };
|
|
17
|
+
case 'client': return { hook: 'useT', hookModule: 'next-i18next/client', transModule: 'next-i18next/client', call: args => `useT(${args})` };
|
|
18
|
+
case 'pages': return { hook: 'useTranslation', hookModule: 'next-i18next/pages', transModule: 'next-i18next/pages', call: args => `useTranslation(${args})` };
|
|
19
|
+
default: return { hook: 'useTranslation', hookModule: 'react-i18next', transModule: 'react-i18next', call: args => `useTranslation(${args})` };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
10
22
|
/**
|
|
11
23
|
* Transforms a source file, replacing candidate strings with instrumented code.
|
|
12
24
|
* Also injects useTranslation() hooks into React function components that
|
|
@@ -27,11 +39,18 @@ function transformFile(content, file, candidates, options) {
|
|
|
27
39
|
importAdded: false,
|
|
28
40
|
hookInjected: false
|
|
29
41
|
};
|
|
42
|
+
const bindings = bindingsFor(options.next);
|
|
43
|
+
// A <Trans> in a Server Component has no React context: it takes `t` and `i18n` from getT()
|
|
44
|
+
// (and in a component that Server and Client Components both render, from its props)
|
|
45
|
+
const transProps = ['server', 'shared', 'unknown'].includes(options.next?.kind ?? '') ? ' t={t} i18n={i18n}' : '';
|
|
46
|
+
// <Trans> attributes in the quotes the file's JSX attributes use (`title='…'` or `title="…"`)
|
|
47
|
+
// (a file without quoted attributes: the quotes of its imports)
|
|
48
|
+
const singleQuoted = (single, double) => Math.sign((content.match(single)?.length ?? 0) - (content.match(double)?.length ?? 0));
|
|
49
|
+
const jsxQuote = (singleQuoted(/\s[\w-]+='/g, /\s[\w-]+="/g) || singleQuoted(/\sfrom '/g, /\sfrom "/g)) > 0 ? "'" : '"';
|
|
30
50
|
// Filter high-confidence candidates
|
|
31
51
|
const highConfidenceCandidates = candidates.filter(c => c.confidence >= 0.7);
|
|
32
52
|
// Track which components have transformed candidates
|
|
33
53
|
const transformedComponents = new Set();
|
|
34
|
-
let hasComponentCandidates = false;
|
|
35
54
|
let hasNonComponentCandidates = false;
|
|
36
55
|
let hasTransCandidates = false;
|
|
37
56
|
// ── Language-change site injections ────────────────────────────────────
|
|
@@ -65,7 +84,6 @@ function transformFile(content, file, candidates, options) {
|
|
|
65
84
|
if (site.insideComponent) {
|
|
66
85
|
componentsNeedingI18n.add(site.insideComponent);
|
|
67
86
|
transformedComponents.add(site.insideComponent);
|
|
68
|
-
hasComponentCandidates = true;
|
|
69
87
|
}
|
|
70
88
|
else {
|
|
71
89
|
hasNonComponentCandidates = true;
|
|
@@ -75,6 +93,7 @@ function transformFile(content, file, candidates, options) {
|
|
|
75
93
|
errors.push(`Failed to inject changeLanguage at offset ${site.callStart}: ${err}`);
|
|
76
94
|
}
|
|
77
95
|
}
|
|
96
|
+
const rewrittenHelperCalls = new Map();
|
|
78
97
|
// Apply transformations in reverse order (to maintain correct offsets)
|
|
79
98
|
for (let i = highConfidenceCandidates.length - 1; i >= 0; i--) {
|
|
80
99
|
const candidate = highConfidenceCandidates[i];
|
|
@@ -83,22 +102,27 @@ function transformFile(content, file, candidates, options) {
|
|
|
83
102
|
const useHookStyle = !!candidate.insideComponent;
|
|
84
103
|
const defaultNS = options.config.extract?.defaultNS ?? 'translation';
|
|
85
104
|
const nsForReplacement = (options.namespace && options.namespace !== defaultNS) ? options.namespace : undefined;
|
|
86
|
-
|
|
105
|
+
// <Trans> works in any render code, a helper outside a component too; without React the text stays
|
|
106
|
+
if (candidate.type === 'jsx-mixed' && !options.hasReact)
|
|
107
|
+
continue;
|
|
108
|
+
const replacement = buildReplacement(candidate, key, useHookStyle, nsForReplacement, jsxQuote, transProps);
|
|
87
109
|
if (replacement) {
|
|
88
110
|
s.overwrite(candidate.offset, candidate.endOffset, replacement);
|
|
89
111
|
transformCount++;
|
|
112
|
+
if (candidate.pluralHelper)
|
|
113
|
+
rewrittenHelperCalls.set(candidate.pluralHelper, (rewrittenHelperCalls.get(candidate.pluralHelper) ?? 0) + 1);
|
|
90
114
|
if (candidate.type === 'jsx-mixed') {
|
|
91
115
|
hasTransCandidates = true;
|
|
92
116
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
117
|
+
// jsx-mixed candidates use <Trans>, not t(), so they need neither useTranslation nor i18next (but in a
|
|
118
|
+
// Server Component its `t` and `i18n`)
|
|
119
|
+
if (candidate.type !== 'jsx-mixed' || (transProps && candidate.insideComponent)) {
|
|
120
|
+
if (candidate.insideComponent) {
|
|
96
121
|
transformedComponents.add(candidate.insideComponent);
|
|
97
|
-
hasComponentCandidates = true;
|
|
98
122
|
}
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
123
|
+
else {
|
|
124
|
+
hasNonComponentCandidates = true;
|
|
125
|
+
}
|
|
102
126
|
}
|
|
103
127
|
}
|
|
104
128
|
}
|
|
@@ -106,65 +130,86 @@ function transformFile(content, file, candidates, options) {
|
|
|
106
130
|
errors.push(`Failed to transform candidate at offset ${candidate.offset}: ${err}`);
|
|
107
131
|
}
|
|
108
132
|
}
|
|
133
|
+
// A plural helper whose every call became a plural t() is no longer used: its import goes
|
|
134
|
+
for (const helper of options.pluralHelperImports ?? []) {
|
|
135
|
+
const rewritten = rewrittenHelperCalls.get(helper.name) ?? 0;
|
|
136
|
+
if (rewritten > 0 && rewritten === helper.references)
|
|
137
|
+
s.remove(helper.removeStart, helper.removeEnd);
|
|
138
|
+
}
|
|
139
|
+
// A memoized callback that now calls t() must run again when the language changes: `t` joins its dependencies
|
|
140
|
+
for (const hook of options.memoHooks ?? []) {
|
|
141
|
+
const usesT = highConfidenceCandidates.some(c => c.insideComponent && c.type !== 'jsx-mixed' &&
|
|
142
|
+
c.offset >= hook.callbackStart && c.endOffset <= hook.callbackEnd);
|
|
143
|
+
if (usesT && !hook.hasT)
|
|
144
|
+
s.appendLeft(hook.insertAt, hook.hasDeps ? ', t' : 't');
|
|
145
|
+
}
|
|
109
146
|
// Add necessary imports and hooks if any transformations were made
|
|
110
147
|
if (transformCount > 0 || languageChangeCount > 0) {
|
|
111
148
|
const components = options.components || [];
|
|
112
149
|
// Inject useTranslation() hooks into affected React components
|
|
113
150
|
if (options.hasReact && transformedComponents.size > 0) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
151
|
+
const addHookLine = (comp, line) => {
|
|
152
|
+
const indent = comp.expressionBody ? lineIndent(content, comp.bodyStart) + ' ' : detectIndent(content, comp.bodyStart);
|
|
153
|
+
if (comp.expressionBody) {
|
|
154
|
+
// `() => <p>…</p>` becomes `() => { const { t } = useTranslation(); return <p>…</p> }`
|
|
155
|
+
s.prependLeft(comp.bodyStart, `{\n${indent}${line}\n${indent}return `);
|
|
156
|
+
s.appendRight(comp.bodyEnd, `\n${indent.slice(2)}}`);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
s.appendRight(comp.bodyStart + 1, `\n${indent}${line}`);
|
|
160
|
+
}
|
|
161
|
+
// getT() is awaited: a Server Component becomes async, and `export const metadata = {…}` the function
|
|
162
|
+
// Next.js calls instead, `export async function generateMetadata () { …; return {…} }`
|
|
163
|
+
if (comp.metadataHead) {
|
|
164
|
+
const { start, end, type } = comp.metadataHead;
|
|
165
|
+
// contentOnly: the block that wraps the object starts at `end`, and stays
|
|
166
|
+
s.overwrite(start, end, `async function generateMetadata ()${type ? `: Promise<${type}>` : ''} `, { contentOnly: true });
|
|
167
|
+
}
|
|
168
|
+
else if (options.next?.kind === 'server' && !comp.isAsync && comp.start !== undefined) {
|
|
169
|
+
s.appendLeft(comp.start, 'async ');
|
|
170
|
+
// an async function returns a promise: `(): JSX.Element` becomes `(): Promise<JSX.Element>`
|
|
171
|
+
const type = comp.returnType;
|
|
172
|
+
if (type && !/^Promise\s*</.test(content.slice(type.start, type.end))) {
|
|
173
|
+
s.appendLeft(type.start, 'Promise<');
|
|
174
|
+
s.appendRight(type.end, '>');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
injections.hookInjected = true;
|
|
178
|
+
};
|
|
179
|
+
// Components in reverse order of bodyStart to avoid offset shifts
|
|
180
|
+
for (const comp of components.filter(c => transformedComponents.has(c.name)).sort((a, b) => b.bodyStart - a.bodyStart)) {
|
|
120
181
|
const defaultNS = options.config.extract?.defaultNS ?? 'translation';
|
|
121
182
|
const nsArg = (options.namespace && options.namespace !== defaultNS) ? `'${options.namespace}'` : '';
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
if (needsT)
|
|
129
|
-
parts.push('t');
|
|
130
|
-
if (needsI18n)
|
|
131
|
-
parts.push('i18n');
|
|
132
|
-
// Skip if component needs neither t nor i18n
|
|
133
|
-
// (e.g. component only has jsx-mixed / <Trans> candidates)
|
|
134
|
-
if (!needsT && !needsI18n)
|
|
183
|
+
// `t` for its t() calls (and a <Trans> in a Server Component), `i18n` for a language change (and that <Trans>)
|
|
184
|
+
const own = highConfidenceCandidates.filter(c => c.insideComponent === comp.name);
|
|
185
|
+
const needsT = !comp.hasUseTranslation && own.some(c => c.type !== 'jsx-mixed' || transProps);
|
|
186
|
+
const needsI18n = componentsNeedingI18n.has(comp.name) || (!!transProps && !comp.i18nParam && own.some(c => c.type === 'jsx-mixed'));
|
|
187
|
+
const missing = [needsT && 't', needsI18n && !comp.hookPattern?.names.includes('i18n') && 'i18n'].filter(Boolean);
|
|
188
|
+
if (!missing.length)
|
|
135
189
|
continue;
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
// Match `{ t }` or `{ t, ... }` in `const { t } = useTranslation`
|
|
151
|
-
const hookRe = /const\s*\{\s*t\s*\}\s*=\s*useTranslation/;
|
|
152
|
-
const hookMatch = hookRe.exec(bodyText);
|
|
153
|
-
if (hookMatch) {
|
|
154
|
-
const absStart = comp.bodyStart + hookMatch.index;
|
|
155
|
-
const absEnd = absStart + hookMatch[0].length;
|
|
156
|
-
const upgraded = hookMatch[0].replace(/\{\s*t\s*\}/, '{ t, i18n }');
|
|
157
|
-
s.overwrite(absStart, absEnd, upgraded);
|
|
158
|
-
}
|
|
190
|
+
// that call gives `t` only to the code after it: a text before it would read `t` before its declaration
|
|
191
|
+
const before = (offset) => offset < comp.hookPattern.statement;
|
|
192
|
+
const usedBefore = comp.hookPattern && (own.some(c => before(c.offset)) ||
|
|
193
|
+
languageChangeSites.some(site => site.insideComponent === comp.name && before(site.callStart)));
|
|
194
|
+
if (comp.hookPattern && !usedBefore && (comp.hasUseTranslation || !comp.hookPattern.names.includes('t'))) {
|
|
195
|
+
// it calls a translation hook already (`const { i18n } = useT('ns')`): that call gives them, from its
|
|
196
|
+
// namespace (`{ t, i18n }`)
|
|
197
|
+
if (missing.includes('t'))
|
|
198
|
+
s.appendLeft(comp.hookPattern.first, 't, ');
|
|
199
|
+
if (missing.includes('i18n'))
|
|
200
|
+
s.appendRight(comp.hookPattern.last, ', i18n');
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
addHookLine(comp, `const { ${missing.join(', ')} } = ${bindings.call(missing.includes('t') ? nsArg : '')}`);
|
|
159
204
|
}
|
|
160
205
|
}
|
|
161
206
|
}
|
|
162
207
|
// Add import statements
|
|
163
|
-
addImportStatements(s, content,
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
208
|
+
addImportStatements(s, content, [
|
|
209
|
+
// only for a hook injected here: a component with a `t` of its own (a prop) needs none
|
|
210
|
+
...(injections.hookInjected ? [{ name: bindings.hook, module: bindings.hookModule }] : []),
|
|
211
|
+
...(hasTransCandidates && options.hasReact ? [{ name: 'Trans', module: bindings.transModule }] : [])
|
|
212
|
+
], hasNonComponentCandidates || !options.hasReact, options.imports);
|
|
168
213
|
injections.importAdded = true;
|
|
169
214
|
}
|
|
170
215
|
// Warn when i18next.t() is used in React projects (translations may not be loaded yet)
|
|
@@ -196,7 +241,7 @@ function transformFile(content, file, candidates, options) {
|
|
|
196
241
|
* @param useHookStyle - If true, uses t() (from useTranslation hook); otherwise uses i18next.t()
|
|
197
242
|
* @param namespace - Optional namespace (only set when different from defaultNS)
|
|
198
243
|
*/
|
|
199
|
-
function buildReplacement(candidate, key, useHookStyle, namespace) {
|
|
244
|
+
function buildReplacement(candidate, key, useHookStyle, namespace, jsxQuote = '"', transProps = '') {
|
|
200
245
|
const tFunc = useHookStyle ? 't' : 'i18next.t';
|
|
201
246
|
const escapedContent = escapeString(candidate.content);
|
|
202
247
|
// ── Plural form: t('key', { defaultValue_zero: '…', …, count: expr }) ──
|
|
@@ -245,12 +290,10 @@ function buildReplacement(candidate, key, useHookStyle, namespace) {
|
|
|
245
290
|
case 'jsx-text':
|
|
246
291
|
case 'jsx-attribute':
|
|
247
292
|
return `{${tCall}}`;
|
|
248
|
-
case 'jsx-mixed':
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
}
|
|
253
|
-
return candidate.content;
|
|
293
|
+
case 'jsx-mixed': {
|
|
294
|
+
const nsAttr = namespace ? ` ns=${jsxQuote}${namespace}${jsxQuote}` : '';
|
|
295
|
+
return `<Trans i18nKey=${jsxQuote}${key}${jsxQuote}${nsAttr}${transProps}>${candidate.content}</Trans>`;
|
|
296
|
+
}
|
|
254
297
|
case 'template-literal':
|
|
255
298
|
case 'string-literal':
|
|
256
299
|
default:
|
|
@@ -280,6 +323,11 @@ function hasImport(content, moduleName) {
|
|
|
280
323
|
* Detects the indentation level used after an opening brace.
|
|
281
324
|
* Skips blank lines and reads the whitespace of the first line that has actual content.
|
|
282
325
|
*/
|
|
326
|
+
/** The indentation of the line `offset` is on. */
|
|
327
|
+
function lineIndent(content, offset) {
|
|
328
|
+
const lineStart = content.lastIndexOf('\n', offset - 1) + 1;
|
|
329
|
+
return /^[ \t]*/.exec(content.slice(lineStart))[0];
|
|
330
|
+
}
|
|
283
331
|
function detectIndent(content, braceOffset) {
|
|
284
332
|
let searchFrom = braceOffset;
|
|
285
333
|
while (searchFrom < content.length) {
|
|
@@ -302,26 +350,33 @@ function detectIndent(content, braceOffset) {
|
|
|
302
350
|
return ' ';
|
|
303
351
|
}
|
|
304
352
|
/**
|
|
305
|
-
* Adds
|
|
353
|
+
* Adds the import statements the rewrite needs: the named imports `needed` (a hook, `Trans`), each from its module
|
|
354
|
+
* (added to an import of that module the file has), and `i18next` for `i18next.t()`.
|
|
306
355
|
*/
|
|
307
|
-
function addImportStatements(s, content,
|
|
356
|
+
function addImportStatements(s, content, needed, needsI18next, imports) {
|
|
308
357
|
let importStatement = '';
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
if (!
|
|
317
|
-
|
|
358
|
+
const imported = (moduleName) => imports
|
|
359
|
+
? imports.some(i => i.source === moduleName) || new RegExp(`require\\(['"]${moduleName}['"]\\)`).test(content)
|
|
360
|
+
: hasImport(content, moduleName);
|
|
361
|
+
// A name the file imports already, from any module (`useTranslation` re-exported by a shared package)
|
|
362
|
+
const bound = (name) => !!imports?.some(i => i.locals?.includes(name));
|
|
363
|
+
const byModule = new Map();
|
|
364
|
+
for (const { name, module } of needed) {
|
|
365
|
+
if (!bound(name))
|
|
366
|
+
byModule.set(module, [...(byModule.get(module) ?? []), name]);
|
|
367
|
+
}
|
|
368
|
+
for (const [module, names] of byModule) {
|
|
369
|
+
if (!imported(module)) {
|
|
370
|
+
importStatement += `import { ${names.join(', ')} } from '${module}'\n`;
|
|
318
371
|
}
|
|
319
372
|
else {
|
|
320
|
-
//
|
|
321
|
-
|
|
373
|
+
// the module is imported already: augment it with the missing named exports
|
|
374
|
+
const existing = imports?.find(i => i.source === module);
|
|
375
|
+
augmentNamedImport(s, content, module, names, existing?.start ?? 0);
|
|
322
376
|
}
|
|
323
377
|
}
|
|
324
|
-
|
|
378
|
+
// `i18next.t()` needs that name: with the AST, an import of i18next under another name does not count
|
|
379
|
+
if (needsI18next && (imports ? !bound('i18next') : !imported('i18next'))) {
|
|
325
380
|
importStatement += "import i18next from 'i18next'\n";
|
|
326
381
|
}
|
|
327
382
|
if (!importStatement)
|
|
@@ -332,6 +387,25 @@ function addImportStatements(s, content, needs) {
|
|
|
332
387
|
if (content.startsWith('#!')) {
|
|
333
388
|
insertPos = content.indexOf('\n') + 1;
|
|
334
389
|
}
|
|
390
|
+
// and the directives (`'use client'`), which must stay the first statements
|
|
391
|
+
const directives = DIRECTIVES_RE.exec(content.slice(insertPos));
|
|
392
|
+
if (directives) {
|
|
393
|
+
insertPos += directives[0].length;
|
|
394
|
+
if (content[insertPos - 1] !== '\n')
|
|
395
|
+
importStatement = `\n${importStatement}`;
|
|
396
|
+
}
|
|
397
|
+
if (imports) {
|
|
398
|
+
// After the last import declaration's line
|
|
399
|
+
const lastEnd = Math.max(...imports.map(i => i.end), -1);
|
|
400
|
+
if (lastEnd >= 0) {
|
|
401
|
+
const newline = content.indexOf('\n', lastEnd);
|
|
402
|
+
insertPos = newline === -1 ? content.length : newline + 1;
|
|
403
|
+
}
|
|
404
|
+
if (insertPos > 0 && content[insertPos - 1] !== '\n')
|
|
405
|
+
importStatement = `\n${importStatement}`;
|
|
406
|
+
s.appendRight(insertPos, importStatement);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
335
409
|
// Find the end of the last import statement. Imports may span multiple lines
|
|
336
410
|
// (e.g. `import {\n CCol,\n} from '...'`), so we can't treat each `import`
|
|
337
411
|
// line as a complete statement — we scan to the real end of each declaration.
|
|
@@ -349,6 +423,8 @@ function addImportStatements(s, content, needs) {
|
|
|
349
423
|
importStatement = `\n${importStatement}`;
|
|
350
424
|
s.appendRight(insertPos, importStatement);
|
|
351
425
|
}
|
|
426
|
+
/** The directive prologue: `'use client'`, `'use strict'` and the like, with the comments around them, to the line end. */
|
|
427
|
+
const DIRECTIVES_RE = /^(?:(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(['"])use [\w ]+\1;?[^\S\n]*(?:\/\/[^\n]*)?(?:\n|$))+/;
|
|
352
428
|
/**
|
|
353
429
|
* Returns the offset just past the end of the import statement that begins at
|
|
354
430
|
* `start`, handling multi-line imports with `{ ... }` clauses. The statement
|
|
@@ -397,19 +473,25 @@ function findImportStatementEnd(content, start) {
|
|
|
397
473
|
return content.length;
|
|
398
474
|
}
|
|
399
475
|
/**
|
|
400
|
-
* Augments an existing `import { ... } from '
|
|
476
|
+
* Augments an existing `import { ... } from '<module>'` with any missing
|
|
401
477
|
* named exports (e.g. adds `Trans` when only `useTranslation` is imported).
|
|
478
|
+
* A module imported without braces (`import i18n from …`) gets its own import.
|
|
402
479
|
*/
|
|
403
|
-
function
|
|
404
|
-
const
|
|
405
|
-
|
|
480
|
+
function augmentNamedImport(s, content, module, needed, from = 0) {
|
|
481
|
+
const quoted = module.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
482
|
+
const importRegex = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*['"]${quoted}['"]`, 'g');
|
|
483
|
+
importRegex.lastIndex = from;
|
|
484
|
+
const importMatch = importRegex.exec(content);
|
|
485
|
+
if (!importMatch) {
|
|
486
|
+
s.prependLeft(from, `import { ${needed.join(', ')} } from '${module}'\n`);
|
|
406
487
|
return;
|
|
488
|
+
}
|
|
407
489
|
const existingImports = importMatch[1].split(',').map(x => x.trim()).filter(Boolean);
|
|
408
490
|
const toAdd = needed.filter(n => !existingImports.includes(n));
|
|
409
491
|
if (toAdd.length === 0)
|
|
410
492
|
return;
|
|
411
493
|
const newImports = [...existingImports, ...toAdd].join(', ');
|
|
412
|
-
const newImportStatement = `import { ${newImports} } from '
|
|
494
|
+
const newImportStatement = `import { ${newImports} } from '${module}'`;
|
|
413
495
|
const matchStart = importMatch.index;
|
|
414
496
|
const matchEnd = matchStart + importMatch[0].length;
|
|
415
497
|
s.overwrite(matchStart, matchEnd, newImportStatement);
|
|
@@ -52,8 +52,11 @@ all commands.
|
|
|
52
52
|
for future agent sessions.
|
|
53
53
|
3. Instrument: run \`npx i18next-cli instrument --dry-run\` and review the
|
|
54
54
|
planned changes; then \`npx i18next-cli instrument\` to apply. Inspect the
|
|
55
|
-
git diff carefully
|
|
56
|
-
|
|
55
|
+
git diff carefully and the warnings it prints. In a Next.js app it writes
|
|
56
|
+
next-i18next's calls (await getT() in Server Components, useT() in Client
|
|
57
|
+
Components); texts it left (components that Server and Client Components
|
|
58
|
+
both render, texts outside components) are listed: move them or give the
|
|
59
|
+
component a t prop. If it printed next-i18next setup steps, do them. Commit.
|
|
57
60
|
4. Extract: run \`npx i18next-cli extract\`. Verify the locale JSON files were
|
|
58
61
|
written (check the extract.output path in the config). If the developer
|
|
59
62
|
chose repository files only: translate the extracted keys yourself or
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var promises = require('node:fs/promises');
|
|
4
4
|
var node_path = require('node:path');
|
|
5
|
+
var fileUtils = require('../utils/file-utils.js');
|
|
5
6
|
|
|
6
7
|
async function pathExists(path) {
|
|
7
8
|
try {
|
|
@@ -12,16 +13,6 @@ async function pathExists(path) {
|
|
|
12
13
|
return false;
|
|
13
14
|
}
|
|
14
15
|
}
|
|
15
|
-
async function readPackageDeps() {
|
|
16
|
-
try {
|
|
17
|
-
const content = await promises.readFile(node_path.join(process.cwd(), 'package.json'), 'utf-8');
|
|
18
|
-
const packageJson = JSON.parse(content);
|
|
19
|
-
return { ...packageJson.dependencies, ...packageJson.devDependencies };
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
return {};
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
16
|
/**
|
|
26
17
|
* Detects the project stack relevant to the `localize` orchestrator:
|
|
27
18
|
* frontend framework, i18next presence, an existing i18n init file,
|
|
@@ -34,7 +25,7 @@ async function readPackageDeps() {
|
|
|
34
25
|
* (injected to reuse the instrumenter's implementation)
|
|
35
26
|
*/
|
|
36
27
|
async function detectStack(findInitFile) {
|
|
37
|
-
const deps = await
|
|
28
|
+
const deps = await fileUtils.readProjectDeps();
|
|
38
29
|
const has = (name) => !!deps[name];
|
|
39
30
|
let framework = 'unknown';
|
|
40
31
|
if (has('next'))
|
|
@@ -58,6 +49,7 @@ async function detectStack(findInitFile) {
|
|
|
58
49
|
initFile: await findInitFile(),
|
|
59
50
|
hasAppRouter,
|
|
60
51
|
hasParaglide,
|
|
52
|
+
usesNextI18next: framework === 'next' && (has('next-i18next') || !(has('i18next') || has('react-i18next'))),
|
|
61
53
|
};
|
|
62
54
|
}
|
|
63
55
|
/** File extensions associated with frameworks the instrumenter cannot transform natively. */
|
|
@@ -10,6 +10,7 @@ var heuristicConfig = require('../heuristic-config.js');
|
|
|
10
10
|
var extractor = require('../extractor/core/extractor.js');
|
|
11
11
|
require('node:path');
|
|
12
12
|
require('jsonc-parser');
|
|
13
|
+
require('minimatch');
|
|
13
14
|
require('jiti');
|
|
14
15
|
require('@croct/json5-parser');
|
|
15
16
|
require('yaml');
|
|
@@ -17,7 +18,7 @@ require('node:module');
|
|
|
17
18
|
require('@swc/core');
|
|
18
19
|
var nestedObject = require('../utils/nested-object.js');
|
|
19
20
|
var instrumenter = require('../instrumenter/core/instrumenter.js');
|
|
20
|
-
require('../
|
|
21
|
+
require('../instrumenter/core/string-detector.js');
|
|
21
22
|
require('magic-string');
|
|
22
23
|
var locize = require('../locize.js');
|
|
23
24
|
var locizeOnboarding = require('../utils/locize-onboarding.js');
|
|
@@ -139,12 +140,33 @@ function printCompleteness(completeness) {
|
|
|
139
140
|
console.log(node_util.styleText(color, ` ${locale}: ${translated}/${total} (${pct}%)`));
|
|
140
141
|
}
|
|
141
142
|
}
|
|
142
|
-
function printEpilogue(config) {
|
|
143
|
+
function printEpilogue(config, nextApp = false) {
|
|
143
144
|
const projectId = config.locize?.projectId || '<your-project-id>';
|
|
144
145
|
console.log(node_util.styleText('green', '\n✅ Done. Your app is localized.'));
|
|
145
146
|
console.log(node_util.styleText('cyan', '\nYour AI translations come with confidence scores; low-confidence ones are flagged for review in Locize.'));
|
|
146
147
|
console.log('\nOptional — switch to CDN delivery so translation fixes go live without redeploying your app:');
|
|
147
148
|
console.log(node_util.styleText('cyan', ' npm install i18next-locize-backend'));
|
|
149
|
+
if (nextApp) {
|
|
150
|
+
// next-i18next takes the backend in its config (and, for the browser, in I18nProvider's `use`: see the docs)
|
|
151
|
+
console.log(node_util.styleText('gray', `
|
|
152
|
+
// in your next-i18next config (i18n.config):
|
|
153
|
+
import LocizeBackend from 'i18next-locize-backend'
|
|
154
|
+
|
|
155
|
+
export default defineConfig({
|
|
156
|
+
// ...
|
|
157
|
+
use: [LocizeBackend],
|
|
158
|
+
i18nextOptions: {
|
|
159
|
+
backend: {
|
|
160
|
+
projectId: '${projectId}',
|
|
161
|
+
version: 'latest', // no apiKey in production!
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
`));
|
|
166
|
+
console.log('Docs: https://github.com/i18next/next-i18next#i18next-locize-backend');
|
|
167
|
+
console.log('Your current setup (local translation files) keeps working either way; run `i18next-cli locize-download` in CI to refresh the files.');
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
148
170
|
console.log(node_util.styleText('gray', `
|
|
149
171
|
// in your i18n init file:
|
|
150
172
|
import LocizeBackend from 'i18next-locize-backend'
|
|
@@ -269,8 +291,8 @@ async function runLocalize(options = {}, configPath) {
|
|
|
269
291
|
if (!proceed)
|
|
270
292
|
skipInstrument = true;
|
|
271
293
|
}
|
|
272
|
-
if (stack.
|
|
273
|
-
warn(
|
|
294
|
+
if (stack.usesNextI18next) {
|
|
295
|
+
warn('Next.js: instrument writes next-i18next calls, await getT() in Server Components and useT() in Client Components. Review the diff and the texts it lists as left.');
|
|
274
296
|
}
|
|
275
297
|
if (!skipInstrument) {
|
|
276
298
|
const results = await instrumenter.runInstrumenter(config$1, {
|
|
@@ -471,7 +493,7 @@ async function runLocalize(options = {}, configPath) {
|
|
|
471
493
|
else if (completeness.length > 0) {
|
|
472
494
|
ok('All languages translated and downloaded.');
|
|
473
495
|
}
|
|
474
|
-
printEpilogue(config$1);
|
|
496
|
+
printEpilogue(config$1, stack.usesNextI18next);
|
|
475
497
|
}
|
|
476
498
|
|
|
477
499
|
exports.runLocalize = runLocalize;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var promises = require('node:fs/promises');
|
|
4
4
|
var node_path = require('node:path');
|
|
5
|
+
var minimatch = require('minimatch');
|
|
5
6
|
var jiti = require('jiti');
|
|
6
7
|
var config = require('../config.js');
|
|
7
8
|
var json5Parser = require('@croct/json5-parser');
|
|
@@ -29,6 +30,52 @@ class ParseTranslationFileError extends Error {
|
|
|
29
30
|
this.name = 'ParseTranslationFileError';
|
|
30
31
|
}
|
|
31
32
|
}
|
|
33
|
+
async function readPackageJson(dir) {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(await promises.readFile(node_path.resolve(dir, 'package.json'), 'utf-8'));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const depsOf = (pkg) => ({ ...pkg?.peerDependencies, ...pkg?.devDependencies, ...pkg?.dependencies });
|
|
42
|
+
/** A workspace root's package globs: npm/yarn `workspaces` (array or `{ packages }`), or `pnpm-workspace.yaml`. */
|
|
43
|
+
async function workspaceGlobs(dir, pkg) {
|
|
44
|
+
const workspaces = pkg?.workspaces;
|
|
45
|
+
if (Array.isArray(workspaces))
|
|
46
|
+
return workspaces;
|
|
47
|
+
if (Array.isArray(workspaces?.packages))
|
|
48
|
+
return workspaces.packages;
|
|
49
|
+
try {
|
|
50
|
+
const packages = yaml__default.default.parse(await promises.readFile(node_path.resolve(dir, 'pnpm-workspace.yaml'), 'utf-8'))?.packages;
|
|
51
|
+
return Array.isArray(packages) ? packages : [];
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The project's declared packages: `dependencies`, `devDependencies` and `peerDependencies` of the
|
|
59
|
+
* `package.json` in `cwd`, plus, for a package of a workspace (npm/yarn `workspaces` or
|
|
60
|
+
* `pnpm-workspace.yaml`), the ones of the workspace root, where shared packages such as `react` are often
|
|
61
|
+
* declared only once. The nearer package wins; a folder the root's globs do not list gets nothing from it.
|
|
62
|
+
*/
|
|
63
|
+
async function readProjectDeps(cwd = process.cwd()) {
|
|
64
|
+
const own = await readPackageJson(cwd);
|
|
65
|
+
const deps = depsOf(own);
|
|
66
|
+
if (own?.workspaces)
|
|
67
|
+
return deps;
|
|
68
|
+
for (let dir = node_path.dirname(node_path.resolve(cwd)); dir !== node_path.dirname(dir); dir = node_path.dirname(dir)) {
|
|
69
|
+
const pkg = await readPackageJson(dir);
|
|
70
|
+
const globs = await workspaceGlobs(dir, pkg);
|
|
71
|
+
if (!globs)
|
|
72
|
+
continue;
|
|
73
|
+
const member = node_path.relative(dir, node_path.resolve(cwd)).split(node_path.sep).join('/');
|
|
74
|
+
const isMember = globs.some(g => !g.startsWith('!') && minimatch.minimatch(member, g.replace(/^\.\//, '').replace(/\/$/, '')));
|
|
75
|
+
return isMember ? { ...depsOf(pkg), ...deps } : deps;
|
|
76
|
+
}
|
|
77
|
+
return deps;
|
|
78
|
+
}
|
|
32
79
|
/**
|
|
33
80
|
* Resolve an output template (string or function) into an actual path string.
|
|
34
81
|
*
|
|
@@ -240,4 +287,5 @@ exports.ignoredNamespaceMatcher = ignoredNamespaceMatcher;
|
|
|
240
287
|
exports.inferFormatFromPath = inferFormatFromPath;
|
|
241
288
|
exports.loadRawJson5Content = loadRawJson5Content;
|
|
242
289
|
exports.loadTranslationFile = loadTranslationFile;
|
|
290
|
+
exports.readProjectDeps = readProjectDeps;
|
|
243
291
|
exports.serializeTranslationFile = serializeTranslationFile;
|
|
@@ -29,7 +29,9 @@ const translatableAttributes = [
|
|
|
29
29
|
'aria-roledescription', 'aria-valuetext',
|
|
30
30
|
'content', 'description',
|
|
31
31
|
'label', 'placeholder',
|
|
32
|
-
'summary', 'caption', 'title'
|
|
32
|
+
'summary', 'caption', 'title',
|
|
33
|
+
// tooltip libraries (react-tooltip and the like)
|
|
34
|
+
'data-tip', 'data-tooltip', 'data-tooltip-content'
|
|
33
35
|
];
|
|
34
36
|
/**
|
|
35
37
|
* Pre-built Set (lower-cased) for fast membership checks in hot loops.
|