cc-translate 1.3.0 → 1.3.2

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/CHANGELOG.md CHANGED
@@ -6,6 +6,34 @@ All notable changes to this project will be documented in this file.
6
6
 
7
7
  ### Added
8
8
 
9
+ - Source JSON files can define optional `_meta.context` for file-wide
10
+ business context and `_meta.noTranslate` for words or phrases that should
11
+ be preserved inside translated sentences.
12
+ - The agent accepts global `noTranslate` terms. File-level matches take
13
+ precedence when they overlap with global matches.
14
+ - Tracked reference changes retranslate only the affected keys in each target
15
+ language, even when the source text stays the same.
16
+
17
+ ## [1.3.2] - 2026-11-26
18
+
19
+ ### Fixed
20
+
21
+ - Retry responses that contain translation preambles or response labels
22
+ while allowing inline JSON examples in the translated text.
23
+ - Use NodeNext-compatible relative imports in published TypeScript declarations.
24
+
25
+ ## [1.3.1] - 2026-11-25
26
+
27
+ ### Added
28
+
29
+ - `translate()` now accepts an ordered array of reference plugins alongside
30
+ the existing single-plugin call. Available references are passed to each
31
+ translation request in array order.
32
+
33
+ ## [1.3.0] - 2026-11-25
34
+
35
+ ### Added
36
+
9
37
  - Added the optional `TranslationReferencePlugin` for using a reviewed locale
10
38
  as context for pending translations. It matches by filename and JSON key,
11
39
  with translation eligibility determined by the existing cache.
@@ -20,6 +48,15 @@ All notable changes to this project will be documented in this file.
20
48
  keep their existing translations and cache state. The reference locale is
21
49
  read-only.
22
50
 
51
+ ### Changed
52
+
53
+ - Improved terminal translation progress and added a final task summary.
54
+
55
+ ### Fixed
56
+
57
+ - Added progress updates and per-request timeouts during reference conflict
58
+ checks. Entries that still time out after retries are logged and skipped.
59
+
23
60
  ## [1.0.0] - 2026-03-04
24
61
 
25
62
  ### Changed
