{{ message }}
Repository navigation
Expand file tree
/
Copy pathgenerateTranslations.ts
More file actions
executable file
·1517 lines (1300 loc) · 70.3 KB
/
Copy pathgenerateTranslations.ts
File metadata and controls
executable file
·1517 lines (1300 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bun
/*
* This script uses src/languages/en.ts as the source of truth, and leverages ChatGPT to generate translations for other languages.
*/
import GitHubUtils from '@github/libs/GithubUtils';
import decodeUnicode from '@libs/StringUtils/decodeUnicode';
import hashStr from '@libs/StringUtils/hash';
import {isTranslationTargetLocale, TRANSLATION_TARGET_LOCALES} from '@src/CONST/LOCALES';
import type {TranslationTargetLocale} from '@src/CONST/LOCALES';
import en from '@src/languages/en';
import type {TranslationPaths} from '@src/languages/types';
import type {TemplateExpression} from '@typescript/typescript6';
import ts from '@typescript/typescript6';
import {execFileSync} from 'child_process';
import * as dotenv from 'dotenv';
import {Str} from 'expensify-common';
import CLI from 'expensify-common/CLI';
import fs from 'fs';
// eslint-disable-next-line you-dont-need-lodash-underscore/get
import get from 'lodash/get';
import path from 'path';
import type {DiffResult} from './utils/Git';
import type Translator from './utils/Translator/Translator';
import type {StringWithContext} from './utils/Translator/types';
import type {TransformerResult} from './utils/TSCompilerUtils';
import COLORS from './utils/COLORS';
import Git from './utils/Git';
import Oxfmt from './utils/Oxfmt';
import PromisePool from './utils/PromisePool';
import ChatGPTTranslator from './utils/Translator/ChatGPTTranslator';
import DummyTranslator from './utils/Translator/DummyTranslator';
import TSCompilerUtils, {TransformerAction} from './utils/TSCompilerUtils';
const GENERATED_FILE_PREFIX = Str.dedent(`
/**
* _____ __ __
* / ___/__ ___ ___ _______ _/ /____ ___/ /
* / (_ / -_) _ \\/ -_) __/ _ \\\`/ __/ -_) _ /
* \\___/\\__/_//_/\\__/_/ \\_,_/\\__/\\__/\\_,_/
*
* This file was automatically generated. Please consider these alternatives before manually editing it:
*
* - Improve the prompts in prompts/translation, or
* - Improve context annotations in src/languages/en.ts
*/
`);
const tsPrinter = ts.createPrinter({removeComments: true});
/**
* If the estimated cost of translation exceeds this threshold (in USD), prompt the user for confirmation before proceeding.
*/
const COST_CONFIRMATION_THRESHOLD = 1;
/**
* This class encapsulates most of the non-CLI logic to generate translations.
* The primary reason it exists as a class is so we can import this file with no side effects at the top level of the script.
* This is useful for unit testing.
*
* At a high level, this is how it works:
* - It takes in a set of languages to generate translations for, a directory where translations are stored, and a file to use as the source of truth for translations.
* - It then uses the source file to recursively extract all string literals and template expressions, and uses ChatGPT to generate translations for each of them.
* - It then replaces the original string literals and template expressions with the translated ones, and writes the resulting code to a file.
* - It also formats the files using Oxfmt.
*/
class TranslationGenerator {
/**
* Regex to match context annotations.
*/
private static readonly CONTEXT_REGEX = /^\s*(?:\/{2}|\*|\/\*)?\s*@context\s+([^\n*/]+)/;
/**
* Regex to validate a full 40-character git SHA hash.
*/
private static readonly GIT_SHA_REGEX = /^[a-fA-F0-9]{40}$/;
/**
* HTTP 406 Not Acceptable - returned by GitHub API when diff is too large.
*/
private static readonly HTTP_STATUS_DIFF_TOO_LARGE = 406;
/**
* Extracts a readable error message from an unknown error type.
*/
private static getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
/**
* The languages to generate translations for.
*/
private readonly targetLanguages: TranslationTargetLocale[];
/**
* The directory where translations are stored.
*/
private readonly languagesDir: string;
/**
* The file to use as the source of truth for translations.
*/
private readonly sourceFile: ts.SourceFile;
/**
* Translator module to perform translations.
*/
private readonly translator: Translator;
/**
* Ref to use for existing translations.
*/
private readonly compareRef: string;
/**
* Paths to add (don't exist in target file yet).
*/
private readonly pathsToAdd: Set<TranslationPaths>;
/**
* Paths to modify (exist in target file and need retranslation).
*/
private readonly pathsToModify: Set<TranslationPaths>;
/**
* Paths to remove (only populated when using compareRef).
*/
private readonly pathsToRemove: Set<TranslationPaths>;
/**
* Should we print verbose logs?
*/
private readonly verbose: boolean;
/**
* Is this an incremental translation run, or a full translation run?
*/
private readonly isIncremental: boolean;
/**
* PR number for GitHub API diff (CI mode).
* When provided, uses GitHub API for accurate PR-specific diff instead of git diff.
* Requires GITHUB_TOKEN environment variable to be set.
*/
private readonly prNumber: number;
/**
* The git ref (SHA or branch) that the diff was computed against.
* Used by extractRemovedPaths to get the old version of en.ts at the correct commit.
* Set in buildPathsFromGitDiff: merge-base SHA (local or CI).
*/
private diffBase: string;
/**
* Whether the GitHub API was successfully used for the diff.
* When false (fallback to git diff or local mode), extractRemovedPaths uses Git.show instead of the GitHub API.
*/
private useGitHubAPI: boolean;
/**
* CLI instance for user prompts.
*/
/* eslint-disable @typescript-eslint/naming-convention */
private readonly cli: CLI<{
flags: {
'dry-run': {description: string};
verbose: {description: string};
};
namedArgs: {
locales: {
description: string;
default: TranslationTargetLocale[];
parse: (val: string) => TranslationTargetLocale[];
};
'compare-ref': {
description: string;
default: string;
parse: (val: string) => string;
};
'pr-number': {
description: string;
default: number;
parse: (val: string) => number;
};
paths: {
description: string;
parse: (val: string) => Set<TranslationPaths>;
supersedes: string[];
required: false;
};
};
}>;
/* eslint-enable @typescript-eslint/naming-convention */
/**
* If a complex template expression comes from an existing translation file rather than ChatGPT, then the hashes of its spans will be serialized from the translated version of those spans.
* This map provides us a way to look up the English hash for each translated span hash, so that when we're transforming the English file and we encounter a translated expression hash,
* we can look up English hash and use it to look up the translation for that hash (since the translation map is keyed by English string hashes).
*/
private readonly translatedSpanHashToEnglishSpanHash = new Map<number, number>();
/**
* Set of translation keys for strings that are arguments to Str.dedent() calls.
* These need special handling to preserve whitespace structure.
*/
private readonly dedentStringKeys = new Set<number>();
constructor() {
this.languagesDir = process.env.LANGUAGES_DIR ?? path.join(__dirname, '../src/languages');
const enSourceFile = path.join(this.languagesDir, 'en.ts');
/* eslint-disable @typescript-eslint/naming-convention */
this.cli = new CLI({
flags: {
'dry-run': {
description: 'If true, just do local mocked translations rather than making real requests to an AI translator.',
},
verbose: {
description: 'Should we print verbose logs?',
},
},
namedArgs: {
locales: {
description: 'Locales to generate translations for.',
default: Object.values(TRANSLATION_TARGET_LOCALES),
parse: (val: string): TranslationTargetLocale[] => {
const rawLocales = val.split(',');
const validatedLocales: TranslationTargetLocale[] = [];
for (const locale of rawLocales) {
if (!isTranslationTargetLocale(locale)) {
throw new Error(`Invalid locale ${String(locale)}`);
}
validatedLocales.push(locale);
}
return validatedLocales;
},
},
'compare-ref': {
description:
'For incremental translations, this ref is the previous version of the codebase to compare to. Only strings that changed or had their context changed since this ref will be retranslated.',
default: '',
parse: (val: string): string => {
if (!val.trim()) {
return val;
}
if (!Git.isValidRef(val)) {
throw new Error(`Invalid git reference: "${val}". Please provide a valid branch, tag, or commit hash.`);
}
return val;
},
},
'pr-number': {
description: 'PR number to get diff from GitHub API (CI only, requires GITHUB_TOKEN). When provided, uses GitHub API for accurate PR-specific diff instead of git diff.',
default: 0,
parse: (val: string): number => {
const parsed = parseInt(val, 10);
if (Number.isNaN(parsed) || parsed <= 0) {
throw new Error(`Invalid PR number: "${val}". Please provide a valid positive integer.`);
}
return parsed;
},
},
paths: {
description: 'Comma-separated list of specific translation paths to retranslate (e.g., "common.save,errors.generic").',
parse: (val: string): Set<TranslationPaths> => {
const rawPaths = val.split(',').map((translationPath) => translationPath.trim());
const validatedPaths = new Set<TranslationPaths>();
const invalidPaths: string[] = [];
for (const rawPath of rawPaths) {
if (get(en, rawPath)) {
validatedPaths.add(rawPath as TranslationPaths);
} else {
invalidPaths.push(rawPath);
}
}
if (invalidPaths.length > 0) {
throw new Error(`found the following invalid paths: ${JSON.stringify(invalidPaths)}`);
}
return validatedPaths;
},
supersedes: ['compare-ref'],
required: false,
},
},
} as const);
/* eslint-enable @typescript-eslint/naming-convention */
this.targetLanguages = this.cli.namedArgs.locales;
this.compareRef = this.cli.namedArgs['compare-ref'];
this.prNumber = this.cli.namedArgs['pr-number'];
this.diffBase = this.compareRef;
this.useGitHubAPI = false;
this.pathsToAdd = new Set<TranslationPaths>();
this.pathsToModify = this.cli.namedArgs.paths ?? new Set<TranslationPaths>();
this.pathsToRemove = new Set<TranslationPaths>();
this.verbose = this.cli.flags.verbose;
this.isIncremental = this.pathsToModify.size > 0 || !!this.compareRef || !!this.prNumber;
if (this.prNumber && !process.env.GITHUB_TOKEN) {
throw new Error('GITHUB_TOKEN environment variable is required when using --pr-number');
}
const sourceCode = fs.readFileSync(enSourceFile, 'utf8');
this.sourceFile = ts.createSourceFile(enSourceFile, sourceCode, ts.ScriptTarget.Latest, true);
if (this.cli.flags['dry-run']) {
console.log('🍸 Dry run enabled');
this.translator = new DummyTranslator();
} else {
if (!process.env.OPENAI_API_KEY) {
dotenv.config({path: path.resolve(__dirname, '../.env')});
if (!process.env.OPENAI_API_KEY) {
throw new Error('❌ OPENAI_API_KEY not found in environment.');
}
}
this.translator = new ChatGPTTranslator(process.env.OPENAI_API_KEY);
}
}
public async generateTranslations(): Promise<void> {
// map of translations for each locale
const translations = new Map<TranslationTargetLocale, Map<number, string>>();
if (this.isIncremental && this.pathsToModify.size === 0) {
await this.buildPathsFromGitDiff();
}
if (this.verbose) {
console.log(`🎯 Initial path sets:`);
console.log(` pathsToModify: ${Array.from(this.pathsToModify).join(', ')}`);
console.log(` pathsToAdd: ${Array.from(this.pathsToAdd).join(', ')}`);
console.log(` pathsToRemove: ${Array.from(this.pathsToRemove).join(', ')}`);
}
// Extract strings to translate once (locale-independent)
const stringsToTranslate = new Map<number, StringWithContext>();
this.extractStringsToTranslate(this.sourceFile, stringsToTranslate);
// Estimate cost and prompt user if needed (respects --yes/--no flags)
await this.promptForCostApproval(stringsToTranslate);
// Translate locales sequentially (each locale fully translates before the next begins)
for (const targetLanguage of this.targetLanguages) {
await this.generateTranslationsForLocale(targetLanguage, stringsToTranslate, translations.get(targetLanguage) ?? new Map<number, string>());
}
// Print error summary if there were any failures
this.printErrorSummary();
}
/**
* Print a summary of all translations that failed after exhausting retries.
*/
private printErrorSummary(): void {
const failures = this.translator.getFailedTranslations();
if (failures.length === 0) {
return;
}
console.log('\n');
console.log('═'.repeat(80));
console.log('❌ TRANSLATION ERRORS SUMMARY');
console.log('═'.repeat(80));
console.log(`\nThe following ${failures.length} translation(s) failed after exhausting all retries:`);
console.log('(The original text was used as a fallback for these translations)\n');
// Group failures by locale for cleaner output
const byLocale = new Map<string, typeof failures>();
for (const failure of failures) {
const existing = byLocale.get(failure.targetLang) ?? [];
existing.push(failure);
byLocale.set(failure.targetLang, existing);
}
for (const [locale, localeFailures] of byLocale) {
console.log(`\n📍 ${locale} (${localeFailures.length} failure${localeFailures.length > 1 ? 's' : ''}):`);
console.log('─'.repeat(60));
for (const failure of localeFailures) {
const truncatedText = failure.text.length > 60 ? `${failure.text.slice(0, 60)}...` : failure.text;
console.log(` • "${truncatedText}"`);
if (failure.id) {
console.log(` Path: ${failure.id}`);
}
const firstErrorLine = failure.error.split('\n').at(0) ?? failure.error;
console.log(` Error: ${firstErrorLine}`);
}
}
console.log(`\n${'═'.repeat(80)}`);
console.log(`Total failures: ${failures.length}`);
console.log(`${'═'.repeat(80)}\n`);
}
/**
* Generates translations for a single locale.
* Translations within a locale are processed in parallel (up to 8 at a time).
*/
private async generateTranslationsForLocale(
targetLanguage: TranslationTargetLocale,
stringsToTranslate: Map<number, StringWithContext>,
translationsForLocale: Map<number, string>,
): Promise<void> {
// Translate strings in parallel (up to 8 at a time)
const translationPool = new PromisePool<void>(8);
const translationPromises: Array<Promise<void>> = [];
for (const [key, {text, context, id}] of stringsToTranslate) {
if (translationsForLocale.has(key)) {
// This means that the translation for this key was already parsed from an existing translation file, so we don't need to translate it with ChatGPT
continue;
}
const translationPromise = translationPool.add(async () => {
// Special handling for dedent strings - preserve leading newline
let textToTranslate = text;
let hadLeadingNewline = false;
if (this.dedentStringKeys.has(key)) {
hadLeadingNewline = text.startsWith('\n');
textToTranslate = Str.dedent(text);
}
let result = await this.translator.translate(targetLanguage, textToTranslate, context, id);
// Special handling for dedent strings - add back leading newline if it was removed
if (hadLeadingNewline) {
result = `\n${result}`;
}
translationsForLocale.set(key, result);
});
translationPromises.push(translationPromise);
}
await Promise.all(translationPromises);
// Replace translated strings in the AST
let transformedSourceFile: ts.SourceFile;
if (this.isIncremental) {
// Make sure the target file exists
const targetPath = path.join(this.languagesDir, `${targetLanguage}.ts`);
if (!fs.existsSync(targetPath)) {
throw new Error(`Target file ${targetPath} does not exist for incremental translation`);
}
// Transform en.ts with path filtering for pathsToModify and pathsToAdd.
// The result is a "patch" of the main translations node, including only the paths that are added or modified,
// where the values are translated to the target language.
const enResult = ts.transform(this.sourceFile, [this.createTranslationTransformer(translationsForLocale)]);
const transformedEnSourceFile = enResult.transformed.at(0);
if (!transformedEnSourceFile) {
throw new Error('Failed to create translated patch from en.ts');
}
// Extract translated code strings from the transformed en.ts
const translatedCodeMap = new Map<string, string>();
this.extractTranslatedNodes(transformedEnSourceFile, translatedCodeMap);
enResult.dispose();
// Transform the target file using the translated node map
const existingContent = fs.readFileSync(targetPath, 'utf8');
const existingSourceFile = ts.createSourceFile(targetPath, existingContent, ts.ScriptTarget.Latest, true);
const targetTransformer = this.createIncrementalTargetTransformer(translatedCodeMap);
const targetResult = ts.transform(existingSourceFile, [targetTransformer]);
const transformedTargetResult = targetResult.transformed.at(0);
if (!transformedTargetResult) {
throw new Error('Failed to transform target file');
}
transformedSourceFile = transformedTargetResult;
targetResult.dispose();
} else {
// Full transformation for non-incremental mode - transform en.ts
const transformer = this.createTranslationTransformer(translationsForLocale);
const result = ts.transform(this.sourceFile, [transformer]);
transformedSourceFile = result.transformed.at(0) ?? this.sourceFile;
result.dispose();
}
// Import en.ts (addImport will check if it already exists)
transformedSourceFile = TSCompilerUtils.addImport(transformedSourceFile, 'en', './en', true);
// Generate translated TypeScript code
const translatedCode = decodeUnicode(tsPrinter.printFile(transformedSourceFile));
// Write to file
const outputPath = path.join(this.languagesDir, `${targetLanguage}.ts`);
fs.writeFileSync(outputPath, translatedCode, 'utf8');
// Enforce that the type of translated files matches en.ts
let finalFileContent = fs.readFileSync(outputPath, 'utf8');
finalFileContent = finalFileContent.replace('const translations = {', 'const translations: TranslationDeepObject<typeof en> = {');
finalFileContent = finalFileContent.replace('export default translations satisfies TranslationDeepObject<typeof translations>;', 'export default translations;');
fs.writeFileSync(outputPath, finalFileContent, 'utf8');
// Format the file with Oxfmt
Oxfmt.format(outputPath);
// Apply dedent formatting after Oxfmt so we have accurate source positions
this.formatDedentCallsInFile(outputPath);
// Format again with Oxfmt to ensure consistent formatting after dedent transformation
Oxfmt.format(outputPath);
// Add a fun ascii art touch with a helpful message
// This must be done AFTER formatDedentCallsInFile since that function uses the printer which removes comments
finalFileContent = fs.readFileSync(outputPath, 'utf8');
if (!finalFileContent.startsWith(GENERATED_FILE_PREFIX)) {
finalFileContent = `${GENERATED_FILE_PREFIX}${finalFileContent}`;
}
fs.writeFileSync(outputPath, finalFileContent, 'utf8');
console.log(`✅ Translated file created: ${outputPath}`);
}
/**
* Estimates the cost of translating the given strings and prompts the user for confirmation if the cost exceeds the threshold.
* If the user declines, the process exits.
* Skips prompting in dry-run mode since no real API calls are made.
*/
private async promptForCostApproval(stringsToTranslate: Map<number, StringWithContext>): Promise<void> {
const numStrings = stringsToTranslate.size;
const numLocales = this.targetLanguages.length;
if (numStrings === 0 || numLocales === 0) {
return;
}
const estimatedCost = await this.translator.estimateCost(Array.from(stringsToTranslate.values()), this.targetLanguages);
if (estimatedCost > COST_CONFIRMATION_THRESHOLD) {
console.warn(
`${COLORS.YELLOW}${Str.dedent(`
⚠️ Warning: This translation will cost approximately $${estimatedCost.toFixed(2)} USD.
Strings to translate: ${stringsToTranslate.size.toLocaleString()}
Target locales: ${numLocales}
`)}${COLORS.RESET}`,
);
if (!this.isIncremental) {
const scriptPath = path.relative(process.cwd(), path.resolve(__dirname, 'generateTranslations.ts'));
console.log(
`Note: You are currently running a full retranslation of the entire \`en.ts\` file. To incrementally translate only what you changed on your branch, run: ${COLORS.BLUE}\`bun ${scriptPath} --compare-ref main\`${COLORS.RESET}\n`,
);
}
const userConfirmed = await this.cli.promptUserConfirmation(`Do you want to proceed? ${COLORS.BOLD}Estimated cost: $${estimatedCost.toFixed(2)} USD.${COLORS.RESET} (y/n) `);
if (!userConfirmed) {
console.log('\n❌ Translation cancelled by user.');
process.exit(0);
}
console.log('\n✅ Proceeding with translation...\n');
}
}
/**
* Each translation file should have an object called translations that's later default-exported.
* This function finds that object for a given SourceFile
*/
private findTranslationsNode(sourceFile: ts.SourceFile): ts.ObjectLiteralExpression {
const defaultExport = TSCompilerUtils.findDefaultExport(sourceFile);
if (!defaultExport) {
throw new Error('Could not find default export in source file');
}
const defaultExportIdentifier = TSCompilerUtils.extractIdentifierFromExpression(defaultExport);
const variableDeclaration = TSCompilerUtils.resolveDeclaration(defaultExportIdentifier ?? '', sourceFile);
if (!variableDeclaration || !ts.isVariableDeclaration(variableDeclaration) || !variableDeclaration.initializer) {
throw new Error('Could not find translations object literal in source file');
}
if (!ts.isObjectLiteralExpression(variableDeclaration.initializer)) {
throw new Error('Default export is not an object literal expression');
}
return variableDeclaration.initializer;
}
/**
* Should we translate the given node?
*/
private shouldTranslateNode(node: ts.Node): node is ts.StringLiteral | ts.TemplateExpression | ts.NoSubstitutionTemplateLiteral {
// We only translate string literals and template expressions
if (!ts.isStringLiteral(node) && !ts.isTemplateExpression(node) && !ts.isNoSubstitutionTemplateLiteral(node)) {
return false;
}
// Don't translate property keys (the name part of property assignments)
if (node.parent && ts.isPropertyAssignment(node.parent) && node.parent.name === node) {
return false;
}
// Don't translate any strings or expressions that affect code execution by being part of control flow.
// We want to translate only strings that are "leaves" or "results" of any expression or code block
const isPartOfControlFlow =
node.parent &&
// imports and exports
(ts.isImportDeclaration(node.parent) ||
ts.isExportDeclaration(node.parent) ||
// Switch/case clause
ts.isCaseClause(node.parent) ||
// any binary expression except coalescing operators, += operators, and string concatenation
(ts.isBinaryExpression(node.parent) &&
node.parent.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionToken &&
node.parent.operatorToken.kind !== ts.SyntaxKind.BarBarToken &&
node.parent.operatorToken.kind !== ts.SyntaxKind.PlusEqualsToken &&
// Allow string concatenation with +
!(node.parent.operatorToken.kind === ts.SyntaxKind.PlusToken && TSCompilerUtils.isStringConcatenationChain(node.parent))));
if (isPartOfControlFlow) {
return false;
}
// Don't translate any logs
const isArgumentToLogFunction =
node.parent &&
ts.isCallExpression(node.parent) &&
ts.isPropertyAccessExpression(node.parent.expression) &&
((ts.isIdentifier(node.parent.expression.expression) && node.parent.expression.expression.getText() === 'console') ||
(ts.isIdentifier(node.parent.expression.expression) && node.parent.expression.expression.getText() === 'Log'));
if (isArgumentToLogFunction) {
return false;
}
// Don't translate a string that's a literal type annotation
if (ts.isLiteralTypeNode(node.parent)) {
return false;
}
// Don't translate object keys
if (ts.isComputedPropertyName(node.parent)) {
return false;
}
// Only translate string literals if they contain at least one real letter
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
// \p{L} matches a-z, à-ö, Α-Ω, Ж, 文, … – but NOT digits, emoji, punctuation, etc.
return /\p{L}/u.test(node.text);
}
// Only translate a template expression if it contains alphabet characters outside the spans
let staticText = node.head.text;
for (const span of node.templateSpans) {
staticText += span.literal.text;
}
return /[a-zA-Z]/.test(staticText);
}
/**
* Check if a given translation path should be translated based on the paths filter.
* If no paths are specified, all paths should be translated.
* If paths are specified, only paths that match exactly or are nested under a specified path should be translated.
*/
private shouldTranslatePath(currentPath: string): boolean {
if (!this.isIncremental) {
return true;
}
// Check if path is in either pathsToModify or pathsToAdd
const allPathsToTranslate = new Set([...this.pathsToModify, ...this.pathsToAdd]);
for (const targetPath of allPathsToTranslate) {
if (currentPath === targetPath || currentPath.startsWith(`${targetPath}.`)) {
return true;
}
}
return false;
}
/**
* Check if a call expression is a dedent() call (either standalone or Str.dedent()).
*/
private isDedentCallExpression(expression: ts.LeftHandSideExpression): boolean {
if (ts.isIdentifier(expression) && expression.text === 'dedent') {
return true;
}
return ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === 'Str' && expression.name.text === 'dedent';
}
/**
* Check if a node is a direct argument to a Str.dedent() call.
*/
private isArgumentToDedent(node: ts.Node): boolean {
if (!node.parent || !ts.isCallExpression(node.parent)) {
return false;
}
const callExpression = node.parent;
return this.isDedentCallExpression(callExpression.expression) && callExpression.arguments.includes(node as ts.Expression);
}
/**
* Is a given expression (i.e: template placeholder) "simple"?
* We define an expression as "simple" if it is an identifier or property access expression. Anything else is complex.
*
* @example ${name} => true
* @example ${user.firstName} => true
* @example ${CONST.REPORT.TYPES.EXPENSE} => true
* @example ${name ?? 'someone'} => false
* @example ${condition ? 'A' : 'B'} => false
*/
private isSimpleExpression(expr: ts.Expression): boolean {
return ts.isIdentifier(expr) || ts.isPropertyAccessExpression(expr) || ts.isElementAccessExpression(expr);
}
/**
* Is the given template expression "simple"? (i.e: can it be sent directly to ChatGPT to be translated)
* We define a template expression as "simple" if each of its spans' expressions are simple (as defined by this.isSimpleTemplateSpan)
*
* @example `Hello, ${name}!` => true
* @example `Welcome ${user.firstName}` => true
* @example `Submit ${CONST.REPORT.TYPES.EXPENSE} report` => true
* @example `Pay ${name ?? 'someone'}` => false
* @example `Edit ${condition ? 'A' : 'B'}` => false
*/
private isSimpleTemplateExpression(node: ts.TemplateExpression): boolean {
return node.templateSpans.every((span) => this.isSimpleExpression(span.expression));
}
/**
* Extract context annotation value from a string (comment or text).
* Returns the context value if found, undefined otherwise.
*/
private extractContextAnnotationFromString(text: string): string | undefined {
const match = text.match(TranslationGenerator.CONTEXT_REGEX);
return match?.[1].trim();
}
/**
* Check if a specific line in the source file contains a context annotation.
*/
private lineContainsContextAnnotation(lineNumber: number, sourceFile: ts.SourceFile): boolean {
const lines = sourceFile.getFullText().split('\n');
const line = lines.at(lineNumber - 1); // Convert to 0-based index
if (!line) {
return false;
}
return this.extractContextAnnotationFromString(line) !== undefined;
}
/**
* Extract any leading context annotation for a given node.
*/
private getContextForNode(node: ts.Node): string | undefined {
// First, check for an inline context comment
const inlineContext = this.extractContextAnnotationFromString(node.getFullText());
if (inlineContext) {
return inlineContext;
}
// Otherwise, look for the nearest ancestor that may have a comment attached.
// For now, we only support property assignments.
const nearestPropertyAssignmentAncestor = TSCompilerUtils.findAncestor(node, (n): n is ts.PropertyAssignment => ts.isPropertyAssignment(n));
if (!nearestPropertyAssignmentAncestor) {
return undefined;
}
// Search through comments looking for a context comment
const commentRanges = ts.getLeadingCommentRanges(this.sourceFile.getFullText(), nearestPropertyAssignmentAncestor.getFullStart()) ?? [];
for (const range of commentRanges.reverse()) {
const commentText = this.sourceFile.getFullText().slice(range.pos, range.end);
const context = this.extractContextAnnotationFromString(commentText);
if (context) {
return context;
}
}
// No context comments were found
return undefined;
}
/**
* Generate a hash of the string representation of a node along with any context comments.
*/
private getTranslationKey(node: ts.Node): number {
if (!ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node) && !ts.isTemplateExpression(node)) {
throw new Error(`Cannot generate translation key for node: ${node.getText()}`);
}
// Trim leading whitespace, quotation marks, and backticks
let keyBase = node
.getText()
.trim()
.replaceAll(/^['"`]/g, '')
.replaceAll(/['"`]$/g, '');
const context = this.getContextForNode(node);
if (context) {
keyBase += context;
}
return hashStr(keyBase);
}
/**
* Recursively extract all string literals and templates to translate from the subtree rooted at the given node.
* Simple templates (as defined by this.isSimpleTemplateExpression) can be translated directly.
* Complex templates must have each of their spans recursively translated first, so we'll extract all the lowest-level strings to translate.
* Then complex templates will be serialized with a hash of complex spans in place of the span text, and we'll translate that.
*/
private extractStringsToTranslate(node: ts.Node, stringsToTranslate: Map<number, StringWithContext>, currentPath = '') {
if (this.shouldTranslateNode(node)) {
// Check if this translation path should be included based on the paths filter
if (!this.shouldTranslatePath(currentPath)) {
return; // Skip this node and its children if the path doesn't match
}
const context = this.getContextForNode(node);
const translationKey = this.getTranslationKey(node);
// Track if this node is an argument to Str.dedent()
if (this.isArgumentToDedent(node)) {
this.dedentStringKeys.add(translationKey);
}
// String literals and no-substitution templates can be translated directly
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
stringsToTranslate.set(translationKey, {
text: node.text,
context,
id: currentPath,
});
}
// Template expressions must be encoded directly before they can be translated
else if (ts.isTemplateExpression(node)) {
if (this.isSimpleTemplateExpression(node)) {
stringsToTranslate.set(translationKey, {
text: this.templateExpressionToString(node),
context,
id: currentPath,
});
} else {
if (this.verbose) {
console.debug('😵💫 Encountered complex template, recursively translating its spans first:', node.getText());
}
for (const span of node.templateSpans) {
this.extractStringsToTranslate(span, stringsToTranslate, currentPath);
}
stringsToTranslate.set(translationKey, {
text: this.templateExpressionToString(node),
context,
id: currentPath,
});
}
}
}
node.forEachChild(
TSCompilerUtils.createPathAwareVisitor((child, childPath) => {
this.extractStringsToTranslate(child, stringsToTranslate, childPath);
}, currentPath),
);
}
/**
* Convert a template expression into a plain string representation that can be predictably serialized.
* All ${...} spans containing complex expressions are replaced in the string by hashes of the expression text.
*
* @example templateExpressionToString(`Edit ${action?.type === 'IOU' ? 'expense' : 'comment'} on ${date}`)
* => `Edit ${HASH1} on ${date}`
*/
private templateExpressionToString(expression: TemplateExpression): string {
let result = expression.head.text;
for (const span of expression.templateSpans) {
if (this.isSimpleExpression(span.expression)) {
result += `\${${span.expression.getText()}}`;
} else {
result += `\${${hashStr(span.expression.getText())}}`;
}
result += span.literal.text;
}
return result;
}
/**
* Convert our string-encoded template expression to a template expression.
* If the template contains any complex spans, those must be translated first, and those translations need to be passed in.
*/
private stringToTemplateExpression(input: string, translatedComplexExpressions = new Map<number, ts.Expression>()): ts.TemplateExpression {
const regex = /\$\{([^}]*)}/g;
const matches = [...input.matchAll(regex)];
const headText = input.slice(0, matches.at(0)?.index ?? input.length);
const templateHead = ts.factory.createTemplateHead(headText);
const spans: ts.TemplateSpan[] = [];
for (let i = 0; i < matches.length; i++) {
const match = matches.at(i);
if (!match) {
continue;
}
const [fullMatch, placeholder] = match;
let expression: ts.Expression;
const trimmed = placeholder.trim();
if (/^\d+$/.test(trimmed)) {
// It's a hash reference to a complex span
const hashed = Number(trimmed);
// If the translated, serialized template expression came from an existing translation file, then the hash of the complex expression will be a hash of the translated expression.
// If the translated, serialized template expression came from ChatGPT, then the hash of the complex expression will be a hash of the English expression.
// Meanwhile, translatedComplexExpressions is keyed by English hashes, because it comes from createTransformer, which is parsing and transforming an English file.
// So when rebuilding the template expression from its serialized form, we first search for the translated expression assuming the expression is serialized with English hashes.
// If that fails, we look up the English expression hash associated with the translated expression hash, then look up the translated expression using the English hash.
const translatedExpression = translatedComplexExpressions.get(hashed) ?? translatedComplexExpressions.get(this.translatedSpanHashToEnglishSpanHash.get(hashed) ?? hashed);
if (!translatedExpression) {
throw new Error(`No template found for hash: ${hashed}`);
}
expression = translatedExpression;
} else {
// Assume it's a simple identifier or property access
expression = ts.factory.createIdentifier(trimmed);
}
const startOfMatch = match.index;
const nextStaticTextStart = startOfMatch + fullMatch.length;
const nextStaticTextEnd = i + 1 < matches.length ? matches.at(i + 1)?.index : input.length;
const staticText = input.slice(nextStaticTextStart, nextStaticTextEnd);
const literal = i === matches.length - 1 ? ts.factory.createTemplateTail(staticText) : ts.factory.createTemplateMiddle(staticText);
spans.push(ts.factory.createTemplateSpan(expression, literal));
}
return ts.factory.createTemplateExpression(templateHead, spans);
}
/**
* Build dot-notation paths from git diff by analyzing changed lines.
* Uses GitHub API diff when --pr-number is provided (CI mode), falls back to git diff otherwise.
*/
private async buildPathsFromGitDiff(): Promise<void> {
try {
// Get the relative path from the git repo root
const relativePath = path.relative(process.cwd(), path.join(this.languagesDir, 'en.ts'));
let diffResult: DiffResult;
if (this.prNumber) {
// CI mode: Use GitHub API for accurate PR-specific diff
try {
if (this.verbose) {
console.log(`🌐 Using GitHub API diff for PR #${this.prNumber}`);
}
// GitHub's PR diff is a three-dot diff (merge-base...head), so we need the
// actual merge-base commit, not the tip of the base branch.
this.diffBase = await GitHubUtils.getPullRequestMergeBaseSHA(this.prNumber);
this.useGitHubAPI = true;
if (this.verbose) {
console.log(`📌 PR merge-base SHA: ${this.diffBase.slice(0, 8)}`);
}
const prDiff = await GitHubUtils.getPullRequestDiff(this.prNumber);
const parsedDiff = Git.parseDiff(prDiff);
// Filter to only en.ts
const enTsFile = parsedDiff.files.find((f) => f.filePath === relativePath);
diffResult = {
files: enTsFile ? [enTsFile] : [],
hasChanges: !!enTsFile,
};
if (this.verbose) {
const enTsMatchCount = diffResult.hasChanges ? 1 : 0;
console.log(`📄 GitHub API diff: ${parsedDiff.files.length} files total, ${enTsMatchCount} matching en.ts`);
}
} catch (apiError: unknown) {
// Fallback to git diff if GitHub API fails (e.g., 406 for large diffs >20K lines)
const isLargeDiff = apiError !== null && typeof apiError === 'object' && 'status' in apiError && apiError.status === TranslationGenerator.HTTP_STATUS_DIFF_TOO_LARGE;
if (isLargeDiff) {
console.warn('⚠️ GitHub API diff too large (>20K lines or >1MB). Falling back to git diff.');
} else {
console.warn(`⚠️ GitHub API failed: ${TranslationGenerator.getErrorMessage(apiError)}. Falling back to git diff.`);
}
this.useGitHubAPI = false;
if (this.compareRef) {
this.diffBase = this.compareRef;
diffResult = Git.diff(this.compareRef, undefined, relativePath);
} else {
throw new Error('GitHub API failed and no --compare-ref provided for fallback');
}
}
} else {
// Local mode: Use git merge-base for accurate diff
You can’t perform that action at this time.
