i18next-cli 1.74.1 → 1.74.3
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/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/ast-visitors.js +7 -1
- package/dist/cjs/extractor/core/extractor.js +38 -0
- package/dist/cjs/extractor/core/key-finder.js +7 -3
- package/dist/cjs/extractor/parsers/ast-utils.js +15 -16
- package/dist/cjs/extractor/parsers/expression-resolver.js +272 -91
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/ast-visitors.js +7 -1
- package/dist/esm/extractor/core/extractor.js +38 -0
- package/dist/esm/extractor/core/key-finder.js +7 -3
- package/dist/esm/extractor/parsers/ast-utils.js +15 -16
- package/dist/esm/extractor/parsers/expression-resolver.js +272 -91
- package/package.json +17 -17
- package/types/extractor/core/ast-visitors.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/key-finder.d.ts.map +1 -1
- package/types/extractor/parsers/ast-utils.d.ts.map +1 -1
- package/types/extractor/parsers/expression-resolver.d.ts +45 -4
- package/types/extractor/parsers/expression-resolver.d.ts.map +1 -1
|
@@ -2,6 +2,40 @@
|
|
|
2
2
|
|
|
3
3
|
var astUtils = require('./ast-utils.js');
|
|
4
4
|
|
|
5
|
+
// Whether `next` holds everything `prev` does: every value of a list, every
|
|
6
|
+
// member of a map (recursively), or the same primitive.
|
|
7
|
+
const covers = (next, prev) => {
|
|
8
|
+
if (Array.isArray(prev)) {
|
|
9
|
+
const has = new Set(Array.isArray(next) ? next : []);
|
|
10
|
+
return prev.every(v => has.has(v));
|
|
11
|
+
}
|
|
12
|
+
if (prev && typeof prev === 'object') {
|
|
13
|
+
return !!next && typeof next === 'object' && Object.keys(prev).every(k => covers(next[k], prev[k]));
|
|
14
|
+
}
|
|
15
|
+
return next === prev;
|
|
16
|
+
};
|
|
17
|
+
// Whether replacing `prev` by `next` only adds to it.
|
|
18
|
+
const grows = (next, prev) => prev === undefined || (covers(next, prev) && !covers(prev, next));
|
|
19
|
+
// The parts of return expressions that still resolve without the file's local
|
|
20
|
+
// bindings: members of enums / objects (`Kind.A`) and calls of other functions.
|
|
21
|
+
function crossFileRefs(exprs) {
|
|
22
|
+
const refs = [];
|
|
23
|
+
const add = (e) => {
|
|
24
|
+
e = astUtils.unwrapParens(e);
|
|
25
|
+
if (e?.type === 'ConditionalExpression') {
|
|
26
|
+
add(e.consequent);
|
|
27
|
+
add(e.alternate);
|
|
28
|
+
}
|
|
29
|
+
else if (e?.type === 'MemberExpression' && e.object?.type === 'Identifier') {
|
|
30
|
+
refs.push(e);
|
|
31
|
+
}
|
|
32
|
+
else if (e?.type === 'CallExpression' && e.callee?.type === 'Identifier') {
|
|
33
|
+
refs.push({ type: 'CallExpression', callee: e.callee, arguments: [] });
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
exprs.forEach(add);
|
|
37
|
+
return refs;
|
|
38
|
+
}
|
|
5
39
|
class ExpressionResolver {
|
|
6
40
|
hooks;
|
|
7
41
|
// Per-file symbol table for statically analyzable variables.
|
|
@@ -46,6 +80,22 @@ class ExpressionResolver {
|
|
|
46
80
|
// Every other table is keyed by the *declared* name, so without this a type
|
|
47
81
|
// referenced through an alias resolves to nothing.
|
|
48
82
|
sharedImportAliases = new Map();
|
|
83
|
+
// Type parameters of generic object types, e.g. `type Base<T> = { type: T }`.
|
|
84
|
+
objectTypeParams = new Map();
|
|
85
|
+
// Values bound to type parameters while a generic type is being resolved.
|
|
86
|
+
typeParamBindings = new Map();
|
|
87
|
+
// Shared (cross-file) member maps of functions returning an object type,
|
|
88
|
+
// e.g. `const getAnimal = (): Animal => …` -> { getAnimal: { type: ['DUCK', 'DOG'] } }
|
|
89
|
+
sharedFunctionReturnMembers = new Map();
|
|
90
|
+
// Per-file identifiers holding an object type, from their annotation or from the
|
|
91
|
+
// function they were initialised by: `const animal = getAnimal()` -> { animal: { type: [...] } }
|
|
92
|
+
objectVariables = new Map();
|
|
93
|
+
// Set while the pre-scan runs. Captures that read other declarations queue a
|
|
94
|
+
// replay here, because what they read may be declared in a file scanned later.
|
|
95
|
+
recording = false;
|
|
96
|
+
replays = [];
|
|
97
|
+
replaying = false;
|
|
98
|
+
grew = false;
|
|
49
99
|
constructor(hooks) {
|
|
50
100
|
this.hooks = hooks;
|
|
51
101
|
}
|
|
@@ -57,6 +107,45 @@ class ExpressionResolver {
|
|
|
57
107
|
this.typeAliasTable.clear();
|
|
58
108
|
this.temporaryVariables.clear();
|
|
59
109
|
this.arrayElementMembers.clear();
|
|
110
|
+
this.objectVariables.clear();
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Call once every file has been pre-scanned. Captures ran in file order, so one
|
|
114
|
+
* that refers to a declaration in a later file (`type Kind = Base | 'extra'`
|
|
115
|
+
* with `Base` declared further down the list) came out short. They are replayed
|
|
116
|
+
* against the complete tables until nothing grows, then renaming imports are
|
|
117
|
+
* mirrored.
|
|
118
|
+
*/
|
|
119
|
+
finishPreScan() {
|
|
120
|
+
this.resetFileSymbols();
|
|
121
|
+
// ponytail: each round fixes one more link of a chain declared against file order; 10 is plenty
|
|
122
|
+
for (let round = 0; round < 10; round++) {
|
|
123
|
+
this.applyImportAliases();
|
|
124
|
+
this.grew = false;
|
|
125
|
+
this.replaying = true;
|
|
126
|
+
for (const replay of this.replays)
|
|
127
|
+
replay();
|
|
128
|
+
this.replaying = false;
|
|
129
|
+
if (!this.grew)
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
this.applyImportAliases();
|
|
133
|
+
this.replays = [];
|
|
134
|
+
this.resetFileSymbols();
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Write an entry of a cross-file table. While replaying, an entry only grows:
|
|
138
|
+
* a replayed declaration has lost its file's local bindings and must not shrink
|
|
139
|
+
* what the pre-scan resolved, and two same-named declarations in different files
|
|
140
|
+
* must not keep overwriting each other.
|
|
141
|
+
*/
|
|
142
|
+
setShared(table, name, value) {
|
|
143
|
+
if (this.replaying) {
|
|
144
|
+
if (!grows(value, table.get(name)))
|
|
145
|
+
return;
|
|
146
|
+
this.grew = true;
|
|
147
|
+
}
|
|
148
|
+
table.set(name, value);
|
|
60
149
|
}
|
|
61
150
|
/**
|
|
62
151
|
* Capture a VariableDeclarator node to record simple statically analyzable
|
|
@@ -107,11 +196,11 @@ class ExpressionResolver {
|
|
|
107
196
|
}
|
|
108
197
|
return;
|
|
109
198
|
}
|
|
110
|
-
// ── ObjectPattern id: `const { unit } = rate`
|
|
199
|
+
// ── ObjectPattern id: `const { unit } = rate` / `const { type } = getAnimal()`
|
|
111
200
|
// Bind each destructured local to the source object's property values.
|
|
112
|
-
if (node.id.type === 'ObjectPattern' && node.init
|
|
113
|
-
const map = this.getObjectMap(node.init.value);
|
|
114
|
-
const objMembers = this.
|
|
201
|
+
if (node.id.type === 'ObjectPattern' && node.init) {
|
|
202
|
+
const map = node.init.type === 'Identifier' ? this.getObjectMap(node.init.value) : undefined;
|
|
203
|
+
const objMembers = this.objectMembersOf(node.init);
|
|
115
204
|
if (!map && !objMembers)
|
|
116
205
|
return;
|
|
117
206
|
for (const prop of (node.id.properties ?? [])) {
|
|
@@ -140,6 +229,12 @@ class ExpressionResolver {
|
|
|
140
229
|
if (elementMembers)
|
|
141
230
|
this.arrayElementMembers.set(name, elementMembers);
|
|
142
231
|
}
|
|
232
|
+
// `const animal: Animal = …` / `const animal = getAnimal()` → `animal.type`
|
|
233
|
+
// resolves to the member's values.
|
|
234
|
+
const objMembers = (idTypeAnnotation && this.resolveTypeMembers(idTypeAnnotation)) ||
|
|
235
|
+
(node.init && this.objectMembersOf(node.init));
|
|
236
|
+
if (objMembers)
|
|
237
|
+
this.objectVariables.set(name, objMembers);
|
|
143
238
|
// pattern 1:
|
|
144
239
|
// Handle `declare const x: 'a' | 'b'` and `declare const x: SomeUnion`
|
|
145
240
|
// where there is no initializer but a TypeScript type annotation.
|
|
@@ -252,25 +347,9 @@ class ExpressionResolver {
|
|
|
252
347
|
this.variableTable.set(name, vals);
|
|
253
348
|
return;
|
|
254
349
|
}
|
|
255
|
-
// pattern 3 (arrow function variant):
|
|
256
|
-
// `const fn = (): 'a' | 'b' => ...` — capture the explicit return type annotation,
|
|
257
|
-
// OR fall back to walking the body's return expressions / expression body
|
|
258
|
-
// when no annotation is present (mirrors TS's own return-type inference).
|
|
350
|
+
// pattern 3 (arrow function variant): `const fn = (): 'a' | 'b' => ...`
|
|
259
351
|
if (unwrappedInit.type === 'ArrowFunctionExpression' || unwrappedInit.type === 'FunctionExpression') {
|
|
260
|
-
|
|
261
|
-
const rawReturnType = unwrappedInit.returnType ?? unwrappedInit.typeAnnotation;
|
|
262
|
-
if (rawReturnType) {
|
|
263
|
-
// Explicit annotation — trust it even when it resolves to [].
|
|
264
|
-
const tsType = rawReturnType.typeAnnotation ?? rawReturnType;
|
|
265
|
-
returnVals = this.resolvePossibleStringValuesFromType(tsType);
|
|
266
|
-
}
|
|
267
|
-
else {
|
|
268
|
-
returnVals = this.inferReturnValuesFromFunctionBody(unwrappedInit);
|
|
269
|
-
}
|
|
270
|
-
if (returnVals.length > 0) {
|
|
271
|
-
this.variableTable.set(name, returnVals);
|
|
272
|
-
this.sharedFunctionReturnTable.set(name, returnVals);
|
|
273
|
-
}
|
|
352
|
+
this.captureFunctionReturn(name, unwrappedInit);
|
|
274
353
|
}
|
|
275
354
|
}
|
|
276
355
|
catch {
|
|
@@ -294,20 +373,30 @@ class ExpressionResolver {
|
|
|
294
373
|
const tsType = node.typeAnnotation ?? node.typeAnn;
|
|
295
374
|
if (!tsType)
|
|
296
375
|
return;
|
|
376
|
+
if (this.recording)
|
|
377
|
+
this.replays.push(() => this.captureTypeAliasDeclaration(node));
|
|
378
|
+
const params = node.typeParams?.parameters;
|
|
297
379
|
// `type IProps = { size: ChangeType }` — object shape, not a string union.
|
|
298
380
|
if (tsType.type === 'TsTypeLiteral') {
|
|
299
|
-
this.
|
|
300
|
-
|
|
381
|
+
if (!this.replaying)
|
|
382
|
+
this.setObjectTypeRaw(name, tsType.members, params);
|
|
383
|
+
const members = this.withTypeParams(params, undefined, () => this.collectObjectTypeMembers(tsType.members));
|
|
301
384
|
if (members)
|
|
302
|
-
this.objectTypeTable
|
|
385
|
+
this.setShared(this.objectTypeTable, name, members);
|
|
303
386
|
return;
|
|
304
387
|
}
|
|
305
|
-
const vals = this.resolvePossibleStringValuesFromType(tsType);
|
|
388
|
+
const vals = this.withTypeParams(params, undefined, () => this.resolvePossibleStringValuesFromType(tsType));
|
|
306
389
|
if (vals.length > 0) {
|
|
307
|
-
this.
|
|
390
|
+
if (!this.replaying)
|
|
391
|
+
this.typeAliasTable.set(name, vals);
|
|
308
392
|
// Also share so importing files can resolve this alias by name
|
|
309
|
-
this.sharedTypeAliasTable
|
|
393
|
+
this.setShared(this.sharedTypeAliasTable, name, vals);
|
|
394
|
+
return;
|
|
310
395
|
}
|
|
396
|
+
// `type Animal = Duck | Dog`, `type Duck = Base<'DUCK'> & { fly: true }`
|
|
397
|
+
const members = this.withTypeParams(params, undefined, () => this.resolveTypeMembers(tsType));
|
|
398
|
+
if (members)
|
|
399
|
+
this.setShared(this.objectTypeTable, name, members);
|
|
311
400
|
}
|
|
312
401
|
catch {
|
|
313
402
|
// noop
|
|
@@ -349,12 +438,15 @@ class ExpressionResolver {
|
|
|
349
438
|
this.sharedEnumTable,
|
|
350
439
|
this.sharedVariableTable,
|
|
351
440
|
this.sharedFunctionReturnTable,
|
|
441
|
+
this.sharedFunctionReturnMembers,
|
|
352
442
|
this.objectTypeTable,
|
|
353
443
|
this.objectTypeMembersRaw,
|
|
444
|
+
this.objectTypeParams,
|
|
354
445
|
];
|
|
355
446
|
for (const [local, declared] of this.sharedImportAliases) {
|
|
356
447
|
for (const table of tables) {
|
|
357
|
-
|
|
448
|
+
// A replayed declaration may have grown since it was last mirrored
|
|
449
|
+
if (table.has(declared) && grows(table.get(declared), table.get(local)))
|
|
358
450
|
table.set(local, table.get(declared));
|
|
359
451
|
}
|
|
360
452
|
}
|
|
@@ -371,16 +463,62 @@ class ExpressionResolver {
|
|
|
371
463
|
const name = node?.id?.type === 'Identifier' ? node.id.value : undefined;
|
|
372
464
|
if (!name)
|
|
373
465
|
return;
|
|
374
|
-
if (
|
|
375
|
-
this.
|
|
376
|
-
const
|
|
466
|
+
if (this.recording)
|
|
467
|
+
this.replays.push(() => this.captureInterfaceDeclaration(node));
|
|
468
|
+
const params = node.typeParams?.parameters;
|
|
469
|
+
if (!this.replaying && Array.isArray(node?.body?.body))
|
|
470
|
+
this.setObjectTypeRaw(name, node.body.body, params);
|
|
471
|
+
const members = this.withTypeParams(params, undefined, () => this.collectObjectTypeMembers(node?.body?.body));
|
|
377
472
|
if (members)
|
|
378
|
-
this.objectTypeTable
|
|
473
|
+
this.setShared(this.objectTypeTable, name, members);
|
|
379
474
|
}
|
|
380
475
|
catch {
|
|
381
476
|
// noop
|
|
382
477
|
}
|
|
383
478
|
}
|
|
479
|
+
setObjectTypeRaw(name, members, params) {
|
|
480
|
+
this.objectTypeMembersRaw.set(name, members);
|
|
481
|
+
if (params?.length)
|
|
482
|
+
this.objectTypeParams.set(name, params);
|
|
483
|
+
else
|
|
484
|
+
this.objectTypeParams.delete(name);
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Run `fn` with the parameters of a generic type bound to the values of their
|
|
488
|
+
* arguments, falling back to each one's default and then its constraint, so
|
|
489
|
+
* that `type Base<T extends Kind> = { type: T }` used bare has `type: Kind`.
|
|
490
|
+
*/
|
|
491
|
+
withTypeParams(params, args, fn) {
|
|
492
|
+
if (!params?.length)
|
|
493
|
+
return fn();
|
|
494
|
+
const values = params.map((p, i) => {
|
|
495
|
+
const arg = args?.[i] ?? p.default ?? p.constraint;
|
|
496
|
+
return arg ? this.resolvePossibleStringValuesFromType(arg) : [];
|
|
497
|
+
});
|
|
498
|
+
const saved = this.typeParamBindings;
|
|
499
|
+
this.typeParamBindings = new Map(saved);
|
|
500
|
+
params.forEach((p, i) => { if (p.name?.value)
|
|
501
|
+
this.typeParamBindings.set(p.name.value, values[i]); });
|
|
502
|
+
try {
|
|
503
|
+
return fn();
|
|
504
|
+
}
|
|
505
|
+
finally {
|
|
506
|
+
this.typeParamBindings = saved;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* The member map of an object held by `expr`: a parameter typed by an interface
|
|
511
|
+
* (`props`), a variable holding an object type (`animal`) or a call of a
|
|
512
|
+
* function returning one (`getAnimal()`).
|
|
513
|
+
*/
|
|
514
|
+
objectMembersOf(expr) {
|
|
515
|
+
expr = astUtils.unwrapParens(expr);
|
|
516
|
+
if (expr?.type === 'Identifier')
|
|
517
|
+
return this.temporaryObjectVariables.get(expr.value) ?? this.objectVariables.get(expr.value);
|
|
518
|
+
if (expr?.type === 'CallExpression' && expr.callee?.type === 'Identifier')
|
|
519
|
+
return this.sharedFunctionReturnMembers.get(expr.callee.value);
|
|
520
|
+
return undefined;
|
|
521
|
+
}
|
|
384
522
|
/**
|
|
385
523
|
* Build `{ memberName: possibleStringValues }` for an object-shaped type
|
|
386
524
|
* (interface body or object type-literal members). Only members whose type
|
|
@@ -416,11 +554,31 @@ class ExpressionResolver {
|
|
|
416
554
|
try {
|
|
417
555
|
if (!tsType)
|
|
418
556
|
return undefined;
|
|
557
|
+
if (tsType.type === 'TsParenthesizedType')
|
|
558
|
+
return this.resolveTypeMembers(tsType.typeAnnotation);
|
|
419
559
|
if (tsType.type === 'TsTypeLiteral') {
|
|
420
560
|
return this.collectObjectTypeMembers(tsType.members);
|
|
421
561
|
}
|
|
562
|
+
// `Duck | Dog`, `Base<'DUCK'> & { fly: true }` → every member with the values
|
|
563
|
+
// it has in any of the parts (`animal.type` → 'DUCK' | 'DOG')
|
|
564
|
+
if (tsType.type === 'TsUnionType' || tsType.type === 'TsIntersectionType') {
|
|
565
|
+
const merged = {};
|
|
566
|
+
for (const part of tsType.types) {
|
|
567
|
+
for (const [member, vals] of Object.entries(this.resolveTypeMembers(part) ?? {})) {
|
|
568
|
+
merged[member] = [...new Set([...(merged[member] ?? []), ...vals])];
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
572
|
+
}
|
|
422
573
|
if (tsType.type === 'TsTypeReference' && tsType.typeName?.type === 'Identifier') {
|
|
423
|
-
|
|
574
|
+
const name = tsType.typeName.value;
|
|
575
|
+
// `Base<'DUCK'>` → instantiate the generic type's members with the argument
|
|
576
|
+
const args = tsType.typeParams?.params;
|
|
577
|
+
const params = this.objectTypeParams.get(name);
|
|
578
|
+
if (args?.length && params) {
|
|
579
|
+
return this.withTypeParams(params, args, () => this.collectObjectTypeMembers(this.objectTypeMembersRaw.get(name) ?? []));
|
|
580
|
+
}
|
|
581
|
+
return this.objectTypeTable.get(name);
|
|
424
582
|
}
|
|
425
583
|
}
|
|
426
584
|
catch { }
|
|
@@ -489,46 +647,64 @@ class ExpressionResolver {
|
|
|
489
647
|
return;
|
|
490
648
|
// SWC places the return type annotation in `.function.returnType` (FunctionDeclaration)
|
|
491
649
|
// or directly in `.returnType` (FunctionExpression / ArrowFunctionExpression).
|
|
492
|
-
|
|
493
|
-
const rawReturnType = fn.returnType ?? fn.typeAnnotation;
|
|
494
|
-
let vals = [];
|
|
495
|
-
if (rawReturnType) {
|
|
496
|
-
// Unwrap TsTypeAnnotation wrapper if present. Explicit annotations are
|
|
497
|
-
// authoritative: if the author declared the return type we trust it,
|
|
498
|
-
// even when it resolves to [] (e.g. plain `string`). Falling back to
|
|
499
|
-
// body inference in that case would invent keys the author deliberately
|
|
500
|
-
// opted out of.
|
|
501
|
-
const tsType = rawReturnType.typeAnnotation ?? rawReturnType;
|
|
502
|
-
vals = this.resolvePossibleStringValuesFromType(tsType);
|
|
503
|
-
}
|
|
504
|
-
else {
|
|
505
|
-
// No annotation — infer from body. Mirrors TS's own return-type
|
|
506
|
-
// inference for functions like:
|
|
507
|
-
// function getCurrentAppType() {
|
|
508
|
-
// if (...) return OrganizationType.ROUTING;
|
|
509
|
-
// if (...) return OrganizationType.CONTRACTOR;
|
|
510
|
-
// }
|
|
511
|
-
vals = this.inferReturnValuesFromFunctionBody(fn);
|
|
512
|
-
}
|
|
513
|
-
if (vals.length > 0) {
|
|
514
|
-
this.variableTable.set(name, vals);
|
|
515
|
-
this.sharedFunctionReturnTable.set(name, vals);
|
|
516
|
-
}
|
|
650
|
+
this.captureFunctionReturn(name, node.function ?? node);
|
|
517
651
|
}
|
|
518
652
|
catch {
|
|
519
653
|
// noop
|
|
520
654
|
}
|
|
521
655
|
}
|
|
522
656
|
/**
|
|
523
|
-
*
|
|
524
|
-
*
|
|
525
|
-
|
|
657
|
+
* Record what a function returns: string values for `t(fn())`, and the members
|
|
658
|
+
* of an object return type for `fn().type` / `const x = fn(); x.type`.
|
|
659
|
+
*/
|
|
660
|
+
captureFunctionReturn(name, fn) {
|
|
661
|
+
const rawReturnType = fn.returnType ?? fn.typeAnnotation;
|
|
662
|
+
// Unwrap TsTypeAnnotation wrapper if present. Explicit annotations are
|
|
663
|
+
// authoritative: if the author declared the return type we trust it,
|
|
664
|
+
// even when it resolves to [] (e.g. plain `string`). Falling back to
|
|
665
|
+
// body inference in that case would invent keys the author deliberately
|
|
666
|
+
// opted out of.
|
|
667
|
+
const returnType = rawReturnType?.typeAnnotation ?? rawReturnType;
|
|
668
|
+
// No annotation: infer from body. Mirrors TS's own return-type
|
|
669
|
+
// inference for functions like:
|
|
670
|
+
// function getCurrentAppType() {
|
|
671
|
+
// if (...) return OrganizationType.ROUTING;
|
|
672
|
+
// if (...) return OrganizationType.CONTRACTOR;
|
|
673
|
+
// }
|
|
674
|
+
const exprs = returnType ? [] : this.returnExpressions(fn);
|
|
675
|
+
const vals = returnType
|
|
676
|
+
? this.resolvePossibleStringValuesFromType(returnType)
|
|
677
|
+
: [...new Set(exprs.flatMap(e => this.resolvePossibleStringValuesFromExpression(e)))];
|
|
678
|
+
if (vals.length > 0)
|
|
679
|
+
this.variableTable.set(name, vals);
|
|
680
|
+
// A replay has lost the file's local bindings, so it re-resolves only the
|
|
681
|
+
// return type, or the returned enum / object members and calls of other
|
|
682
|
+
// functions, kept as small nodes so no function body stays in memory.
|
|
683
|
+
const refs = this.recording ? crossFileRefs(exprs) : [];
|
|
684
|
+
const store = () => {
|
|
685
|
+
const all = returnType
|
|
686
|
+
? this.resolvePossibleStringValuesFromType(returnType)
|
|
687
|
+
: [...new Set([...vals, ...refs.flatMap(e => this.resolvePossibleStringValuesFromExpression(e))])];
|
|
688
|
+
if (all.length > 0)
|
|
689
|
+
this.setShared(this.sharedFunctionReturnTable, name, all);
|
|
690
|
+
const members = returnType && this.resolveTypeMembers(returnType);
|
|
691
|
+
if (members)
|
|
692
|
+
this.setShared(this.sharedFunctionReturnMembers, name, members);
|
|
693
|
+
};
|
|
694
|
+
store();
|
|
695
|
+
if (this.recording && (returnType || refs.length > 0))
|
|
696
|
+
this.replays.push(store);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Collect a function's return expressions (the expression body of an arrow
|
|
700
|
+
* function, or the arguments of its ReturnStatements). Does NOT descend into
|
|
701
|
+
* nested function declarations (their returns belong to the inner function, not us).
|
|
526
702
|
*
|
|
527
703
|
* This is how we mirror TypeScript's implicit return-type inference for the
|
|
528
704
|
* purpose of extracting translation keys — we don't need exhaustiveness, just
|
|
529
705
|
* the set of string values any return statement could produce.
|
|
530
706
|
*/
|
|
531
|
-
|
|
707
|
+
returnExpressions(fn) {
|
|
532
708
|
const body = fn?.body;
|
|
533
709
|
if (!body)
|
|
534
710
|
return [];
|
|
@@ -541,11 +717,8 @@ class ExpressionResolver {
|
|
|
541
717
|
n.type === 'FunctionExpression' ||
|
|
542
718
|
n.type === 'ArrowFunctionExpression'))
|
|
543
719
|
return;
|
|
544
|
-
if (n.type === 'ReturnStatement' && n.argument)
|
|
545
|
-
|
|
546
|
-
if (vals.length > 0)
|
|
547
|
-
collected.push(...vals);
|
|
548
|
-
}
|
|
720
|
+
if (n.type === 'ReturnStatement' && n.argument)
|
|
721
|
+
collected.push(n.argument);
|
|
549
722
|
for (const key of Object.keys(n)) {
|
|
550
723
|
const child = n[key];
|
|
551
724
|
if (Array.isArray(child)) {
|
|
@@ -562,14 +735,10 @@ class ExpressionResolver {
|
|
|
562
735
|
// Arrow functions with an expression body (no block) — `() => expr` —
|
|
563
736
|
// have their return expression directly as `body`. swc >=1.16 types function
|
|
564
737
|
// bodies as 'FunctionBody'; older versions used 'BlockStatement'.
|
|
565
|
-
if (body.type !== 'BlockStatement' && body.type !== 'FunctionBody')
|
|
566
|
-
|
|
567
|
-
if (vals.length > 0)
|
|
568
|
-
return Array.from(new Set(vals));
|
|
569
|
-
return [];
|
|
570
|
-
}
|
|
738
|
+
if (body.type !== 'BlockStatement' && body.type !== 'FunctionBody')
|
|
739
|
+
return [body];
|
|
571
740
|
visit(body);
|
|
572
|
-
return
|
|
741
|
+
return collected;
|
|
573
742
|
}
|
|
574
743
|
/**
|
|
575
744
|
* Extract a raw TsType node from an identifier's type annotation.
|
|
@@ -800,28 +969,22 @@ class ExpressionResolver {
|
|
|
800
969
|
try {
|
|
801
970
|
const obj = expression.object;
|
|
802
971
|
const prop = expression.property;
|
|
972
|
+
const propName = prop.type === 'Identifier'
|
|
973
|
+
? prop.value
|
|
974
|
+
: prop.type === 'Computed' && prop.expression?.type === 'StringLiteral'
|
|
975
|
+
? prop.expression.value
|
|
976
|
+
: undefined;
|
|
977
|
+
// Object type held by a parameter (`props.size`), a variable (`animal.type`)
|
|
978
|
+
// or returned by a call (`getAnimal().type`)
|
|
979
|
+
const objMembers = this.objectMembersOf(obj);
|
|
980
|
+
if (propName && objMembers?.[propName])
|
|
981
|
+
return objMembers[propName];
|
|
803
982
|
// only handle simple identifier base + simple property (Identifier or computed StringLiteral)
|
|
804
983
|
if (obj.type === 'Identifier') {
|
|
805
|
-
// Parameter typed by an interface / object type: `props.size`
|
|
806
|
-
const objMembers = this.temporaryObjectVariables.get(obj.value);
|
|
807
|
-
if (objMembers) {
|
|
808
|
-
const propName = prop.type === 'Identifier'
|
|
809
|
-
? prop.value
|
|
810
|
-
: prop.type === 'Computed' && prop.expression?.type === 'StringLiteral'
|
|
811
|
-
? prop.expression.value
|
|
812
|
-
: undefined;
|
|
813
|
-
if (propName && objMembers[propName])
|
|
814
|
-
return objMembers[propName];
|
|
815
|
-
}
|
|
816
984
|
const baseVar = this.variableTable.get(obj.value);
|
|
817
985
|
const baseShared = this.sharedEnumTable.get(obj.value);
|
|
818
986
|
const base = baseVar ?? baseShared;
|
|
819
987
|
if (base && typeof base !== 'string' && !Array.isArray(base)) {
|
|
820
|
-
let propName;
|
|
821
|
-
if (prop.type === 'Identifier')
|
|
822
|
-
propName = prop.value;
|
|
823
|
-
else if (prop.type === 'Computed' && prop.expression?.type === 'StringLiteral')
|
|
824
|
-
propName = prop.expression.value;
|
|
825
988
|
if (propName && base[propName] !== undefined) {
|
|
826
989
|
return [base[propName]];
|
|
827
990
|
}
|
|
@@ -838,6 +1001,13 @@ class ExpressionResolver {
|
|
|
838
1001
|
return Object.values(base);
|
|
839
1002
|
}
|
|
840
1003
|
}
|
|
1004
|
+
// `COLORS[i]` → one of the array's elements
|
|
1005
|
+
if (prop.type === 'Computed') {
|
|
1006
|
+
const elements = this.sharedVariableTable.get(obj.value);
|
|
1007
|
+
const index = prop.expression;
|
|
1008
|
+
if (elements)
|
|
1009
|
+
return index.type === 'NumericLiteral' && elements[index.value] !== undefined ? [elements[index.value]] : elements;
|
|
1010
|
+
}
|
|
841
1011
|
}
|
|
842
1012
|
}
|
|
843
1013
|
catch { }
|
|
@@ -972,6 +1142,10 @@ class ExpressionResolver {
|
|
|
972
1142
|
? type.typeName.value
|
|
973
1143
|
: undefined;
|
|
974
1144
|
if (typeName) {
|
|
1145
|
+
// Inside a generic type: the parameter's argument, default or constraint
|
|
1146
|
+
const bound = this.typeParamBindings.get(typeName);
|
|
1147
|
+
if (bound)
|
|
1148
|
+
return bound;
|
|
975
1149
|
// 1. Check type alias table first (exact match for string-literal unions)
|
|
976
1150
|
const aliasVals = this.typeAliasTable.get(typeName) ?? this.sharedTypeAliasTable.get(typeName);
|
|
977
1151
|
if (aliasVals && aliasVals.length > 0)
|
|
@@ -1009,6 +1183,13 @@ class ExpressionResolver {
|
|
|
1009
1183
|
const vals = this.getVariableValues(varName);
|
|
1010
1184
|
if (vals && vals.length > 0)
|
|
1011
1185
|
return vals;
|
|
1186
|
+
// `(typeof COLOR)[keyof typeof COLOR]` → the as-const object's (or enum's) values
|
|
1187
|
+
const map = this.getObjectMap(varName);
|
|
1188
|
+
if (map) {
|
|
1189
|
+
const keys = this.resolvePossibleStringValuesFromType(type.indexType);
|
|
1190
|
+
const picked = keys.map(k => map[k]).filter((v) => v !== undefined);
|
|
1191
|
+
return picked.length > 0 ? picked : Object.values(map);
|
|
1192
|
+
}
|
|
1012
1193
|
}
|
|
1013
1194
|
}
|
|
1014
1195
|
}
|
package/dist/esm/cli.js
CHANGED
|
@@ -31,7 +31,7 @@ const program = new Command();
|
|
|
31
31
|
program
|
|
32
32
|
.name('i18next-cli')
|
|
33
33
|
.description('A unified, high-performance i18next CLI.')
|
|
34
|
-
.version('1.74.
|
|
34
|
+
.version('1.74.3') // This string is replaced with the actual version at build time by rollup
|
|
35
35
|
.addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
|
|
36
36
|
// new: global config override option
|
|
37
37
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
|
|
@@ -96,7 +96,13 @@ class ASTVisitors {
|
|
|
96
96
|
*/
|
|
97
97
|
preScanForConstants(node) {
|
|
98
98
|
this.expressionResolver.resetFileSymbols();
|
|
99
|
-
this.
|
|
99
|
+
this.expressionResolver.recording = true;
|
|
100
|
+
try {
|
|
101
|
+
this._walkForConstants(node);
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
this.expressionResolver.recording = false;
|
|
105
|
+
}
|
|
100
106
|
}
|
|
101
107
|
/**
|
|
102
108
|
* Recursive walker used exclusively by `preScanForConstants`.
|
|
@@ -130,6 +130,39 @@ function isExtExplicitlyInInputPatterns(ext, input) {
|
|
|
130
130
|
return new RegExp(`[{,*]${escaped}[},*]|[.]${escaped}(?:[^a-z]|$)`).test(p);
|
|
131
131
|
});
|
|
132
132
|
}
|
|
133
|
+
const extractionSiteRegexes = new WeakMap();
|
|
134
|
+
/**
|
|
135
|
+
* Cheap textual test for anything the extraction walk can turn into a key: a call
|
|
136
|
+
* to a configured function (`t(`, `i18n.t(`, `t?.(`, `t<Ns>(`, `new TranslatedError(`, a
|
|
137
|
+
* `t(` comment), or a mention of what binds a translation function under any name
|
|
138
|
+
* (useTranslation-style hooks, getFixedT, TFunction params) or of a Trans component.
|
|
139
|
+
* A false positive only costs a parse; a false negative would drop keys.
|
|
140
|
+
*
|
|
141
|
+
* @internal
|
|
142
|
+
*/
|
|
143
|
+
function mayContainExtractionSite(code, config) {
|
|
144
|
+
let re = extractionSiteRegexes.get(config);
|
|
145
|
+
if (!re) {
|
|
146
|
+
const calls = new Set(['t']);
|
|
147
|
+
const names = new Set(['getFixedT', 'TFunction']);
|
|
148
|
+
for (const fn of config.extract.functions || ['t', '*.t']) {
|
|
149
|
+
// 'tProps.*' matches any `tProps.<x>(` call, so the prefix is what to look for
|
|
150
|
+
if (fn.endsWith('.*'))
|
|
151
|
+
names.add(fn.slice(0, -2).split('.').pop());
|
|
152
|
+
else
|
|
153
|
+
calls.add(fn.split('.').pop());
|
|
154
|
+
}
|
|
155
|
+
for (const hook of config.extract.useTranslationNames || ['useTranslation', 'getT', 'useT']) {
|
|
156
|
+
names.add(typeof hook === 'string' ? hook : hook.name);
|
|
157
|
+
}
|
|
158
|
+
for (const component of config.extract.transComponents || ['Trans'])
|
|
159
|
+
names.add(component.split('.').pop());
|
|
160
|
+
const alt = (set) => [...set].map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
|
|
161
|
+
re = new RegExp(`(?<!\\w)(?:(?:${alt(calls)})\\s*(?:\\?\\.\\s*)?[(<]|(?:${alt(names)})(?![\\w$]))`);
|
|
162
|
+
extractionSiteRegexes.set(config, re);
|
|
163
|
+
}
|
|
164
|
+
return re.test(code);
|
|
165
|
+
}
|
|
133
166
|
/**
|
|
134
167
|
* Processes an individual source file for translation key extraction.
|
|
135
168
|
*
|
|
@@ -195,6 +228,11 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
195
228
|
}
|
|
196
229
|
return;
|
|
197
230
|
}
|
|
231
|
+
// A file that mentions no translation function, hook or component cannot yield
|
|
232
|
+
// a key, so skip the parse and walk (#297). The pre-scan has already harvested
|
|
233
|
+
// its constants and types for the other files. onVisitNode plugins see every node.
|
|
234
|
+
if (!plugins.some(p => p.onVisitNode) && !mayContainExtractionSite(code, config))
|
|
235
|
+
return;
|
|
198
236
|
// When a plugin transformed a non-native file, always use tsx so SWC can
|
|
199
237
|
// handle TypeScript syntax that the plugin may have extracted from the file.
|
|
200
238
|
const effectiveExt = (!isNativeExt && wasTransformedByPlugin) ? '.tsx' : fileExt;
|
|
@@ -92,9 +92,10 @@ async function findKeys(config, logger = new ConsoleLogger(), fileErrors) {
|
|
|
92
92
|
for (const file of sourceFiles) {
|
|
93
93
|
await preScanFile(file, astVisitors, otherConfig, logger, fileErrors);
|
|
94
94
|
}
|
|
95
|
-
// 6b.
|
|
95
|
+
// 6b. Re-resolve declarations that refer to ones in files scanned after them, and
|
|
96
|
+
// mirror declarations onto the local names they were imported as, so that
|
|
96
97
|
// `import { ResourceStatus as Status }` resolves like the unaliased import.
|
|
97
|
-
sharedExpressionResolver.
|
|
98
|
+
sharedExpressionResolver.finishPreScan();
|
|
98
99
|
// 7. Extraction pass: all shared tables are now fully populated, so every
|
|
99
100
|
// identifier reference can be resolved regardless of file order.
|
|
100
101
|
for (const file of sourceFiles) {
|
|
@@ -138,13 +139,16 @@ async function processSourceFiles(config) {
|
|
|
138
139
|
const userIgnore = Array.isArray(config.extract.ignore)
|
|
139
140
|
? config.extract.ignore
|
|
140
141
|
: config.extract.ignore ? [config.extract.ignore] : [];
|
|
141
|
-
|
|
142
|
+
const files = await glob(config.extract.input, {
|
|
142
143
|
// Combine default ignore patterns with user-configured ones
|
|
143
144
|
ignore: [...defaultIgnore, ...userIgnore],
|
|
144
145
|
cwd: process.cwd(),
|
|
145
146
|
// A directory named e.g. `abc.tsx` matches the input globs
|
|
146
147
|
nodir: true,
|
|
147
148
|
});
|
|
149
|
+
// glob's order is not stable across runs, and when two call sites give one key
|
|
150
|
+
// different defaults the file visited first wins, so sort for reproducible output (#296)
|
|
151
|
+
return files.sort();
|
|
148
152
|
}
|
|
149
153
|
|
|
150
154
|
export { findKeys };
|