package/README.md CHANGED
@@ -45,6 +45,7 @@ const agent = new I18nTranslateAgent({
45
45
  "This is a crypto wallet product",
46
46
  "Keep blockchain terms consistent",
47
47
  ],
48
+ noTranslate: ["USDC", "Cozy Card"],
48
49
  chatCompletionCreateParams: {
49
50
  model: "gpt-4o",
50
51
  temperature: 0.2,
@@ -72,26 +73,97 @@ const reference = new TranslationReferencePlugin({
72
73
  await agent.translate(reference);
73
74
  ```
74
75
 
75
- The existing cache determines which entries need translation. Enabling the
76
- plugin or editing the reference locale alone leaves cached translations intact.
76
+ Pass multiple plugins as an array, for example
77
+ `await agent.translate([chineseReference, frenchReference])`. Reference
78
+ matching, optional conflict checks, and reference texts in the translation
79
+ request follow the array order. Each target entry is translated once using
80
+ all the references available for that entry. An empty array runs without plugins.
81
+
82
+ The cache compares source text and tracked reference text for each target
83
+ language. Changing a reference value requeues the corresponding key even if
84
+ the source text is unchanged. A newly filled reference also requeues its key
85
+ if the key was previously tracked without a value. Clearing or deleting a
86
+ reference leaves existing translations intact.
87
+
88
+ On the first run with an old source-only cache, the current references become
89
+ the baseline for existing translations without a bulk retranslation. Reference
90
+ snapshots are saved under `<cache>/<target-language>/.references/`. Each target
91
+ updates its snapshot only after a successful translation, so failed entries
92
+ can be retried independently. The source and reference files are read-only
93
+ during translation.
94
+
77
95
  Before any model calls, the plugin reports the reference language, directory,
78
96
  file matches, and coverage of pending keys.
79
97
 
80
98
  - When every pending entry has a non-empty reference, translation starts automatically.
81
- - Missing files or entries trigger a terminal prompt. If you confirm, unmatched
82
- entries use the source text alone. Declining or running without an interactive
83
- terminal ends the run before translation.
99
+ - Missing files or entries in a reference directory trigger a terminal prompt.
100
+ If you confirm, translation uses the source and any references that matched
101
+ in other directories. Declining or running without an interactive terminal
102
+ ends the run before translation.
84
103
  - A missing or unreadable reference directory, or an invalid matching JSON
85
104
  file, stops the run with an error that identifies the path.
86
105
 
87
106
  The reference locale is read-only and its language is excluded from the output
88
107
  targets. By default, the translation request includes both the source text and
89
108
  its matched reference. Set `checkConflicts: true` to run a separate check before
90
- translation. Each matched entry then gets one check shared by all targets.
109
+ translation. Each matched reference then gets one check shared by all targets.
91
110
  Clear conflicts and checks that still fail after retries receive distinct
92
111
  entries in `error.log`, once per filename and key. The affected keys are skipped
93
- across all targets, preserving existing translations and leaving their cache
94
- entries unchanged for the next run.
112
+ across all targets and subsequent conflict checks, preserving existing
113
+ translations and leaving their cache entries unchanged for the next run.
114
+
115
+ ## File Context and Protected Terms
116
+
117
+ Add an optional `_meta` object at the top level of a **source-language** JSON
118
+ file, such as `locales/en/bots.json`.
119
+
120
+ ```json
121
+ {
122
+ "_meta": {
123
+ "context": "Trading bot settings for opening positions and configuring margin.",
124
+ "noTranslate": ["MAX", "Cozy Card"]
125
+ },
126
+ "keyword.long": "Long",
127
+ "trade.hint": "Tap MAX to use your full balance.",
128
+ "trade.max": "MAX"
129
+ }
130
+ ```
131
+
132
+ | Field | Accepted value | Behavior |
133
+ | --- | --- | --- |
134
+ | `context` | Non-blank string | Adds business context to every translation request for this file. It works alongside global `fineTune` and any matched reference translation. |
135
+ | `noTranslate` | Non-empty array of non-blank strings | Preserves the listed words or phrases in this file. Entries are terms such as `MAX` or `Cozy Card`, with case-sensitive, whole-term matching. |
136
+
137
+ Both fields are optional and validated independently. For example, a valid
138
+ `context` still applies if `noTranslate` is accidentally written as a string.
139
+ Missing or invalid metadata is ignored. The script reads metadata from the
140
+ source file and excludes `_meta` from generated translations and caches.
141
+
142
+ In the example, `trade.hint` can become `点击 MAX 使用全部余额。` in Chinese.
143
+ The surrounding sentence is translated while `MAX` is restored verbatim.
144
+ The word `maximum` can still be translated. A value that consists entirely of
145
+ a protected term, such as `trade.max`, is copied directly to the target locale.
146
+ If a model response drops or duplicates a protected placeholder, the script
147
+ uses the existing retry policy and leaves the entry pending if retries are
148
+ exhausted.
149
+
150
+ ### Global protected terms
151
+
152
+ Set `noTranslate: ["USDC", "Cozy Card"]` on `I18nTranslateAgent` to protect
153
+ these terms in every source JSON file. Keep application-wide names and symbols
154
+ in this configuration, and put file-specific terms in `_meta.noTranslate`.
155
+ Both lists use the same validation and matching rules. For a long list, keep it
156
+ in a separate project configuration file and import it into the entry script.
157
+
158
+ When matching a sentence, the script applies file rules first. Global rules
159
+ then protect any remaining matches. For example, if the global list contains
160
+ `["Cozy Card", "USDC"]` and a file lists `["Card"]`, that file protects
161
+ `Card` and `USDC`. Other files still protect the full phrase `Cozy Card`.
162
+
163
+ The cache still selects which entries are processed. Editing either list or
164
+ the context alone does not retranslate existing entries. To apply a change
165
+ to previously translated copy, clear the affected keys from the relevant
166
+ target-language caches.
95
167
 
96
168
  ## Directory Layout
97
169
 
@@ -121,6 +193,7 @@ your-project/
121
193
  | `outputRootPath` | `string` | No | Output directory, defaults to `fileRootPath` |
122
194
  | `concurrency` | `number` | No | Queue length, default `8` |
123
195
  | `fineTune` | `string[]` | No | Extra translation context lines |
196
+ | `noTranslate` | `readonly string[]` | No | Terms preserved across source files. File-level matches take precedence where they overlap. |
124
197
  | `chatCompletionCreateParams` | `Partial<ChatCompletionCreateParams>` | No | Extra chat completion params |
125
198
 
126
199
  ### Utility Exports
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ClientOptions, OpenAI } from "openai";
2
- import { II18nTranslateAgentParams, IJson, IOutputLanguageFile, ISingleTranslate, ITranslateChat, ITranslateChatResponse, SupportLanguageType } from "./types";
2
+ import { II18nTranslateAgentParams, IJson, IOutputLanguageFile, ISingleTranslate, ITranslateChat, ITranslateChatResponse, SupportLanguageType } from "./types/index.js";
3
3
  import { TranslationReferencePlugin } from "./lib/translation-reference.js";
4
4
  import { ChatCompletionCreateParams } from "openai/resources";
5
5
  export { generateCache, deleteBatchCache } from "./lib/cache/index.js";
@@ -21,6 +21,7 @@ export declare class I18nTranslateAgent {
21
21
  client: OpenAI | null;
22
22
  /** 微调模型 */
23
23
  fineTune: string[];
24
+ readonly noTranslate?: readonly string[];
24
25
  /** 翻译任务并发数(队列长度),完成一个即取下一个 */
25
26
  concurrency: number;
26
27
  /** openai 客户端配置 */
@@ -32,17 +33,17 @@ export declare class I18nTranslateAgent {
32
33
  taskRetryBaseDelayMs: number;
33
34
  constructor(params: II18nTranslateAgentParams);
34
35
  /** 支持翻译的语言列表 */
35
- get supportLanguages(): import("./types").ILanguage[];
36
+ get supportLanguages(): import("./types/index.js").ILanguage[];
36
37
  /** 输出文件根路径 */
37
38
  get outputPath(): string;
38
39
  /** 搜索语言 */
39
- searchLanguage(code: SupportLanguageType): import("./types").ILanguage | undefined;
40
+ searchLanguage(code: SupportLanguageType): import("./types/index.js").ILanguage | undefined;
40
41
  /** 创建openai客户端 */
41
42
  createOpenAIClient: () => void;
42
43
  /**
43
44
  * 翻译入口文件的所有支持的语言文件夹和其中的文件
44
45
  */
45
- translate: (referencePlugin?: TranslationReferencePlugin) => Promise<void>;
46
+ translate: (referencePlugins?: TranslationReferencePlugin | readonly TranslationReferencePlugin[]) => Promise<void>;
46
47
  private reviewReferences;
47
48
  /**
48
49
  * 翻译单个文件
@@ -65,7 +66,7 @@ export declare class I18nTranslateAgent {
65
66
  * @param fileName
66
67
  * @returns
67
68
  */
68
- getTranslateContent: (language: SupportLanguageType, fileName: string, deferredEmptyFiles?: IOutputLanguageFile[]) => Promise<IJson | undefined>;
69
+ getTranslateContent: (language: SupportLanguageType, fileName: string, deferredEmptyFiles?: IOutputLanguageFile[], sourceEntries?: IJson) => Promise<IJson | undefined>;
69
70
  /**
70
71
  * 输出语言文件
71
72
  * @param {Object} jsonMap
package/index.js CHANGED
@@ -7,16 +7,29 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
10
21
  import path from "path";
11
22
  import fs from "fs";
12
23
  import colors from "ansi-colors";
13
24
  import { OpenAI } from "openai";
14
25
  import cliProgress from "cli-progress";
15
26
  import { getRandomNumber, notExistsToCreateFile, readFileOfDirSync, readJsonFileSync, runWithConcurrencyLimit, sleep, } from "./lib/utils.js";
16
- import { getCacheFileSync, registerLanguageCacheFile, translateJSONDiffToJson, } from "./lib/cache/index.js";
27
+ import { getCacheFileSync, readReferenceCache, registerLanguageCacheFile, translateJSONDiffToJson, writeReferenceCache, } from "./lib/cache/index.js";
17
28
  import { logErrorToFile } from "./lib/log/index.js";
18
29
  import { SUPPORT_LANGUAGE_MAP } from "./lib/support.js";
30
+ import { isProtectedText, protectTerms, readProtectedTerms, readTranslationMetadata, } from "./lib/translation-metadata.js";
19
31
  import { TranslationReferencePlugin } from "./lib/translation-reference.js";
32
+ import { readTranslationResponse } from "./lib/translation-response.js";
20
33
  export { generateCache, deleteBatchCache } from "./lib/cache/index.js";
21
34
  export { TranslationReferencePlugin };
22
35
  const DEFAULT_CHAT_COMPLETION_CREATE_PARAMS = {
@@ -39,9 +52,12 @@ export class I18nTranslateAgent {
39
52
  /**
40
53
  * 翻译入口文件的所有支持的语言文件夹和其中的文件
41
54
  */
42
- this.translate = (referencePlugin) => __awaiter(this, void 0, void 0, function* () {
43
- var _a;
44
- if (!referencePlugin)
55
+ this.translate = (referencePlugins) => __awaiter(this, void 0, void 0, function* () {
56
+ var _a, _b, _c, _d;
57
+ const plugins = referencePlugins && "prepare" in referencePlugins
58
+ ? [referencePlugins]
59
+ : referencePlugins !== null && referencePlugins !== void 0 ? referencePlugins : [];
60
+ if (plugins.length === 0)
45
61
  fs.writeFileSync("error.log", "", "utf8");
46
62
  console.log("🚀 Start translation");
47
63
  console.log(`🚀 Using model: ${this.chatCompletionCreateParams.model} 🚀`);
@@ -54,39 +70,111 @@ export class I18nTranslateAgent {
54
70
  const tasks = [];
55
71
  const skippedNoContent = [];
56
72
  const emptyFiles = [];
57
- const targetLanguages = this.supportLanguages.filter(({ code }) => code !== this.SOURCE_LANGUAGE && code !== (referencePlugin === null || referencePlugin === void 0 ? void 0 : referencePlugin.language));
73
+ const referenceLanguages = new Set(plugins.map(({ language }) => language));
74
+ const targetLanguages = this.supportLanguages.filter(({ code }) => code !== this.SOURCE_LANGUAGE && !referenceLanguages.has(code));
75
+ const sourceFiles = new Map();
76
+ for (const fileName of translateFolders) {
77
+ const _e = (_a = (yield readJsonFileSync(path.join(translateFolderPath, fileName)))) !== null && _a !== void 0 ? _a : {}, { _meta } = _e, entries = __rest(_e, ["_meta"]);
78
+ sourceFiles.set(fileName, { entries, metadata: readTranslationMetadata(_meta) });
79
+ }
80
+ const writableDirectories = targetLanguages.flatMap(({ code }) => [
81
+ path.join(this.outputPath, code),
82
+ path.join(this.CACHE_ROOT_PATH, code),
83
+ path.join(this.CACHE_ROOT_PATH, code, ".references"),
84
+ ]);
85
+ const loadedReferences = plugins.map((plugin) => ({
86
+ plugin,
87
+ identity: JSON.stringify([plugin.language, plugin.directory]),
88
+ files: plugin.readFiles(sourceFiles.keys(), writableDirectories),
89
+ }));
90
+ // 用本次匹配和发送给模型的参考译文建立快照,避免两次读取之间发生变化。
91
+ const referenceSnapshots = new Map();
92
+ if (loadedReferences.length) {
93
+ for (const [fileName, { entries, metadata }] of sourceFiles) {
94
+ const snapshots = new Map();
95
+ for (const [key, source] of Object.entries(entries)) {
96
+ if (isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate))
97
+ continue;
98
+ snapshots.set(key, Object.fromEntries(loadedReferences.map(({ identity, files }) => {
99
+ var _a, _b;
100
+ return [
101
+ identity,
102
+ (_b = (_a = files.get(fileName)) === null || _a === void 0 ? void 0 : _a.get(key)) !== null && _b !== void 0 ? _b : null,
103
+ ];
104
+ })));
105
+ }
106
+ referenceSnapshots.set(fileName, snapshots);
107
+ }
108
+ }
109
+ const baselines = [];
58
110
  for (const item of targetLanguages) {
59
- for (const fileName of translateFolders) {
60
- const translateJson = yield this.getTranslateContent(item.code, fileName, referencePlugin ? emptyFiles : undefined);
61
- if (!translateJson) {
111
+ for (const [fileName, { entries, metadata }] of sourceFiles) {
112
+ const translateJson = (_b = (yield this.getTranslateContent(item.code, fileName, plugins.length ? emptyFiles : undefined, entries))) !== null && _b !== void 0 ? _b : {};
113
+ const current = referenceSnapshots.get(fileName);
114
+ let referenceCache;
115
+ if (current === null || current === void 0 ? void 0 : current.size) {
116
+ const filePath = path.join(this.CACHE_ROOT_PATH, item.code, ".references", fileName);
117
+ const observed = readReferenceCache(filePath);
118
+ referenceCache = { filePath, observed, current };
119
+ let addedBaseline = false;
120
+ for (const [key, snapshot] of current) {
121
+ if (Object.prototype.hasOwnProperty.call(translateJson, key))
122
+ continue;
123
+ const previous = (_c = observed.get(key)) !== null && _c !== void 0 ? _c : {};
124
+ const values = Object.entries(snapshot);
125
+ // 参考译文被清空或删除时,保留已有译文。
126
+ if (values.some(([id, value]) => value !== null && previous[id] !== undefined && previous[id] !== value)) {
127
+ translateJson[key] = entries[key];
128
+ continue;
129
+ }
130
+ // 旧缓存只记录源文案。首次遇到未记录的参考时建立比对基准,不回填旧译文。
131
+ const untracked = values.filter(([id]) => previous[id] === undefined);
132
+ if (untracked.length) {
133
+ observed.set(key, Object.assign(Object.assign({}, previous), Object.fromEntries(untracked)));
134
+ addedBaseline = true;
135
+ }
136
+ }
137
+ if (addedBaseline)
138
+ baselines.push(referenceCache);
139
+ }
140
+ if (Object.keys(translateJson).length === 0) {
62
141
  skippedNoContent.push(`${item.code}:${fileName}`);
63
142
  continue;
64
143
  }
65
- tasks.push({ language: item.code, fileName, translateJson });
144
+ tasks.push({ language: item.code, fileName, translateJson, metadata, referenceCache });
66
145
  }
67
146
  }
68
- if (referencePlugin) {
69
- const writableDirectories = targetLanguages.flatMap(({ code }) => [
70
- path.join(this.outputPath, code),
71
- path.join(this.CACHE_ROOT_PATH, code),
72
- ]);
73
- const matches = yield referencePlugin.prepare(tasks, writableDirectories);
74
- if (!matches)
75
- return;
147
+ if (plugins.length) {
148
+ const prepared = [];
149
+ for (const { plugin, files } of loadedReferences) {
150
+ const matches = yield plugin.prepare(tasks, writableDirectories, this.noTranslate, files);
151
+ if (!matches)
152
+ return;
153
+ prepared.push({ plugin, matches });
154
+ }
76
155
  fs.writeFileSync("error.log", "", "utf8");
77
- const blockedByFile = referencePlugin.checkConflicts
78
- ? yield this.reviewReferences(matches, referencePlugin.language)
79
- : undefined;
80
- for (const task of tasks) {
81
- const fileMatches = matches.get(task.fileName);
82
- if (fileMatches) {
83
- task.reference = {
84
- language: referencePlugin.language,
85
- matches: fileMatches,
86
- };
156
+ // 所有参考匹配预览通过后,才写入比对基准。
157
+ for (const baseline of baselines)
158
+ writeReferenceCache(baseline);
159
+ const blockedByFile = new Map();
160
+ for (const { plugin, matches } of prepared) {
161
+ if (plugin.checkConflicts) {
162
+ yield this.reviewReferences(matches, plugin.language, blockedByFile);
87
163
  }
88
- task.blockedKeys = blockedByFile === null || blockedByFile === void 0 ? void 0 : blockedByFile.get(task.fileName);
89
- for (const key of (_a = task.blockedKeys) !== null && _a !== void 0 ? _a : []) {
164
+ }
165
+ for (const task of tasks) {
166
+ const fileReferences = prepared.flatMap(({ plugin, matches }) => {
167
+ const fileMatches = matches.get(task.fileName);
168
+ return fileMatches
169
+ ? [{ language: plugin.language, matches: fileMatches }]
170
+ : [];
171
+ });
172
+ if (fileReferences.length === 1)
173
+ task.reference = fileReferences[0];
174
+ else if (fileReferences.length > 1)
175
+ task.references = fileReferences;
176
+ task.blockedKeys = blockedByFile.get(task.fileName);
177
+ for (const key of (_d = task.blockedKeys) !== null && _d !== void 0 ? _d : []) {
90
178
  delete task.translateJson[key];
91
179
  }
92
180
  }
@@ -161,20 +249,24 @@ export class I18nTranslateAgent {
161
249
  /** 待翻译的语言 */
162
250
  language,
163
251
  /** 待翻译的文件名 */
164
- fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, blockedKeys, } = params;
252
+ fileName, translateJson, multiBar, progressBar: taskProgressBar, callback, reference, references, blockedKeys, metadata, referenceCache, } = params;
165
253
  try {
254
+ const fileReferences = references !== null && references !== void 0 ? references : (reference ? [reference] : []);
166
255
  // 生成chat循环代码
167
256
  const promiseList = Object.entries(translateJson).map(([key, value], index) => () => {
168
- const match = reference === null || reference === void 0 ? void 0 : reference.matches.get(key);
257
+ const matched = fileReferences.flatMap(({ language, matches }) => {
258
+ const match = matches.get(key);
259
+ return match ? [{ language, value: match.translation }] : [];
260
+ });
169
261
  return this.translateChat({
170
262
  key,
171
263
  value,
172
264
  language,
173
265
  index,
174
266
  fileName,
175
- reference: reference && match
176
- ? { language: reference.language, value: match.translation }
177
- : undefined,
267
+ reference: matched.length === 1 ? matched[0] : undefined,
268
+ references: matched.length > 1 ? matched : undefined,
269
+ metadata,
178
270
  });
179
271
  });
180
272
  const progressBar = taskProgressBar !== null && taskProgressBar !== void 0 ? taskProgressBar : multiBar === null || multiBar === void 0 ? void 0 : multiBar.create(promiseList.length, 0, {
@@ -188,6 +280,13 @@ export class I18nTranslateAgent {
188
280
  fileName,
189
281
  blockedKeys,
190
282
  });
283
+ // 译文写入成功后才更新参考快照,失败或跳过的词条留待下次处理。
284
+ const snapshot = referenceCache === null || referenceCache === void 0 ? void 0 : referenceCache.current.get(result.key);
285
+ if (referenceCache && snapshot) {
286
+ const previous = referenceCache.observed.get(result.key);
287
+ referenceCache.observed.set(result.key, Object.assign(Object.assign({}, previous), snapshot));
288
+ writeReferenceCache(referenceCache);
289
+ }
191
290
  delete translateJson[result.key];
192
291
  progressBar === null || progressBar === void 0 ? void 0 : progressBar.increment();
193
292
  }
@@ -212,11 +311,9 @@ export class I18nTranslateAgent {
212
311
  * @returns
213
312
  */
214
313
  this.translateChat = (params) => __awaiter(this, void 0, void 0, function* () {
215
- var _a, _b, _c, _d;
216
- const { key, value, language, index, fileName, reference } = params;
314
+ var _a, _b;
315
+ const { key, value, language, index, fileName, reference, references, metadata } = params;
217
316
  try {
218
- if (!this.client)
219
- throw new Error("Connection failed");
220
317
  const targetLanguage = this.searchLanguage(language);
221
318
  const originLanguage = this.searchLanguage(this.SOURCE_LANGUAGE);
222
319
  if (!targetLanguage) {
@@ -225,41 +322,72 @@ export class I18nTranslateAgent {
225
322
  if (!originLanguage) {
226
323
  throw new Error(`Unsupported language:${this.SOURCE_LANGUAGE}`);
227
324
  }
325
+ if (isProtectedText(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate)) {
326
+ return { key, value, index };
327
+ }
328
+ if (!this.client)
329
+ throw new Error("Connection failed");
330
+ const protectedText = protectTerms(value, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, this.noTranslate);
331
+ const source = (_a = protectedText === null || protectedText === void 0 ? void 0 : protectedText.text) !== null && _a !== void 0 ? _a : value;
332
+ const referenceEntries = (references !== null && references !== void 0 ? references : (reference ? [reference] : [])).map(({ language, value }) => {
333
+ var _a, _b;
334
+ return ({
335
+ referenceLanguage: (_b = (_a = SUPPORT_LANGUAGE_MAP[language]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : language,
336
+ reference: value,
337
+ });
338
+ });
339
+ let input = source;
340
+ let referenceInstruction = "";
341
+ if (referenceEntries.length > 0) {
342
+ referenceInstruction =
343
+ ". For ambiguous words, abbreviations, and short UI labels, use the reviewed reference to determine the intended product meaning before interpreting or rewriting the source. " +
344
+ "Translate that meaning using the established terminology of the target language and domain.";
345
+ if (referenceEntries.length === 1) {
346
+ input = JSON.stringify(Object.assign({ source }, referenceEntries[0]));
347
+ }
348
+ else {
349
+ input = JSON.stringify({ source, references: referenceEntries });
350
+ referenceInstruction += " Consider the references in the given order.";
351
+ }
352
+ }
353
+ const instructions = [
354
+ `Please translate ${originLanguage.name} to ${targetLanguage.name}${referenceInstruction}`,
355
+ ];
356
+ if (metadata === null || metadata === void 0 ? void 0 : metadata.context) {
357
+ instructions.push(`Business context for this file: ${metadata.context}`);
358
+ }
359
+ if (protectedText) {
360
+ instructions.push("Copy each {__CC_PROTECTED_...} placeholder exactly once. Translate the surrounding text normally.");
361
+ }
228
362
  yield sleep(getRandomNumber(200, 300));
229
- const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
363
+ const chatCompletion = yield this.client.chat.completions.create(Object.assign(Object.assign({ model: (_b = this.chatCompletionCreateParams.model) !== null && _b !== void 0 ? _b : "gpt-4o" }, this.chatCompletionCreateParams), { stream: false, messages: [
230
364
  ...this.fineTune.map((val) => ({
231
365
  role: "system",
232
366
  content: val,
233
367
  })),
234
368
  {
235
369
  role: "system",
236
- content: `Please translate ${originLanguage.name} to ${targetLanguage.name}` +
237
- (reference
238
- ? ". Use the reference translation to clarify the meaning of the source text."
239
- : ""),
370
+ content: instructions.join("\n"),
240
371
  },
241
372
  {
242
373
  role: "system",
243
- content: `After translation is complete, directly output the corresponding meaning without any irrelevant content`,
374
+ content: "Return only the translated text in the requested language. " +
375
+ "Do not add the source text, response labels, JSON or Markdown wrappers, or explanations. " +
376
+ "Preserve JSON examples that are part of the source text.",
244
377
  },
245
378
  {
246
379
  role: "user",
247
- content: reference
248
- ? JSON.stringify({
249
- source: value,
250
- referenceLanguage: (_c = (_b = SUPPORT_LANGUAGE_MAP[reference.language]) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : reference.language,
251
- reference: reference.value,
252
- })
253
- : value,
380
+ content: input,
254
381
  },
255
382
  ] }));
256
- const translation = (_d = chatCompletion === null || chatCompletion === void 0 ? void 0 : chatCompletion.choices[0]) === null || _d === void 0 ? void 0 : _d.message.content;
257
- if (reference && !(translation === null || translation === void 0 ? void 0 : translation.trim())) {
258
- throw new Error("No translation returned for referenced entry");
383
+ const choice = chatCompletion === null || chatCompletion === void 0 ? void 0 : chatCompletion.choices[0];
384
+ if ((choice === null || choice === void 0 ? void 0 : choice.message.refusal) || ((choice === null || choice === void 0 ? void 0 : choice.finish_reason) && choice.finish_reason !== "stop")) {
385
+ throw new Error("The model did not complete the translation");
259
386
  }
387
+ const translation = readTranslationResponse(choice === null || choice === void 0 ? void 0 : choice.message.content, source);
260
388
  return {
261
389
  key,
262
- value: translation !== null && translation !== void 0 ? translation : value,
390
+ value: protectedText ? protectedText.restore(translation) : translation,
263
391
  index,
264
392
  };
265
393
  }
@@ -279,7 +407,8 @@ export class I18nTranslateAgent {
279
407
  * @param fileName
280
408
  * @returns
281
409
  */
282
- this.getTranslateContent = (language, fileName, deferredEmptyFiles) => __awaiter(this, void 0, void 0, function* () {
410
+ this.getTranslateContent = (language, fileName, deferredEmptyFiles, sourceEntries) => __awaiter(this, void 0, void 0, function* () {
411
+ var _a;
283
412
  const translateFilePath = path.join(this.ENTRY_ROOT_PATH, this.SOURCE_LANGUAGE, fileName);
284
413
  /** 缓存文件路径 */
285
414
  const cacheFilePath = path.join(this.CACHE_ROOT_PATH, language, fileName);
@@ -287,7 +416,7 @@ export class I18nTranslateAgent {
287
416
  console.dir(`File not found: ${translateFilePath}`);
288
417
  return;
289
418
  }
290
- const translateFileObject = yield readJsonFileSync(translateFilePath);
419
+ const _b = (_a = sourceEntries !== null && sourceEntries !== void 0 ? sourceEntries : (yield readJsonFileSync(translateFilePath))) !== null && _a !== void 0 ? _a : {}, { _meta } = _b, translateFileObject = __rest(_b, ["_meta"]);
291
420
  const cacheObject = yield getCacheFileSync(cacheFilePath);
292
421
  const diffObject = translateJSONDiffToJson(cacheObject, translateFileObject);
293
422
  if (Object.values(diffObject).length === 0) {
@@ -332,6 +461,7 @@ export class I18nTranslateAgent {
332
461
  delete oldJsonMap[key];
333
462
  }
334
463
  const newJsonMap = Object.assign(oldJsonMap, jsonMap);
464
+ delete newJsonMap._meta;
335
465
  yield fs.writeFileSync(path.resolve(outputFilePath), JSON.stringify(newJsonMap, null, 2), "utf8");
336
466
  // 注册缓存
337
467
  yield registerLanguageCacheFile({
@@ -357,6 +487,7 @@ export class I18nTranslateAgent {
357
487
  this.OUTPUT_ROOT_PATH = params.outputRootPath;
358
488
  /** 微调模型 */
359
489
  this.fineTune = (_d = params.fineTune) !== null && _d !== void 0 ? _d : [];
490
+ this.noTranslate = readProtectedTerms(params.noTranslate);
360
491
  /** 需要翻译的语言列表 */
361
492
  this.languages = (_e = params.languages) !== null && _e !== void 0 ? _e : [];
362
493
  /** 翻译任务并发数(队列长度),完成一个即取下一个 */
@@ -383,75 +514,80 @@ export class I18nTranslateAgent {
383
514
  searchLanguage(code) {
384
515
  return this.supportLanguages.find((item) => item.code === code);
385
516
  }
386
- reviewReferences(matches, language) {
517
+ reviewReferences(matches, language, blocked) {
387
518
  return __awaiter(this, void 0, void 0, function* () {
388
519
  var _a, _b, _c, _d, _e;
389
- const blocked = new Map();
520
+ let skipped = 0;
390
521
  const sourceLanguage = (_b = (_a = SUPPORT_LANGUAGE_MAP[this.SOURCE_LANGUAGE]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : this.SOURCE_LANGUAGE;
391
522
  const referenceLanguage = (_d = (_c = SUPPORT_LANGUAGE_MAP[language]) === null || _c === void 0 ? void 0 : _c.name) !== null && _d !== void 0 ? _d : language;
392
523
  const timeout = (_e = this.openaiClientConfig.timeout) !== null && _e !== void 0 ? _e : 30000;
393
- const checks = Array.from(matches).flatMap(([fileName, entries]) => Array.from(entries, ([key, { source, translation }]) => () => __awaiter(this, void 0, void 0, function* () {
394
- var _a, _b, _c;
395
- let issue;
396
- for (let attempt = 0;; attempt++) {
397
- const deadline = new AbortController();
398
- const timer = setTimeout(() => deadline.abort(), timeout);
399
- try {
400
- if (!this.client)
401
- throw new Error("Connection failed");
402
- const response = yield this.client.chat.completions.create({
403
- model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o",
404
- messages: [
405
- {
406
- role: "system",
407
- content: "Compare the source UI text and its reference translation. " +
408
- "Reply CONFLICT only when they clearly express incompatible product meanings. " +
409
- "A reference that clarifies an ambiguous source or adds compatible detail is not a conflict. " +
410
- "Reply COMPATIBLE in all other cases. Output exactly one label.",
411
- },
412
- {
413
- role: "user",
414
- content: JSON.stringify({
415
- sourceLanguage,
416
- source,
417
- referenceLanguage,
418
- reference: translation,
419
- }),
420
- },
421
- ],
422
- }, { signal: deadline.signal, timeout, maxRetries: 0 });
423
- const verdict = (_c = (_b = response.choices[0]) === null || _b === void 0 ? void 0 : _b.message.content) === null || _c === void 0 ? void 0 : _c.trim();
424
- if (verdict === "COMPATIBLE")
425
- return;
426
- if (verdict !== "CONFLICT")
427
- throw new Error("Invalid reference verdict");
428
- issue = new Error("Reference conflict");
429
- break;
430
- }
431
- catch (error) {
432
- if (attempt >= this.maxTaskRetries) {
433
- const reason = deadline.signal.aborted
434
- ? `request timed out after ${timeout} ms`
435
- : error;
436
- issue = new Error(`Reference judgment failed: ${reason}`);
524
+ const checks = Array.from(matches).flatMap(([fileName, entries]) => {
525
+ const blockedKeys = blocked.get(fileName);
526
+ const pending = Array.from(entries).filter(([key]) => !(blockedKeys === null || blockedKeys === void 0 ? void 0 : blockedKeys.has(key)));
527
+ return pending.map(([key, { source, translation }]) => () => __awaiter(this, void 0, void 0, function* () {
528
+ var _a, _b, _c;
529
+ let issue;
530
+ for (let attempt = 0;; attempt++) {
531
+ const deadline = new AbortController();
532
+ const timer = setTimeout(() => deadline.abort(), timeout);
533
+ try {
534
+ if (!this.client)
535
+ throw new Error("Connection failed");
536
+ const response = yield this.client.chat.completions.create({
537
+ model: (_a = this.chatCompletionCreateParams.model) !== null && _a !== void 0 ? _a : "gpt-4o",
538
+ messages: [
539
+ {
540
+ role: "system",
541
+ content: "Compare the source UI text and its reference translation. " +
542
+ "Reply CONFLICT only when they clearly express incompatible product meanings. " +
543
+ "A reference that clarifies an ambiguous source or adds compatible detail is not a conflict. " +
544
+ "Reply COMPATIBLE in all other cases. Output exactly one label.",
545
+ },
546
+ {
547
+ role: "user",
548
+ content: JSON.stringify({
549
+ sourceLanguage,
550
+ source,
551
+ referenceLanguage,
552
+ reference: translation,
553
+ }),
554
+ },
555
+ ],
556
+ }, { signal: deadline.signal, timeout, maxRetries: 0 });
557
+ const verdict = (_c = (_b = response.choices[0]) === null || _b === void 0 ? void 0 : _b.message.content) === null || _c === void 0 ? void 0 : _c.trim();
558
+ if (verdict === "COMPATIBLE")
559
+ return;
560
+ if (verdict !== "CONFLICT")
561
+ throw new Error("Invalid reference verdict");
562
+ issue = new Error("Reference conflict");
437
563
  break;
438
564
  }
565
+ catch (error) {
566
+ if (attempt >= this.maxTaskRetries) {
567
+ const reason = deadline.signal.aborted
568
+ ? `request timed out after ${timeout} ms`
569
+ : error;
570
+ issue = new Error(`Reference judgment failed: ${reason}`);
571
+ break;
572
+ }
573
+ }
574
+ finally {
575
+ clearTimeout(timer);
576
+ }
577
+ yield sleep(this.taskRetryBaseDelayMs * (attempt + 1));
439
578
  }
440
- finally {
441
- clearTimeout(timer);
579
+ let keys = blocked.get(fileName);
580
+ if (!keys) {
581
+ keys = new Set();
582
+ blocked.set(fileName, keys);
442
583
  }
443
- yield sleep(this.taskRetryBaseDelayMs * (attempt + 1));
444
- }
445
- let keys = blocked.get(fileName);
446
- if (!keys) {
447
- keys = new Set();
448
- blocked.set(fileName, keys);
449
- }
450
- keys.add(key);
451
- yield logErrorToFile({ error: issue, fileName, key, language });
452
- })));
584
+ keys.add(key);
585
+ skipped++;
586
+ yield logErrorToFile({ error: issue, fileName, key, language });
587
+ }));
588
+ });
453
589
  if (checks.length === 0)
454
- return blocked;
590
+ return;
455
591
  let completed = 0;
456
592
  const reportProgress = () => {
457
593
  console.log(`Reference checks: ${completed}/${checks.length} completed`);
@@ -472,11 +608,9 @@ export class I18nTranslateAgent {
472
608
  clearInterval(progressTimer);
473
609
  }
474
610
  reportProgress();
475
- const skipped = Array.from(blocked.values()).reduce((count, keys) => count + keys.size, 0);
476
611
  if (skipped) {
477
612
  console.warn(`Skipped ${skipped} reference entries. See error.log for details.`);
478
613
  }
479
- return blocked;
480
614
  });
481
615
  }
482
616
  }
@@ -1,4 +1,4 @@
1
- import { IDeleteSingleCacheParams, IGenerateCacheParams, IJson, IRegisterLanguageCacheFile } from "../../types";
1
+ import { IDeleteSingleCacheParams, IGenerateCacheParams, IJson, IRegisterLanguageCacheFile, ReferenceCacheState, ReferenceSnapshot } from "../../types/index.js";
2
2
  /**
3
3
  * 和翻译缓存json文件对比 返回存在更改的json文件
4
4
  * @param {object} cacheObject 已经缓存的对象
@@ -12,6 +12,8 @@ export declare const translateJSONDiffToJson: (cacheObject: IJson, translateObje
12
12
  * @returns {Promise<{key:value}>}
13
13
  */
14
14
  export declare const getCacheFileSync: (filePath: string) => Promise<IJson>;
15
+ export declare const readReferenceCache: (filePath: string) => Map<string, ReferenceSnapshot>;
16
+ export declare const writeReferenceCache: ({ filePath, observed }: ReferenceCacheState) => void;
15
17
  /**
16
18
  * 注册语言缓存文件
17
19
  * @param {string} language
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/cache/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAEL,wBAAwB,EACxB,oBAAoB,EACpB,KAAK,EACL,0BAA0B,EAC3B,MAAM,aAAa,CAAC;AAErB;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,gBACrB,KAAK,mBACD,KAAK,UAiBvB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,aAAoB,MAAM,KAAG,OAAO,CAAC,KAAK,CAMtE,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,WAC5B,0BAA0B,kBAmBnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,WAAkB,oBAAoB,kBAwC/D,CAAC;AAwCF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,WAAY,wBAAwB,SA8BhE,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/cache/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,wBAAwB,EACxB,oBAAoB,EACpB,KAAK,EACL,0BAA0B,EAC1B,mBAAmB,EACnB,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAE9B;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,gBACrB,KAAK,mBACD,KAAK,UAiBvB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,aAAoB,MAAM,KAAG,OAAO,CAAC,KAAK,CAMtE,CAAC;AAGF,eAAO,MAAM,kBAAkB,aAAc,MAAM,KAAG,GAAG,CAAC,MAAM,EAAE,iBAAiB,CAGpE,CAAC;AAEhB,eAAO,MAAM,mBAAmB,2BAA4B,mBAAmB,SAS9E,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,WAC5B,0BAA0B,kBAoBnC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,WAAkB,oBAAoB,kBAwC/D,CAAC;AAwCF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,WAAY,wBAAwB,SA8BhE,CAAC"}
@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import path from "path";
11
11
  import fs from "fs";
12
+ import { randomUUID } from "node:crypto";
12
13
  import { intersection, notExistsToCreateFile, readJsonFileSync, } from "../utils.js";
13
14
  /**
14
15
  * 和翻译缓存json文件对比 返回存在更改的json文件
@@ -46,6 +47,21 @@ export const getCacheFileSync = (filePath) => __awaiter(void 0, void 0, void 0,
46
47
  return {};
47
48
  }
48
49
  });
50
+ // 参考快照单独存储,保留现有源文案缓存的格式。
51
+ export const readReferenceCache = (filePath) => fs.existsSync(filePath)
52
+ ? new Map(Object.entries(JSON.parse(fs.readFileSync(filePath, "utf8"))))
53
+ : new Map();
54
+ export const writeReferenceCache = ({ filePath, observed }) => {
55
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
56
+ const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
57
+ try {
58
+ fs.writeFileSync(temporaryPath, JSON.stringify(Object.fromEntries(observed), null, 2));
59
+ fs.renameSync(temporaryPath, filePath);
60
+ }
61
+ finally {
62
+ fs.rmSync(temporaryPath, { force: true });
63
+ }
64
+ };
49
65
  /**
50
66
  * 注册语言缓存文件
51
67
  * @param {string} language
@@ -56,8 +72,10 @@ export const registerLanguageCacheFile = (params) => __awaiter(void 0, void 0, v
56
72
  const sourceObject = yield readJsonFileSync(sourceFilePath);
57
73
  const cacheObject = yield readJsonFileSync(cacheFilePath);
58
74
  Object.entries(jsonMap).forEach(([key, value]) => {
59
- cacheObject[key] = sourceObject[key];
75
+ if (key !== "_meta")
76
+ cacheObject[key] = sourceObject[key];
60
77
  });
78
+ delete cacheObject._meta;
61
79
  if (Object.values(jsonMap).length === 0)
62
80
  return;
63
81
  notExistsToCreateFile(folderName);
@@ -85,7 +103,7 @@ export const generateCache = (params) => __awaiter(void 0, void 0, void 0, funct
85
103
  const translated = {};
86
104
  // 遍历文件中的已经翻译的内容
87
105
  Object.entries(data).forEach(([key, value]) => {
88
- if (value) {
106
+ if (key !== "_meta" && value) {
89
107
  translated[key] = sourceFileMap[fileName].data[key];
90
108
  }
91
109
  });
@@ -1,3 +1,3 @@
1
- import { ITranslateLogError } from "../../types";
1
+ import type { ITranslateLogError } from "../../types/index.js";
2
2
  export declare function logErrorToFile(params: ITranslateLogError): Promise<void>;
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/log/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD,wBAAgB,cAAc,CAAC,MAAM,EAAE,kBAAkB,iBAWxD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/log/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D,wBAAgB,cAAc,CAAC,MAAM,EAAE,kBAAkB,iBAWxD"}
package/lib/support.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { SupportLanguageMap } from "../types";
1
+ import type { SupportLanguageMap } from "../types/index.js";
2
2
  export declare const SUPPORT_LANGUAGE_MAP: SupportLanguageMap;
3
3
  //# sourceMappingURL=support.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"support.d.ts","sourceRoot":"","sources":["../src/lib/support.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE9C,eAAO,MAAM,oBAAoB,EAAE,kBA6GlC,CAAC"}
1
+ {"version":3,"file":"support.d.ts","sourceRoot":"","sources":["../src/lib/support.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,eAAO,MAAM,oBAAoB,EAAE,kBA6GlC,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { FileTranslationMetadata } from "../types/index.js";
2
+ export declare const readProtectedTerms: (value: unknown) => readonly string[] | undefined;
3
+ export declare const readTranslationMetadata: (value: unknown) => FileTranslationMetadata | undefined;
4
+ export declare const protectTerms: (text: string, localTerms?: readonly string[], globalTerms?: readonly string[]) => {
5
+ text: string;
6
+ restore(translation: string): string;
7
+ } | undefined;
8
+ export declare const isProtectedText: (text: string, localTerms?: readonly string[], globalTerms?: readonly string[]) => boolean;
9
+ //# sourceMappingURL=translation-metadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translation-metadata.d.ts","sourceRoot":"","sources":["../src/lib/translation-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAEjE,eAAO,MAAM,kBAAkB,UAAW,OAAO,KAAG,SAAS,MAAM,EAAE,GAAG,SAQvE,CAAC;AAEF,eAAO,MAAM,uBAAuB,UAAW,OAAO,KAAG,uBAAuB,GAAG,SASlF,CAAC;AAEF,eAAO,MAAM,YAAY,SACjB,MAAM,eACC,SAAS,MAAM,EAAE,gBAChB,SAAS,MAAM,EAAE;;yBAgCR,MAAM;aAW9B,CAAC;AAEF,eAAO,MAAM,eAAe,SACpB,MAAM,eACC,SAAS,MAAM,EAAE,gBAChB,SAAS,MAAM,EAAE,YAMhC,CAAC"}
@@ -0,0 +1,67 @@
1
+ export const readProtectedTerms = (value) => {
2
+ if (Array.isArray(value) &&
3
+ value.length > 0 &&
4
+ value.every((term) => typeof term === "string" && term.trim() !== "")) {
5
+ return [...new Set(value.map((term) => term.trim()))];
6
+ }
7
+ };
8
+ export const readTranslationMetadata = (value) => {
9
+ if (!value || typeof value !== "object" || Array.isArray(value))
10
+ return;
11
+ const { context, noTranslate } = value;
12
+ const fileContext = typeof context === "string" ? context.trim() : "";
13
+ const protectedTerms = readProtectedTerms(noTranslate);
14
+ if (fileContext || protectedTerms) {
15
+ return { context: fileContext || undefined, noTranslate: protectedTerms };
16
+ }
17
+ };
18
+ export const protectTerms = (text, localTerms, globalTerms) => {
19
+ if (!(localTerms === null || localTerms === void 0 ? void 0 : localTerms.length) && !(globalTerms === null || globalTerms === void 0 ? void 0 : globalTerms.length))
20
+ return;
21
+ let prefix = "{__CC_PROTECTED_";
22
+ while (text.includes(prefix))
23
+ prefix += "_";
24
+ const placeholders = new Map();
25
+ let masked = text;
26
+ const wordCharacters = "[\\p{L}\\p{M}\\p{N}_]";
27
+ for (const terms of [localTerms, globalTerms]) {
28
+ if (!(terms === null || terms === void 0 ? void 0 : terms.length))
29
+ continue;
30
+ const alternatives = [...terms]
31
+ .sort((first, second) => second.length - first.length)
32
+ .map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
33
+ const pattern = new RegExp(`(?<!${wordCharacters})(?:${alternatives.join("|")})(?!${wordCharacters})`, "gu");
34
+ const segments = masked.split(/(\{[^{}]*\}|<[^<>]*>)/);
35
+ for (let index = 0; index < segments.length; index += 2) {
36
+ segments[index] = segments[index].replace(pattern, (term) => {
37
+ const placeholder = `${prefix}${placeholders.size}__}`;
38
+ placeholders.set(placeholder, term);
39
+ return placeholder;
40
+ });
41
+ }
42
+ masked = segments.join("");
43
+ }
44
+ if (placeholders.size === 0)
45
+ return;
46
+ return {
47
+ text: masked,
48
+ restore(translation) {
49
+ for (const [placeholder, term] of placeholders) {
50
+ const parts = translation.split(placeholder);
51
+ if (parts.length !== 2) {
52
+ throw new Error(`Translation must preserve protected placeholder ${placeholder} exactly once`);
53
+ }
54
+ translation = parts.join(term);
55
+ }
56
+ return translation;
57
+ },
58
+ };
59
+ };
60
+ export const isProtectedText = (text, localTerms, globalTerms) => {
61
+ if (!(localTerms === null || localTerms === void 0 ? void 0 : localTerms.length) && !(globalTerms === null || globalTerms === void 0 ? void 0 : globalTerms.length))
62
+ return false;
63
+ const value = text.trim();
64
+ if (localTerms === null || localTerms === void 0 ? void 0 : localTerms.includes(value))
65
+ return true;
66
+ return Boolean((globalTerms === null || globalTerms === void 0 ? void 0 : globalTerms.includes(value)) && !protectTerms(value, localTerms));
67
+ };
@@ -1,4 +1,4 @@
1
- import type { ISingleTranslate, SupportLanguageType } from "../types";
1
+ import type { ISingleTranslate, SupportLanguageType } from "../types/index.js";
2
2
  export interface TranslationReferenceOptions {
3
3
  language: SupportLanguageType;
4
4
  directory: string;
@@ -9,12 +9,14 @@ interface ReferenceMatch {
9
9
  translation: string;
10
10
  }
11
11
  export type ReferenceMatches = Map<string, Map<string, ReferenceMatch>>;
12
+ export type ReferenceFiles = ReadonlyMap<string, ReadonlyMap<string, string>>;
12
13
  export declare class TranslationReferencePlugin {
13
14
  readonly language: SupportLanguageType;
14
15
  readonly directory: string;
15
16
  readonly checkConflicts: boolean;
16
17
  constructor({ language, directory, checkConflicts, }: TranslationReferenceOptions);
17
- prepare(tasks: readonly Pick<ISingleTranslate, "fileName" | "translateJson">[], writableDirectories: string[]): Promise<ReferenceMatches | undefined>;
18
+ readFiles(sourceFiles: Iterable<string>, writableDirectories: string[]): ReferenceFiles;
19
+ prepare(tasks: readonly Pick<ISingleTranslate, "fileName" | "translateJson" | "metadata">[], writableDirectories: string[], globalNoTranslate?: readonly string[], references?: ReferenceFiles): Promise<ReferenceMatches | undefined>;
18
20
  }
19
21
  export {};
20
22
  //# sourceMappingURL=translation-reference.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"translation-reference.d.ts","sourceRoot":"","sources":["../src/lib/translation-reference.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAEtE,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,gBAAgB,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AAExE,qBAAa,0BAA0B;IACrC,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;gBAErB,EACV,QAAQ,EACR,SAAS,EACT,cAAsB,GACvB,EAAE,2BAA2B;IAMxB,OAAO,CACX,KAAK,EAAE,SAAS,IAAI,CAAC,gBAAgB,EAAE,UAAU,GAAG,eAAe,CAAC,EAAE,EACtE,mBAAmB,EAAE,MAAM,EAAE;CAkGhC"}
1
+ {"version":3,"file":"translation-reference.d.ts","sourceRoot":"","sources":["../src/lib/translation-reference.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAG/E,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,MAAM,gBAAgB,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AACxE,MAAM,MAAM,cAAc,GAAG,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAE9E,qBAAa,0BAA0B;IACrC,QAAQ,CAAC,QAAQ,EAAE,mBAAmB,CAAC;IACvC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC;gBAErB,EACV,QAAQ,EACR,SAAS,EACT,cAAsB,GACvB,EAAE,2BAA2B;IAM9B,SAAS,CAAC,WAAW,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,mBAAmB,EAAE,MAAM,EAAE,GAAG,cAAc;IAwCjF,OAAO,CACX,KAAK,EAAE,SAAS,IAAI,CAAC,gBAAgB,EAAE,UAAU,GAAG,eAAe,GAAG,UAAU,CAAC,EAAE,EACnF,mBAAmB,EAAE,MAAM,EAAE,EAC7B,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,EACrC,UAAU,CAAC,EAAE,cAAc;CAuE9B"}
@@ -10,66 +10,83 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import fs from "fs";
11
11
  import path from "path";
12
12
  import { createInterface } from "node:readline";
13
+ import { isProtectedText } from "./translation-metadata.js";
13
14
  export class TranslationReferencePlugin {
14
15
  constructor({ language, directory, checkConflicts = false, }) {
15
16
  this.language = language;
16
17
  this.directory = path.resolve(directory);
17
18
  this.checkConflicts = checkConflicts;
18
19
  }
19
- prepare(tasks, writableDirectories) {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- var _a;
22
- let fileNames;
23
- let referenceDirectory;
20
+ readFiles(sourceFiles, writableDirectories) {
21
+ let fileNames;
22
+ let referenceDirectory;
23
+ try {
24
+ fileNames = new Set(fs.readdirSync(this.directory));
25
+ referenceDirectory = fs.realpathSync(this.directory);
26
+ }
27
+ catch (error) {
28
+ throw new Error(`Cannot read reference directory ${this.directory}: ${error}`);
29
+ }
30
+ for (const directory of writableDirectories) {
31
+ if (fs.existsSync(directory) &&
32
+ fs.realpathSync(directory) === referenceDirectory) {
33
+ throw new Error(`Reference directory is read-only for translation: ${this.directory}`);
34
+ }
35
+ }
36
+ const references = new Map();
37
+ for (const fileName of sourceFiles) {
38
+ if (!fileNames.has(fileName))
39
+ continue;
40
+ const referencePath = path.join(this.directory, fileName);
24
41
  try {
25
- fileNames = new Set(fs.readdirSync(this.directory));
26
- referenceDirectory = fs.realpathSync(this.directory);
42
+ const data = JSON.parse(fs.readFileSync(referencePath, "utf8"));
43
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
44
+ throw new Error("Expected a JSON object");
45
+ }
46
+ const entries = new Map();
47
+ for (const [key, value] of Object.entries(data)) {
48
+ if (typeof value === "string" && value.trim())
49
+ entries.set(key, value);
50
+ }
51
+ references.set(fileName, entries);
27
52
  }
28
53
  catch (error) {
29
- throw new Error(`Cannot read reference directory ${this.directory}: ${error}`);
30
- }
31
- for (const directory of writableDirectories) {
32
- if (fs.existsSync(directory) &&
33
- fs.realpathSync(directory) === referenceDirectory) {
34
- throw new Error(`Reference directory is read-only for translation: ${this.directory}`);
35
- }
54
+ throw new Error(`Cannot read reference file ${referencePath}: ${error}`);
36
55
  }
56
+ }
57
+ return references;
58
+ }
59
+ prepare(tasks, writableDirectories, globalNoTranslate, references) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ var _a;
37
62
  const pending = new Map();
38
- for (const { fileName, translateJson } of tasks) {
63
+ for (const { fileName, translateJson, metadata } of tasks) {
39
64
  let entries = pending.get(fileName);
40
- if (!entries) {
41
- entries = new Map();
42
- pending.set(fileName, entries);
43
- }
44
65
  for (const [key, source] of Object.entries(translateJson)) {
66
+ if (isProtectedText(source, metadata === null || metadata === void 0 ? void 0 : metadata.noTranslate, globalNoTranslate))
67
+ continue;
68
+ if (!entries) {
69
+ entries = new Map();
70
+ pending.set(fileName, entries);
71
+ }
45
72
  entries.set(key, source);
46
73
  }
47
74
  }
48
75
  const matches = new Map();
49
76
  const report = [];
50
77
  let hasUnmatched = false;
78
+ const referenceFiles = references !== null && references !== void 0 ? references : this.readFiles(pending.keys(), writableDirectories);
51
79
  for (const [fileName, entries] of pending) {
52
- if (!fileNames.has(fileName)) {
80
+ const reference = referenceFiles.get(fileName);
81
+ if (!reference) {
53
82
  report.push(` ${fileName}: missing reference file (0/${entries.size} matched)`);
54
83
  hasUnmatched = true;
55
84
  continue;
56
85
  }
57
- const referencePath = path.join(this.directory, fileName);
58
- let reference;
59
- try {
60
- const data = JSON.parse(fs.readFileSync(referencePath, "utf8"));
61
- if (!data || typeof data !== "object" || Array.isArray(data)) {
62
- throw new Error("Expected a JSON object");
63
- }
64
- reference = data;
65
- }
66
- catch (error) {
67
- throw new Error(`Cannot read reference file ${referencePath}: ${error}`);
68
- }
69
86
  const fileMatches = new Map();
70
87
  for (const [key, source] of entries) {
71
- const translation = reference[key];
72
- if (typeof translation === "string" && translation.trim()) {
88
+ const translation = reference.get(key);
89
+ if (translation !== undefined) {
73
90
  fileMatches.set(key, { source, translation });
74
91
  }
75
92
  }
@@ -86,7 +103,7 @@ export class TranslationReferencePlugin {
86
103
  console.log("All pending entries have matching references.");
87
104
  return matches;
88
105
  }
89
- console.log("Unmatched entries will be translated without a reference.");
106
+ console.log("Unmatched entries will omit the reference from this directory.");
90
107
  if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CI) {
91
108
  console.warn("Translation cancelled: confirmation requires an interactive terminal.");
92
109
  return;
@@ -0,0 +1,2 @@
1
+ export declare function readTranslationResponse(content: string | null | undefined, source: string): string;
2
+ //# sourceMappingURL=translation-response.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translation-response.d.ts","sourceRoot":"","sources":["../src/lib/translation-response.ts"],"names":[],"mappings":"AAQA,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAClC,MAAM,EAAE,MAAM,GACb,MAAM,CA6CR"}
@@ -0,0 +1,47 @@
1
+ const codeFence = /^\x60{3}(?:json|text|plaintext)?[ \t]*\r?\n([\s\S]*?)\r?\n\x60{3}$/i;
2
+ const structuredPrefix = /^\{\s*["'}]|^\[\s*["{\[\]]/;
3
+ const responseLabel = /(?:^|\r?\n)\s*(?:\*{1,2})?(?:source|target|translation|translated text)(?:\*{1,2})?\s*:/i;
4
+ const responsePreamble = /(?:^|\r?\n)\s*(?:\*{1,2})?(?:(?:here (?:is|are)|here['’]s)\b[^:\r\n]*\b(?:translation|translated text)(?:\s+(?:in|to|of)\s+[^:\r\n]+)?|the(?: [a-z-]+){0,4} translation is(?: as follows)?)(?:\*{1,2})?\s*:/i;
5
+ const inlineEnvelope = /(?:\{|,)\s*"(?:source|target|translation)"\s*:/i;
6
+ export function readTranslationResponse(content, source) {
7
+ let text = content === null || content === void 0 ? void 0 : content.trim();
8
+ if (!text)
9
+ throw new Error("No translation returned");
10
+ const fenced = codeFence.exec(text);
11
+ if (fenced)
12
+ text = fenced[1].trim();
13
+ if (/^[{[\"]/.test(text)) {
14
+ let parsed;
15
+ try {
16
+ parsed = JSON.parse(text);
17
+ }
18
+ catch (_a) {
19
+ if (structuredPrefix.test(text)) {
20
+ throw new Error("Malformed structured translation response");
21
+ }
22
+ }
23
+ if (typeof parsed === "string") {
24
+ text = parsed.trim();
25
+ }
26
+ else if (parsed && typeof parsed === "object") {
27
+ const { target, translation } = parsed;
28
+ const value = target !== null && target !== void 0 ? target : translation;
29
+ if (typeof value !== "string" ||
30
+ (target != null && translation != null && target !== translation)) {
31
+ throw new Error("Structured response must contain one unambiguous translation");
32
+ }
33
+ text = value.trim();
34
+ }
35
+ }
36
+ // 识别响应包装时,保留原文中本来就有的内嵌 JSON 示例和文案标签。
37
+ if (!text ||
38
+ text.startsWith("\x60\x60\x60") ||
39
+ text.endsWith("\x60\x60\x60") ||
40
+ structuredPrefix.test(text) ||
41
+ (inlineEnvelope.test(text) && !inlineEnvelope.test(source)) ||
42
+ (responseLabel.test(text) && !responseLabel.test(source)) ||
43
+ (responsePreamble.test(text) && !responsePreamble.test(source))) {
44
+ throw new Error("Expected only the translated text");
45
+ }
46
+ return text;
47
+ }
package/lib/utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ICreateJsonFileParams } from "../types";
1
+ import type { ICreateJsonFileParams } from "../types/index.js";
2
2
  /**
3
3
  * 不存在的文件夹则创建
4
4
  * @param {string} path
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/lib/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAEjD;;;GAGG;AACH,eAAO,MAAM,qBAAqB,SAAU,MAAM,SAGjD,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,SAAgB,MAAM,iBAUlD,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,WAAY,qBAAqB,SAS3D,CAAC;AAEF,eAAO,MAAM,eAAe,QAAS,MAAM,OAAO,MAAM,WAEvD,CAAC;AAEF,eAAO,MAAM,KAAK,OAAQ,MAAM,kBACyB,CAAC;AAE1D,eAAO,MAAM,eAAe,SAAU,MAAM,YAG3C,CAAC;AAEF,eAAO,MAAM,iBAAiB,YAAa,MAAM,aAKhD,CAAC;AAEF,wBAAgB,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,MAAM,SASzE;AAED,wBAAgB,YAAY,CAAC,CAA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I,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAczD;AAGD,MAAM,MAAM,UAAU,CAAC,CAAC,IACpB;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GACjC;IAAE,MAAM,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,GAAG,CAAA;CAAE,CAAC;AAExC;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,CAAC;AAC7C,sCAAsC;AACtC,KAAK,EAAE,CAAC,MAAM,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE;AAC3B,gBAAgB;AAChB,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,CA2B1B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-translate",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "A language translation tool based on OpenAI",
5
5
  "author": "maybe",
6
6
  "license": "ISC",
package/types/index.d.ts CHANGED
@@ -40,6 +40,26 @@ export interface IRegisterLanguageCacheFile {
40
40
  export interface IJson {
41
41
  [key: string]: string;
42
42
  }
43
+ export type ReferenceSnapshot = Record<string, string | null>;
44
+ export interface ReferenceCacheState {
45
+ filePath: string;
46
+ observed: Map<string, ReferenceSnapshot>;
47
+ current: ReadonlyMap<string, ReferenceSnapshot>;
48
+ }
49
+ export interface FileTranslationMetadata {
50
+ context?: string;
51
+ noTranslate?: readonly string[];
52
+ }
53
+ interface TranslationReference {
54
+ language: SupportLanguageType;
55
+ value: string;
56
+ }
57
+ interface FileTranslationReference {
58
+ language: SupportLanguageType;
59
+ matches: ReadonlyMap<string, {
60
+ translation: string;
61
+ }>;
62
+ }
43
63
  export interface ISingleTranslate {
44
64
  language: SupportLanguageType;
45
65
  fileName: string;
@@ -47,13 +67,11 @@ export interface ISingleTranslate {
47
67
  multiBar?: MultiBar;
48
68
  progressBar?: SingleBar;
49
69
  callback?: () => void;
50
- reference?: {
51
- language: SupportLanguageType;
52
- matches: ReadonlyMap<string, {
53
- translation: string;
54
- }>;
55
- };
70
+ reference?: FileTranslationReference;
71
+ references?: readonly FileTranslationReference[];
56
72
  blockedKeys?: ReadonlySet<string>;
73
+ metadata?: FileTranslationMetadata;
74
+ referenceCache?: ReferenceCacheState;
57
75
  }
58
76
  export interface ITranslateChat {
59
77
  key: string;
@@ -61,10 +79,9 @@ export interface ITranslateChat {
61
79
  language: SupportLanguageType;
62
80
  index: number;
63
81
  fileName: string;
64
- reference?: {
65
- language: SupportLanguageType;
66
- value: string;
67
- };
82
+ reference?: TranslationReference;
83
+ references?: readonly TranslationReference[];
84
+ metadata?: FileTranslationMetadata;
68
85
  }
69
86
  export interface ITranslateChatResponse {
70
87
  key: string;
@@ -92,6 +109,8 @@ export interface II18nTranslateAgentParams {
92
109
  concurrency?: number;
93
110
  /** 微调模型 */
94
111
  fineTune?: string[];
112
+ /** 全局保护词语 */
113
+ noTranslate?: readonly string[];
95
114
  /** 翻译任务最大重试次数 */
96
115
  maxTaskRetries?: number;
97
116
  /** 翻译任务重试间隔时间(毫秒) */
@@ -117,4 +136,5 @@ export interface ICacheFile {
117
136
  filePath: string;
118
137
  data: Record<string, string>;
119
138
  }
139
+ export {};
120
140
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACnD,OAAe,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAE9D,MAAM,WAAW,SAAS;IACxB,aAAa;IACb,IAAI,EAAE,mBAAmB,CAAC;IAC1B,UAAU;IACV,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,MAAM,mBAAmB,GAC3B,IAAI,GACJ,OAAO,GACP,OAAO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