-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathcontrol-ui-i18n.ts
More file actions
1876 lines (1722 loc) · 59.1 KB
/
Copy pathcontrol-ui-i18n.ts
File metadata and controls
1876 lines (1722 loc) · 59.1 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
// Control Ui I18N script supports OpenClaw repository automation.
import { spawn, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync } from "node:fs";
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { completeSimple, type AssistantMessage, type Model } from "openclaw/plugin-sdk/llm";
import * as ts from "typescript";
import { formatErrorMessage } from "../src/infra/errors.ts";
import { resolveWindowsTaskkillPath } from "./lib/windows-taskkill.mjs";
const { formatGeneratedModule } = (await import(
new URL("./lib/format-generated-module.mjs", import.meta.url).href
)) as {
formatGeneratedModule: (
source: string,
options: {
errorLabel: string;
outputPath: string;
repoRoot: string;
},
) => string;
};
interface TranslationMap {
[key: string]: string | TranslationMap;
}
type TranslationValue = string | { [key: string]: TranslationValue };
type LocaleEntry = {
exportName: string;
fileName: string;
languageKey: string;
locale: string;
};
type GlossaryEntry = {
source: string;
target: string;
};
type RunProcessParentSignalState = {
done: boolean;
signal: NodeJS.Signals | null;
};
type TranslationMemoryEntry = {
cache_key: string;
model: string;
provider: string;
segment_id: string;
source_path: string;
src_lang: string;
text: string;
text_hash: string;
tgt_lang: string;
translated: string;
updated_at: string;
};
type LocaleMeta = {
fallbackKeys: string[];
generatedAt: string;
locale: string;
model: string;
provider: string;
sourceHash: string;
totalKeys: number;
translatedKeys: number;
workflow: number;
};
type TranslationBatchItem = {
cacheKey: string;
key: string;
text: string;
textHash: string;
};
type RawCopyFinding = {
kind: "html-attribute" | "html-text" | "object-property";
line: number;
name: string;
path: string;
text: string;
};
type RawCopyBaselineEntry = {
count: number;
kind: RawCopyFinding["kind"];
name: string;
path: string;
text: string;
};
type RawCopyBaseline = {
version: number;
entries: RawCopyBaselineEntry[];
};
const CONTROL_UI_I18N_WORKFLOW = 1;
const DEFAULT_OPENAI_MODEL = "gpt-5.5";
const DEFAULT_ANTHROPIC_MODEL = "claude-opus-4-6";
const DEFAULT_PROVIDER = "openai";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "..");
const LOCALES_DIR = path.join(ROOT, "ui", "src", "i18n", "locales");
const I18N_ASSETS_DIR = path.join(ROOT, "ui", "src", "i18n", ".i18n");
const SOURCE_LOCALE_PATH = path.join(LOCALES_DIR, "en.ts");
const SOURCE_LOCALE = "en";
const CONTROL_UI_SOURCE_DIR = path.join(ROOT, "ui", "src", "ui");
const RAW_COPY_BASELINE_PATH = path.join(I18N_ASSETS_DIR, "raw-copy-baseline.json");
const RAW_COPY_BASELINE_VERSION = 1;
const MAX_BATCH_ITEMS = 20;
const DEFAULT_BATCH_CHAR_BUDGET = 2_000;
const TRANSLATE_MAX_ATTEMPTS = 2;
const TRANSLATE_BASE_DELAY_MS = 15_000;
const DEFAULT_PROMPT_TIMEOUT_MS = 120_000;
const RUN_PROCESS_OUTPUT_MAX_CHARS = 1024 * 1024;
const RUN_PROCESS_TIMEOUT_MS = 120_000;
const RUN_PROCESS_KILL_GRACE_MS = 5_000;
const activeRunProcessParentSignals = new Set<RunProcessParentSignalState>();
const PROGRESS_HEARTBEAT_MS = 30_000;
const ENV_PROVIDER = "OPENCLAW_CONTROL_UI_I18N_PROVIDER";
const ENV_MODEL = "OPENCLAW_CONTROL_UI_I18N_MODEL";
const ENV_THINKING = "OPENCLAW_CONTROL_UI_I18N_THINKING";
const ENV_BATCH_CHAR_BUDGET = "OPENCLAW_CONTROL_UI_I18N_BATCH_CHAR_BUDGET";
const ENV_PROMPT_TIMEOUT = "OPENCLAW_CONTROL_UI_I18N_PROMPT_TIMEOUT";
const ENV_AUTH_OPTIONAL = "OPENCLAW_CONTROL_UI_I18N_AUTH_OPTIONAL";
type TranslationProvider = "openai" | "anthropic";
const TRANSLATION_PROVIDER_DEFAULTS: Record<TranslationProvider, Omit<Model, "id" | "name">> = {
openai: {
api: "openai-responses",
provider: "openai",
baseUrl: "https://api.openai.com/v1",
reasoning: true,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 400_000,
maxTokens: 32_000,
},
anthropic: {
api: "anthropic-messages",
provider: "anthropic",
baseUrl: "https://api.anthropic.com",
reasoning: true,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200_000,
maxTokens: 32_000,
},
};
const LOCALE_ENTRIES: readonly LocaleEntry[] = [
{ locale: "zh-CN", fileName: "zh-CN.ts", exportName: "zh_CN", languageKey: "zhCN" },
{ locale: "zh-TW", fileName: "zh-TW.ts", exportName: "zh_TW", languageKey: "zhTW" },
{ locale: "pt-BR", fileName: "pt-BR.ts", exportName: "pt_BR", languageKey: "ptBR" },
{ locale: "de", fileName: "de.ts", exportName: "de", languageKey: "de" },
{ locale: "es", fileName: "es.ts", exportName: "es", languageKey: "es" },
{ locale: "ja-JP", fileName: "ja-JP.ts", exportName: "ja_JP", languageKey: "jaJP" },
{ locale: "ko", fileName: "ko.ts", exportName: "ko", languageKey: "ko" },
{ locale: "fr", fileName: "fr.ts", exportName: "fr", languageKey: "fr" },
{ locale: "ar", fileName: "ar.ts", exportName: "ar", languageKey: "ar" },
{ locale: "it", fileName: "it.ts", exportName: "it", languageKey: "it" },
{ locale: "tr", fileName: "tr.ts", exportName: "tr", languageKey: "tr" },
{ locale: "uk", fileName: "uk.ts", exportName: "uk", languageKey: "uk" },
{ locale: "id", fileName: "id.ts", exportName: "id", languageKey: "id" },
{ locale: "pl", fileName: "pl.ts", exportName: "pl", languageKey: "pl" },
{ locale: "th", fileName: "th.ts", exportName: "th", languageKey: "th" },
{ locale: "vi", fileName: "vi.ts", exportName: "vi", languageKey: "vi" },
{ locale: "nl", fileName: "nl.ts", exportName: "nl", languageKey: "nl" },
{ locale: "fa", fileName: "fa.ts", exportName: "fa", languageKey: "fa" },
];
const DEFAULT_GLOSSARY: readonly GlossaryEntry[] = [
{ source: "OpenClaw", target: "OpenClaw" },
{ source: "Gateway", target: "Gateway" },
{ source: "Control UI", target: "Control UI" },
{ source: "Skills", target: "Skills" },
{ source: "Tailscale", target: "Tailscale" },
{ source: "WhatsApp", target: "WhatsApp" },
{ source: "Telegram", target: "Telegram" },
{ source: "Discord", target: "Discord" },
{ source: "Signal", target: "Signal" },
{ source: "iMessage", target: "iMessage" },
];
function usage(): never {
console.error(
[
"Usage:",
" node --import tsx scripts/control-ui-i18n.ts check",
" node --import tsx scripts/control-ui-i18n.ts sync [--write] [--locale <code>] [--force]",
].join("\n"),
);
process.exit(2);
}
function parseArgs(argv: string[]) {
const [command, ...rest] = argv;
if (command !== "check" && command !== "sync") {
usage();
}
let localeFilter: string | null = null;
let write = false;
let force = false;
for (let index = 0; index < rest.length; index += 1) {
const part = rest[index];
switch (part) {
case "--locale":
localeFilter = rest[index + 1] ?? null;
index += 1;
break;
case "--write":
write = true;
break;
case "--force":
force = true;
break;
default:
usage();
}
}
if (command === "check" && write) {
usage();
}
return {
command,
force,
localeFilter,
write,
};
}
function prettyLanguageLabel(locale: string): string {
switch (locale) {
case "en":
return "English";
case "zh-CN":
return "Simplified Chinese";
case "zh-TW":
return "Traditional Chinese";
case "pt-BR":
return "Brazilian Portuguese";
case "ja-JP":
return "Japanese";
case "ko":
return "Korean";
case "fr":
return "French";
case "ar":
return "Arabic";
case "it":
return "Italian";
case "tr":
return "Turkish";
case "uk":
return "Ukrainian";
case "id":
return "Indonesian";
case "pl":
return "Polish";
case "th":
return "Thai";
case "vi":
return "Vietnamese";
case "nl":
return "Dutch";
case "fa":
return "Persian";
case "de":
return "German";
case "es":
return "Spanish";
default:
return locale;
}
}
function resolveConfiguredProvider(): string {
const configured = process.env[ENV_PROVIDER]?.trim();
if (configured) {
return configured;
}
if (process.env.OPENAI_API_KEY?.trim()) {
return "openai";
}
if (process.env.ANTHROPIC_API_KEY?.trim()) {
return "anthropic";
}
return DEFAULT_PROVIDER;
}
function resolveConfiguredModel(): string {
const configured = process.env[ENV_MODEL]?.trim();
if (configured) {
return configured;
}
return resolveConfiguredProvider() === "anthropic"
? DEFAULT_ANTHROPIC_MODEL
: DEFAULT_OPENAI_MODEL;
}
function hasTranslationProvider(): boolean {
return Boolean(process.env.OPENAI_API_KEY?.trim() || process.env.ANTHROPIC_API_KEY?.trim());
}
function resolveKnownTranslationProvider(): TranslationProvider {
const provider = resolveConfiguredProvider();
if (provider === "openai" || provider === "anthropic") {
return provider;
}
throw new Error(`Unsupported translation provider: ${provider}`);
}
function normalizeText(text: string): string {
return text.trim().split(/\s+/).join(" ");
}
function sha256(input: string | Uint8Array): string {
return createHash("sha256").update(input).digest("hex");
}
function hashText(text: string): string {
return sha256(normalizeText(text));
}
function cacheNamespace(): string {
return [
`wf=${CONTROL_UI_I18N_WORKFLOW}`,
"engine=openclaw-llm",
`provider=${resolveConfiguredProvider()}`,
`model=${resolveConfiguredModel()}`,
].join("|");
}
function cacheKey(segmentId: string, textHash: string, targetLocale: string): string {
return sha256([cacheNamespace(), SOURCE_LOCALE, targetLocale, segmentId, textHash].join("|"));
}
function localeFilePath(entry: LocaleEntry): string {
return path.join(LOCALES_DIR, entry.fileName);
}
function glossaryPath(entry: LocaleEntry): string {
return path.join(I18N_ASSETS_DIR, `glossary.${entry.locale}.json`);
}
function metaPath(entry: LocaleEntry): string {
return path.join(I18N_ASSETS_DIR, `${entry.locale}.meta.json`);
}
function tmPath(entry: LocaleEntry): string {
return path.join(I18N_ASSETS_DIR, `${entry.locale}.tm.jsonl`);
}
async function importLocaleModule<T>(filePath: string): Promise<T> {
const stats = await stat(filePath);
const href = `${pathToFileURL(filePath).href}?ts=${stats.mtimeMs}`;
return (await import(href)) as T;
}
async function loadLocaleMap(filePath: string, exportName: string): Promise<TranslationMap | null> {
if (!existsSync(filePath)) {
return null;
}
const mod = await importLocaleModule<Record<string, TranslationMap>>(filePath);
return mod[exportName] ?? null;
}
function flattenTranslations(value: TranslationMap, prefix = "", out = new Map<string, string>()) {
for (const [key, nested] of Object.entries(value)) {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof nested === "string") {
out.set(fullKey, nested);
continue;
}
flattenTranslations(nested, fullKey, out);
}
return out;
}
function setNestedValue(root: TranslationMap, dottedKey: string, value: string) {
const parts = dottedKey.split(".");
let cursor: TranslationMap = root;
for (let index = 0; index < parts.length - 1; index += 1) {
const key = parts[index];
const next = cursor[key];
if (!next || typeof next === "string") {
const replacement: TranslationMap = {};
cursor[key] = replacement;
cursor = replacement;
continue;
}
cursor = next;
}
cursor[parts.at(-1)!] = value;
}
function compareStringArrays(left: string[], right: string[]) {
if (left.length !== right.length) {
return false;
}
return left.every((value, index) => value === right[index]);
}
export type PlaceholderMismatch = {
key: string;
locale: string;
sourcePlaceholders: string[];
translatedPlaceholders: string[];
};
function extractTranslationPlaceholders(text: string): string[] {
return [...new Set([...text.matchAll(/\{(\w+)\}/g)].map((match) => match[1] ?? ""))]
.filter(Boolean)
.toSorted((left, right) => left.localeCompare(right));
}
export function findPlaceholderMismatches(
sourceFlat: ReadonlyMap<string, string>,
translatedFlat: ReadonlyMap<string, string>,
locale: string,
): PlaceholderMismatch[] {
const mismatches: PlaceholderMismatch[] = [];
for (const [key, sourceText] of sourceFlat.entries()) {
const sourcePlaceholders = extractTranslationPlaceholders(sourceText);
const translatedPlaceholders = extractTranslationPlaceholders(translatedFlat.get(key) ?? "");
if (!compareStringArrays(sourcePlaceholders, translatedPlaceholders)) {
mismatches.push({
key,
locale,
sourcePlaceholders,
translatedPlaceholders,
});
}
}
return mismatches;
}
function assertPlaceholderParity(
sourceFlat: ReadonlyMap<string, string>,
translatedFlat: ReadonlyMap<string, string>,
locale: string,
) {
const mismatches = findPlaceholderMismatches(sourceFlat, translatedFlat, locale);
if (mismatches.length === 0) {
return;
}
const details = mismatches
.slice(0, 20)
.map(
(mismatch) =>
`${mismatch.locale}:${mismatch.key} expected {${mismatch.sourcePlaceholders.join("},{")}} got {${mismatch.translatedPlaceholders.join("},{")}}`,
)
.join("\n");
throw new Error(
[
`control-ui-i18n placeholder mismatch detected for ${locale}.`,
details,
mismatches.length > 20 ? `...and ${mismatches.length - 20} more` : "",
]
.filter(Boolean)
.join("\n"),
);
}
function isIdentifier(value: string): boolean {
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);
}
function renderTranslationValue(value: TranslationValue, indent = 0): string {
if (typeof value === "string") {
return JSON.stringify(value);
}
const entries = Object.entries(value);
if (entries.length === 0) {
return "{}";
}
const pad = " ".repeat(indent);
const innerPad = " ".repeat(indent + 1);
return `{\n${entries
.map(([key, nested]) => {
const renderedKey = isIdentifier(key) ? key : JSON.stringify(key);
return `${innerPad}${renderedKey}: ${renderTranslationValue(nested, indent + 1)},`;
})
.join("\n")}\n${pad}}`;
}
function renderLocaleModule(entry: LocaleEntry, value: TranslationMap): string {
return [
"// Generated locale bundle for Control UI translations.",
"// Run `pnpm ui:i18n:sync` instead of editing this file directly.",
'import type { TranslationMap } from "../lib/types.ts";',
"",
`export const ${entry.exportName}: TranslationMap = ${renderTranslationValue(value)};`,
"",
].join("\n");
}
async function loadGlossary(filePath: string): Promise<GlossaryEntry[]> {
if (!existsSync(filePath)) {
return [];
}
const raw = await readFile(filePath, "utf8");
const parsed = JSON.parse(raw) as GlossaryEntry[];
return Array.isArray(parsed) ? parsed : [];
}
function renderGlossary(entries: readonly GlossaryEntry[]): string {
return `${JSON.stringify(entries, null, 2)}\n`;
}
async function loadMeta(filePath: string): Promise<LocaleMeta | null> {
if (!existsSync(filePath)) {
return null;
}
const raw = await readFile(filePath, "utf8");
return JSON.parse(raw) as LocaleMeta;
}
function renderMeta(meta: LocaleMeta): string {
return `${JSON.stringify(meta, null, 2)}\n`;
}
async function loadTranslationMemory(
filePath: string,
): Promise<Map<string, TranslationMemoryEntry>> {
const entries = new Map<string, TranslationMemoryEntry>();
if (!existsSync(filePath)) {
return entries;
}
const raw = await readFile(filePath, "utf8");
for (const line of raw.split("\n")) {
const trimmed = line.trim();
if (!trimmed) {
continue;
}
const parsed = JSON.parse(trimmed) as TranslationMemoryEntry;
if (parsed.cache_key && parsed.translated.trim()) {
entries.set(parsed.cache_key, parsed);
}
}
return entries;
}
function renderTranslationMemory(entries: Map<string, TranslationMemoryEntry>): string {
const ordered = [...entries.values()].toSorted((left, right) =>
left.cache_key.localeCompare(right.cache_key),
);
if (ordered.length === 0) {
return "";
}
return `${ordered.map((entry) => JSON.stringify(entry)).join("\n")}\n`;
}
function buildTranslationMemoryByTextHash(
entries: Map<string, TranslationMemoryEntry>,
locale: string,
): Map<string, TranslationMemoryEntry> {
const byTextHash = new Map<string, TranslationMemoryEntry>();
for (const entry of entries.values()) {
if (entry.tgt_lang !== locale || !entry.text_hash || !entry.translated.trim()) {
continue;
}
byTextHash.set(entry.text_hash, entry);
}
return byTextHash;
}
function buildGlossaryPrompt(glossary: readonly GlossaryEntry[]): string {
if (glossary.length === 0) {
return "";
}
return [
"Required terminology (use exactly when the source term matches):",
...glossary
.filter((entry) => entry.source.trim() && entry.target.trim())
.map((entry) => `- ${entry.source} -> ${entry.target}`),
].join("\n");
}
function buildSystemPrompt(targetLocale: string, glossary: readonly GlossaryEntry[]): string {
const glossaryBlock = buildGlossaryPrompt(glossary);
const lines = [
"You are a translation function, not a chat assistant.",
`Translate UI strings from ${prettyLanguageLabel(SOURCE_LOCALE)} to ${prettyLanguageLabel(targetLocale)}.`,
"",
"Rules:",
"- Output ONLY valid JSON.",
"- The JSON must be an object whose keys exactly match the provided ids.",
"- Translate all English prose; keep code, URLs, product names, CLI commands, config keys, and env vars in English.",
"- Preserve placeholders exactly, including {count}, {time}, {shown}, {total}, and similar tokens.",
"- Preserve punctuation, ellipses, arrows, and casing when they are part of literal UI text.",
"- Preserve Markdown, inline code, HTML tags, and slash commands when present.",
"- Use fluent, neutral product UI language.",
"- Do not add explanations, comments, or extra keys.",
"- Never return an empty string for a key; if unsure, return the source text unchanged.",
];
if (glossaryBlock) {
lines.push("", glossaryBlock);
}
return lines.join("\n");
}
function buildBatchPrompt(items: readonly TranslationBatchItem[]): string {
const payload = Object.fromEntries(items.map((item) => [item.key, item.text]));
return [
"Translate this JSON object.",
"Return ONLY a JSON object with the same keys.",
"",
JSON.stringify(payload, null, 2),
].join("\n");
}
function sleep(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function formatDuration(ms: number): string {
if (ms < 1_000) {
return `${Math.round(ms)}ms`;
}
if (ms < 60_000) {
return `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)}s`;
}
const totalSeconds = Math.round(ms / 1_000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes}m ${seconds}s`;
}
function logProgress(message: string) {
process.stdout.write(`control-ui-i18n: ${message}\n`);
}
function toRepoPath(filePath: string): string {
return path.relative(ROOT, filePath).split(path.sep).join("/");
}
function normalizeRawCopyText(raw: string): string {
return raw
.replace(/\\n/g, " ")
.replace(/\s+/g, " ")
.replace(/·/giu, "·")
.trim();
}
function hasHumanLetters(text: string): boolean {
return /\p{L}/u.test(text);
}
function lineNumberForOffset(source: string, offset: number): number {
let line = 1;
for (let index = 0; index < offset && index < source.length; index += 1) {
if (source.charCodeAt(index) === 10) {
line += 1;
}
}
return line;
}
function parseDoubleQuotedString(raw: string): string {
try {
return JSON.parse(`"${raw}"`) as string;
} catch {
return raw;
}
}
function pushRawCopyFinding(
findings: RawCopyFinding[],
params: Omit<RawCopyFinding, "text"> & { text: string },
) {
const text = normalizeRawCopyText(params.text);
if (!text || !hasHumanLetters(text)) {
return;
}
findings.push({
...params,
text,
});
}
async function walkControlUiSourceFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
if (entry.name === "test-helpers") {
continue;
}
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await walkControlUiSourceFiles(fullPath)));
continue;
}
if (!entry.isFile() || !/\.tsx?$/u.test(entry.name)) {
continue;
}
if (/\.(?:test|browser\.test|node\.test)\.tsx?$/u.test(entry.name)) {
continue;
}
files.push(fullPath);
}
return files;
}
function collectRawCopyFromSource(params: {
filePath: string;
source: string;
sourceFile: ts.SourceFile;
}): RawCopyFinding[] {
const { filePath, source, sourceFile } = params;
const repoPath = toRepoPath(filePath);
const findings: RawCopyFinding[] = [];
const attrPattern =
/\b(aria-label|placeholder|title)\s*=\s*"((?:(?!\$\{)[^"\\]|\\.)*?\p{L}(?:(?!\$\{)[^"\\]|\\.)*?)"/gu;
for (const match of source.matchAll(attrPattern)) {
const rawText = match[2];
if (!rawText) {
continue;
}
pushRawCopyFinding(findings, {
kind: "html-attribute",
line: lineNumberForOffset(source, match.index ?? 0),
name: match[1] ?? "attribute",
path: repoPath,
text: parseDoubleQuotedString(rawText),
});
}
const propertyPattern =
/\b(label|title|subtitle|description|help|placeholder)\s*:\s*"((?:[^"\\]|\\.)*?\p{L}(?:[^"\\]|\\.)*?)"/gu;
for (const match of source.matchAll(propertyPattern)) {
const rawText = match[2];
if (!rawText) {
continue;
}
pushRawCopyFinding(findings, {
kind: "object-property",
line: lineNumberForOffset(source, match.index ?? 0),
name: match[1] ?? "property",
path: repoPath,
text: parseDoubleQuotedString(rawText),
});
}
const textPattern = />\s*([^<>{}]*?\p{L}[^<>{}]*?)\s*</gu;
const visit = (node: ts.Node) => {
if (ts.isTaggedTemplateExpression(node) && node.tag.getText(sourceFile) === "html") {
const template = node.template;
const chunks: Array<{ offset: number; text: string }> = [];
if (ts.isNoSubstitutionTemplateLiteral(template)) {
chunks.push({
offset: template.getStart(sourceFile) + 1,
text: template.text,
});
} else {
chunks.push({
offset: template.head.getStart(sourceFile) + 1,
text: template.head.text,
});
for (const span of template.templateSpans) {
chunks.push({
offset: span.literal.getStart(sourceFile) + 1,
text: span.literal.text,
});
}
}
for (const chunk of chunks) {
for (const match of chunk.text.matchAll(textPattern)) {
const rawText = match[1];
if (!rawText) {
continue;
}
pushRawCopyFinding(findings, {
kind: "html-text",
line: lineNumberForOffset(source, chunk.offset + (match.index ?? 0)),
name: "text",
path: repoPath,
text: rawText,
});
}
}
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
return findings;
}
async function collectControlUiRawCopyFindings(): Promise<RawCopyFinding[]> {
const files = await walkControlUiSourceFiles(CONTROL_UI_SOURCE_DIR);
const findings: RawCopyFinding[] = [];
for (const filePath of files.toSorted((left, right) => left.localeCompare(right))) {
const source = await readFile(filePath, "utf8");
const sourceFile = ts.createSourceFile(
filePath,
source,
ts.ScriptTarget.Latest,
true,
filePath.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
);
findings.push(...collectRawCopyFromSource({ filePath, source, sourceFile }));
}
return findings;
}
function summarizeRawCopyFindings(findings: RawCopyFinding[]): RawCopyBaselineEntry[] {
const counts = new Map<string, RawCopyBaselineEntry>();
for (const finding of findings) {
const key = [finding.path, finding.kind, finding.name, finding.text].join("\u0000");
const existing = counts.get(key);
if (existing) {
existing.count += 1;
continue;
}
counts.set(key, {
count: 1,
kind: finding.kind,
name: finding.name,
path: finding.path,
text: finding.text,
});
}
return [...counts.values()].toSorted(
(left, right) =>
left.path.localeCompare(right.path) ||
left.kind.localeCompare(right.kind) ||
left.name.localeCompare(right.name) ||
left.text.localeCompare(right.text),
);
}
function formatRawCopyBaseline(entries: RawCopyBaselineEntry[]): string {
return `${JSON.stringify(
{
version: RAW_COPY_BASELINE_VERSION,
entries,
} satisfies RawCopyBaseline,
null,
2,
)}\n`;
}
function formatRawCopyBaselineDiff(
current: RawCopyBaselineEntry[],
expected: RawCopyBaselineEntry[],
) {
const keyFor = (entry: RawCopyBaselineEntry) =>
[entry.path, entry.kind, entry.name, entry.text].join("\u0000");
const currentByKey = new Map(current.map((entry) => [keyFor(entry), entry]));
const expectedByKey = new Map(expected.map((entry) => [keyFor(entry), entry]));
const added = current.filter((entry) => {
const expectedEntry = expectedByKey.get(keyFor(entry));
return !expectedEntry || expectedEntry.count !== entry.count;
});
const removed = expected.filter((entry) => {
const currentEntry = currentByKey.get(keyFor(entry));
return !currentEntry || currentEntry.count !== entry.count;
});
const lines: string[] = [];
for (const entry of added.slice(0, 20)) {
lines.push(
`+ ${entry.path} ${entry.kind}:${entry.name} x${entry.count} ${JSON.stringify(entry.text)}`,
);
}
for (const entry of removed.slice(0, 20)) {
lines.push(
`- ${entry.path} ${entry.kind}:${entry.name} x${entry.count} ${JSON.stringify(entry.text)}`,
);
}
const extra = added.length + removed.length - lines.length;
if (extra > 0) {
lines.push(`... ${extra} more baseline delta(s)`);
}
return lines.join("\n");
}
async function syncControlUiRawCopyBaseline(options: { checkOnly: boolean; write: boolean }) {
const findings = await collectControlUiRawCopyFindings();
const entries = summarizeRawCopyFindings(findings);
const expected = formatRawCopyBaseline(entries);
const current = existsSync(RAW_COPY_BASELINE_PATH)
? await readFile(RAW_COPY_BASELINE_PATH, "utf8")
: "";
if (!options.checkOnly && options.write && current !== expected) {
await mkdir(I18N_ASSETS_DIR, { recursive: true });
await writeFile(RAW_COPY_BASELINE_PATH, expected, "utf8");
}
if (options.checkOnly && current !== expected) {
let currentEntries: RawCopyBaselineEntry[];
try {
const parsed = JSON.parse(current) as Partial<RawCopyBaseline>;
currentEntries = Array.isArray(parsed.entries) ? parsed.entries : [];
} catch {
currentEntries = [];
}
const diff = formatRawCopyBaselineDiff(entries, currentEntries);
throw new Error(
[
"control-ui raw-copy baseline drift detected.",
diff,
"Move user-facing strings into ui/src/i18n/locales/en.ts, or update the baseline with `node --import tsx scripts/control-ui-i18n.ts sync --write` when the raw string is intentional.",
]
.filter(Boolean)
.join("\n"),
);
}
logProgress(`raw-copy: baseline entries=${entries.length}`);
}
function isPromptTimeoutError(error: Error): boolean {
return error.message.toLowerCase().includes("timed out");
}
export function isProviderAuthError(error: Error): boolean {
const message = error.message.toLowerCase();
return (
message.includes("401") ||
message.includes("authentication_error") ||
message.includes("incorrect api key") ||
message.includes("invalid x-api-key")
);
}
function isProviderAuthOptional(): boolean {
const raw = process.env[ENV_AUTH_OPTIONAL]?.trim().toLowerCase();
return raw === "1" || raw === "true" || raw === "yes";
}
function resolvePromptTimeoutMs(): number {
const raw = process.env[ENV_PROMPT_TIMEOUT]?.trim();
if (!raw) {
return DEFAULT_PROMPT_TIMEOUT_MS;
}
const parsed = Number(raw);
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_PROMPT_TIMEOUT_MS;
}
function resolveThinkingLevel(): "low" | "high" {
return process.env[ENV_THINKING]?.trim().toLowerCase() === "high" ? "high" : "low";
}
function resolveBatchCharBudget(): number {
const raw = process.env[ENV_BATCH_CHAR_BUDGET]?.trim();
if (!raw) {
return DEFAULT_BATCH_CHAR_BUDGET;
}
const parsed = Number(raw);
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_BATCH_CHAR_BUDGET;
}
function estimateBatchChars(items: readonly TranslationBatchItem[]): number {
return items.reduce((total, item) => total + item.key.length + item.text.length + 8, 2);
}
type RunProcessOptions = {
cwd?: string;
input?: string;
killGraceMs?: number;
maxOutputChars?: number;
rejectOnFailure?: boolean;
timeoutMs?: number;
};
type ProcessOutputCapture = {
text: string;
truncatedChars: number;
};
function resolveRunProcessOutputLimit(options: RunProcessOptions): number {
const value = options.maxOutputChars;
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
return RUN_PROCESS_OUTPUT_MAX_CHARS;
}
return Math.max(1, Math.floor(value));
}
export function appendBoundedProcessOutput(
capture: ProcessOutputCapture,
chunk: unknown,
maxChars: number,
): ProcessOutputCapture {
const nextText = capture.text + String(chunk);
if (nextText.length <= maxChars) {