@boringparts/lioni 0.0.0-stage → 0.4.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.
@@ -0,0 +1,3797 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ // ../../packages/core/dist/quality/profiler.js
4
+ const sessions = /* @__PURE__ */ new WeakMap();
5
+ /** 创建单次检查运行专用的采集器;不得重置、复用或在运行中读取。 */
6
+ function createQualityProfiler(options = {}) {
7
+ const limit = options.slowestCandidates ?? 10;
8
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new TypeError("slowestCandidates 必须为非负安全整数。");
9
+ const state = {
10
+ used: false,
11
+ limit
12
+ };
13
+ const profiler = Object.freeze({ report() {
14
+ if (state.report === void 0) throw new TypeError("性能采集尚未结束。");
15
+ return structuredClone(state.report);
16
+ } });
17
+ sessions.set(profiler, state);
18
+ return profiler;
19
+ }
20
+ /** 内部正式运行接缝,不作为产品 SDK 导出。 */
21
+ function beginQualityProfile(profiler) {
22
+ const state = sessions.get(profiler);
23
+ if (state === void 0 || state.used) throw new TypeError("性能采集器必须由工厂创建且只能使用一次。");
24
+ state.used = true;
25
+ const started = performance.now();
26
+ const stages = /* @__PURE__ */ new Map();
27
+ const checks = /* @__PURE__ */ new Map();
28
+ const open = /* @__PURE__ */ new Set();
29
+ const candidates = /* @__PURE__ */ new Set();
30
+ const checkSpans = /* @__PURE__ */ new Set();
31
+ function check(id) {
32
+ let entry = checks.get(id);
33
+ if (entry === void 0) {
34
+ entry = {
35
+ checkId: id,
36
+ durationMs: 0,
37
+ candidateCount: 0,
38
+ executedRules: 0,
39
+ outcomes: {},
40
+ timings: /* @__PURE__ */ new Map(),
41
+ cache: {
42
+ enabled: false,
43
+ reads: {
44
+ hit: 0,
45
+ miss: 0,
46
+ invalid: 0,
47
+ error: 0
48
+ },
49
+ writes: {
50
+ completed: 0,
51
+ error: 0
52
+ }
53
+ },
54
+ slowestCandidates: []
55
+ };
56
+ checks.set(id, entry);
57
+ }
58
+ return entry;
59
+ }
60
+ function span(target, stage, total) {
61
+ const start = performance.now();
62
+ let closed = false;
63
+ let duration = 0;
64
+ const end = () => {
65
+ if (closed) return duration;
66
+ closed = true;
67
+ open.delete(end);
68
+ checkSpans.delete(end);
69
+ duration = performance.now() - start;
70
+ const timing = target.get(stage) ?? {
71
+ stage,
72
+ durationMs: 0,
73
+ calls: 0
74
+ };
75
+ timing.durationMs += duration;
76
+ timing.calls++;
77
+ target.set(stage, timing);
78
+ if (total !== void 0) total.durationMs += duration;
79
+ return duration;
80
+ };
81
+ open.add(end);
82
+ if (target !== stages) checkSpans.add(end);
83
+ return end;
84
+ }
85
+ function endChecks() {
86
+ for (const end of [...checkSpans].reverse()) end();
87
+ for (const interrupt of candidates) interrupt();
88
+ }
89
+ return {
90
+ endChecks,
91
+ configure(id, enabled) {
92
+ check(id).cache.enabled = enabled;
93
+ },
94
+ stage: (stage) => span(stages, stage),
95
+ checkStage(id, stage) {
96
+ const entry = check(id);
97
+ return span(entry.timings, stage, entry);
98
+ },
99
+ candidate(id, identity, enabled) {
100
+ const entry = check(id);
101
+ entry.candidateCount++;
102
+ entry.cache.enabled = enabled;
103
+ const timings = /* @__PURE__ */ new Map();
104
+ const endTotal = span(entry.timings, "candidates", entry);
105
+ let closed = false;
106
+ const finish = (status, completed) => {
107
+ if (closed) return;
108
+ closed = true;
109
+ candidates.delete(interrupt);
110
+ entry.outcomes[status] = (entry.outcomes[status] ?? 0) + 1;
111
+ const durationMs = endTotal();
112
+ if (state.limit === 0) return;
113
+ const record = {
114
+ ...identity,
115
+ status,
116
+ completed,
117
+ durationMs,
118
+ timings: [...timings.values()]
119
+ };
120
+ entry.slowestCandidates.push(record);
121
+ entry.slowestCandidates.sort((a, b) => b.durationMs - a.durationMs || a.subjectIndex - b.subjectIndex);
122
+ if (entry.slowestCandidates.length > state.limit) entry.slowestCandidates.pop();
123
+ };
124
+ const interrupt = () => finish("interrupted", false);
125
+ candidates.add(interrupt);
126
+ return {
127
+ stage(stage) {
128
+ const local = span(timings, stage);
129
+ const aggregate = span(entry.timings, stage);
130
+ return () => {
131
+ local();
132
+ aggregate();
133
+ };
134
+ },
135
+ executed() {
136
+ entry.executedRules++;
137
+ },
138
+ read(result) {
139
+ entry.cache.reads[result]++;
140
+ },
141
+ write(result) {
142
+ entry.cache.writes[result]++;
143
+ },
144
+ finish: (status) => finish(status, true)
145
+ };
146
+ },
147
+ finish(status) {
148
+ endChecks();
149
+ for (const end of [...open].reverse()) end();
150
+ state.report = {
151
+ schemaVersion: 1,
152
+ status,
153
+ totalMs: performance.now() - started,
154
+ stages: [...stages.values()],
155
+ checks: [...checks.values()].map((entry) => ({
156
+ ...entry,
157
+ timings: [...entry.timings.values()]
158
+ }))
159
+ };
160
+ }
161
+ };
162
+ }
163
+ // ../../packages/core/dist/read-coverage.js
164
+ /** 汇总已枚举的范围;空范围表示本次未读取。 */
165
+ function readStatus(scopes, error) {
166
+ if (error !== void 0 || scopes.some(({ enumeration }) => enumeration === "failed")) return "failed";
167
+ if (scopes.length === 0) return "notRead";
168
+ return scopes.every(({ enumeration }) => enumeration === "complete") ? "complete" : "incomplete";
169
+ }
170
+ // ../../packages/memo/dist/index.js
171
+ var MemoScopeClosedError = class extends Error {
172
+ constructor() {
173
+ super("计算复用范围已经结束,不能继续计算。");
174
+ this.name = "MemoScopeClosedError";
175
+ }
176
+ };
177
+ const negativeZero = Symbol("负零键");
178
+ const argumentKeys = (...args) => args;
179
+ function createNode() {
180
+ return { children: /* @__PURE__ */ new Map() };
181
+ }
182
+ /**
183
+ * 创建一个显式拥有的计算复用范围。
184
+ * 参数按 Object.is 比较,对象按身份;输入、策略和复用结果须保持不可变。
185
+ * 同步异常和拒绝的 Promise 也保留到范围结束,不隐式重试。
186
+ */
187
+ function createMemoScope() {
188
+ const operations = /* @__PURE__ */ new Map();
189
+ let closed = false;
190
+ function ensureOpen() {
191
+ if (closed) throw new MemoScopeClosedError();
192
+ }
193
+ function memo(operation, options = {}) {
194
+ ensureOpen();
195
+ const keyOf = options.key ?? argumentKeys;
196
+ let policies = operations.get(operation);
197
+ if (policies === void 0) {
198
+ policies = /* @__PURE__ */ new Map();
199
+ operations.set(operation, policies);
200
+ }
201
+ const existing = policies.get(keyOf);
202
+ if (existing !== void 0) return existing.invoke;
203
+ const root = createNode();
204
+ const invoke = (...args) => {
205
+ ensureOpen();
206
+ const keys = keyOf(...args);
207
+ if (!Array.isArray(keys)) throw new TypeError("计算缓存的键函数必须返回参数元组。");
208
+ let node = root;
209
+ for (const value of keys) {
210
+ const key = Object.is(value, -0) ? negativeZero : value;
211
+ let child = node.children.get(key);
212
+ if (child === void 0) {
213
+ child = createNode();
214
+ node.children.set(key, child);
215
+ }
216
+ node = child;
217
+ }
218
+ const entry = node.entry;
219
+ if (entry?.kind === "value") return entry.value;
220
+ if (entry?.kind === "failure") throw entry.error;
221
+ try {
222
+ const value = operation(...args);
223
+ if (!closed) node.entry = {
224
+ kind: "value",
225
+ value
226
+ };
227
+ return value;
228
+ } catch (error) {
229
+ if (!closed) node.entry = {
230
+ kind: "failure",
231
+ error
232
+ };
233
+ throw error;
234
+ }
235
+ };
236
+ policies.set(keyOf, {
237
+ root,
238
+ invoke
239
+ });
240
+ return invoke;
241
+ }
242
+ return {
243
+ memo,
244
+ dispose: () => {
245
+ if (closed) return;
246
+ closed = true;
247
+ for (const policies of operations.values()) for (const { root } of policies.values()) {
248
+ root.children.clear();
249
+ delete root.entry;
250
+ }
251
+ operations.clear();
252
+ }
253
+ };
254
+ }
255
+ // ../../packages/core/dist/language-scope.js
256
+ function resolveLanguageSelection(configuredLanguages, options) {
257
+ const requested = options.languages;
258
+ if (requested === void 0) return configuredLanguages;
259
+ if (!Array.isArray(requested) || requested.length === 0 || requested.some((language) => typeof language !== "string")) throw new TypeError("本次执行的 languages 必须是非空语言列表。");
260
+ for (const language of requested) if (!configuredLanguages.includes(language)) throw new TypeError(`目标语言 ${JSON.stringify(language)} 未在配置中声明。`);
261
+ const selected = new Set(requested);
262
+ return [...new Set(configuredLanguages)].filter((language) => selected.has(language));
263
+ }
264
+ // ../../packages/core/dist/object-guards.js
265
+ /** 识别可读取字符串键的非数组对象,包括带自定义原型的对象。 */
266
+ function isRecord(value) {
267
+ return typeof value === "object" && value !== null && !Array.isArray(value);
268
+ }
269
+ /** 识别 JSON 对象形状:普通原型或空原型对象。 */
270
+ function isPlainRecord(value) {
271
+ if (!isRecord(value)) return false;
272
+ const prototype = Object.getPrototypeOf(value);
273
+ return prototype === Object.prototype || prototype === null;
274
+ }
275
+ // ../../packages/core/dist/quality/candidate-contract.js
276
+ /** 验证单次 QA 候选都对应本次固定事实中的原文、语言与唯一身份。 */
277
+ function validateQualityCandidateScope(snapshot, candidates) {
278
+ const sourceKeys = new Set(snapshot.source.units.map(({ key }) => key));
279
+ const languages = new Set(snapshot.translations.reads.map(({ language }) => language));
280
+ const candidatesBySource = /* @__PURE__ */ new Map();
281
+ for (const candidate of candidates) {
282
+ if (typeof candidate?.sourceKey !== "string" || typeof candidate.language !== "string") throw new TypeError("译文候选必须包含字符串 sourceKey 与 language。");
283
+ if (!sourceKeys.has(candidate.sourceKey)) throw new TypeError(`译文候选原文键 ${JSON.stringify(candidate.sourceKey)} 不存在于本次已读取的原文中。`);
284
+ if (!languages.has(candidate.language)) throw new TypeError(`译文候选语言 ${JSON.stringify(candidate.language)} 不在本次执行范围内。`);
285
+ let candidateLanguages = candidatesBySource.get(candidate.sourceKey);
286
+ if (candidateLanguages === void 0) {
287
+ candidateLanguages = /* @__PURE__ */ new Set();
288
+ candidatesBySource.set(candidate.sourceKey, candidateLanguages);
289
+ }
290
+ if (candidateLanguages.has(candidate.language)) throw new TypeError(`译文候选身份 ${JSON.stringify({
291
+ sourceKey: candidate.sourceKey,
292
+ language: candidate.language
293
+ })} 重复。`);
294
+ candidateLanguages.add(candidate.language);
295
+ }
296
+ }
297
+ function savedTranslationCandidates(snapshot) {
298
+ return snapshot.associations.flatMap((association) => {
299
+ const record = snapshot.translations.records[association.translationIndexes[0]];
300
+ return record === void 0 || record.bodyAvailability !== "available" ? [] : [{
301
+ sourceKey: association.sourceKey,
302
+ language: association.language,
303
+ content: record.content
304
+ }];
305
+ });
306
+ }
307
+ // ../../packages/core/dist/quality/qa-suppressions.js
308
+ const QA_SUPPRESSION_FORMAT = "lioni.qa-suppressions/v1";
309
+ var QaSuppressionFormatError = class extends TypeError {
310
+ reason;
311
+ constructor(reason, message, options) {
312
+ super(message, options);
313
+ this.name = "QaSuppressionFormatError";
314
+ this.reason = reason;
315
+ }
316
+ };
317
+ /** 从正式报告的一条执行记录创建可手工维护的豁免绑定。 */
318
+ function createQaSuppression(input) {
319
+ const { id, reason, execution } = input;
320
+ assertNonEmptyString(id, "豁免身份");
321
+ assertNonEmptyString(reason, "豁免理由");
322
+ assertNonEmptyString(execution.checkId, "检查项身份");
323
+ assertString(execution.sourceKey, "原文键");
324
+ assertNonEmptyString(execution.language, "目标语言");
325
+ if (execution.inputFingerprint === void 0 || execution.fingerprintSummary === void 0) throw new QaSuppressionFormatError("invalid", "报告执行记录缺少可比较的输入指纹或依据摘要,不能建立豁免。");
326
+ const suppression = {
327
+ id,
328
+ reason,
329
+ checkId: execution.checkId,
330
+ sourceKey: execution.sourceKey,
331
+ language: execution.language,
332
+ inputFingerprint: execution.inputFingerprint,
333
+ fingerprintSummary: {
334
+ version: execution.fingerprintSummary.version,
335
+ inputFingerprint: execution.fingerprintSummary.inputFingerprint
336
+ }
337
+ };
338
+ validateQaSuppression(suppression);
339
+ return suppression;
340
+ }
341
+ /** 从 SDK 报告或 CLI 结构化报告中选择执行记录并写入豁免存储。 */
342
+ async function upsertQaSuppressionFromReport(input) {
343
+ const { report, checkId, executionId, id, reason, store } = input;
344
+ assertNonEmptyString(checkId, "检查项身份");
345
+ if (!Number.isSafeInteger(executionId) || executionId < 0) throw invalid("执行身份必须是非负整数。");
346
+ const reportValue = unwrapQualityReport(report);
347
+ validateQaSuppressions(reportValue.suppressions);
348
+ if (!Array.isArray(reportValue.checks)) throw invalid("QA 报告缺少 checks 执行列表。");
349
+ if (reportValue.diagnostics !== void 0 && !Array.isArray(reportValue.diagnostics)) throw invalid("QA 报告中的 diagnostics 列表无效。");
350
+ let selectedCheck;
351
+ let selectedExecution;
352
+ for (const check of reportValue.checks) {
353
+ if (!isPlainRecord(check) || typeof check.checkId !== "string" || !Array.isArray(check.executions)) throw invalid("QA 报告中的检查执行结构无效。");
354
+ if (check.diagnostics !== void 0 && !Array.isArray(check.diagnostics)) throw invalid("QA 报告中的检查诊断结构无效。");
355
+ if (check.checkId !== checkId) continue;
356
+ for (const execution of check.executions) {
357
+ if (!isPlainRecord(execution)) throw invalid("QA 报告中的检查执行结构无效。");
358
+ if (execution.executionId !== executionId) continue;
359
+ if (execution.checkId !== checkId) throw invalid("检查执行的检查身份与报告分组不一致。");
360
+ if (selectedExecution !== void 0) throw invalid("QA 报告中存在重复的检查与执行身份。");
361
+ selectedCheck = check;
362
+ selectedExecution = execution;
363
+ }
364
+ }
365
+ if (selectedExecution === void 0 || selectedCheck === void 0) throw invalid(`QA 报告中没有检查 ${checkId} 的执行 ${executionId}。`);
366
+ assertExecutionHasDiagnostic(reportValue.diagnostics, selectedCheck.diagnostics, checkId, executionId);
367
+ const suppression = createQaSuppression({
368
+ id,
369
+ reason,
370
+ execution: selectedExecution
371
+ });
372
+ await store.upsert(suppression);
373
+ return suppression;
374
+ }
375
+ function assertExecutionHasDiagnostic(reportDiagnostics, checkDiagnostics, checkId, executionId) {
376
+ const hasReportDiagnostics = Array.isArray(reportDiagnostics);
377
+ const hasCheckDiagnostics = Array.isArray(checkDiagnostics);
378
+ if (!hasReportDiagnostics && !hasCheckDiagnostics) throw invalid(`QA 报告缺少检查 ${checkId} 的诊断明细,不能确认执行 ${executionId} 产生了实际诊断。`);
379
+ if (hasReportDiagnostics && !hasMatchedDiagnostic(reportDiagnostics, checkId, executionId, true)) throw invalid(`检查 ${checkId} 的执行 ${executionId} 没有实际诊断,不能建立豁免。`);
380
+ if (hasCheckDiagnostics && !hasMatchedDiagnostic(checkDiagnostics, checkId, executionId, false)) throw invalid(`检查 ${checkId} 的执行 ${executionId} 没有实际诊断,不能建立豁免。`);
381
+ }
382
+ function hasMatchedDiagnostic(diagnostics, checkId, executionId, requireCheckId) {
383
+ let matched = false;
384
+ for (const diagnostic of diagnostics) {
385
+ if (!isPlainRecord(diagnostic)) throw invalid("QA 报告中的诊断结构无效。");
386
+ if (diagnostic.checkId !== void 0 && diagnostic.checkId !== checkId && !requireCheckId) throw invalid("实际诊断的检查身份与报告分组不一致。");
387
+ if ((requireCheckId ? diagnostic.checkId === checkId : diagnostic.checkId === void 0 || diagnostic.checkId === checkId) && diagnostic.executionId === executionId) matched = true;
388
+ }
389
+ return matched;
390
+ }
391
+ function unwrapQualityReport(value) {
392
+ if (!isPlainRecord(value)) throw invalid("QA 报告必须是对象。");
393
+ if (!Object.hasOwn(value, "data")) return value;
394
+ if (!isPlainRecord(value.data)) throw invalid("CLI QA 报告的 data 结果必须是对象。");
395
+ return value.data;
396
+ }
397
+ /** 验证单条豁免;手写 YAML、SDK 与命令共用此契约。 */
398
+ function validateQaSuppression(value) {
399
+ if (!isPlainRecord(value)) throw invalid("豁免记录必须是对象。");
400
+ assertExactKeys(value, [
401
+ "id",
402
+ "reason",
403
+ "checkId",
404
+ "sourceKey",
405
+ "language",
406
+ "inputFingerprint",
407
+ "fingerprintSummary"
408
+ ], "豁免记录");
409
+ assertNonEmptyString(value.id, "豁免身份");
410
+ assertNonEmptyString(value.reason, "豁免理由");
411
+ assertNonEmptyString(value.checkId, "检查项身份");
412
+ assertString(value.sourceKey, "原文键");
413
+ assertNonEmptyString(value.language, "目标语言");
414
+ assertNonEmptyString(value.inputFingerprint, "输入指纹");
415
+ if (!isPlainRecord(value.fingerprintSummary)) throw invalid("豁免依据摘要必须是对象。");
416
+ assertExactKeys(value.fingerprintSummary, ["version", "inputFingerprint"], "豁免依据摘要");
417
+ assertNonEmptyString(value.fingerprintSummary.version, "检查实现版本");
418
+ assertNonEmptyString(value.fingerprintSummary.inputFingerprint, "业务输入指纹");
419
+ }
420
+ /** 验证版本化豁免文件及其身份唯一性。 */
421
+ function validateQaSuppressionFile(value) {
422
+ if (!isPlainRecord(value)) throw invalid("豁免文件顶层必须是对象。");
423
+ if (value.format !== QA_SUPPRESSION_FORMAT) throw new QaSuppressionFormatError("unsupported", `不支持 QA 豁免文件格式:${typeof value.format === "string" ? value.format : "未标识"}。请依据当前 QA 报告重新建立需要保留的豁免。`);
424
+ assertExactKeys(value, ["format", "suppressions"], "豁免文件");
425
+ validateQaSuppressions(value.suppressions);
426
+ }
427
+ /** 验证由自定义存储或低层 QA 请求提供的豁免列表。 */
428
+ function validateQaSuppressions(value) {
429
+ if (!Array.isArray(value)) throw invalid("豁免列表必须是数组。");
430
+ const ids = /* @__PURE__ */ new Set();
431
+ const bindings = /* @__PURE__ */ new Map();
432
+ for (const suppression of value) {
433
+ validateQaSuppression(suppression);
434
+ if (ids.has(suppression.id)) throw invalid(`豁免身份重复:${suppression.id}。`);
435
+ ids.add(suppression.id);
436
+ const binding = qaSuppressionBindingKey(suppression);
437
+ const existingId = bindings.get(binding);
438
+ if (existingId !== void 0) throw invalid(`检查豁免绑定冲突:${existingId} 与 ${suppression.id} 指向同一检查绑定(${suppression.checkId},${suppression.sourceKey},${suppression.language})。`);
439
+ bindings.set(binding, suppression.id);
440
+ }
441
+ }
442
+ function qaSuppressionBindingKey(suppression) {
443
+ return JSON.stringify([
444
+ suppression.checkId,
445
+ suppression.sourceKey,
446
+ suppression.language,
447
+ suppression.inputFingerprint
448
+ ]);
449
+ }
450
+ /** 判断执行记录是否与豁免绑定的检查依据完全一致。 */
451
+ function qaSuppressionMatchesExecution(suppression, execution) {
452
+ return execution.checkId === suppression.checkId && execution.sourceKey === suppression.sourceKey && execution.language === suppression.language && execution.inputFingerprint === suppression.inputFingerprint;
453
+ }
454
+ /** 只在选定语言的完整已保存资源检查成功后调用,以免把局部未执行误判成失效。 */
455
+ function assertQaSuppressionBindings(input) {
456
+ if (input.suppressions.length === 0) return;
457
+ const executions = /* @__PURE__ */ new Map();
458
+ const diagnosedByCheckId = /* @__PURE__ */ new Set();
459
+ const diagnosedByCheckIndex = /* @__PURE__ */ new Set();
460
+ const identity = ({ checkId, sourceKey, language }) => JSON.stringify([
461
+ checkId,
462
+ sourceKey,
463
+ language
464
+ ]);
465
+ for (const [checkIndex, check] of input.savedChecks.entries()) {
466
+ for (const execution of check.executions) executions.set(identity(execution), {
467
+ checkIndex,
468
+ execution
469
+ });
470
+ for (const diagnostic of check.diagnostics) if (diagnostic.checkId !== void 0) diagnosedByCheckId.add(JSON.stringify([diagnostic.checkId, diagnostic.executionId]));
471
+ else diagnosedByCheckIndex.add(JSON.stringify([checkIndex, diagnostic.executionId]));
472
+ }
473
+ const errors = [];
474
+ for (const suppression of input.suppressions) {
475
+ const { id, checkId, sourceKey, language } = suppression;
476
+ if (input.selectedLanguages && !input.selectedLanguages.includes(language)) continue;
477
+ const reasons = [];
478
+ const checkExists = input.configuredCheckIds.includes(checkId);
479
+ const languageExists = input.configuredLanguages.includes(language);
480
+ const sourceKeyExists = input.completeSourceKeys.has(sourceKey);
481
+ if (!checkExists) reasons.push("检查项已不存在");
482
+ if (!languageExists) reasons.push("目标语言已不存在");
483
+ if (!sourceKeyExists) reasons.push("原文键已不存在");
484
+ const entry = executions.get(identity(suppression));
485
+ if (entry?.execution.inputFingerprint !== void 0) {
486
+ const { checkIndex, execution } = entry;
487
+ if (execution.inputFingerprint !== suppression.inputFingerprint) {
488
+ const recorded = suppression.fingerprintSummary;
489
+ const current = execution.fingerprintSummary;
490
+ if (current === void 0) reasons.push("检查指纹已改变");
491
+ else {
492
+ const versionChanged = recorded.version !== current.version;
493
+ const inputChanged = recorded.inputFingerprint !== current.inputFingerprint;
494
+ if (versionChanged) reasons.push("检查实现版本已改变");
495
+ if (inputChanged) reasons.push("检查输入指纹已改变");
496
+ if (!versionChanged && !inputChanged) reasons.push("检查指纹已改变");
497
+ }
498
+ } else if (execution.executionId === void 0 || !(diagnosedByCheckId.has(JSON.stringify([execution.checkId, execution.executionId])) || diagnosedByCheckIndex.has(JSON.stringify([checkIndex, execution.executionId])))) reasons.push("当前依据下没有可豁免的诊断");
499
+ } else if (checkExists && languageExists && sourceKeyExists) reasons.push(entry === void 0 ? "当前依据下没有可豁免的诊断" : "检查输入指纹已改变");
500
+ if (reasons.length > 0) errors.push(`${id}(${checkId},${sourceKey},${language}):${reasons.join("、")}`);
501
+ }
502
+ if (errors.length > 0) throw new Error(`请清理以下检查豁免:\n${errors.join("\n")}`);
503
+ }
504
+ function assertExactKeys(value, expected, description) {
505
+ const actual = Object.keys(value).sort();
506
+ const sortedExpected = [...expected].sort();
507
+ if (actual.length !== sortedExpected.length || actual.some((key, index) => key !== sortedExpected[index])) throw invalid(`${description}包含未知字段或缺少必需字段。`);
508
+ }
509
+ function assertNonEmptyString(value, description) {
510
+ if (typeof value !== "string" || value.trim().length === 0) throw invalid(`${description}必须是非空文本。`);
511
+ }
512
+ function assertString(value, description) {
513
+ if (typeof value !== "string") throw invalid(`${description}必须是文本。`);
514
+ }
515
+ function invalid(message) {
516
+ return new QaSuppressionFormatError("invalid", message);
517
+ }
518
+ // ../../packages/core/dist/standard-schema.js
519
+ var StandardSchemaContractError = class extends TypeError {
520
+ valueDescription;
521
+ kind;
522
+ issues;
523
+ constructor(valueDescription, kind, message, issues, options) {
524
+ super(message, options);
525
+ this.name = "StandardSchemaContractError";
526
+ this.valueDescription = valueDescription;
527
+ this.kind = kind;
528
+ this.issues = issues;
529
+ }
530
+ };
531
+ async function validateWithStandardSchema(schema, value, valueDescription, options = {}) {
532
+ const preserveValue = options.preserveValue === true || options.snapshotInput === true;
533
+ const requireJson = options.requireJson === true || preserveValue;
534
+ const before = preserveValue ? snapshotJsonValue(value, valueDescription) : void 0;
535
+ if (requireJson && !preserveValue) assertJsonValue(value, valueDescription);
536
+ let result;
537
+ let validationError;
538
+ try {
539
+ result = await schema["~standard"].validate(value);
540
+ } catch (error) {
541
+ validationError = error;
542
+ }
543
+ if (preserveValue && !matchesJsonSnapshot(value, before, valueDescription)) throw new StandardSchemaContractError(valueDescription, "input-mutated", `${valueDescription}的 Standard Schema 在验证时修改了输入值。`, void 0, validationError === void 0 ? void 0 : { cause: validationError });
544
+ if (validationError !== void 0) throw new StandardSchemaContractError(valueDescription, "schema-threw", `${valueDescription}的 Standard Schema 执行失败。`, void 0, { cause: validationError });
545
+ if (!isRecord(result)) throw new StandardSchemaContractError(valueDescription, "invalid-schema-result", `${valueDescription}的 Standard Schema 返回了无效结果。`);
546
+ const issues = result.issues;
547
+ if (issues !== void 0) {
548
+ if (!Array.isArray(issues) || issues.some((issue) => !isRecord(issue) || typeof issue.message !== "string")) throw new StandardSchemaContractError(valueDescription, "invalid-schema-result", `${valueDescription}的 Standard Schema 返回了无效问题列表。`);
549
+ throw new StandardSchemaContractError(valueDescription, "schema-mismatch", `${valueDescription}不符合 Standard Schema:${issues.map((issue) => formatIssue(issue)).join(";")}`, issues);
550
+ }
551
+ if (!Object.hasOwn(result, "value")) throw new StandardSchemaContractError(valueDescription, "invalid-schema-result", `${valueDescription}的 Standard Schema 成功结果缺少 value。`);
552
+ const output = result.value;
553
+ if (requireJson) assertJsonValue(output, `${valueDescription}的验证结果`);
554
+ if (preserveValue && !sameJsonValue(output, before)) throw new StandardSchemaContractError(valueDescription, "output-changed", `${valueDescription}的 Standard Schema 验证结果改动了领域值。`);
555
+ return options.snapshotInput === true ? before : output;
556
+ }
557
+ /** 只验证 JSON 合法性,不创建数据副本。 */
558
+ function assertJsonValue(value, valueDescription, options = {}) {
559
+ visitJsonValue(value, valueDescription, options, false);
560
+ }
561
+ /**
562
+ * 检查并隔离 JSON 数据;同一副本内重复出现的对象仍指向同一副本。
563
+ */
564
+ function snapshotJsonValue(value, valueDescription, options = {}) {
565
+ return copyJsonValue(value, valueDescription, options);
566
+ }
567
+ /** 冻结已验证的 JSON 数据。 */
568
+ function freezeJsonValue(value) {
569
+ if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
570
+ Object.freeze(value);
571
+ if (Array.isArray(value)) for (const item of value) freezeJsonValue(item);
572
+ else for (const item of Object.values(value)) freezeJsonValue(item);
573
+ return value;
574
+ }
575
+ function copyJsonValue(value, valueDescription, options = {}) {
576
+ return visitJsonValue(value, valueDescription, options, true);
577
+ }
578
+ function visitJsonValue(value, valueDescription, options, copy) {
579
+ const active = /* @__PURE__ */ new Set();
580
+ const copies = copy ? /* @__PURE__ */ new WeakMap() : void 0;
581
+ function visit(current, path) {
582
+ if (current === null || typeof current === "string" || typeof current === "boolean") return copy ? current : void 0;
583
+ if (typeof current === "number" && Number.isFinite(current) && !Object.is(current, -0)) return copy ? current : void 0;
584
+ const location = path.length === 0 ? valueDescription : `${valueDescription}${path}`;
585
+ if (typeof current !== "object") throw invalidJson(location);
586
+ if (active.has(current)) throw invalidJson(location);
587
+ const existingCopy = copies?.get(current);
588
+ if (existingCopy !== void 0) return existingCopy;
589
+ active.add(current);
590
+ try {
591
+ if (Array.isArray(current)) {
592
+ if (Object.getPrototypeOf(current) !== Array.prototype) throw invalidJson(location);
593
+ const ownKeys = Reflect.ownKeys(current);
594
+ if (ownKeys.some((key) => typeof key === "symbol")) throw invalidJson(location);
595
+ const result = copy ? [] : void 0;
596
+ for (let index = 0; index < current.length; index += 1) {
597
+ if (!Object.hasOwn(current, index)) throw invalidJson(location);
598
+ const descriptor = Object.getOwnPropertyDescriptor(current, String(index));
599
+ if (descriptor === void 0 || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) throw invalidJson(location);
600
+ const item = visit(descriptor.value, `${path}[${index}]`);
601
+ if (result !== void 0) result.push(item);
602
+ }
603
+ if (ownKeys.some((key) => key !== "length" && (typeof key !== "string" || !isArrayIndexKey(key, current.length)))) throw invalidJson(location);
604
+ if (result !== void 0) copies?.set(current, result);
605
+ return result;
606
+ }
607
+ const prototype = Object.getPrototypeOf(current);
608
+ if (prototype !== Object.prototype && prototype !== null) throw invalidJson(location);
609
+ const keys = Reflect.ownKeys(current);
610
+ if (keys.some((key) => typeof key === "symbol")) throw invalidJson(location);
611
+ const result = copy ? {} : void 0;
612
+ for (const key of keys) {
613
+ if (typeof key !== "string") throw invalidJson(location);
614
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
615
+ if (descriptor === void 0 || !descriptor.enumerable || !Object.hasOwn(descriptor, "value")) throw invalidJson(`${location}.${key}`);
616
+ if (options.omitUndefinedObjectProperties === true && descriptor.value === void 0) continue;
617
+ const propertyValue = visit(descriptor.value, `${path}.${key}`);
618
+ if (result !== void 0) Object.defineProperty(result, key, {
619
+ configurable: true,
620
+ enumerable: true,
621
+ value: propertyValue,
622
+ writable: true
623
+ });
624
+ }
625
+ if (result !== void 0) copies?.set(current, result);
626
+ return result;
627
+ } catch (error) {
628
+ if (error instanceof StandardSchemaContractError) throw error;
629
+ throw invalidJson(location, error);
630
+ } finally {
631
+ active.delete(current);
632
+ }
633
+ }
634
+ return visit(value, "");
635
+ }
636
+ function sameJsonValue(left, right) {
637
+ if (left === null || right === null) return left === right;
638
+ if (typeof left !== typeof right) return false;
639
+ if (typeof left !== "object" || typeof right !== "object") return Object.is(left, right);
640
+ if (Array.isArray(left) || Array.isArray(right)) {
641
+ if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;
642
+ for (let index = 0; index < left.length; index += 1) if (!Object.hasOwn(left, index) || !Object.hasOwn(right, index) || !sameJsonValue(left[index], right[index])) return false;
643
+ const leftKeys = Reflect.ownKeys(left).filter((key) => key !== "length");
644
+ const rightKeys = Reflect.ownKeys(right).filter((key) => key !== "length");
645
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => rightKeys.includes(key));
646
+ }
647
+ const leftKeys = Object.keys(left);
648
+ const rightKeys = Object.keys(right);
649
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(right, key) && sameJsonValue(left[key], right[key]));
650
+ }
651
+ function matchesJsonSnapshot(value, snapshot, valueDescription) {
652
+ try {
653
+ assertJsonValue(value, valueDescription);
654
+ } catch {
655
+ return false;
656
+ }
657
+ return sameJsonValue(value, snapshot);
658
+ }
659
+ function invalidJson(valueDescription, cause) {
660
+ return new StandardSchemaContractError(valueDescription, "invalid-json", `${valueDescription}必须是可无损保存的 JSON 数据。`, void 0, cause === void 0 ? void 0 : { cause });
661
+ }
662
+ function isArrayIndexKey(key, length) {
663
+ const index = Number(key);
664
+ return Number.isInteger(index) && index >= 0 && index < length && String(index) === key;
665
+ }
666
+ function isStandardSchema(value) {
667
+ if (!isRecord(value) || !isRecord(value["~standard"])) return false;
668
+ const standard = value["~standard"];
669
+ return standard.version === 1 && typeof standard.vendor === "string" && typeof standard.validate === "function";
670
+ }
671
+ function formatIssue(issue) {
672
+ if (issue.path === void 0 || issue.path.length === 0) return issue.message;
673
+ return `${issue.path.map((segment) => typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment)).join(".")}:${issue.message}`;
674
+ }
675
+ // ../../packages/core/dist/stable-json.js
676
+ function stableStringify(value) {
677
+ assertJsonValue(value, "稳定 JSON 值");
678
+ return stableStringifyJson(value);
679
+ }
680
+ function stableStringifyJson(value) {
681
+ const serialized = JSON.stringify(sortJsonKeys(value), null, 2);
682
+ if (serialized === void 0) throw new TypeError("值必须可序列化为 JSON。");
683
+ return serialized;
684
+ }
685
+ function sortJsonKeys(value) {
686
+ if (Array.isArray(value)) return value.map(sortJsonKeys);
687
+ if (value === null || typeof value !== "object") return value;
688
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, item]) => [key, sortJsonKeys(item)]));
689
+ }
690
+ // ../../packages/core/dist/quality/quality-cache.js
691
+ function isCachedQualityFindings(value) {
692
+ if (!Array.isArray(value) || !value.every(isQualityFinding)) return false;
693
+ try {
694
+ assertJsonValue(value, "QA 原始诊断");
695
+ return true;
696
+ } catch {
697
+ return false;
698
+ }
699
+ }
700
+ function isQualityFinding(value) {
701
+ return isRecord(value) && (value.severity === "error" || value.severity === "warning" || value.severity === "info") && isQualityObject(value.object) && isQualityLocation(value.location) && typeof value.message === "string" && Array.isArray(value.evidence) && value.evidence.every(isQualityEvidence);
702
+ }
703
+ function isQualityEvidence(value) {
704
+ return isRecord(value) && typeof value.role === "string" && isQualityObject(value.object) && isQualityLocation(value.location) && Object.hasOwn(value, "value");
705
+ }
706
+ function isQualityObject(value) {
707
+ return isRecord(value) && typeof value.kind === "string" && typeof value.key === "string" && (value.language === void 0 || typeof value.language === "string");
708
+ }
709
+ function isQualityLocation(value) {
710
+ return isRecord(value) && (typeof value.language === "string" || value.language === null) && Object.hasOwn(value, "range") && (value.key === void 0 || typeof value.key === "string");
711
+ }
712
+ // ../../packages/core/dist/quality/qa.js
713
+ /** 动态接入未提供有效读取函数时直接报告的契约错误。 */
714
+ var QualityDataReaderContractError = class extends TypeError {
715
+ constructor() {
716
+ super("qualityData.read 的读取函数必须是函数。");
717
+ this.name = "QualityDataReaderContractError";
718
+ }
719
+ };
720
+ /** 创建仅覆盖当前 QA 运行的检查资料读取范围。 */
721
+ function createQualityDataReader() {
722
+ const memo = createMemoScope();
723
+ const operations = /* @__PURE__ */ new WeakMap();
724
+ return {
725
+ reader: { read(reader, ...args) {
726
+ if (typeof reader !== "function") throw new QualityDataReaderContractError();
727
+ let snapshotReader = operations.get(reader);
728
+ if (snapshotReader === void 0) {
729
+ snapshotReader = async (...readerArgs) => {
730
+ const snapshot = snapshotJsonValue(await reader(...readerArgs), "QA 检查资料");
731
+ freezeJsonValue(snapshot);
732
+ return snapshot;
733
+ };
734
+ operations.set(reader, snapshotReader);
735
+ }
736
+ return memo.memo(snapshotReader)(...args);
737
+ } },
738
+ dispose: () => memo.dispose()
739
+ };
740
+ }
741
+ /** 检查器声明或阶段返回结构不符合正式检查契约。 */
742
+ var QualityCheckerContractError = class extends TypeError {
743
+ checkId;
744
+ stage;
745
+ constructor(checkId, stage, message) {
746
+ super(`QA 检查项 ${checkId} ${message}`);
747
+ this.name = "QualityCheckerContractError";
748
+ this.checkId = checkId;
749
+ this.stage = stage;
750
+ }
751
+ };
752
+ const qualityInputFingerprintFormat = "lioni.check-input/v2";
753
+ const qualityCheckDefinitionBrand = Symbol("qualityCheckDefinition");
754
+ /** 宿主类型由公开定义约束,运行时按同一对象取回对应实现。 */
755
+ const qualityCheckImplementations = /* @__PURE__ */ new WeakMap();
756
+ function defineCheckerFor() {
757
+ function define(definition) {
758
+ const { id, version, inputSchema, load, prepare, check } = definition;
759
+ assertQualityCheckIdentity(id, version);
760
+ if (!isStandardSchema(inputSchema)) throw new QualityCheckerContractError(id, "definition", "的 inputSchema 必须是 Standard Schema。");
761
+ if (load !== void 0 && typeof load !== "function") throw new QualityCheckerContractError(id, "definition", "的 load 必须是函数。");
762
+ if (typeof prepare !== "function" || typeof check !== "function") throw new QualityCheckerContractError(id, "definition", "必须提供 prepare 和 check 函数。");
763
+ const qualityCheck = {
764
+ [qualityCheckDefinitionBrand]: true,
765
+ id,
766
+ version
767
+ };
768
+ const prepared = {
769
+ version,
770
+ ...load === void 0 ? {} : { load },
771
+ async prepareInput(input, context) {
772
+ const preparation = await prepare(input);
773
+ const finalInput = await validateWithStandardSchema(inputSchema, preparation, `QA 检查器 ${id} 的输入`, { snapshotInput: true });
774
+ freezeJsonValue(finalInput);
775
+ context.startFingerprint();
776
+ try {
777
+ return {
778
+ ...prepareFingerprint(id, version, context, fingerprintQualityInputBasis(finalInput)),
779
+ execute: () => check(finalInput)
780
+ };
781
+ } finally {
782
+ context.endFingerprint();
783
+ }
784
+ }
785
+ };
786
+ qualityCheckImplementations.set(qualityCheck, prepared);
787
+ return qualityCheck;
788
+ }
789
+ return define;
790
+ }
791
+ /**
792
+ * 声明一次共享加载、逐对象准备及规则计算。规则所需的全部业务依据
793
+ * 必须进入准备结果,框架用同一份固定输入计算指纹并执行规则。
794
+ * 相同输入下规则语义变化时应更新 version。
795
+ * 需要明确宿主类型时,可先调用 withTypes,schema、加载结果和 ID 仍由声明推导。
796
+ */
797
+ const defineChecker = Object.assign(defineCheckerFor(), { withTypes: defineCheckerFor });
798
+ function assertQualityCheckIdentity(id, version) {
799
+ if (typeof id !== "string" || id.trim() === "") throw new TypeError("QA 检查项必须提供非空 id。");
800
+ if (typeof version !== "string" || version.trim() === "") throw new TypeError(`QA 检查项 ${id} 必须提供非空 version。`);
801
+ }
802
+ function prepareFingerprint(id, version, context, inputBasisFingerprint) {
803
+ const fingerprint = qualityInputFingerprint(id, version, inputBasisFingerprint);
804
+ return {
805
+ fingerprint,
806
+ cacheKey: qualityCheckCacheKey(id, context.sourceKey, context.language, fingerprint.inputFingerprint)
807
+ };
808
+ }
809
+ /** 从各检查项结果中裁剪零诊断执行记录,仅保留实际产生了原始诊断的执行归属与指纹。 */
810
+ function pruneCleanExecutions(checks) {
811
+ return checks.map((check) => {
812
+ if (check.executions.length === 0) return check;
813
+ const diagnosed = new Set(check.diagnostics.map(({ executionId }) => executionId));
814
+ const executions = check.executions.filter(({ executionId }) => diagnosed.has(executionId));
815
+ return executions.length === check.executions.length ? check : {
816
+ ...check,
817
+ executions
818
+ };
819
+ });
820
+ }
821
+ /** 校验本次快照的读取范围是否满足运行模式(草稿允许未覆盖新增键,非草稿须完整读取)。 */
822
+ function assertReadableSnapshot(snapshot, options) {
823
+ assertReadCoverageSatisfied("原文", snapshot.source.read, options.draft);
824
+ for (const read of snapshot.translations.reads) assertReadCoverageSatisfied(`译文 ${read.language}`, read, options.draft, read.language);
825
+ }
826
+ /** 校验所选源译关联在非草稿模式下已完整覆盖。 */
827
+ function assertSelectedAssociationsComplete(snapshot, associations) {
828
+ const readsByLanguage = new Map(snapshot.translations.reads.map((read) => [read.language, read]));
829
+ for (const association of associations) {
830
+ if (association.coverageStatus === "complete") continue;
831
+ const read = readsByLanguage.get(association.language);
832
+ const ranges = association.scopeIndexes.map((index) => read?.scopes[index]?.range).filter((range) => range !== void 0).map(displayReadRange);
833
+ const rangeDetail = ranges.length > 0 ? `,范围:${ranges.join("、")}` : ",未覆盖任何读取范围";
834
+ throw new Error(`译文读取不完整(原文键:${association.sourceKey},语言:${association.language}${rangeDetail})`);
835
+ }
836
+ }
837
+ async function runQualityChecksWithQualityData(snapshot, request, checks, options, qualityData) {
838
+ const memo = options.memo ?? createMemoScope();
839
+ try {
840
+ const isDraft = request.candidates !== void 0;
841
+ assertReadableSnapshot(snapshot, { draft: isDraft });
842
+ if (request.candidates !== void 0) validateQualityCandidateScope(snapshot, request.candidates);
843
+ const identityKey = (key) => JSON.stringify([key.sourceKey, key.language]);
844
+ const byIdentity = new Map(snapshot.associations.map((association) => [identityKey(association), association]));
845
+ const sourceUnits = new Map(snapshot.source.units.map((unit) => [unit.key, unit]));
846
+ const selectedAssociations = request.candidates === void 0 ? snapshot.associations : request.candidates.map((candidate) => {
847
+ const association = byIdentity.get(identityKey(candidate));
848
+ if (!association) throw new TypeError("送检候选缺少对应的源译关联。");
849
+ return association;
850
+ });
851
+ if (!isDraft) assertSelectedAssociationsComplete(snapshot, selectedAssociations);
852
+ const candidates = snapshotQualityData(request.candidates ?? savedTranslationCandidates(snapshot));
853
+ const candidateByIdentity = new Map(candidates.map((candidate, index) => [identityKey(candidate), {
854
+ candidate,
855
+ index
856
+ }]));
857
+ const subjects = selectedAssociations.map((association) => {
858
+ const sourceUnit = sourceUnits.get(association.sourceKey);
859
+ if (!sourceUnit) throw new TypeError("送检对象缺少对应的原文单元。");
860
+ const [translationIndex] = association.translationIndexes;
861
+ const entry = candidateByIdentity.get(identityKey(association));
862
+ return {
863
+ sourceUnit,
864
+ association,
865
+ candidateIndex: entry?.index,
866
+ translation: translationIndex === void 0 ? null : snapshot.translations.records[translationIndex] ?? null,
867
+ candidate: entry?.candidate ?? null
868
+ };
869
+ });
870
+ const selected = new Set(selectedAssociations.map(identityKey));
871
+ const relationships = snapshotQualityData(request.relationships ?? []);
872
+ const suppressions = snapshotQualityData(request.suppressions ?? []);
873
+ validateQaSuppressions(suppressions);
874
+ const preparedChecks = [];
875
+ const checkIds = /* @__PURE__ */ new Set();
876
+ for (const definition of checks) {
877
+ options.profile?.configure(definition.id, options.qualityCheckResultCache !== void 0);
878
+ if (checkIds.has(definition.id)) throw new TypeError(`QA 检查项 id ${definition.id} 重复。`);
879
+ checkIds.add(definition.id);
880
+ const prepared = qualityCheckImplementations.get(definition);
881
+ if (prepared === void 0) throw new TypeError(`QA 检查项 ${definition.id} 必须由 defineChecker 创建。`);
882
+ let loaded;
883
+ if (subjects.length > 0 && prepared.load !== void 0) {
884
+ const endLoad = options.profile?.checkStage(definition.id, "load");
885
+ try {
886
+ loaded = await prepared.load({
887
+ snapshot,
888
+ candidates,
889
+ relationships,
890
+ memo,
891
+ qualityData: qualityData.reader
892
+ });
893
+ } catch (error) {
894
+ if (isQualityContractError(error)) throw error;
895
+ throw formatCheckerFailure(definition.id, "load", error);
896
+ } finally {
897
+ endLoad?.();
898
+ }
899
+ }
900
+ preparedChecks.push({
901
+ id: definition.id,
902
+ prepared,
903
+ loaded
904
+ });
905
+ }
906
+ const results = [];
907
+ let nextExecutionId = 0;
908
+ for (const { id, prepared, loaded } of preparedChecks) {
909
+ const diagnostics = [];
910
+ const executions = [];
911
+ for (const [subjectIndex, { candidateIndex, ...subject }] of subjects.entries()) {
912
+ const { sourceKey, language } = subject.association;
913
+ const candidateProfile = options.profile?.candidate(id, {
914
+ subjectIndex,
915
+ sourceKey,
916
+ language
917
+ }, options.qualityCheckResultCache !== void 0);
918
+ const executionId = nextExecutionId;
919
+ nextExecutionId += 1;
920
+ let stage = "prepare";
921
+ let fingerprint;
922
+ let findings;
923
+ try {
924
+ const endPreparation = candidateProfile?.stage("prepareInput");
925
+ let endFingerprintStage;
926
+ const preparationContext = {
927
+ sourceKey,
928
+ language,
929
+ startFingerprint() {
930
+ endPreparation?.();
931
+ endFingerprintStage = candidateProfile?.stage("fingerprint");
932
+ },
933
+ endFingerprint() {
934
+ endFingerprintStage?.();
935
+ endFingerprintStage = void 0;
936
+ }
937
+ };
938
+ let preparation;
939
+ try {
940
+ preparation = await prepared.prepareInput({
941
+ ...subject,
942
+ snapshot,
943
+ candidates,
944
+ relationships,
945
+ loaded,
946
+ memo
947
+ }, preparationContext);
948
+ } finally {
949
+ endPreparation?.();
950
+ preparationContext.endFingerprint();
951
+ }
952
+ fingerprint = preparation.fingerprint;
953
+ stage = "check";
954
+ findings = await resolveQualityFindings(id, preparation, options.qualityCheckResultCache, candidateProfile);
955
+ } catch (error) {
956
+ if (isQualityContractError(error)) throw error;
957
+ candidateProfile?.finish("failed");
958
+ throw formatCheckerFailure(id, stage, error, {
959
+ sourceKey,
960
+ language
961
+ });
962
+ }
963
+ const endResults = candidateProfile?.stage("results");
964
+ const execution = {
965
+ executionId,
966
+ ...candidateIndex === void 0 ? {} : { candidateIndex },
967
+ checkId: id,
968
+ sourceKey,
969
+ language,
970
+ ...fingerprint
971
+ };
972
+ executions.push(execution);
973
+ diagnostics.push(...findings.map((diagnostic) => ({
974
+ ...diagnostic,
975
+ checkId: id,
976
+ executionId,
977
+ handling: handlingFor(execution, suppressions)
978
+ })));
979
+ endResults?.();
980
+ candidateProfile?.finish("complete");
981
+ }
982
+ results.push({
983
+ checkId: id,
984
+ version: prepared.version,
985
+ diagnostics,
986
+ coverage: {
987
+ selected: executions.length,
988
+ evaluated: executions.length
989
+ },
990
+ executions
991
+ });
992
+ }
993
+ const reportedChecks = options.includeCleanExecutions === true ? results : pruneCleanExecutions(results);
994
+ return {
995
+ version: snapshot.version,
996
+ candidates,
997
+ relationships,
998
+ checkScope: {
999
+ configuredCount: checks.length,
1000
+ selectedIds: checks.map(({ id }) => id),
1001
+ evaluatedCount: results.filter((check) => check.coverage.evaluated > 0).length
1002
+ },
1003
+ suppressions,
1004
+ readCoverage: snapshotQualityData({
1005
+ source: snapshot.source.read,
1006
+ translations: snapshot.translations.reads,
1007
+ associations: snapshot.associations.map((association) => ({
1008
+ ...association,
1009
+ subjectSelected: selected.has(identityKey(association))
1010
+ }))
1011
+ }),
1012
+ diagnostics: reportedChecks.flatMap(({ diagnostics }) => diagnostics),
1013
+ checks: reportedChecks
1014
+ };
1015
+ } finally {
1016
+ options.profile?.endChecks();
1017
+ }
1018
+ }
1019
+ function assertReadCoverageSatisfied(label, read, draft, language) {
1020
+ const violated = draft ? read.status === "failed" : read.status !== "complete";
1021
+ const badScopes = read.scopes.filter(({ enumeration }) => draft ? enumeration === "failed" : enumeration !== "complete");
1022
+ if (!violated && badScopes.length === 0) return;
1023
+ const statusText = read.status === "complete" ? "部分枚举" : read.status === "notRead" ? "未读取" : read.status === "incomplete" ? "不完整" : "失败";
1024
+ const scopeRanges = badScopes.map(({ range }) => displayReadRange(range)).filter((range) => range.length > 0);
1025
+ const scopeErrors = badScopes.flatMap(({ error }) => error === void 0 ? [] : [error]);
1026
+ const parts = [
1027
+ ...language === void 0 ? [] : [`语言:${language}`],
1028
+ ...scopeRanges.length > 0 ? [`范围:${scopeRanges.join("、")}`] : read.scopes.length === 0 ? ["范围:未读取任何范围"] : [],
1029
+ ...read.error === void 0 ? [] : [`原因:${read.error}`],
1030
+ ...scopeErrors.length > 0 ? [`详情:${scopeErrors.join(";")}`] : []
1031
+ ];
1032
+ throw new Error(`${label}读取${statusText}${parts.length === 0 ? "" : `(${parts.join(",")})`}`);
1033
+ }
1034
+ function displayReadRange(range) {
1035
+ if (typeof range === "string") return range;
1036
+ if (range === null || range === void 0) return "位置未知";
1037
+ return JSON.stringify(range) ?? "位置未知";
1038
+ }
1039
+ function formatCheckerFailure(checkId, stage, error, subject) {
1040
+ const reason = error instanceof Error ? error.message : String(error);
1041
+ const stageText = stage === "load" ? "加载" : stage === "prepare" ? "准备" : "执行";
1042
+ const locationText = subject === void 0 ? "" : `(原文键:${subject.sourceKey},语言:${subject.language})`;
1043
+ return new Error(`QA 检查项 ${checkId} ${stageText}失败${locationText}:${reason}`, { cause: error });
1044
+ }
1045
+ function isQualityContractError(error) {
1046
+ return error instanceof StandardSchemaContractError || error instanceof QualityDataReaderContractError || error instanceof QualityCheckerContractError;
1047
+ }
1048
+ function snapshotQualityData(value, valueDescription = "QA 输入与结果") {
1049
+ return snapshotJsonValue(value, valueDescription);
1050
+ }
1051
+ function qualityInputFingerprint(checkId, version, inputBasisFingerprint) {
1052
+ return {
1053
+ inputFingerprint: fingerprintJsonObjectComponents([
1054
+ ["checkId", fingerprintJsonValue(checkId)],
1055
+ ["fingerprintFormat", fingerprintJsonValue(qualityInputFingerprintFormat)],
1056
+ ["inputFingerprint", inputBasisFingerprint],
1057
+ ["version", fingerprintJsonValue(version)]
1058
+ ]),
1059
+ fingerprintSummary: {
1060
+ version,
1061
+ inputFingerprint: inputBasisFingerprint
1062
+ }
1063
+ };
1064
+ }
1065
+ function qualityCheckCacheKey(checkId, sourceKey, language, inputFingerprint) {
1066
+ return fingerprintJsonValue({
1067
+ checkId,
1068
+ sourceKey,
1069
+ language,
1070
+ inputFingerprint
1071
+ });
1072
+ }
1073
+ async function resolveQualityFindings(checkId, preparation, cache, profile) {
1074
+ if (cache) {
1075
+ const end = profile?.stage("cacheRead");
1076
+ try {
1077
+ const cached = await cache.get(preparation.cacheKey);
1078
+ if (isCachedQualityFindings(cached)) {
1079
+ profile?.read("hit");
1080
+ const endSnapshot = profile?.stage("snapshot");
1081
+ try {
1082
+ return snapshotQualityData(cached);
1083
+ } finally {
1084
+ endSnapshot?.();
1085
+ }
1086
+ }
1087
+ profile?.read(cached === void 0 ? "miss" : "invalid");
1088
+ } catch {
1089
+ profile?.read("error");
1090
+ } finally {
1091
+ end?.();
1092
+ }
1093
+ }
1094
+ profile?.executed();
1095
+ const endExecute = profile?.stage("execute");
1096
+ let findings;
1097
+ try {
1098
+ findings = await preparation.execute();
1099
+ } finally {
1100
+ endExecute?.();
1101
+ }
1102
+ const endSnapshot = profile?.stage("snapshot");
1103
+ try {
1104
+ if (!isCachedQualityFindings(findings)) throw new QualityCheckerContractError(checkId, "check", "的 check 必须返回有效的诊断数组。");
1105
+ findings = snapshotQualityData(findings);
1106
+ freezeJsonValue(findings);
1107
+ } finally {
1108
+ endSnapshot?.();
1109
+ }
1110
+ if (cache) {
1111
+ const end = profile?.stage("cacheWrite");
1112
+ try {
1113
+ await cache.set(preparation.cacheKey, findings);
1114
+ profile?.write("completed");
1115
+ } catch {
1116
+ profile?.write("error");
1117
+ } finally {
1118
+ end?.();
1119
+ }
1120
+ }
1121
+ return findings;
1122
+ }
1123
+ function fingerprintQualityInputBasis(value) {
1124
+ if (Array.isArray(value)) return fingerprintJsonArrayComponents(value.map((item, index) => [String(index), fingerprintJsonValue(item)]));
1125
+ if (isRecord(value)) return fingerprintJsonObjectComponents(Object.entries(value).map(([key, item]) => [key, fingerprintJsonValue(item)]));
1126
+ return fingerprintJsonValue(value);
1127
+ }
1128
+ function fingerprintJsonValue(value) {
1129
+ return fingerprintComponents(`json-value:${value === null ? "null" : Array.isArray(value) ? "array" : typeof value}`, [["value", stableStringifyJson(value)]]);
1130
+ }
1131
+ function fingerprintJsonObjectComponents(components) {
1132
+ return fingerprintComponents("json-object", [...components].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, fingerprint]) => [JSON.stringify(key), fingerprint]));
1133
+ }
1134
+ function fingerprintJsonArrayComponents(components) {
1135
+ return fingerprintComponents("json-array", components);
1136
+ }
1137
+ function fingerprintComponents(domain, components) {
1138
+ const hash = createHash("sha256");
1139
+ updateFingerprintHash(hash, qualityInputFingerprintFormat);
1140
+ updateFingerprintHash(hash, domain);
1141
+ for (const [key, fingerprint] of components) {
1142
+ updateFingerprintHash(hash, key);
1143
+ updateFingerprintHash(hash, fingerprint);
1144
+ }
1145
+ return `sha256:${hash.digest("hex")}`;
1146
+ }
1147
+ function updateFingerprintHash(hash, value) {
1148
+ hash.update(Buffer.byteLength(value).toString(10));
1149
+ hash.update(":");
1150
+ hash.update(value);
1151
+ }
1152
+ function handlingFor(execution, suppressions) {
1153
+ const suppression = suppressions.find((candidate) => qaSuppressionMatchesExecution(candidate, execution));
1154
+ return suppression === void 0 ? { status: "active" } : {
1155
+ status: "suppressed",
1156
+ suppressionId: suppression.id,
1157
+ reason: suppression.reason
1158
+ };
1159
+ }
1160
+ // ../../packages/core/dist/translation-snapshot.js
1161
+ var TranslationIdentityContractError = class extends TypeError {
1162
+ reason;
1163
+ identity;
1164
+ firstIndex;
1165
+ duplicateIndex;
1166
+ constructor(reason, details = {}) {
1167
+ super(reason === "missing" ? "translations.keyOf 必须返回非空的消息键。" : `译文身份重复:${JSON.stringify(details.identity)}(第 ${(details.firstIndex ?? -1) + 1} 与第 ${(details.duplicateIndex ?? -1) + 1} 条记录)`);
1168
+ this.name = "TranslationIdentityContractError";
1169
+ this.reason = reason;
1170
+ if (details.identity !== void 0) this.identity = details.identity;
1171
+ if (details.firstIndex !== void 0) this.firstIndex = details.firstIndex;
1172
+ if (details.duplicateIndex !== void 0) this.duplicateIndex = details.duplicateIndex;
1173
+ }
1174
+ };
1175
+ function validateTranslationAdapterConfig(translations) {
1176
+ if (!isRecord(translations) || !Array.isArray(translations.languages) || translations.languages.some((language) => typeof language !== "string") || typeof translations.read !== "function" || typeof translations.keyOf !== "function" || typeof translations.contentOf !== "function" || !isStandardSchema(translations.schema) || !isStandardSchema(translations.contentSchema) || translations.unavailableSchema !== void 0 && !isStandardSchema(translations.unavailableSchema)) throw new StandardSchemaContractError("defineConfig 配置", "schema-mismatch", "defineConfig 的 translations 必须提供语言列表、记录与正文 schema、keyOf、read 与 contentOf 函数。");
1177
+ }
1178
+ /** 按给定原文单元读取并验证译文;空集合可用于独立目标身份操作。 */
1179
+ async function readTranslationSnapshot(adapter, sourceUnits, languages = adapter?.languages ?? []) {
1180
+ const translations = {
1181
+ reads: [],
1182
+ records: []
1183
+ };
1184
+ if (adapter === void 0) return translations;
1185
+ validateTranslationAdapterConfig(adapter);
1186
+ const firstTranslationIndexes = /* @__PURE__ */ new Map();
1187
+ for (const language of languages) {
1188
+ let read;
1189
+ let errorMessage;
1190
+ try {
1191
+ read = await adapter.read(language, sourceUnits);
1192
+ } catch (error) {
1193
+ if (error instanceof StandardSchemaContractError) throw error;
1194
+ errorMessage = error instanceof Error ? error.message : String(error);
1195
+ }
1196
+ if (errorMessage === void 0) validateTranslationRead(read);
1197
+ const scopes = [];
1198
+ for (const [scopeIndex, scope] of (read?.scopes ?? []).entries()) {
1199
+ const translationIndexes = [];
1200
+ for (const record of scope.records) {
1201
+ const index = translations.records.length;
1202
+ translationIndexes.push(index);
1203
+ const recordBase = {
1204
+ index,
1205
+ language,
1206
+ scopeIndex,
1207
+ range: scope.range
1208
+ };
1209
+ if (record.bodyAvailability === "available") {
1210
+ const translation = await validateWithStandardSchema(adapter.schema, record.value, `译文记录 ${index + 1}`, {
1211
+ preserveValue: true,
1212
+ requireJson: true
1213
+ });
1214
+ const identity = readTranslationIdentity(adapter.keyOf(translation, language), language);
1215
+ assertUniqueTranslationIdentity(identity, firstTranslationIndexes, index);
1216
+ const content = await validateWithStandardSchema(adapter.contentSchema, adapter.contentOf(translation), `译文正文 ${index + 1}`, {
1217
+ preserveValue: true,
1218
+ requireJson: true
1219
+ });
1220
+ translations.records.push({
1221
+ ...recordBase,
1222
+ record: translation,
1223
+ identity,
1224
+ content,
1225
+ bodyAvailability: "available"
1226
+ });
1227
+ } else if (record.bodyAvailability === "unavailable") {
1228
+ const schema = adapter.unavailableSchema;
1229
+ if (schema === void 0) throw new StandardSchemaContractError(`译文记录 ${index + 1}`, "schema-mismatch", "发现不可用译文记录,但 translations.unavailableSchema 未声明该分支。");
1230
+ const translation = await validateWithStandardSchema(schema, record.value, `不可用译文记录 ${index + 1}`, {
1231
+ preserveValue: true,
1232
+ requireJson: true
1233
+ });
1234
+ const identity = readTranslationIdentity(adapter.keyOf(translation, language), language);
1235
+ assertUniqueTranslationIdentity(identity, firstTranslationIndexes, index);
1236
+ translations.records.push({
1237
+ ...recordBase,
1238
+ record: translation,
1239
+ identity,
1240
+ bodyAvailability: "unavailable"
1241
+ });
1242
+ } else throw new StandardSchemaContractError(`译文记录 ${index + 1}`, "invalid-schema-result", "译文记录的 bodyAvailability 必须为 available 或 unavailable。");
1243
+ }
1244
+ scopes.push({
1245
+ range: scope.range,
1246
+ covers: [...scope.covers],
1247
+ enumeration: scope.enumeration,
1248
+ translationIndexes,
1249
+ ...scope.error === void 0 ? {} : { error: scope.error }
1250
+ });
1251
+ }
1252
+ translations.reads.push({
1253
+ language,
1254
+ status: readStatus(scopes, errorMessage),
1255
+ scopes,
1256
+ ...errorMessage === void 0 ? {} : { error: errorMessage }
1257
+ });
1258
+ }
1259
+ return translations;
1260
+ }
1261
+ function validateTranslationRead(value) {
1262
+ if (!isRecord(value) || !Array.isArray(value.scopes)) invalidTranslationRead("translations.read 必须返回包含 scopes 数组的读取结果。");
1263
+ for (const [scopeIndex, scope] of value.scopes.entries()) {
1264
+ if (!isRecord(scope) || !Array.isArray(scope.records) || !Array.isArray(scope.covers) || scope.covers.some((key) => typeof key !== "string") || scope.enumeration !== "complete" && scope.enumeration !== "partial" && scope.enumeration !== "failed" || scope.error !== void 0 && typeof scope.error !== "string") invalidTranslationRead(`translations.read 的第 ${scopeIndex + 1} 个范围结构无效。`);
1265
+ assertJsonValue(scope.range, `译文范围 ${scopeIndex + 1}`);
1266
+ for (const [recordIndex, record] of scope.records.entries()) if (!isRecord(record) || record.bodyAvailability !== "available" && record.bodyAvailability !== "unavailable") invalidTranslationRead(`translations.read 的第 ${scopeIndex + 1} 个范围中,第 ${recordIndex + 1} 条译文记录结构无效。`);
1267
+ }
1268
+ }
1269
+ function invalidTranslationRead(message) {
1270
+ throw new StandardSchemaContractError("translations.read", "schema-mismatch", message);
1271
+ }
1272
+ function readTranslationIdentity(value, language) {
1273
+ if (typeof value !== "string" || value.trim().length === 0) throw new TranslationIdentityContractError("missing");
1274
+ return {
1275
+ language,
1276
+ key: value
1277
+ };
1278
+ }
1279
+ function assertUniqueTranslationIdentity(identity, firstIndexes, duplicateIndex) {
1280
+ const serialized = JSON.stringify([identity.language, identity.key]);
1281
+ const firstIndex = firstIndexes.get(serialized);
1282
+ if (firstIndex !== void 0) throw new TranslationIdentityContractError("duplicate", {
1283
+ identity,
1284
+ firstIndex,
1285
+ duplicateIndex
1286
+ });
1287
+ firstIndexes.set(serialized, duplicateIndex);
1288
+ }
1289
+ // ../../packages/core/dist/semantic-edits.js
1290
+ /** 校验候选正文数据;是否检查或写入由调用者另外组合。 */
1291
+ async function validateTranslationCandidate(value, config) {
1292
+ if (!isRecord(value) || typeof value.sourceKey !== "string" || typeof value.language !== "string" || !Object.hasOwn(value, "content")) throw new TypeError("译文候选必须包含字符串 sourceKey、language 和 content。");
1293
+ const contentSchema = config.translations?.contentSchema;
1294
+ if (contentSchema === void 0) throw new TypeError("验证译文候选需要 translations.contentSchema。");
1295
+ const validatedContent = await validateWithStandardSchema(contentSchema, value.content, "译文候选正文", {
1296
+ preserveValue: true,
1297
+ requireJson: true
1298
+ });
1299
+ return {
1300
+ sourceKey: value.sourceKey,
1301
+ language: value.language,
1302
+ content: snapshotValue(validatedContent, "译文候选正文")
1303
+ };
1304
+ }
1305
+ /** 校验可保存的写入请求,保留宿主提供的 JSON 正文与完整原文。 */
1306
+ async function validateTranslationWriteRequest(value, config) {
1307
+ assertJsonValue(value, "译文写入请求");
1308
+ if (!isRecord(value) || value.operation !== "write" && value.operation !== "delete") invalidWriteRequest("必须包含 write 或 delete 操作。");
1309
+ const translations = config.translations;
1310
+ if (translations === void 0) invalidWriteRequest("验证译文写入请求需要 translations 配置。");
1311
+ const target = validateTarget(value.target, value.operation);
1312
+ const expectedTarget = await validateExpectedTarget(value.expectedTarget, value.operation, target, translations.contentSchema);
1313
+ const expectedSource = Object.hasOwn(value, "expectedSource") ? await validateExpectedSource(value.expectedSource, config, target) : void 0;
1314
+ if (value.operation === "write") {
1315
+ if (!Object.hasOwn(value, "content")) invalidWriteRequest("write 请求必须包含 content。");
1316
+ const content = snapshotValue(await validateWithStandardSchema(translations.contentSchema, value.content, "译文写入正文", {
1317
+ preserveValue: true,
1318
+ requireJson: true
1319
+ }), "译文写入正文");
1320
+ if ("sourceKey" in target && expectedTarget.status !== "missing" || "identity" in target && expectedTarget.status !== "present") invalidWriteRequest("新建与既有目标的 expectedTarget 不匹配。");
1321
+ return {
1322
+ operation: "write",
1323
+ target,
1324
+ content,
1325
+ ...expectedSource === void 0 ? {} : { expectedSource },
1326
+ expectedTarget
1327
+ };
1328
+ }
1329
+ if (Object.hasOwn(value, "content")) invalidWriteRequest("delete 请求不能包含 content。");
1330
+ if (!("identity" in target)) invalidWriteRequest("delete 只能引用现存译文 identity。");
1331
+ if (expectedTarget.status !== "present") invalidWriteRequest("delete 请求必须包含现存目标的预期身份与正文。");
1332
+ return {
1333
+ operation: "delete",
1334
+ target,
1335
+ ...expectedSource === void 0 ? {} : { expectedSource },
1336
+ expectedTarget
1337
+ };
1338
+ }
1339
+ /**
1340
+ * 直接执行人工或外部工具提供的写入候选与删除决定。
1341
+ * 显式选择语言时,越界请求整批拒绝,写入前后只读取所选语言。
1342
+ */
1343
+ async function writeTranslationRequests(requests, config, condition, options = {}) {
1344
+ const languages = resolveLanguageSelection(config.translations?.languages ?? [], options);
1345
+ if (!Array.isArray(requests)) invalidWriteRequest("requests 必须是数组。");
1346
+ if (requests.length === 0) return { results: [] };
1347
+ const validated = await Promise.all(requests.map((request) => validateTranslationWriteRequest(request, config)));
1348
+ if (options.languages !== void 0) for (const request of validated) {
1349
+ const language = "identity" in request.target ? request.target.identity.language : request.target.language;
1350
+ if (!languages.includes(language)) invalidWriteRequest(`写入请求引用了本次未选择的目标语言 ${JSON.stringify(language)}。`);
1351
+ }
1352
+ const results = validated.map((request) => ({
1353
+ request,
1354
+ status: "notWritable"
1355
+ }));
1356
+ const adapter = config.translationWriteback;
1357
+ if (adapter === void 0 || adapter.write === void 0 && adapter.writeBatch === void 0) return { results: validated.map((request) => ({
1358
+ request,
1359
+ status: "notWritable",
1360
+ reason: "宿主没有提供译文写入能力。"
1361
+ })) };
1362
+ if (adapter.writeBatch !== void 0 && typeof adapter.writeBatch !== "function") throw new StandardSchemaContractError("译文写回适配器", "schema-mismatch", "translationWriteback.writeBatch 必须是函数。");
1363
+ if (adapter.writeBatch === void 0 && typeof adapter.write !== "function") throw new StandardSchemaContractError("译文写回适配器", "schema-mismatch", "translationWriteback.write 必须是函数。");
1364
+ if (condition !== void 0 && typeof condition !== "function") throw new StandardSchemaContractError("译文写入条件", "schema-mismatch", "附加写入条件必须是函数。");
1365
+ const needsSource = condition !== void 0 || validated.some(({ expectedSource, target }) => expectedSource !== void 0 || "sourceKey" in target);
1366
+ const readCurrent = () => condition === void 0 ? readWriteSnapshot(config, needsSource, languages) : readComparisonSnapshot(config, options);
1367
+ let current;
1368
+ try {
1369
+ current = await readCurrent();
1370
+ } catch (error) {
1371
+ rethrowContractError(error);
1372
+ const reason = `读取当前事实失败:${errorMessage$1(error)}`;
1373
+ return { results: validated.map((request) => ({
1374
+ request,
1375
+ status: "notWritable",
1376
+ reason
1377
+ })) };
1378
+ }
1379
+ const prepared = [];
1380
+ for (const [index, request] of validated.entries()) {
1381
+ const resolved = await prepareWrite(index, request, current, config);
1382
+ if (resolved.status !== "ready") {
1383
+ results[index] = {
1384
+ request,
1385
+ status: resolved.status,
1386
+ reason: resolved.reason
1387
+ };
1388
+ continue;
1389
+ }
1390
+ if (condition !== void 0) {
1391
+ let decision;
1392
+ try {
1393
+ decision = await condition({
1394
+ request,
1395
+ current,
1396
+ target: resolved.target,
1397
+ ...resolved.sourceUnit === void 0 ? {} : { sourceUnit: resolved.sourceUnit },
1398
+ ...resolved.currentTranslation === void 0 ? {} : { currentTranslation: resolved.currentTranslation }
1399
+ });
1400
+ } catch (error) {
1401
+ rethrowContractError(error);
1402
+ results[index] = {
1403
+ request,
1404
+ status: "notWritable",
1405
+ reason: `执行附加条件失败:${errorMessage$1(error)}`
1406
+ };
1407
+ continue;
1408
+ }
1409
+ if (decision === false) {
1410
+ results[index] = {
1411
+ request,
1412
+ status: "conflict",
1413
+ reason: "消费者提供的附加条件未通过。"
1414
+ };
1415
+ continue;
1416
+ }
1417
+ if (decision === true || isRecord(decision) && decision.status === "allowed") {} else if (isRecord(decision) && decision.status === "rejected" && typeof decision.reason === "string") {
1418
+ results[index] = {
1419
+ request,
1420
+ status: "conflict",
1421
+ reason: decision.reason
1422
+ };
1423
+ continue;
1424
+ } else throw new StandardSchemaContractError("译文写入条件", "invalid-schema-result", "附加条件必须返回布尔值或 allowed/rejected 结果。");
1425
+ }
1426
+ prepared.push(resolved);
1427
+ }
1428
+ const groups = groupByPhysicalTarget(prepared);
1429
+ const writableGroups = [];
1430
+ const writable = [];
1431
+ for (const group of groups) {
1432
+ if (!compatibleRequests(group)) {
1433
+ for (const item of group) results[item.index] = {
1434
+ request: item.request,
1435
+ status: "conflict",
1436
+ reason: "多个写入请求解析到同一物理目标且修改互不相容。"
1437
+ };
1438
+ continue;
1439
+ }
1440
+ writableGroups.push(group);
1441
+ writable.push(...group);
1442
+ }
1443
+ if (adapter.writeBatch !== void 0) {
1444
+ if (writable.length === 0) return { results: completeWriteResults(validated, results) };
1445
+ const batchRequests = writableGroups.flatMap(([first]) => first === void 0 ? [] : [first]);
1446
+ let batchFailed = false;
1447
+ let batchError;
1448
+ try {
1449
+ await adapter.writeBatch({ requests: batchRequests.map((item) => ({
1450
+ request: item.request,
1451
+ target: item.target,
1452
+ ...item.sourceUnit === void 0 ? {} : { sourceUnit: item.sourceUnit },
1453
+ ...item.currentTranslation === void 0 ? {} : { currentTranslation: item.currentTranslation }
1454
+ })) });
1455
+ } catch (error) {
1456
+ batchFailed = true;
1457
+ batchError = error;
1458
+ }
1459
+ let after;
1460
+ try {
1461
+ after = await readCurrent();
1462
+ } catch (error) {
1463
+ const reason = `批量写入后回读失败:${errorMessage$1(error)}`;
1464
+ for (const item of writable) results[item.index] = {
1465
+ request: item.request,
1466
+ status: "writeUnconfirmed",
1467
+ reason
1468
+ };
1469
+ return {
1470
+ results: completeWriteResults(validated, results),
1471
+ ...batchFailed ? { batchError } : {}
1472
+ };
1473
+ }
1474
+ for (const item of writable) {
1475
+ if (confirmsWrite(item, after)) {
1476
+ results[item.index] = {
1477
+ request: item.request,
1478
+ status: "written"
1479
+ };
1480
+ continue;
1481
+ }
1482
+ if (batchFailed && canConfirmWriteFailure(item, after)) {
1483
+ results[item.index] = {
1484
+ request: item.request,
1485
+ status: "writeFailed",
1486
+ reason: `批量写入失败:${errorMessage$1(batchError)}`
1487
+ };
1488
+ continue;
1489
+ }
1490
+ results[item.index] = {
1491
+ request: item.request,
1492
+ status: "writeUnconfirmed",
1493
+ reason: batchFailed ? `批量写入失败,且回读不足以确认此项:${errorMessage$1(batchError)}` : "批量写入已返回,但回读未确认预期目标结果。"
1494
+ };
1495
+ }
1496
+ return {
1497
+ results: completeWriteResults(validated, results),
1498
+ ...batchFailed ? { batchError } : {}
1499
+ };
1500
+ }
1501
+ for (const group of writableGroups) {
1502
+ const [first] = group;
1503
+ if (first === void 0) continue;
1504
+ try {
1505
+ await adapter.write({
1506
+ request: first.request,
1507
+ target: first.target,
1508
+ ...first.sourceUnit === void 0 ? {} : { sourceUnit: first.sourceUnit },
1509
+ ...first.currentTranslation === void 0 ? {} : { currentTranslation: first.currentTranslation }
1510
+ });
1511
+ } catch (error) {
1512
+ rethrowContractError(error);
1513
+ const reason = `写入失败:${errorMessage$1(error)}`;
1514
+ for (const item of group) results[item.index] = {
1515
+ request: item.request,
1516
+ status: "writeFailed",
1517
+ reason
1518
+ };
1519
+ continue;
1520
+ }
1521
+ let after;
1522
+ try {
1523
+ after = await readCurrent();
1524
+ } catch (error) {
1525
+ rethrowContractError(error);
1526
+ const reason = `写入已返回成功,但回读失败:${errorMessage$1(error)}`;
1527
+ for (const item of group) results[item.index] = {
1528
+ request: item.request,
1529
+ status: "writeUnconfirmed",
1530
+ reason
1531
+ };
1532
+ continue;
1533
+ }
1534
+ for (const item of group) results[item.index] = confirmsWrite(item, after) ? {
1535
+ request: item.request,
1536
+ status: "written"
1537
+ } : {
1538
+ request: item.request,
1539
+ status: "writeUnconfirmed",
1540
+ reason: "写入已返回成功,但回读未确认预期目标结果。"
1541
+ };
1542
+ }
1543
+ return { results: completeWriteResults(validated, results) };
1544
+ }
1545
+ function completeWriteResults(validated, results) {
1546
+ return results.map((result, index) => {
1547
+ if (result !== void 0) return result;
1548
+ const request = validated[index];
1549
+ if (request === void 0) throw new StandardSchemaContractError("译文写入结果", "invalid-schema-result", "执行结果缺少对应请求。");
1550
+ return {
1551
+ request,
1552
+ status: "notWritable",
1553
+ reason: "写入项未处理。"
1554
+ };
1555
+ });
1556
+ }
1557
+ async function readWriteSnapshot(config, includeSource, languages) {
1558
+ const source = includeSource ? await readSourceSnapshot(config) : void 0;
1559
+ const translations = await readTranslationSnapshot(config.translations, source?.units ?? [], languages);
1560
+ return {
1561
+ ...source === void 0 ? {} : { source },
1562
+ translations
1563
+ };
1564
+ }
1565
+ async function prepareWrite(index, request, current, config) {
1566
+ const sourceCheck = checkExpectedSource(request, current);
1567
+ if (sourceCheck.status !== "ready") return sourceCheck;
1568
+ const adapter = config.translationWriteback;
1569
+ if (adapter === void 0) return {
1570
+ status: "notWritable",
1571
+ reason: "宿主没有提供译文写入适配器。"
1572
+ };
1573
+ let sourceUnit = sourceCheck.sourceUnit;
1574
+ let currentTranslation;
1575
+ let target;
1576
+ let resolved;
1577
+ try {
1578
+ if ("sourceKey" in request.target) {
1579
+ sourceUnit = findSourceUnit(current, request.target.sourceKey);
1580
+ if (sourceUnit === void 0) return sourceAbsenceResult(current, request.target.sourceKey);
1581
+ const targetAbsence = checkSourceTargetMissing(current, sourceUnit, request.target.language, config);
1582
+ if (targetAbsence.status !== "ready") return targetAbsence;
1583
+ if (adapter.locateNewTarget === void 0) return {
1584
+ status: "notWritable",
1585
+ reason: "宿主没有提供新目标定位能力。"
1586
+ };
1587
+ if (typeof adapter.locateNewTarget !== "function") throw new StandardSchemaContractError("译文写回适配器", "schema-mismatch", "translationWriteback.locateNewTarget 必须是函数。");
1588
+ resolved = validateWritebackResolution(await adapter.locateNewTarget({
1589
+ sourceKey: request.target.sourceKey,
1590
+ sourceUnit,
1591
+ language: request.target.language
1592
+ }));
1593
+ if (resolved.status === "notWritable") return {
1594
+ status: "notWritable",
1595
+ reason: resolved.reason
1596
+ };
1597
+ target = {
1598
+ kind: "create",
1599
+ locator: snapshotJson(resolved.locator, "目标定位")
1600
+ };
1601
+ } else {
1602
+ currentTranslation = findTranslationByIdentity(current, request.target.identity);
1603
+ if (currentTranslation === void 0) {
1604
+ if (isTranslationReadComplete(current, request.target.identity.language)) return {
1605
+ status: "conflict",
1606
+ reason: "预期存在的译文目标现在已缺失。"
1607
+ };
1608
+ return {
1609
+ status: "notWritable",
1610
+ reason: "目标语言读取不足,无法确认译文目标。"
1611
+ };
1612
+ }
1613
+ if (currentTranslation.bodyAvailability !== "available") return {
1614
+ status: "notWritable",
1615
+ reason: "目标译文正文不可用,无法核对写入条件。"
1616
+ };
1617
+ if (request.expectedTarget.status !== "present") return {
1618
+ status: "notWritable",
1619
+ reason: "现有目标请求缺少预期译文事实。"
1620
+ };
1621
+ if (!isDeepStrictEqual(currentTranslation.content, request.expectedTarget.content)) return {
1622
+ status: "conflict",
1623
+ reason: "目标译文正文已变化。"
1624
+ };
1625
+ if (request.expectedTarget.range !== void 0 && !isDeepStrictEqual(currentTranslation.range, request.expectedTarget.range)) return {
1626
+ status: "conflict",
1627
+ reason: "目标译文所在范围已变化。"
1628
+ };
1629
+ if (request.expectedTarget.record !== void 0 && !isDeepStrictEqual(currentTranslation.record, request.expectedTarget.record)) return {
1630
+ status: "conflict",
1631
+ reason: "目标译文记录已变化。"
1632
+ };
1633
+ if (adapter.locateExistingTarget === void 0) return {
1634
+ status: "notWritable",
1635
+ reason: "宿主没有提供现有目标定位能力。"
1636
+ };
1637
+ if (typeof adapter.locateExistingTarget !== "function") throw new StandardSchemaContractError("译文写回适配器", "schema-mismatch", "translationWriteback.locateExistingTarget 必须是函数。");
1638
+ resolved = validateWritebackResolution(await adapter.locateExistingTarget({
1639
+ identity: request.target.identity,
1640
+ translation: currentTranslation
1641
+ }));
1642
+ if (resolved.status === "notWritable") return {
1643
+ status: "notWritable",
1644
+ reason: resolved.reason
1645
+ };
1646
+ target = {
1647
+ kind: "existing",
1648
+ locator: snapshotJson(resolved.locator, "目标定位")
1649
+ };
1650
+ }
1651
+ } catch (error) {
1652
+ rethrowContractError(error);
1653
+ return {
1654
+ status: "notWritable",
1655
+ reason: errorMessage$1(error)
1656
+ };
1657
+ }
1658
+ return {
1659
+ status: "ready",
1660
+ index,
1661
+ request,
1662
+ target,
1663
+ ...sourceUnit === void 0 ? {} : { sourceUnit },
1664
+ ...currentTranslation === void 0 ? {} : { currentTranslation }
1665
+ };
1666
+ }
1667
+ function validateWritebackResolution(value) {
1668
+ if (!isRecord(value)) throw new StandardSchemaContractError("译文写入定位", "invalid-schema-result", "定位器必须返回对象结果。");
1669
+ if (value.status === "notWritable") {
1670
+ if (typeof value.reason !== "string") throw new StandardSchemaContractError("译文写入定位", "invalid-schema-result", "notWritable 定位结果必须包含字符串原因。");
1671
+ return {
1672
+ status: "notWritable",
1673
+ reason: value.reason
1674
+ };
1675
+ }
1676
+ if (value.status !== "located" || !Object.hasOwn(value, "locator")) throw new StandardSchemaContractError("译文写入定位", "invalid-schema-result", "定位器必须返回 located 或 notWritable 结果。");
1677
+ return {
1678
+ status: "located",
1679
+ locator: snapshotJson(value.locator, "目标定位")
1680
+ };
1681
+ }
1682
+ function checkExpectedSource(request, current) {
1683
+ const expectation = request.expectedSource;
1684
+ if (expectation === void 0) return { status: "ready" };
1685
+ if (current.source === void 0) return {
1686
+ status: "notWritable",
1687
+ reason: "本次写入没有读取原文依据。"
1688
+ };
1689
+ if (expectation.presence === "present") {
1690
+ const sourceUnit = findSourceUnit(current, expectation.key);
1691
+ if (sourceUnit === void 0) {
1692
+ if (isSourceRangeComplete(current, expectation.range)) return {
1693
+ status: "conflict",
1694
+ reason: "预期原文现在已缺失。"
1695
+ };
1696
+ return {
1697
+ status: "notWritable",
1698
+ reason: "原文读取不足,无法核对预期原文。"
1699
+ };
1700
+ }
1701
+ if (sourceUnit.bodyAvailability !== "available") return {
1702
+ status: "notWritable",
1703
+ reason: "当前原文正文不可用。"
1704
+ };
1705
+ const scope = current.source.read.scopes[sourceUnit.scopeIndex];
1706
+ if (scope === void 0 || !isDeepStrictEqual(scope.range, expectation.range)) return {
1707
+ status: "conflict",
1708
+ reason: "原文所在范围已变化。"
1709
+ };
1710
+ if (!isDeepStrictEqual(sourceUnit.unit, expectation.unit)) return {
1711
+ status: "conflict",
1712
+ reason: "原文单元已变化。"
1713
+ };
1714
+ if (!isDeepStrictEqual(sourceUnit.unit.source, expectation.content)) return {
1715
+ status: "conflict",
1716
+ reason: "原文正文已变化。"
1717
+ };
1718
+ return {
1719
+ status: "ready",
1720
+ sourceUnit
1721
+ };
1722
+ }
1723
+ if (findSourceUnit(current, expectation.key) !== void 0) return {
1724
+ status: "conflict",
1725
+ reason: "预期移除的原文现在已存在。"
1726
+ };
1727
+ if (!isSourceRangeComplete(current, expectation.range)) return {
1728
+ status: "notWritable",
1729
+ reason: "原文范围读取不完整,无法核对预期缺席。"
1730
+ };
1731
+ return { status: "ready" };
1732
+ }
1733
+ function checkSourceTargetMissing(current, sourceUnit, language, config) {
1734
+ const translations = config.translations;
1735
+ const languageRead = current.translations.reads.find((read) => read.language === language);
1736
+ if (translations === void 0 || !translations.languages.includes(language)) return {
1737
+ status: "notWritable",
1738
+ reason: "目标语言未配置。"
1739
+ };
1740
+ if (languageRead === void 0) return {
1741
+ status: "notWritable",
1742
+ reason: "目标语言尚未读取。"
1743
+ };
1744
+ const relevantScopes = languageRead.scopes.filter((scope) => scope.covers.includes(sourceUnit.key));
1745
+ if (relevantScopes.length === 0 || relevantScopes.some(({ enumeration }) => enumeration !== "complete")) return {
1746
+ status: "notWritable",
1747
+ reason: "目标范围读取不完整。"
1748
+ };
1749
+ return current.translations.records.filter((translation) => translation.language === language && translation.identity.key === sourceUnit.key).length === 0 ? { status: "ready" } : {
1750
+ status: "conflict",
1751
+ reason: "预期缺失的目标现在已存在。"
1752
+ };
1753
+ }
1754
+ function groupByPhysicalTarget(prepared) {
1755
+ const groups = [];
1756
+ for (const item of prepared) {
1757
+ const group = groups.find((items) => isDeepStrictEqual(items[0]?.target.locator, item.target.locator));
1758
+ if (group === void 0) groups.push([item]);
1759
+ else group.push(item);
1760
+ }
1761
+ return groups;
1762
+ }
1763
+ function compatibleRequests(group) {
1764
+ const first = group[0]?.request;
1765
+ if (first === void 0) return true;
1766
+ return group.every(({ request }) => request.operation === first.operation && (request.operation === "delete" || first.operation === "write" && isDeepStrictEqual(request.content, first.content)));
1767
+ }
1768
+ function confirmsWrite(prepared, after) {
1769
+ const { request } = prepared;
1770
+ if ("identity" in request.target) {
1771
+ const target = findTranslationByIdentity(after, request.target.identity);
1772
+ if (request.operation === "delete") {
1773
+ const prior = prepared.currentTranslation;
1774
+ return target === void 0 && prior !== void 0 && isTranslationRangeComplete(after, request.target.identity.language, prior.range);
1775
+ }
1776
+ return target !== void 0 && target.bodyAvailability === "available" && isDeepStrictEqual(target.content, request.content);
1777
+ }
1778
+ if (request.operation !== "write" || prepared.sourceUnit === void 0) return false;
1779
+ const sourceTarget = request.target;
1780
+ if (!("sourceKey" in sourceTarget)) return false;
1781
+ const currentSource = findSourceUnit(after, sourceTarget.sourceKey);
1782
+ if (currentSource === void 0) return false;
1783
+ const languageRead = after.translations.reads.find(({ language }) => language === sourceTarget.language);
1784
+ if (languageRead === void 0) return false;
1785
+ const relevantScopes = languageRead.scopes.filter((scope) => scope.covers.includes(sourceTarget.sourceKey));
1786
+ if (relevantScopes.length === 0 || relevantScopes.some(({ enumeration }) => enumeration !== "complete")) return false;
1787
+ const matching = after.translations.records.filter((translation) => translation.language === sourceTarget.language && translation.identity.key === currentSource.key);
1788
+ return matching.length === 1 && matching[0]?.bodyAvailability === "available" && isDeepStrictEqual(matching[0].content, request.content);
1789
+ }
1790
+ function canConfirmWriteFailure(prepared, after) {
1791
+ const { request } = prepared;
1792
+ if ("identity" in request.target) {
1793
+ const target = findTranslationByIdentity(after, request.target.identity);
1794
+ if (request.operation === "delete") return target !== void 0;
1795
+ if (target === void 0) return isTranslationReadComplete(after, request.target.identity.language);
1796
+ return target.bodyAvailability === "available" && !isDeepStrictEqual(target.content, request.content);
1797
+ }
1798
+ if (request.operation !== "write") return false;
1799
+ const sourceTarget = request.target;
1800
+ if (!("sourceKey" in sourceTarget)) return false;
1801
+ const currentSource = findSourceUnit(after, sourceTarget.sourceKey);
1802
+ if (currentSource === void 0) return false;
1803
+ const languageRead = after.translations.reads.find(({ language }) => language === sourceTarget.language);
1804
+ if (languageRead === void 0) return false;
1805
+ const relevantScopes = languageRead.scopes.filter((scope) => scope.covers.includes(sourceTarget.sourceKey));
1806
+ if (relevantScopes.length === 0 || relevantScopes.some(({ enumeration }) => enumeration !== "complete")) return false;
1807
+ const matching = after.translations.records.filter((translation) => translation.language === sourceTarget.language && translation.identity.key === currentSource.key);
1808
+ return matching.length !== 1 || matching[0]?.bodyAvailability === "available" && !isDeepStrictEqual(matching[0].content, request.content);
1809
+ }
1810
+ function validateTarget(value, operation) {
1811
+ if (!isRecord(value)) invalidWriteRequest("target 结构无效。");
1812
+ if (Object.hasOwn(value, "identity")) {
1813
+ assertOnlyKeys(value, ["identity"], "target");
1814
+ return { identity: validateIdentity(value.identity) };
1815
+ }
1816
+ if (operation === "delete") invalidWriteRequest("delete 只能引用现存译文 identity。");
1817
+ assertOnlyKeys(value, ["sourceKey", "language"], "target");
1818
+ if (typeof value.sourceKey !== "string" || value.sourceKey.trim().length === 0 || typeof value.language !== "string" || value.language.trim().length === 0) invalidWriteRequest("新建目标必须包含 sourceKey 与 language。");
1819
+ return {
1820
+ sourceKey: value.sourceKey,
1821
+ language: value.language
1822
+ };
1823
+ }
1824
+ async function validateExpectedTarget(value, operation, target, contentSchema) {
1825
+ if (!isRecord(value)) invalidWriteRequest("expectedTarget 结构无效。");
1826
+ if (value.status === "missing") {
1827
+ assertOnlyKeys(value, ["status"], "expectedTarget");
1828
+ if (operation !== "write" || "identity" in target) invalidWriteRequest("仅 sourceKey+language 写入可以预期目标缺失。");
1829
+ return { status: "missing" };
1830
+ }
1831
+ if (value.status !== "present") invalidWriteRequest("expectedTarget.status 必须为 missing 或 present。");
1832
+ assertOnlyKeys(value, [
1833
+ "status",
1834
+ "identity",
1835
+ "content",
1836
+ "range",
1837
+ "record"
1838
+ ], "expectedTarget");
1839
+ const identity = validateIdentity(value.identity);
1840
+ const content = snapshotValue(await validateWithStandardSchema(contentSchema, value.content, "预期译文正文", {
1841
+ preserveValue: true,
1842
+ requireJson: true
1843
+ }), "预期译文正文");
1844
+ if ("identity" in target && !isDeepStrictEqual(target.identity, identity)) invalidWriteRequest("expectedTarget identity 必须与 target identity 相同。");
1845
+ return {
1846
+ status: "present",
1847
+ identity,
1848
+ content,
1849
+ ...Object.hasOwn(value, "range") ? { range: snapshotJson(value.range, "预期译文范围") } : {},
1850
+ ...Object.hasOwn(value, "record") ? { record: snapshotJson(value.record, "预期译文记录") } : {}
1851
+ };
1852
+ }
1853
+ async function validateExpectedSource(value, config, target) {
1854
+ if (!isRecord(value)) invalidWriteRequest("expectedSource 结构无效。");
1855
+ if (value.presence === "absent") {
1856
+ assertOnlyKeys(value, [
1857
+ "presence",
1858
+ "key",
1859
+ "range"
1860
+ ], "expectedSource");
1861
+ if (typeof value.key !== "string" || value.key.trim().length === 0) invalidWriteRequest("expectedSource.key 必须是非空字符串。");
1862
+ const range = snapshotJson(value.range, "预期原文范围");
1863
+ return {
1864
+ presence: "absent",
1865
+ key: value.key,
1866
+ range
1867
+ };
1868
+ }
1869
+ if (value.presence !== "present") invalidWriteRequest("expectedSource.presence 必须为 present 或 absent。");
1870
+ assertOnlyKeys(value, [
1871
+ "presence",
1872
+ "key",
1873
+ "range",
1874
+ "unit",
1875
+ "content"
1876
+ ], "expectedSource");
1877
+ if (typeof value.key !== "string" || value.key.trim().length === 0) invalidWriteRequest("expectedSource.key 必须是非空字符串。");
1878
+ if ("sourceKey" in target && target.sourceKey !== value.key) invalidWriteRequest("expectedSource.key 必须与新建目标 sourceKey 相同。");
1879
+ const unit = snapshotValue(await validateWithStandardSchema(config.source.schema, value.unit, "预期原文单元", {
1880
+ preserveValue: true,
1881
+ requireJson: true
1882
+ }), "预期原文单元");
1883
+ const range = snapshotJson(value.range, "预期原文范围");
1884
+ const content = snapshotJson(value.content, "预期原文正文");
1885
+ if (config.keyOf(unit) !== value.key) invalidWriteRequest("expectedSource.key 与原文单元身份不匹配。");
1886
+ if (!isDeepStrictEqual(unit.source, content)) invalidWriteRequest("expectedSource.content 与原文单元正文不匹配。");
1887
+ return {
1888
+ presence: "present",
1889
+ key: value.key,
1890
+ range,
1891
+ unit,
1892
+ content
1893
+ };
1894
+ }
1895
+ function validateIdentity(value) {
1896
+ if (!isRecord(value) || typeof value.language !== "string" || value.language.trim().length === 0 || typeof value.key !== "string" || value.key.trim().length === 0) invalidWriteRequest("identity 必须包含非空 language 与 key。");
1897
+ assertOnlyKeys(value, ["language", "key"], "identity");
1898
+ return {
1899
+ language: value.language,
1900
+ key: value.key
1901
+ };
1902
+ }
1903
+ function findSourceUnit(current, key) {
1904
+ return current.source?.units.find((unit) => unit.key === key);
1905
+ }
1906
+ function findTranslationByIdentity(current, identity) {
1907
+ return current.translations.records.find((translation) => isDeepStrictEqual(translation.identity, identity));
1908
+ }
1909
+ function sourceAbsenceResult(current, key) {
1910
+ return current.source?.read.status === "complete" ? {
1911
+ status: "conflict",
1912
+ reason: `原文 ${key} 已不存在。`
1913
+ } : {
1914
+ status: "notWritable",
1915
+ reason: `原文读取不足,无法确认 ${key} 存在。`
1916
+ };
1917
+ }
1918
+ function isSourceRangeComplete(current, range) {
1919
+ const source = current.source;
1920
+ if (source === void 0) return false;
1921
+ const scopes = source.read.scopes.filter(({ range: currentRange }) => isDeepStrictEqual(currentRange, range));
1922
+ return scopes.length > 0 && scopes.every(({ enumeration }) => enumeration === "complete");
1923
+ }
1924
+ function isTranslationReadComplete(current, language) {
1925
+ const read = current.translations.reads.find((item) => item.language === language);
1926
+ return read !== void 0 && read.status === "complete" && read.scopes.length > 0 && read.scopes.every(({ enumeration }) => enumeration === "complete");
1927
+ }
1928
+ function isTranslationRangeComplete(current, language, range) {
1929
+ const scopes = current.translations.reads.find((item) => item.language === language)?.scopes.filter((scope) => isDeepStrictEqual(scope.range, range));
1930
+ return scopes !== void 0 && scopes.length > 0 && scopes.every(({ enumeration }) => enumeration === "complete");
1931
+ }
1932
+ function assertOnlyKeys(value, allowed, name) {
1933
+ if (Object.keys(value).some((key) => !allowed.includes(key))) invalidWriteRequest(`${name} 包含不支持的字段。`);
1934
+ }
1935
+ function invalidWriteRequest(message) {
1936
+ throw new TypeError(`译文写入请求无效:${message}`);
1937
+ }
1938
+ function snapshotJson(value, description) {
1939
+ return snapshotJsonValue(value, description);
1940
+ }
1941
+ function snapshotValue(value, description) {
1942
+ return snapshotJsonValue(value, description);
1943
+ }
1944
+ function rethrowContractError(error) {
1945
+ if (error instanceof StandardSchemaContractError || error instanceof TranslationIdentityContractError) throw error;
1946
+ }
1947
+ function errorMessage$1(error) {
1948
+ return error instanceof Error ? error.message : String(error);
1949
+ }
1950
+ // ../../packages/core/dist/translation-associations.js
1951
+ /** 当前读取与历史快照共用消息键关联;范围只决定读取依据,不排除已知的同键译文。 */
1952
+ function associateSnapshot(snapshot) {
1953
+ const associations = [];
1954
+ for (const languageRead of snapshot.translations.reads) for (const sourceUnit of snapshot.source.units) {
1955
+ const scopeIndexes = languageRead.scopes.flatMap((scope, index) => scope.covers.includes(sourceUnit.key) ? [index] : []);
1956
+ const coverageStatus = readStatus(languageRead.scopes.filter((_, index) => scopeIndexes.includes(index)), scopeIndexes.length === 0 ? languageRead.error : void 0);
1957
+ const translationIndexes = snapshot.translations.records.filter(({ language }) => language === languageRead.language).filter(({ identity }) => identity.key === sourceUnit.key).map(({ index }) => index);
1958
+ const status = translationIndexes.length === 0 ? coverageStatus === "complete" ? "missing" : "unknown" : coverageStatus !== "complete" ? "unknown" : snapshot.translations.records[translationIndexes[0]]?.bodyAvailability === "available" ? "matched" : "unavailable";
1959
+ associations.push({
1960
+ sourceKey: sourceUnit.key,
1961
+ language: languageRead.language,
1962
+ status,
1963
+ coverageStatus,
1964
+ scopeIndexes,
1965
+ translationIndexes
1966
+ });
1967
+ }
1968
+ return associations;
1969
+ }
1970
+ // ../../packages/core/dist/comparison.js
1971
+ var ComparisonContractError = class extends TypeError {
1972
+ reason;
1973
+ constructor(reason, message) {
1974
+ super(message);
1975
+ this.name = "ComparisonContractError";
1976
+ this.reason = reason;
1977
+ }
1978
+ };
1979
+ function validateComparisonInput(value) {
1980
+ assertComparisonJsonValue(value, "比较输入", "input");
1981
+ if (!isRecord(value) || !Object.hasOwn(value, "previous")) invalidInput("比较输入必须提供 previous 与 current。");
1982
+ const current = normalizeLegacyComparisonSnapshot(value.current);
1983
+ const previous = value.previous === void 0 ? void 0 : normalizeLegacyComparisonSnapshot(value.previous);
1984
+ validateSnapshot$1(current, "current");
1985
+ if (previous !== void 0) validateSnapshot$1(previous, "previous");
1986
+ }
1987
+ function validateComparisonResult(input, value) {
1988
+ assertComparisonJsonValue(value, "比较结果", "result");
1989
+ if (!isRecord(value)) invalidResult("比较结果必须是对象。");
1990
+ if (!Array.isArray(value.sourceChanges)) invalidResult("比较结果必须提供 sourceChanges 数组。");
1991
+ if (!Array.isArray(value.translationChanges)) invalidResult("比较结果必须提供 translationChanges 数组。");
1992
+ if (!isRecord(value.reads)) invalidResult("比较结果必须提供 reads 对象。");
1993
+ if (!Object.hasOwn(value.reads, "current")) invalidResult("比较结果必须提供 current 读取依据。");
1994
+ if (input.previous !== void 0 && !Object.hasOwn(value.reads, "previous")) invalidResult("存在 previous 快照时,比较结果必须提供 previous 读取依据。");
1995
+ const expectedPrevious = input.previous === void 0 ? void 0 : readEvidence(input.previous);
1996
+ const expectedCurrent = readEvidence(input.current);
1997
+ if (!isDeepStrictEqual(value.reads.previous, expectedPrevious)) invalidResult("比较结果的 previous 读取依据必须与输入一致。");
1998
+ if (!isDeepStrictEqual(value.reads.current, expectedCurrent)) invalidResult("比较结果的 current 读取依据必须与输入一致。");
1999
+ validateSourceChanges(input, value.sourceChanges);
2000
+ validateTranslationChanges(input, value.translationChanges);
2001
+ }
2002
+ function defaultCompare(input) {
2003
+ validateComparisonInput(input);
2004
+ return createDefaultComparison(normalizeLegacyCompareInput(input));
2005
+ }
2006
+ async function compareSnapshots(input, compare) {
2007
+ validateComparisonInput(input);
2008
+ if (compare !== void 0 && typeof compare !== "function") invalidInput("compare 必须是比较函数。");
2009
+ const normalizedInput = normalizeLegacyCompareInput(input);
2010
+ const compared = compare === void 0 || compare === defaultCompare ? createDefaultComparison(normalizedInput) : await compare(normalizedInput);
2011
+ validateComparisonResult(normalizedInput, compared);
2012
+ return compared;
2013
+ }
2014
+ function normalizeLegacyCompareInput(input) {
2015
+ const current = normalizeLegacyComparisonSnapshot(input.current);
2016
+ const previous = input.previous === void 0 ? void 0 : normalizeLegacyComparisonSnapshot(input.previous);
2017
+ if (current === input.current && previous === input.previous) return input;
2018
+ return {
2019
+ previous,
2020
+ current
2021
+ };
2022
+ }
2023
+ function createDefaultComparison(input) {
2024
+ return {
2025
+ sourceChanges: createSourceChanges(input),
2026
+ translationChanges: createTranslationChanges(input),
2027
+ reads: {
2028
+ previous: input.previous === void 0 ? void 0 : readEvidence(input.previous),
2029
+ current: readEvidence(input.current)
2030
+ }
2031
+ };
2032
+ }
2033
+ function createSourceChanges(input) {
2034
+ const previous = input.previous === void 0 ? /* @__PURE__ */ new Map() : sourceRecordMap(input.previous);
2035
+ const current = sourceRecordMap(input.current);
2036
+ return [.../* @__PURE__ */ new Set([...previous.keys(), ...current.keys()])].sort(compareText).map((key) => {
2037
+ const before = previous.get(key);
2038
+ const after = current.get(key);
2039
+ return {
2040
+ key,
2041
+ status: compareSourceStatus(input.previous?.source, input.current.source, before, after),
2042
+ previous: before,
2043
+ current: after
2044
+ };
2045
+ });
2046
+ }
2047
+ function createTranslationChanges(input) {
2048
+ const previous = input.previous === void 0 ? /* @__PURE__ */ new Map() : translationRecordMap(input.previous);
2049
+ const current = translationRecordMap(input.current);
2050
+ return [.../* @__PURE__ */ new Set([...previous.keys(), ...current.keys()])].sort(compareText).map((identityKey) => {
2051
+ const before = previous.get(identityKey);
2052
+ const after = current.get(identityKey);
2053
+ const identity = (after ?? before)?.identity;
2054
+ if (identity === void 0) invalidInput("比较输入中存在无法读取的译文身份。");
2055
+ return {
2056
+ identity,
2057
+ status: compareTranslationStatus(input.previous, input.current, before, after),
2058
+ previous: before,
2059
+ current: after
2060
+ };
2061
+ });
2062
+ }
2063
+ function compareSourceStatus(previousSource, currentSource, previous, current) {
2064
+ const evidenceStatus = sourceEvidenceStatus(previousSource, currentSource, previous, current);
2065
+ if (evidenceStatus !== "comparable") return evidenceStatus;
2066
+ if (previous === void 0 || current === void 0) invalidInput("可比较的原文必须同时提供前后事实。");
2067
+ return isDeepStrictEqual(previous.unit, current.unit) ? "unchanged" : "modified";
2068
+ }
2069
+ function sourceEvidenceStatus(previousSource, currentSource, previous, current) {
2070
+ if (previous === void 0 && current !== void 0) {
2071
+ if (previousSource === void 0) return "historyMissing";
2072
+ return hasCompleteSourceScope(previousSource.read, sourceRange(currentSource, current)) ? "added" : "historyInsufficient";
2073
+ }
2074
+ if (previous !== void 0 && current === void 0) {
2075
+ if (previousSource === void 0) invalidInput("缺少 previous 快照,却提供了历史原文事实。");
2076
+ return hasCompleteSourceScope(currentSource.read, sourceRange(previousSource, previous)) ? "removed" : "currentInsufficient";
2077
+ }
2078
+ if (previous === void 0 || current === void 0) return "historyInsufficient";
2079
+ if (previous.bodyAvailability === "unavailable" && current.bodyAvailability === "unavailable") return "bothInsufficient";
2080
+ if (previous.bodyAvailability === "unavailable") return "historyInsufficient";
2081
+ if (current.bodyAvailability === "unavailable") return "currentInsufficient";
2082
+ return "comparable";
2083
+ }
2084
+ function compareTranslationStatus(previousSnapshot, currentSnapshot, previous, current) {
2085
+ const evidenceStatus = translationEvidenceStatus(previousSnapshot, currentSnapshot, previous, current);
2086
+ if (evidenceStatus !== "comparable") return evidenceStatus;
2087
+ if (previous === void 0 || current === void 0) invalidInput("可比较的译文必须同时提供前后事实。");
2088
+ return isDeepStrictEqual(previous.content, current.content) ? "unchanged" : "modified";
2089
+ }
2090
+ function translationEvidenceStatus(previousSnapshot, currentSnapshot, previous, current) {
2091
+ if (previous === void 0 && current !== void 0) {
2092
+ if (previousSnapshot === void 0) return "historyMissing";
2093
+ return hasCompleteTranslationScope(previousSnapshot.translations.reads, current.identity.language, current.range) ? "added" : "historyInsufficient";
2094
+ }
2095
+ if (previous !== void 0 && current === void 0) {
2096
+ if (previousSnapshot === void 0) invalidInput("缺少 previous 快照,却提供了历史译文事实。");
2097
+ return hasCompleteTranslationScope(currentSnapshot.translations.reads, previous.identity.language, previous.range) ? "removed" : "currentInsufficient";
2098
+ }
2099
+ if (previous === void 0 || current === void 0) return "historyInsufficient";
2100
+ if (previous.bodyAvailability === "unavailable" && current.bodyAvailability === "unavailable") return "bothInsufficient";
2101
+ if (previous.bodyAvailability === "unavailable") return "historyInsufficient";
2102
+ if (current.bodyAvailability === "unavailable") return "currentInsufficient";
2103
+ return "comparable";
2104
+ }
2105
+ function validateSourceChanges(input, value) {
2106
+ const previous = input.previous === void 0 ? /* @__PURE__ */ new Map() : sourceRecordMap(input.previous);
2107
+ const current = sourceRecordMap(input.current);
2108
+ const expectedKeys = /* @__PURE__ */ new Set([...previous.keys(), ...current.keys()]);
2109
+ const seen = /* @__PURE__ */ new Set();
2110
+ for (const [index, rawChange] of value.entries()) {
2111
+ if (!isRecord(rawChange) || typeof rawChange.key !== "string") invalidResult(`第 ${index + 1} 个原文变化必须提供 key。`);
2112
+ if (seen.has(rawChange.key)) invalidResult(`原文变化身份重复:${rawChange.key}。`);
2113
+ seen.add(rawChange.key);
2114
+ if (!expectedKeys.has(rawChange.key)) invalidResult(`原文变化身份不在输入中:${rawChange.key}。`);
2115
+ const before = previous.get(rawChange.key);
2116
+ const after = current.get(rawChange.key);
2117
+ validateBeforeAndAfter(rawChange, before, after, `原文 ${rawChange.key}`);
2118
+ validateSourceStatus(input.previous?.source, input.current.source, before, after, rawChange.status, `原文 ${rawChange.key}`);
2119
+ }
2120
+ if (seen.size !== expectedKeys.size) invalidResult("sourceChanges 必须覆盖输入中的每个原文身份。");
2121
+ }
2122
+ function validateTranslationChanges(input, value) {
2123
+ const previous = input.previous === void 0 ? /* @__PURE__ */ new Map() : translationRecordMap(input.previous);
2124
+ const current = translationRecordMap(input.current);
2125
+ const expectedKeys = /* @__PURE__ */ new Set([...previous.keys(), ...current.keys()]);
2126
+ const seen = /* @__PURE__ */ new Set();
2127
+ for (const [index, rawChange] of value.entries()) {
2128
+ if (!isRecord(rawChange) || !isIdentity$1(rawChange.identity)) invalidResult(`第 ${index + 1} 个译文变化必须提供完整身份。`);
2129
+ const identityKey = translationIdentityKey(rawChange.identity);
2130
+ if (seen.has(identityKey)) invalidResult(`译文变化身份重复:${JSON.stringify(rawChange.identity)}。`);
2131
+ seen.add(identityKey);
2132
+ if (!expectedKeys.has(identityKey)) invalidResult(`译文变化身份不在输入中:${JSON.stringify(rawChange.identity)}。`);
2133
+ const before = previous.get(identityKey);
2134
+ const after = current.get(identityKey);
2135
+ const expectedIdentity = (after ?? before)?.identity;
2136
+ if (expectedIdentity === void 0 || !isDeepStrictEqual(rawChange.identity, expectedIdentity)) invalidResult("译文变化的 identity 必须与输入事实一致。");
2137
+ validateBeforeAndAfter(rawChange, before, after, `译文 ${JSON.stringify(rawChange.identity)}`);
2138
+ validateTranslationStatus(input.previous, input.current, before, after, rawChange.status, `译文 ${JSON.stringify(rawChange.identity)}`);
2139
+ }
2140
+ if (seen.size !== expectedKeys.size) invalidResult("translationChanges 必须覆盖输入中的每个译文身份。");
2141
+ }
2142
+ function validateBeforeAndAfter(change, previous, current, description) {
2143
+ const previousMatches = previous === void 0 ? change.previous === void 0 : Object.hasOwn(change, "previous") && isDeepStrictEqual(change.previous, previous);
2144
+ const currentMatches = current === void 0 ? change.current === void 0 : Object.hasOwn(change, "current") && isDeepStrictEqual(change.current, current);
2145
+ if (!previousMatches || !currentMatches) invalidResult(`${description} 的前后事实必须与输入一致。`);
2146
+ }
2147
+ function validateSourceStatus(previousSource, currentSource, previous, current, status, description) {
2148
+ if (typeof status !== "string" || !isComparisonStatus$1(status)) invalidResult(`${description} 的 status 无效。`);
2149
+ if (previous !== void 0 && current !== void 0) {
2150
+ if (status === "historyMissing" || status === "added" || status === "removed") invalidResult(`${description} 前后都有同一身份,只能标记比较或依据不足。`);
2151
+ return;
2152
+ }
2153
+ validateStatusChoice(status, sourceEvidenceStatus(previousSource, currentSource, previous, current), description);
2154
+ }
2155
+ function validateTranslationStatus(previousSnapshot, currentSnapshot, previous, current, status, description) {
2156
+ if (typeof status !== "string" || !isComparisonStatus$1(status)) invalidResult(`${description} 的 status 无效。`);
2157
+ if (previous !== void 0 && current !== void 0) {
2158
+ if (status === "historyMissing" || status === "added" || status === "removed") invalidResult(`${description} 前后都有同一身份,只能标记比较或依据不足。`);
2159
+ return;
2160
+ }
2161
+ validateStatusChoice(status, translationEvidenceStatus(previousSnapshot, currentSnapshot, previous, current), description);
2162
+ }
2163
+ function validateStatusChoice(status, expected, description) {
2164
+ if (expected === "comparable") {
2165
+ if (status !== "modified" && status !== "unchanged") invalidResult(`${description} 已有双方可用正文,只能标记 modified 或 unchanged。`);
2166
+ return;
2167
+ }
2168
+ if (status !== expected) invalidResult(`${description} 的 status 必须是 ${expected}。`);
2169
+ }
2170
+ function sourceRecordMap(snapshot) {
2171
+ return new Map(snapshot.source.units.map((unit) => [unit.key, unit]));
2172
+ }
2173
+ function translationRecordMap(snapshot) {
2174
+ return new Map(snapshot.translations.records.map((record) => [translationIdentityKey(record.identity), record]));
2175
+ }
2176
+ function validateSnapshot$1(value, description) {
2177
+ if (!isRecord(value) || typeof value.version !== "string") invalidInput(`${description} 快照结构无效。`);
2178
+ if (!isRecord(value.source) || !isRecord(value.source.read)) invalidInput(`${description} 快照缺少 source.read。`);
2179
+ if (!Array.isArray(value.source.read.scopes) || !Array.isArray(value.source.units)) invalidInput(`${description} 快照的原文事实结构无效。`);
2180
+ if (!isCoverageStatus(value.source.read.status)) invalidInput(`${description} 快照的原文读取状态无效。`);
2181
+ for (const scope of value.source.read.scopes) if (!isRecord(scope) || !isEnumerationCompleteness(scope.enumeration)) invalidInput(`${description} 快照的原文读取范围结构无效。`);
2182
+ const sourceKeys = /* @__PURE__ */ new Set();
2183
+ for (const unit of value.source.units) {
2184
+ if (!isRecord(unit) || typeof unit.key !== "string" || unit.key.trim().length === 0 || !isBodyAvailability(unit.bodyAvailability) || !Number.isInteger(unit.scopeIndex) || unit.scopeIndex < 0 || unit.scopeIndex >= value.source.read.scopes.length) invalidInput(`${description} 快照包含无效原文事实。`);
2185
+ if (sourceKeys.has(unit.key)) invalidInput(`${description} 快照原文身份重复:${unit.key}。`);
2186
+ sourceKeys.add(unit.key);
2187
+ }
2188
+ if (!isRecord(value.translations) || !Array.isArray(value.translations.reads) || !Array.isArray(value.translations.records)) invalidInput(`${description} 快照的译文事实结构无效。`);
2189
+ for (const read of value.translations.reads) {
2190
+ if (!isRecord(read) || typeof read.language !== "string" || !isCoverageStatus(read.status) || !Array.isArray(read.scopes)) invalidInput(`${description} 快照的译文读取依据无效。`);
2191
+ for (const scope of read.scopes) if (!isRecord(scope) || !isEnumerationCompleteness(scope.enumeration)) invalidInput(`${description} 快照的译文读取范围结构无效。`);
2192
+ }
2193
+ const translationKeys = /* @__PURE__ */ new Set();
2194
+ for (const translation of value.translations.records) {
2195
+ if (!isRecord(translation) || typeof translation.language !== "string" || !isIdentity$1(translation.identity) || translation.identity.language !== translation.language || !isBodyAvailability(translation.bodyAvailability)) invalidInput(`${description} 快照包含无效译文事实。`);
2196
+ const identityKey = translationIdentityKey(translation.identity);
2197
+ if (translationKeys.has(identityKey)) invalidInput(`${description} 快照译文身份重复:${JSON.stringify(translation.identity)}。`);
2198
+ translationKeys.add(identityKey);
2199
+ }
2200
+ }
2201
+ function hasCompleteSourceScope(read, range) {
2202
+ return read.scopes.some((scope) => scope.enumeration === "complete" && isDeepStrictEqual(scope.range, range));
2203
+ }
2204
+ function hasCompleteTranslationScope(reads, language, range) {
2205
+ return reads.some((read) => read.language === language && read.scopes.some((scope) => scope.enumeration === "complete" && isDeepStrictEqual(scope.range, range)));
2206
+ }
2207
+ function sourceRange(source, sourceUnit) {
2208
+ return source.read.scopes[sourceUnit.scopeIndex]?.range;
2209
+ }
2210
+ /**
2211
+ * 将升级前 v2 基线或更新计划中的旧译文字段 `translation` 无损归一化为 `record`。
2212
+ * 可写对象原地迁移,冻结对象返回浅拷贝以兼容只读历史输入。
2213
+ */
2214
+ function normalizeLegacyTranslationRecord(value) {
2215
+ if (!isRecord(value)) return value;
2216
+ if (Object.hasOwn(value, "record") || !Object.hasOwn(value, "translation")) return value;
2217
+ const descriptor = Object.getOwnPropertyDescriptor(value, "translation");
2218
+ if (Object.isExtensible(value) && descriptor?.configurable === true) {
2219
+ const mutable = value;
2220
+ mutable.record = mutable.translation;
2221
+ delete mutable.translation;
2222
+ return value;
2223
+ }
2224
+ const { translation: record, ...rest } = value;
2225
+ return {
2226
+ ...rest,
2227
+ record
2228
+ };
2229
+ }
2230
+ /**
2231
+ * 归一化比较快照中的译文记录数组,兼容读取升级前保存的 v2 快照。
2232
+ */
2233
+ function normalizeLegacyComparisonSnapshot(value) {
2234
+ if (!isRecord(value) || !isRecord(value.translations)) return value;
2235
+ const rawRecords = value.translations.records;
2236
+ if (!Array.isArray(rawRecords)) return value;
2237
+ let changed = false;
2238
+ const records = rawRecords.map((item) => {
2239
+ const normalized = normalizeLegacyTranslationRecord(item);
2240
+ if (normalized !== item) changed = true;
2241
+ return normalized;
2242
+ });
2243
+ if (!changed) return value;
2244
+ const mutable = value;
2245
+ const translations = value.translations;
2246
+ const translationsDescriptor = Object.getOwnPropertyDescriptor(value, "translations");
2247
+ const recordsDescriptor = Object.getOwnPropertyDescriptor(translations, "records");
2248
+ if (Object.isExtensible(translations) && recordsDescriptor?.configurable === true && recordsDescriptor.writable === true) {
2249
+ translations.records = records;
2250
+ return value;
2251
+ }
2252
+ const nextTranslations = {
2253
+ ...translations,
2254
+ records
2255
+ };
2256
+ if (Object.isExtensible(value) && translationsDescriptor?.configurable === true && translationsDescriptor.writable === true) {
2257
+ mutable.translations = nextTranslations;
2258
+ return value;
2259
+ }
2260
+ return {
2261
+ ...value,
2262
+ translations: nextTranslations
2263
+ };
2264
+ }
2265
+ function readEvidence(snapshot) {
2266
+ return {
2267
+ source: snapshot.source.read,
2268
+ translations: snapshot.translations.reads
2269
+ };
2270
+ }
2271
+ function translationIdentityKey(identity) {
2272
+ return JSON.stringify([identity.language, identity.key]);
2273
+ }
2274
+ function isIdentity$1(value) {
2275
+ return isRecord(value) && typeof value.language === "string" && Object.keys(value).length === 2 && typeof value.key === "string" && value.key.trim().length > 0;
2276
+ }
2277
+ function isComparisonStatus$1(value) {
2278
+ return value === "historyMissing" || value === "historyInsufficient" || value === "currentInsufficient" || value === "bothInsufficient" || value === "added" || value === "removed" || value === "modified" || value === "unchanged";
2279
+ }
2280
+ function isBodyAvailability(value) {
2281
+ return value === "available" || value === "unavailable";
2282
+ }
2283
+ function isCoverageStatus(value) {
2284
+ return value === "complete" || value === "incomplete" || value === "failed" || value === "notRead";
2285
+ }
2286
+ function isEnumerationCompleteness(value) {
2287
+ return value === "complete" || value === "partial" || value === "failed";
2288
+ }
2289
+ function compareText(left, right) {
2290
+ return left < right ? -1 : left > right ? 1 : 0;
2291
+ }
2292
+ function invalidInput(message) {
2293
+ throw new ComparisonContractError("invalid-input", message);
2294
+ }
2295
+ function assertComparisonJsonValue(value, description, kind) {
2296
+ let valueToValidate = value;
2297
+ if (kind === "input" && isRecord(value)) {
2298
+ const { previous, ...input } = value;
2299
+ valueToValidate = previous === void 0 ? input : value;
2300
+ } else if (kind === "result" && isRecord(value)) {
2301
+ const { sourceChanges, translationChanges, reads, ...result } = value;
2302
+ valueToValidate = {
2303
+ ...result,
2304
+ sourceChanges: withoutUndefinedSides(sourceChanges),
2305
+ translationChanges: withoutUndefinedSides(translationChanges),
2306
+ reads: withoutUndefinedReadPrevious(reads)
2307
+ };
2308
+ }
2309
+ try {
2310
+ assertJsonValue(valueToValidate, description);
2311
+ } catch (error) {
2312
+ const message = error instanceof Error ? error.message : String(error);
2313
+ if (kind === "input") invalidInput(message);
2314
+ invalidResult(message);
2315
+ }
2316
+ }
2317
+ function withoutUndefinedSides(value) {
2318
+ if (!Array.isArray(value)) return value;
2319
+ return value.map((change) => {
2320
+ if (!isRecord(change)) return change;
2321
+ const { previous, current, ...rest } = change;
2322
+ return {
2323
+ ...rest,
2324
+ ...previous === void 0 ? {} : { previous },
2325
+ ...current === void 0 ? {} : { current }
2326
+ };
2327
+ });
2328
+ }
2329
+ function withoutUndefinedReadPrevious(value) {
2330
+ if (!isRecord(value)) return value;
2331
+ const { previous, ...rest } = value;
2332
+ return previous === void 0 ? rest : value;
2333
+ }
2334
+ function invalidResult(message) {
2335
+ throw new ComparisonContractError("invalid-result", message);
2336
+ }
2337
+ // ../../packages/core/dist/baselines.js
2338
+ const COMPARISON_BASELINE_FORMAT = "lioni.comparison-baseline/v2";
2339
+ var ComparisonBaselineFormatError = class extends TypeError {
2340
+ reason;
2341
+ constructor(reason, message) {
2342
+ super(message);
2343
+ this.name = "ComparisonBaselineFormatError";
2344
+ this.reason = reason;
2345
+ }
2346
+ };
2347
+ var ComparisonBaselineIncompleteSnapshotError = class extends Error {
2348
+ language;
2349
+ constructor(message, language) {
2350
+ super(message);
2351
+ this.name = "ComparisonBaselineIncompleteSnapshotError";
2352
+ if (language !== void 0) this.language = language;
2353
+ }
2354
+ };
2355
+ /**
2356
+ * 替换明确选择的快照范围并保留其余历史。未提供选择时,采用当前快照中观察到的全部范围。
2357
+ */
2358
+ function replaceComparisonBaseline(options) {
2359
+ if (options.previous !== void 0) validateComparisonBaseline(options.previous);
2360
+ const previous = options.previous === void 0 ? void 0 : normalizeLegacyComparisonBaseline(options.previous);
2361
+ const current = normalizeLegacyComparisonSnapshot(options.current);
2362
+ validateSnapshot(current);
2363
+ const sourceRanges = options.selection?.sourceRanges ?? (options.selection === void 0 ? current.source.read.scopes.map(({ range }) => range) : []);
2364
+ const translationRanges = options.selection?.translationRanges ?? (options.selection === void 0 ? current.translations.reads.flatMap(({ language, scopes }) => scopes.map(({ range }) => ({
2365
+ language,
2366
+ range
2367
+ }))) : []);
2368
+ const selectedSourceIndexes = selectScopeIndexes(current.source.read.scopes, sourceRanges, "原文");
2369
+ const translationIndexesByLanguage = selectTranslationScopeIndexes(current.translations.reads, translationRanges);
2370
+ const sourceEntries = mergeScopeEntries(previous?.snapshot.source.read.scopes ?? [], current.source.read.scopes, selectedSourceIndexes);
2371
+ const sourceScopes = sourceEntries.map(({ value }) => ({ ...value }));
2372
+ const sourceUnits = sourceEntries.flatMap((entry, scopeIndex) => {
2373
+ const snapshot = entry.origin === "current" ? current : previous?.snapshot;
2374
+ if (snapshot === void 0) return [];
2375
+ return snapshot.source.units.filter(({ scopeIndex: oldIndex }) => oldIndex === entry.index).map((unit) => ({
2376
+ ...unit,
2377
+ scopeIndex
2378
+ }));
2379
+ });
2380
+ assertUniqueSourceKeys(sourceUnits);
2381
+ const previousSourceRead = previous?.snapshot.source.read;
2382
+ const snapshot = createSnapshot(createSourceSnapshot(createSourceRead(sourceScopes, options.selection === void 0 ? current.source.read.error : previousSourceRead?.error), sourceUnits), createTranslations({
2383
+ previous,
2384
+ current,
2385
+ entries: mergeTranslationReads({
2386
+ previous,
2387
+ current,
2388
+ selection: options.selection,
2389
+ translationRangesByLanguage: translationIndexesByLanguage
2390
+ }),
2391
+ selection: translationRanges
2392
+ }));
2393
+ if (previous !== void 0 && sameSnapshot(previous.snapshot, snapshot)) return previous;
2394
+ const result = {
2395
+ format: COMPARISON_BASELINE_FORMAT,
2396
+ snapshot
2397
+ };
2398
+ validateComparisonBaseline(result);
2399
+ return result;
2400
+ }
2401
+ /** 读取配置的源译事实并显式记录为基线;此入口不计算关联、比较、策略或 QA。 */
2402
+ async function recordComparisonBaseline(config, store) {
2403
+ return recordComparisonBaselineFromSnapshot(await readComparisonSnapshot(config), store);
2404
+ }
2405
+ /** 保存已经完成读取和核对的快照,供组合工作流复用同一份新事实。 */
2406
+ async function recordComparisonBaselineFromSnapshot(current, store) {
2407
+ assertCompleteSnapshot(current);
2408
+ const loaded = await store.load();
2409
+ const previous = loaded === void 0 ? void 0 : normalizeLegacyComparisonBaseline(loaded);
2410
+ const baseline = replaceComparisonBaseline({
2411
+ ...previous === void 0 ? {} : { previous },
2412
+ current
2413
+ });
2414
+ if (previous !== void 0 && stableStringify(previous) === stableStringify(baseline)) return {
2415
+ outcome: "unchanged",
2416
+ baseline
2417
+ };
2418
+ await store.save(baseline);
2419
+ return {
2420
+ outcome: "saved",
2421
+ baseline
2422
+ };
2423
+ }
2424
+ /** 验证比较基线数据;兼容读取升级前保存的 v2 快照字段,旧处理基线不会转换为新格式。 */
2425
+ function validateComparisonBaseline(value) {
2426
+ if (!isRecord(value)) throw new ComparisonBaselineFormatError("invalid", "比较基线必须是对象。");
2427
+ if (value.formatVersion !== void 0 || value.entries !== void 0) throw new ComparisonBaselineFormatError("unsupported", "该文件使用旧处理基线格式,不适用于比较基线;请删除旧文件后重新记录。");
2428
+ if (value.format !== COMPARISON_BASELINE_FORMAT) throw new ComparisonBaselineFormatError("unsupported", `不支持比较基线格式:${typeof value.format === "string" ? value.format : "未标识"}。`);
2429
+ assertJsonValue(value, "比较基线");
2430
+ validateSnapshot(normalizeLegacyComparisonBaseline(value).snapshot);
2431
+ }
2432
+ function normalizeLegacyComparisonBaseline(value) {
2433
+ if (!isRecord(value) || !Object.hasOwn(value, "snapshot")) return value;
2434
+ const snapshot = normalizeLegacyComparisonSnapshot(value.snapshot);
2435
+ if (snapshot === value.snapshot) return value;
2436
+ const descriptor = Object.getOwnPropertyDescriptor(value, "snapshot");
2437
+ if (Object.isExtensible(value) && descriptor?.configurable === true && descriptor.writable === true) {
2438
+ value.snapshot = snapshot;
2439
+ return value;
2440
+ }
2441
+ return {
2442
+ ...value,
2443
+ snapshot
2444
+ };
2445
+ }
2446
+ function mergeScopeEntries(previous, current, selectedCurrentIndexes) {
2447
+ const entries = previous.map((value, index) => ({
2448
+ range: value.range,
2449
+ value,
2450
+ origin: "previous",
2451
+ index
2452
+ }));
2453
+ for (const currentIndex of selectedCurrentIndexes) {
2454
+ const value = current[currentIndex];
2455
+ if (value === void 0) continue;
2456
+ const existingIndex = entries.findIndex(({ range }) => isDeepStrictEqual(range, value.range));
2457
+ const entry = {
2458
+ range: value.range,
2459
+ value,
2460
+ origin: "current",
2461
+ index: currentIndex
2462
+ };
2463
+ if (existingIndex === -1) entries.push(entry);
2464
+ else entries[existingIndex] = entry;
2465
+ }
2466
+ return entries;
2467
+ }
2468
+ function selectScopeIndexes(scopes, ranges, description) {
2469
+ assertDistinctRanges(ranges, `${description}替换范围`);
2470
+ return ranges.map((range) => {
2471
+ const index = scopes.findIndex((scope) => isDeepStrictEqual(scope.range, range));
2472
+ if (index === -1) throw new TypeError(`所选${description}范围 ${JSON.stringify(range)} 没有对应的本次读取证据。`);
2473
+ return index;
2474
+ });
2475
+ }
2476
+ function selectTranslationScopeIndexes(reads, ranges) {
2477
+ const indexes = /* @__PURE__ */ new Map();
2478
+ const seen = [];
2479
+ for (const selection of ranges) {
2480
+ assertJsonValue(selection.range, "译文替换范围");
2481
+ if (seen.some(({ language, range }) => language === selection.language && isDeepStrictEqual(range, selection.range))) throw new TypeError(`译文替换范围重复:${selection.language} ${JSON.stringify(selection.range)}。`);
2482
+ seen.push(selection);
2483
+ const readIndex = reads.findIndex(({ language }) => language === selection.language);
2484
+ const scopeIndex = reads[readIndex]?.scopes.findIndex((scope) => isDeepStrictEqual(scope.range, selection.range)) ?? -1;
2485
+ if (readIndex === -1 || scopeIndex === -1) throw new TypeError(`所选译文范围 ${selection.language} ${JSON.stringify(selection.range)} 没有对应的本次读取证据。`);
2486
+ const languageIndexes = indexes.get(selection.language) ?? [];
2487
+ languageIndexes.push(scopeIndex);
2488
+ indexes.set(selection.language, languageIndexes);
2489
+ }
2490
+ return indexes;
2491
+ }
2492
+ function mergeTranslationReads(options) {
2493
+ const previousReads = options.previous?.snapshot.translations.reads ?? [];
2494
+ const currentReads = options.current.translations.reads;
2495
+ const languages = previousReads.map(({ language }) => language);
2496
+ for (const read of currentReads) {
2497
+ if (languages.includes(read.language)) continue;
2498
+ if (options.selection === void 0 || (options.translationRangesByLanguage.get(read.language)?.length ?? 0) > 0) languages.push(read.language);
2499
+ }
2500
+ return languages.flatMap((language) => {
2501
+ const previousRead = previousReads.find((read) => read.language === language);
2502
+ const currentRead = currentReads.find((read) => read.language === language);
2503
+ const selectedIndexes = options.selection === void 0 ? currentRead?.scopes.map((_scope, index) => index) ?? [] : options.translationRangesByLanguage.get(language) ?? [];
2504
+ if (previousRead === void 0 && selectedIndexes.length === 0) return [];
2505
+ const entries = mergeScopeEntries(previousRead?.scopes ?? [], currentRead?.scopes ?? [], selectedIndexes);
2506
+ const error = options.selection === void 0 && currentRead !== void 0 ? currentRead.error : previousRead?.error;
2507
+ return [{
2508
+ language,
2509
+ status: readStatus(entries.map(({ value }) => value), error),
2510
+ scopes: entries.map(({ value }) => ({ ...value })),
2511
+ ...error === void 0 ? {} : { error }
2512
+ }];
2513
+ });
2514
+ }
2515
+ function createTranslations(options) {
2516
+ const reads = [];
2517
+ const records = [];
2518
+ for (const read of options.entries) {
2519
+ const previousRead = options.previous?.snapshot.translations.reads.find((candidate) => candidate.language === read.language);
2520
+ const currentRead = options.current.translations.reads.find((candidate) => candidate.language === read.language);
2521
+ const scopes = [];
2522
+ for (const [scopeIndex, scope] of read.scopes.entries()) {
2523
+ const selected = options.selection.some(({ language, range }) => language === read.language && isDeepStrictEqual(range, scope.range));
2524
+ const originSnapshot = selected ? options.current : options.previous?.snapshot;
2525
+ const originScopeIndex = (selected ? currentRead : previousRead)?.scopes.findIndex((candidate) => isDeepStrictEqual(candidate.range, scope.range)) ?? -1;
2526
+ const scopeRecords = originSnapshot === void 0 || originScopeIndex === -1 ? [] : originSnapshot.translations.records.filter((record) => record.language === read.language && record.scopeIndex === originScopeIndex);
2527
+ const translationIndexes = [];
2528
+ for (const record of scopeRecords) {
2529
+ const index = records.length;
2530
+ translationIndexes.push(index);
2531
+ records.push({
2532
+ ...record,
2533
+ index,
2534
+ scopeIndex
2535
+ });
2536
+ }
2537
+ scopes.push({
2538
+ ...scope,
2539
+ translationIndexes
2540
+ });
2541
+ }
2542
+ reads.push({
2543
+ ...read,
2544
+ scopes
2545
+ });
2546
+ }
2547
+ assertUniqueTranslationIdentities(records);
2548
+ return {
2549
+ reads,
2550
+ records
2551
+ };
2552
+ }
2553
+ function createSourceSnapshot(read, units) {
2554
+ const totalUnitCount = read.status === "complete" ? units.length : null;
2555
+ return {
2556
+ version: hashJson({
2557
+ read,
2558
+ units
2559
+ }),
2560
+ read,
2561
+ totalUnitCount,
2562
+ units
2563
+ };
2564
+ }
2565
+ function createSnapshot(source, translations) {
2566
+ return {
2567
+ version: hashJson({
2568
+ source,
2569
+ translations
2570
+ }),
2571
+ source,
2572
+ translations
2573
+ };
2574
+ }
2575
+ function createSourceRead(scopes, error) {
2576
+ return {
2577
+ status: readStatus(scopes, error),
2578
+ scopes,
2579
+ ...error === void 0 ? {} : { error }
2580
+ };
2581
+ }
2582
+ function assertCompleteSnapshot(snapshot) {
2583
+ if (snapshot.source.read.status !== "complete") throw new ComparisonBaselineIncompleteSnapshotError(`原文读取${statusText(snapshot.source.read.status)},比较基线未保存。`);
2584
+ for (const read of snapshot.translations.reads) if (read.status !== "complete") throw new ComparisonBaselineIncompleteSnapshotError(`目标语言 ${read.language} 读取${statusText(read.status)},比较基线未保存。`, read.language);
2585
+ }
2586
+ function statusText(status) {
2587
+ return {
2588
+ complete: "完整",
2589
+ incomplete: "不完整",
2590
+ failed: "失败",
2591
+ notRead: "未读取"
2592
+ }[status] ?? status;
2593
+ }
2594
+ function assertDistinctRanges(ranges, description) {
2595
+ for (const [index, range] of ranges.entries()) {
2596
+ assertJsonValue(range, description);
2597
+ if (ranges.slice(0, index).some((existing) => isDeepStrictEqual(existing, range))) throw new TypeError(`${description}不能重复:${JSON.stringify(range)}。`);
2598
+ }
2599
+ }
2600
+ function assertUniqueSourceKeys(units) {
2601
+ const keys = /* @__PURE__ */ new Set();
2602
+ for (const { key } of units) {
2603
+ if (keys.has(key)) throw new TypeError(`比较基线中的原文身份重复:${JSON.stringify(key)}。`);
2604
+ keys.add(key);
2605
+ }
2606
+ }
2607
+ function assertUniqueTranslationIdentities(records) {
2608
+ const identities = /* @__PURE__ */ new Set();
2609
+ for (const { identity } of records) {
2610
+ const serialized = JSON.stringify([identity.language, identity.key]);
2611
+ if (identities.has(serialized)) throw new TypeError(`比较基线中的译文身份重复:${serialized}。`);
2612
+ identities.add(serialized);
2613
+ }
2614
+ }
2615
+ function sameSnapshot(previous, current) {
2616
+ const { version: _previousVersion, ...previousSource } = previous.source;
2617
+ const { version: _currentVersion, ...currentSource } = current.source;
2618
+ return stableStringify({
2619
+ source: previousSource,
2620
+ translations: previous.translations
2621
+ }) === stableStringify({
2622
+ source: currentSource,
2623
+ translations: current.translations
2624
+ });
2625
+ }
2626
+ function validateSnapshot(value) {
2627
+ if (!isRecord(value)) invalidBaseline("比较快照必须是对象。");
2628
+ assertJsonValue(value, "比较快照");
2629
+ if (typeof value.version !== "string" || !isRecord(value.source) || !isRecord(value.translations)) invalidBaseline("比较快照缺少版本、原文或译文事实。");
2630
+ const source = value.source;
2631
+ const translations = value.translations;
2632
+ validateSourceSnapshot(source);
2633
+ validateTranslationSnapshot(translations);
2634
+ const expectedStatus = readStatus(source.read.scopes, source.read.error);
2635
+ if (source.read.status !== expectedStatus) invalidBaseline("比较快照的原文读取状态与范围证据不一致。");
2636
+ }
2637
+ function validateSourceSnapshot(value) {
2638
+ if (!isRecord(value) || typeof value.version !== "string") invalidBaseline("原文事实缺少版本。");
2639
+ if (!isRecord(value.read) || !Array.isArray(value.read.scopes)) invalidBaseline("原文事实缺少读取范围。");
2640
+ if (value.read.error !== void 0 && typeof value.read.error !== "string") invalidBaseline("原文读取错误必须是文本。");
2641
+ validateStatus(value.read.status);
2642
+ const scopeCounts = value.read.scopes.map(() => 0);
2643
+ for (const [index, scope] of value.read.scopes.entries()) {
2644
+ if (!isRecord(scope) || !isEnumeration(scope.enumeration) || !Number.isInteger(scope.recordCount) || scope.recordCount < 0 || scope.error !== void 0 && typeof scope.error !== "string") invalidBaseline(`第 ${index + 1} 个原文范围无效。`);
2645
+ assertJsonValue(scope.range, `原文范围 ${index + 1}`);
2646
+ if (value.read.scopes.slice(0, index).some((previous) => isDeepStrictEqual(previous.range, scope.range))) invalidBaseline("原文读取范围身份重复。");
2647
+ }
2648
+ if (!Array.isArray(value.units)) invalidBaseline("原文单元必须是数组。");
2649
+ const keys = /* @__PURE__ */ new Set();
2650
+ for (const [index, unit] of value.units.entries()) {
2651
+ if (!isRecord(unit) || typeof unit.key !== "string" || unit.key.trim().length === 0 || unit.bodyAvailability !== "available" && unit.bodyAvailability !== "unavailable" || !Number.isInteger(unit.scopeIndex) || unit.scopeIndex < 0 || unit.scopeIndex >= value.read.scopes.length) invalidBaseline(`第 ${index + 1} 个原文单元无效。`);
2652
+ if (keys.has(unit.key)) invalidBaseline("原文单元身份重复。");
2653
+ keys.add(unit.key);
2654
+ assertJsonValue(unit.unit, `原文单元 ${index + 1}`);
2655
+ scopeCounts[unit.scopeIndex] = (scopeCounts[unit.scopeIndex] ?? 0) + 1;
2656
+ }
2657
+ for (const [scopeIndex, scope] of value.read.scopes.entries()) if (scope.recordCount !== scopeCounts[scopeIndex]) invalidBaseline("原文范围记录数与事实不一致。");
2658
+ const expectedTotal = value.read.status === "complete" ? value.units.length : null;
2659
+ if (value.totalUnitCount !== expectedTotal) invalidBaseline("原文总数与读取状态不一致。");
2660
+ }
2661
+ function validateTranslationSnapshot(value) {
2662
+ if (!isRecord(value) || !Array.isArray(value.reads) || !Array.isArray(value.records)) invalidBaseline("译文事实必须包含读取结果与实际译文数组。");
2663
+ const languages = /* @__PURE__ */ new Set();
2664
+ const readsByLanguage = /* @__PURE__ */ new Map();
2665
+ for (const [readIndex, read] of value.reads.entries()) {
2666
+ if (!isRecord(read) || typeof read.language !== "string" || !Array.isArray(read.scopes) || read.error !== void 0 && typeof read.error !== "string") invalidBaseline(`第 ${readIndex + 1} 个译文读取结果无效。`);
2667
+ validateStatus(read.status);
2668
+ if (languages.has(read.language)) invalidBaseline("目标语言读取重复。");
2669
+ languages.add(read.language);
2670
+ readsByLanguage.set(read.language, read);
2671
+ for (const [scopeIndex, scope] of read.scopes.entries()) {
2672
+ if (!isRecord(scope) || !Array.isArray(scope.covers) || scope.covers.some((key) => typeof key !== "string") || !Array.isArray(scope.translationIndexes) || !isEnumeration(scope.enumeration) || scope.error !== void 0 && typeof scope.error !== "string") invalidBaseline(`目标语言 ${read.language} 的第 ${scopeIndex + 1} 个范围无效。`);
2673
+ assertJsonValue(scope.range, `目标语言 ${read.language} 的范围 ${scopeIndex + 1}`);
2674
+ if (read.scopes.slice(0, scopeIndex).some((previous) => isDeepStrictEqual(previous.range, scope.range))) invalidBaseline(`目标语言 ${read.language} 的读取范围身份重复。`);
2675
+ }
2676
+ if (read.status !== readStatus(read.scopes, read.error)) invalidBaseline(`目标语言 ${read.language} 的读取状态与范围证据不一致。`);
2677
+ }
2678
+ const translationIndexesByScope = /* @__PURE__ */ new Map();
2679
+ const identities = /* @__PURE__ */ new Set();
2680
+ for (const [index, record] of value.records.entries()) {
2681
+ if (!isRecord(record) || record.index !== index || typeof record.language !== "string" || !isRecord(record.identity) || record.identity.language !== record.language || Object.keys(record.identity).length !== 2 || typeof record.identity.key !== "string" || record.identity.key.trim().length === 0 || !Number.isInteger(record.scopeIndex) || record.bodyAvailability !== "available" && record.bodyAvailability !== "unavailable") invalidBaseline(`第 ${index + 1} 条实际译文无效。`);
2682
+ const identityKey = JSON.stringify([record.identity.language, record.identity.key]);
2683
+ if (identities.has(identityKey)) invalidBaseline("实际译文身份重复。");
2684
+ identities.add(identityKey);
2685
+ const read = readsByLanguage.get(record.language);
2686
+ const scope = read?.scopes[record.scopeIndex];
2687
+ if (read === void 0 || scope === void 0) invalidBaseline("实际译文引用了不存在的语言或读取范围。");
2688
+ if (!isDeepStrictEqual(scope.range, record.range)) invalidBaseline("实际译文的范围与读取证据不一致。");
2689
+ if (record.bodyAvailability === "available") {
2690
+ if (!Object.hasOwn(record, "content")) invalidBaseline("正文可用的实际译文必须包含正文。");
2691
+ assertJsonValue(record.content, `实际译文 ${index + 1} 正文`);
2692
+ } else if (Object.hasOwn(record, "content")) invalidBaseline("正文不可用的实际译文不能包含正文。");
2693
+ assertJsonValue(record.record, `实际译文 ${index + 1}`);
2694
+ const scopeKey = JSON.stringify([record.language, record.scopeIndex]);
2695
+ const scopeIndexes = translationIndexesByScope.get(scopeKey) ?? [];
2696
+ scopeIndexes.push(index);
2697
+ translationIndexesByScope.set(scopeKey, scopeIndexes);
2698
+ }
2699
+ for (const read of value.reads) for (const [scopeIndex, scope] of read.scopes.entries()) {
2700
+ const expectedIndexes = translationIndexesByScope.get(JSON.stringify([read.language, scopeIndex])) ?? [];
2701
+ if (!isDeepStrictEqual(scope.translationIndexes, expectedIndexes)) invalidBaseline("译文读取范围中的索引与实际记录不一致。");
2702
+ }
2703
+ }
2704
+ function validateStatus(value) {
2705
+ if (value !== "complete" && value !== "incomplete" && value !== "failed" && value !== "notRead") invalidBaseline("读取状态无效。");
2706
+ }
2707
+ function isEnumeration(value) {
2708
+ return value === "complete" || value === "partial" || value === "failed";
2709
+ }
2710
+ function invalidBaseline(message) {
2711
+ throw new ComparisonBaselineFormatError("invalid", message);
2712
+ }
2713
+ function hashJson(value) {
2714
+ const serialized = JSON.stringify(value);
2715
+ if (serialized === void 0) throw new TypeError("比较基线及事实必须可序列化为 JSON。");
2716
+ return `sha256:${createHash("sha256").update(serialized).digest("hex")}`;
2717
+ }
2718
+ // ../../packages/core/dist/plans.js
2719
+ const UPDATE_PLAN_FORMAT = "lioni.update-plan/v2";
2720
+ /**
2721
+ * 纯业务规划入口。比较结果、两侧快照与关联均为显式输入;策略只调用一次,
2722
+ * 计划可 JSON 序列化后交给另一阶段消费。
2723
+ */
2724
+ async function createUpdatePlan(options) {
2725
+ const current = snapshotOf(options.current);
2726
+ const compareInput = {
2727
+ previous: options.previous,
2728
+ current
2729
+ };
2730
+ validateComparisonInput(compareInput);
2731
+ validateComparisonResult(compareInput, options.comparisons);
2732
+ assertUpdatePlanAssociations(options.associations);
2733
+ if (options.createPlaceholderContent !== void 0 && typeof options.createPlaceholderContent !== "function") throw new TypeError("createPlaceholderContent 必须是同步的原文正文到目标正文函数。");
2734
+ if (options.updatePolicy !== void 0 && typeof options.updatePolicy !== "function") throw new TypeError("updatePolicy 必须是集合更新策略函数。");
2735
+ const items = await (options.updatePolicy ?? defaultUpdatePolicy)(options);
2736
+ assertUpdatePlanItems(items);
2737
+ const plan = snapshotJsonValue({
2738
+ format: UPDATE_PLAN_FORMAT,
2739
+ ...options.previous === void 0 ? {} : { previous: options.previous },
2740
+ current,
2741
+ comparisons: options.comparisons,
2742
+ associations: options.associations,
2743
+ items
2744
+ }, "更新计划", { omitUndefinedObjectProperties: true });
2745
+ validateUpdatePlan(plan);
2746
+ return plan;
2747
+ }
2748
+ /** 默认策略保留现有译文;仅为完整读取的缺译补占位,并删除有历史依据的未改目标。 */
2749
+ async function defaultUpdatePolicy(input) {
2750
+ const items = [];
2751
+ const current = input.current;
2752
+ const sourceChanges = new Map(input.comparisons.sourceChanges.map((change) => [change.key, change]));
2753
+ const translationChanges = new Map(input.comparisons.translationChanges.map((change) => [identityKey(change.identity), change]));
2754
+ for (const sourceUnit of current.source.units) for (const languageRead of current.translations.reads) {
2755
+ const association = input.associations.current.find((entry) => entry.sourceKey === sourceUnit.key && entry.language === languageRead.language);
2756
+ const associated = association === void 0 ? [] : association.translationIndexes.flatMap((index) => {
2757
+ const record = current.translations.records[index];
2758
+ return record === void 0 ? [] : [record];
2759
+ });
2760
+ const changes = sourceDecisionChanges(sourceChanges.get(sourceUnit.key), associated.map((record) => translationChanges.get(identityKey(record.identity))));
2761
+ const base = {
2762
+ sourceKey: sourceUnit.key,
2763
+ language: languageRead.language,
2764
+ changes
2765
+ };
2766
+ if (association === void 0) {
2767
+ items.push({
2768
+ ...base,
2769
+ action: "review",
2770
+ reason: "本次没有对应的源译关联依据,请复核目标范围。"
2771
+ });
2772
+ continue;
2773
+ }
2774
+ if (association.status === "matched") {
2775
+ const target = associated[0];
2776
+ if (target === void 0) {
2777
+ items.push({
2778
+ ...base,
2779
+ action: "review",
2780
+ reason: "关联结果缺少对应译文事实,请复核当前读取。"
2781
+ });
2782
+ continue;
2783
+ }
2784
+ if (changes.source?.status === "modified") {
2785
+ if (target.bodyAvailability !== "available") {
2786
+ items.push({
2787
+ ...base,
2788
+ action: "blocked",
2789
+ target: target.identity,
2790
+ reason: "目标译文正文不可用,无法安全重置为待译占位。"
2791
+ });
2792
+ continue;
2793
+ }
2794
+ if (sourceUnit.bodyAvailability !== "available") {
2795
+ items.push({
2796
+ ...base,
2797
+ action: "blocked",
2798
+ target: target.identity,
2799
+ reason: "当前原文正文不可用,无法生成待译占位。"
2800
+ });
2801
+ continue;
2802
+ }
2803
+ const sourceRange = current.source.read.scopes[sourceUnit.scopeIndex]?.range;
2804
+ if (sourceRange === void 0) {
2805
+ items.push({
2806
+ ...base,
2807
+ action: "blocked",
2808
+ target: target.identity,
2809
+ reason: "原文读取事实缺少可验证的范围,无法保留写入依据。"
2810
+ });
2811
+ continue;
2812
+ }
2813
+ let content;
2814
+ try {
2815
+ content = await placeholderContent(input, sourceUnit.unit.source);
2816
+ } catch {
2817
+ items.push({
2818
+ ...base,
2819
+ action: "blocked",
2820
+ target: target.identity,
2821
+ reason: "生成待译占位失败或未通过目标正文校验,未写入。"
2822
+ });
2823
+ continue;
2824
+ }
2825
+ const request = {
2826
+ operation: "write",
2827
+ target: { identity: target.identity },
2828
+ content,
2829
+ expectedSource: {
2830
+ presence: "present",
2831
+ key: sourceUnit.key,
2832
+ unit: sourceUnit.unit,
2833
+ content: sourceUnit.unit.source,
2834
+ range: sourceRange
2835
+ },
2836
+ expectedTarget: {
2837
+ status: "present",
2838
+ identity: target.identity,
2839
+ content: target.content,
2840
+ range: target.range,
2841
+ record: target.record
2842
+ }
2843
+ };
2844
+ items.push({
2845
+ ...base,
2846
+ action: "write",
2847
+ target: target.identity,
2848
+ after: { content },
2849
+ request,
2850
+ reason: "原文已变化;使用当前原文生成待译占位并重置现有译文。"
2851
+ });
2852
+ continue;
2853
+ }
2854
+ items.push({
2855
+ ...base,
2856
+ action: "retain",
2857
+ target: target.identity,
2858
+ reason: "保留已存在的译文。"
2859
+ });
2860
+ continue;
2861
+ }
2862
+ if (association.status === "missing") {
2863
+ if (sourceUnit.bodyAvailability !== "available") {
2864
+ items.push({
2865
+ ...base,
2866
+ action: "blocked",
2867
+ reason: "原文正文不可用,无法生成待译占位。"
2868
+ });
2869
+ continue;
2870
+ }
2871
+ let content;
2872
+ try {
2873
+ content = await placeholderContent(input, sourceUnit.unit.source);
2874
+ } catch {
2875
+ items.push({
2876
+ ...base,
2877
+ action: "blocked",
2878
+ reason: "生成待译占位失败或未通过目标正文校验,未写入。"
2879
+ });
2880
+ continue;
2881
+ }
2882
+ const range = current.source.read.scopes[sourceUnit.scopeIndex]?.range;
2883
+ if (range === void 0) {
2884
+ items.push({
2885
+ ...base,
2886
+ action: "blocked",
2887
+ reason: "原文读取事实缺少可验证的范围,无法保留写入依据。"
2888
+ });
2889
+ continue;
2890
+ }
2891
+ const request = {
2892
+ operation: "write",
2893
+ target: {
2894
+ sourceKey: sourceUnit.key,
2895
+ language: languageRead.language
2896
+ },
2897
+ content,
2898
+ expectedSource: {
2899
+ presence: "present",
2900
+ key: sourceUnit.key,
2901
+ unit: sourceUnit.unit,
2902
+ content: sourceUnit.unit.source,
2903
+ range
2904
+ },
2905
+ expectedTarget: { status: "missing" }
2906
+ };
2907
+ items.push({
2908
+ ...base,
2909
+ action: "write",
2910
+ after: { content },
2911
+ request,
2912
+ reason: "目标范围已完整读取且没有对应译文;使用当前原文生成待译占位。"
2913
+ });
2914
+ continue;
2915
+ }
2916
+ items.push({
2917
+ ...base,
2918
+ action: association.status === "unavailable" ? "blocked" : "review",
2919
+ ...associated.length === 1 ? { target: associated[0].identity } : {},
2920
+ reason: association.status === "unavailable" ? "译文正文不可用;保留目标并阻止自动修改。" : "目标读取依据不完整;不判断为缺译或已处理。"
2921
+ });
2922
+ }
2923
+ const associatedTargets = new Set(input.associations.current.flatMap(({ translationIndexes }) => translationIndexes));
2924
+ for (const translation of current.translations.records) {
2925
+ if (associatedTargets.has(translation.index)) continue;
2926
+ const change = translationChanges.get(identityKey(translation.identity));
2927
+ const previousRecord = input.previous?.translations.records.find(({ identity }) => sameIdentity(identity, translation.identity));
2928
+ const previousAssociation = previousRecord === void 0 ? void 0 : input.associations.previous.find((association) => association.translationIndexes.includes(previousRecord.index));
2929
+ const sourceChange = previousAssociation === void 0 ? void 0 : sourceChanges.get(previousAssociation.sourceKey);
2930
+ const source = sourceChange?.previous?.key === previousAssociation?.sourceKey ? sourceChange?.previous : void 0;
2931
+ const changes = sourceDecisionChanges(source === void 0 ? void 0 : sourceChange, change === void 0 ? [] : [change]);
2932
+ const base = {
2933
+ language: translation.language,
2934
+ target: translation.identity,
2935
+ changes
2936
+ };
2937
+ const removedSource = source !== void 0 && previousAssociation?.status === "matched" ? {
2938
+ source,
2939
+ sourceChange
2940
+ } : void 0;
2941
+ if (removedSource?.sourceChange?.status === "removed") {
2942
+ const read = current.translations.reads.find(({ language }) => language === translation.language);
2943
+ const scope = read?.scopes[translation.scopeIndex];
2944
+ if (read?.status !== "complete" || scope?.enumeration !== "complete" || translation.bodyAvailability !== "available") {
2945
+ items.push({
2946
+ ...base,
2947
+ action: "review",
2948
+ reason: "原文移除已确认,但当前目标的正文或完整读取依据不足;保留并复核。"
2949
+ });
2950
+ continue;
2951
+ }
2952
+ if (change?.status === "unchanged") {
2953
+ const previousRange = input.previous?.source.read.scopes[removedSource.source.scopeIndex]?.range;
2954
+ const sourceRange = previousRange === void 0 ? void 0 : sourceRangeForRemoved(previousRange, current);
2955
+ if (sourceRange === void 0) {
2956
+ items.push({
2957
+ ...base,
2958
+ action: "review",
2959
+ reason: "未能确认原文移除对应的完整当前范围;保留目标并复核。"
2960
+ });
2961
+ continue;
2962
+ }
2963
+ items.push({
2964
+ ...base,
2965
+ action: "delete",
2966
+ request: {
2967
+ operation: "delete",
2968
+ target: { identity: translation.identity },
2969
+ expectedSource: {
2970
+ presence: "absent",
2971
+ key: removedSource.source.key,
2972
+ range: sourceRange
2973
+ },
2974
+ expectedTarget: {
2975
+ status: "present",
2976
+ identity: translation.identity,
2977
+ content: translation.content,
2978
+ range: translation.range,
2979
+ record: translation.record
2980
+ }
2981
+ },
2982
+ reason: "该译文明确关联的历史原文已从完整范围移除,目标正文未变化;可删除。"
2983
+ });
2984
+ continue;
2985
+ }
2986
+ items.push({
2987
+ ...base,
2988
+ action: "retain",
2989
+ reason: translation.bodyAvailability === "available" && change?.status === "modified" ? "历史原文已移除,但目标正文此后发生变化;保留人工修改。" : "历史原文已移除,但缺少确认目标未变化的历史依据;保留目标。"
2990
+ });
2991
+ continue;
2992
+ }
2993
+ if (previousAssociation === void 0) {
2994
+ items.push({
2995
+ ...base,
2996
+ action: "retain",
2997
+ reason: "没有充分的历史原文关联依据;保留目标独有项。"
2998
+ });
2999
+ continue;
3000
+ }
3001
+ items.push({
3002
+ ...base,
3003
+ action: "review",
3004
+ reason: "历史原文尚未被充分确认移除;保留目标并复核当前证据。"
3005
+ });
3006
+ }
3007
+ return items;
3008
+ }
3009
+ async function placeholderContent(input, source) {
3010
+ const candidate = input.createPlaceholderContent === void 0 ? source : input.createPlaceholderContent(source);
3011
+ const content = input.contentSchema === void 0 ? candidate : await validateWithStandardSchema(input.contentSchema, candidate, "更新占位正文", {
3012
+ preserveValue: true,
3013
+ requireJson: true
3014
+ });
3015
+ assertJsonValue(content, "更新占位正文");
3016
+ return content;
3017
+ }
3018
+ /**
3019
+ * 读取当前事实、选用配置比较器并生成业务计划;不写资源或推进基线。
3020
+ * 显式选择语言时,历史事实、比较器和策略均限定在该范围,策略不得扩大范围。
3021
+ */
3022
+ async function previewUpdate(config, store, options = {}) {
3023
+ validateFrameworkConfig(config);
3024
+ const languages = resolveLanguageSelection(config.translations?.languages ?? [], options);
3025
+ if (config.updatePolicy !== void 0 && typeof config.updatePolicy !== "function") throw new TypeError("defineConfig 的 updatePolicy 必须是集合更新策略函数。");
3026
+ if (config.createPlaceholderContent !== void 0 && typeof config.createPlaceholderContent !== "function") throw new TypeError("defineConfig 的 createPlaceholderContent 必须是同步填充函数。");
3027
+ const baseline = await store?.load();
3028
+ if (baseline !== void 0) validateComparisonBaseline(baseline);
3029
+ const previousSnapshot = baseline === void 0 ? void 0 : normalizeLegacyComparisonSnapshot(baseline.snapshot);
3030
+ const current = await readProjectSnapshot(config, options);
3031
+ const previous = previousSnapshot === void 0 ? void 0 : options.languages === void 0 ? previousSnapshot : selectSnapshotLanguages(previousSnapshot, languages);
3032
+ const comparisons = await compareSnapshots({
3033
+ previous,
3034
+ current: snapshotOf(current)
3035
+ }, config.compare);
3036
+ const associations = {
3037
+ previous: previous === void 0 ? [] : associateSnapshot(previous),
3038
+ current: current.associations
3039
+ };
3040
+ const plan = await createUpdatePlan({
3041
+ ...previous === void 0 ? {} : { previous },
3042
+ current,
3043
+ comparisons,
3044
+ associations,
3045
+ ...config.createPlaceholderContent === void 0 ? {} : { createPlaceholderContent: config.createPlaceholderContent },
3046
+ ...config.translations === void 0 ? {} : { contentSchema: config.translations.contentSchema },
3047
+ ...config.updatePolicy === void 0 ? {} : { updatePolicy: config.updatePolicy }
3048
+ });
3049
+ if (options.languages !== void 0) assertUpdatePlanLanguages(plan, languages);
3050
+ return plan;
3051
+ }
3052
+ function selectSnapshotLanguages(snapshot, languages) {
3053
+ const indexes = /* @__PURE__ */ new Map();
3054
+ const records = snapshot.translations.records.filter(({ language }) => languages.includes(language)).map((record, index) => {
3055
+ indexes.set(record.index, index);
3056
+ return {
3057
+ ...record,
3058
+ index
3059
+ };
3060
+ });
3061
+ const reads = snapshot.translations.reads.filter(({ language }) => languages.includes(language)).map((read) => ({
3062
+ ...read,
3063
+ scopes: read.scopes.map((scope) => ({
3064
+ ...scope,
3065
+ translationIndexes: scope.translationIndexes.map((index) => {
3066
+ const selectedIndex = indexes.get(index);
3067
+ if (selectedIndex === void 0) throw new TypeError("比较基线的译文范围引用了其他语言的记录。");
3068
+ return selectedIndex;
3069
+ })
3070
+ }))
3071
+ }));
3072
+ const selected = {
3073
+ source: snapshot.source,
3074
+ translations: {
3075
+ reads,
3076
+ records
3077
+ }
3078
+ };
3079
+ return {
3080
+ version: `sha256:${createHash("sha256").update(JSON.stringify(selected)).digest("hex")}`,
3081
+ ...selected
3082
+ };
3083
+ }
3084
+ /** 显式选择语言时,策略和保存的计划都不能扩大执行范围。 */
3085
+ function assertUpdatePlanLanguages(plan, languages) {
3086
+ for (const item of plan.items) {
3087
+ const referenced = [
3088
+ item.language,
3089
+ ...item.target === void 0 ? [] : [item.target.language],
3090
+ ...item.changes.translations.flatMap((change) => [
3091
+ change.identity.language,
3092
+ ...change.previous === void 0 ? [] : [change.previous.language, change.previous.identity.language],
3093
+ ...change.current === void 0 ? [] : [change.current.language, change.current.identity.language]
3094
+ ])
3095
+ ];
3096
+ if (item.request !== void 0) {
3097
+ const request = item.request;
3098
+ referenced.push("identity" in request.target ? request.target.identity.language : request.target.language);
3099
+ if (request.expectedTarget.status === "present") referenced.push(request.expectedTarget.identity.language);
3100
+ }
3101
+ for (const language of referenced) if (!languages.includes(language)) throw new TypeError(`更新计划引用了本次未选择的目标语言 ${JSON.stringify(language)}。`);
3102
+ }
3103
+ }
3104
+ /** 验证保存后的 JSON 计划;兼容读取升级前 v2 译文字段,不会重新比较、关联或调用策略。 */
3105
+ function validateUpdatePlan(value) {
3106
+ assertJsonValue(value, "更新计划");
3107
+ if (!isRecord(value) || value.format !== UPDATE_PLAN_FORMAT || !isPlanAssociations(value.associations) || !Array.isArray(value.items) || value.items.some((item) => !isPlanItem(item))) invalidPlan("格式无效或包含不完整的业务决定。");
3108
+ const normalized = normalizeLegacyUpdatePlan(value);
3109
+ const comparisonInput = {
3110
+ previous: normalized.previous,
3111
+ current: normalized.current
3112
+ };
3113
+ validateComparisonInput(comparisonInput);
3114
+ validateComparisonResult(comparisonInput, normalized.comparisons);
3115
+ const associations = normalized.associations;
3116
+ assertAssociationKeys(associations.previous, comparisonInput.previous);
3117
+ assertAssociationKeys(associations.current, comparisonInput.current);
3118
+ }
3119
+ /**
3120
+ * 将升级前 v2 更新计划中的旧译文字段 `translation` 无损归一化为 `record`。
3121
+ * 覆盖快照记录、顶层比较变化以及逐项决定内的译文变化。
3122
+ */
3123
+ function normalizeLegacyUpdatePlan(value) {
3124
+ if (!isRecord(value)) return value;
3125
+ const previous = Object.hasOwn(value, "previous") ? normalizeLegacyComparisonSnapshot(value.previous) : value.previous;
3126
+ const current = normalizeLegacyComparisonSnapshot(value.current);
3127
+ const comparisons = normalizeLegacyPlanComparisons(value.comparisons);
3128
+ const items = mapNormalizedArray(value.items, normalizeLegacyPlanItem);
3129
+ let next = value;
3130
+ if (Object.hasOwn(value, "previous")) next = updateRecordProperty(next, "previous", previous);
3131
+ next = updateRecordProperty(next, "current", current);
3132
+ next = updateRecordProperty(next, "comparisons", comparisons);
3133
+ next = updateRecordProperty(next, "items", items);
3134
+ return next;
3135
+ }
3136
+ function normalizeLegacyPlanComparisons(value) {
3137
+ if (!isRecord(value)) return value;
3138
+ return updateRecordProperty(value, "translationChanges", mapNormalizedArray(value.translationChanges, normalizeLegacyTranslationChange));
3139
+ }
3140
+ function normalizeLegacyPlanItem(value) {
3141
+ if (!isRecord(value) || !isRecord(value.changes)) return value;
3142
+ const translations = mapNormalizedArray(value.changes.translations, normalizeLegacyTranslationChange);
3143
+ return updateRecordProperty(value, "changes", updateRecordProperty(value.changes, "translations", translations));
3144
+ }
3145
+ function normalizeLegacyTranslationChange(value) {
3146
+ if (!isRecord(value)) return value;
3147
+ let next = value;
3148
+ if (Object.hasOwn(value, "previous")) next = updateRecordProperty(next, "previous", normalizeLegacyTranslationRecord(value.previous));
3149
+ if (Object.hasOwn(value, "current")) next = updateRecordProperty(next, "current", normalizeLegacyTranslationRecord(value.current));
3150
+ return next;
3151
+ }
3152
+ function mapNormalizedArray(value, normalizeItem) {
3153
+ if (!Array.isArray(value)) return value;
3154
+ let changed = false;
3155
+ const mapped = value.map((item) => {
3156
+ const normalized = normalizeItem(item);
3157
+ if (normalized !== item) changed = true;
3158
+ return normalized;
3159
+ });
3160
+ return changed ? mapped : value;
3161
+ }
3162
+ function updateRecordProperty(target, key, nextValue) {
3163
+ if (target[key] === nextValue) return target;
3164
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
3165
+ if (Object.isExtensible(target) && descriptor?.configurable === true && descriptor.writable === true) {
3166
+ target[key] = nextValue;
3167
+ return target;
3168
+ }
3169
+ return {
3170
+ ...target,
3171
+ [key]: nextValue
3172
+ };
3173
+ }
3174
+ /** 保存计划中的关联必须仍指向同一消息键,不接受自定义交叉配对。 */
3175
+ function assertAssociationKeys(associations, snapshot) {
3176
+ const sourceKeys = new Set(snapshot?.source.units.map(({ key }) => key));
3177
+ for (const association of associations) {
3178
+ if (!sourceKeys.has(association.sourceKey)) invalidPlan("源译关联引用了不存在的原文键。");
3179
+ for (const index of association.translationIndexes) {
3180
+ const record = snapshot?.translations.records[index];
3181
+ if (record?.identity.language !== association.language || record.identity.key !== association.sourceKey) invalidPlan("原文与译文必须按语言和消息键唯一对应。");
3182
+ }
3183
+ }
3184
+ }
3185
+ function snapshotOf(snapshot) {
3186
+ return {
3187
+ version: snapshot.version,
3188
+ source: snapshot.source,
3189
+ translations: snapshot.translations
3190
+ };
3191
+ }
3192
+ function sourceDecisionChanges(source, translations) {
3193
+ return {
3194
+ ...source === void 0 ? {} : { source: {
3195
+ key: source.key,
3196
+ status: source.status,
3197
+ ...source.previous === void 0 ? {} : { previous: source.previous },
3198
+ ...source.current === void 0 ? {} : { current: source.current }
3199
+ } },
3200
+ translations: translations.flatMap((change) => change === void 0 ? [] : [{
3201
+ identity: change.identity,
3202
+ status: change.status,
3203
+ ...change.previous === void 0 ? {} : { previous: change.previous },
3204
+ ...change.current === void 0 ? {} : { current: change.current }
3205
+ }])
3206
+ };
3207
+ }
3208
+ function sourceRangeForRemoved(previousRange, current) {
3209
+ return current.source.read.scopes.find(({ range: currentRange, enumeration }) => enumeration === "complete" && isDeepStrictEqual(currentRange, previousRange))?.range;
3210
+ }
3211
+ function identityKey(identity) {
3212
+ return JSON.stringify([identity.language, identity.key]);
3213
+ }
3214
+ function sameIdentity(left, right) {
3215
+ return identityKey(left) === identityKey(right);
3216
+ }
3217
+ function isPlanAssociations(value) {
3218
+ return isRecord(value) && Array.isArray(value.previous) && value.previous.every(isAssociation) && Array.isArray(value.current) && value.current.every(isAssociation) && hasUniqueAssociations(value.previous) && hasUniqueAssociations(value.current);
3219
+ }
3220
+ function hasUniqueAssociations(associations) {
3221
+ const subjects = /* @__PURE__ */ new Set();
3222
+ const targets = /* @__PURE__ */ new Set();
3223
+ for (const association of associations) {
3224
+ const subject = JSON.stringify([association.language, association.sourceKey]);
3225
+ if (subjects.has(subject)) return false;
3226
+ subjects.add(subject);
3227
+ for (const index of association.translationIndexes) {
3228
+ if (targets.has(index)) return false;
3229
+ targets.add(index);
3230
+ }
3231
+ }
3232
+ return true;
3233
+ }
3234
+ function assertUpdatePlanAssociations(value) {
3235
+ assertJsonValue(value, "更新计划中的关联事实");
3236
+ if (!isPlanAssociations(value)) throw new TypeError("更新计划中的关联事实必须按语言和消息键唯一对应。");
3237
+ }
3238
+ function assertUpdatePlanItems(value) {
3239
+ if (!Array.isArray(value)) {
3240
+ assertJsonValue(value, "更新计划中的更新决定");
3241
+ return;
3242
+ }
3243
+ assertJsonValue(value.map((item) => {
3244
+ if (!isRecord(item) || !isRecord(item.changes)) return item;
3245
+ const { source, translations, ...changes } = item.changes;
3246
+ return {
3247
+ ...item,
3248
+ changes: {
3249
+ ...changes,
3250
+ ...source === void 0 ? {} : { source: withoutUndefinedComparisonSides(source) },
3251
+ ...translations === void 0 ? {} : { translations: Array.isArray(translations) ? translations.map(withoutUndefinedComparisonSides) : translations }
3252
+ }
3253
+ };
3254
+ }), "更新计划中的更新决定");
3255
+ }
3256
+ function withoutUndefinedComparisonSides(value) {
3257
+ if (!isRecord(value)) return value;
3258
+ const { previous, current, ...change } = value;
3259
+ return {
3260
+ ...change,
3261
+ ...previous === void 0 ? {} : { previous },
3262
+ ...current === void 0 ? {} : { current }
3263
+ };
3264
+ }
3265
+ function isPlanItem(value) {
3266
+ if (!isRecord(value) || !isPlanAction(value.action) || typeof value.language !== "string" || typeof value.reason !== "string" || !isRecord(value.changes) || value.sourceKey !== void 0 && typeof value.sourceKey !== "string" || value.target !== void 0 && !isIdentity(value.target) || value.changes.source !== void 0 && (!isRecord(value.changes.source) || typeof value.changes.source.key !== "string" || !isComparisonStatus(value.changes.source.status)) || !Array.isArray(value.changes.translations) || !value.changes.translations.every((change) => isRecord(change) && isIdentity(change.identity) && isComparisonStatus(change.status)) || value.after !== void 0 && !isRecord(value.after)) return false;
3267
+ if (value.action === "write") return isWriteRequest(value.request) && value.request.operation === "write" && isRecord(value.after) && Object.hasOwn(value.after, "content") && isDeepStrictEqual(value.after.content, value.request.content);
3268
+ if (value.action === "delete") return isDeleteRequest(value.request) && value.request.operation === "delete";
3269
+ return value.request === void 0 && value.after === void 0;
3270
+ }
3271
+ function isWriteRequest(value) {
3272
+ if (!isRecord(value) || value.operation !== "write" || !isRecord(value.target) || Object.hasOwn(value, "content") === false || !isTargetExpectation(value.expectedTarget) || value.expectedSource !== void 0 && !isSourceExpectation(value.expectedSource)) return false;
3273
+ if (typeof value.target.sourceKey === "string" && typeof value.target.language === "string") return value.expectedTarget.status === "missing";
3274
+ return isIdentity(value.target.identity) && value.expectedTarget.status === "present" && sameIdentity(value.target.identity, value.expectedTarget.identity);
3275
+ }
3276
+ function isDeleteRequest(value) {
3277
+ return isRecord(value) && value.operation === "delete" && isRecord(value.target) && isIdentity(value.target.identity) && isRecord(value.expectedTarget) && value.expectedTarget.status === "present" && isIdentity(value.expectedTarget.identity) && sameIdentity(value.target.identity, value.expectedTarget.identity) && (value.expectedSource === void 0 || isSourceExpectation(value.expectedSource));
3278
+ }
3279
+ function isSourceExpectation(value) {
3280
+ return isRecord(value) && (value.presence === "present" ? typeof value.key === "string" && Object.hasOwn(value, "unit") && Object.hasOwn(value, "content") && Object.hasOwn(value, "range") : value.presence === "absent" && typeof value.key === "string" && Object.hasOwn(value, "range"));
3281
+ }
3282
+ function isTargetExpectation(value) {
3283
+ return isRecord(value) && (value.status === "missing" || value.status === "present" && isIdentity(value.identity) && Object.hasOwn(value, "content") && (!Object.hasOwn(value, "range") || value.range !== void 0) && (!Object.hasOwn(value, "record") || value.record !== void 0));
3284
+ }
3285
+ function isAssociation(value) {
3286
+ return isRecord(value) && typeof value.sourceKey === "string" && typeof value.language === "string" && [
3287
+ "matched",
3288
+ "missing",
3289
+ "unavailable",
3290
+ "unknown"
3291
+ ].includes(String(value.status)) && [
3292
+ "complete",
3293
+ "incomplete",
3294
+ "failed",
3295
+ "notRead"
3296
+ ].includes(String(value.coverageStatus)) && Array.isArray(value.scopeIndexes) && value.scopeIndexes.every((index) => Number.isInteger(index)) && Array.isArray(value.translationIndexes) && value.translationIndexes.length <= 1 && value.translationIndexes.every((index) => Number.isInteger(index));
3297
+ }
3298
+ function isIdentity(value) {
3299
+ return isRecord(value) && typeof value.language === "string" && typeof value.key === "string";
3300
+ }
3301
+ function isPlanAction(value) {
3302
+ return [
3303
+ "write",
3304
+ "delete",
3305
+ "retain",
3306
+ "review",
3307
+ "blocked"
3308
+ ].includes(String(value));
3309
+ }
3310
+ function isComparisonStatus(value) {
3311
+ return [
3312
+ "historyMissing",
3313
+ "historyInsufficient",
3314
+ "currentInsufficient",
3315
+ "bothInsufficient",
3316
+ "added",
3317
+ "removed",
3318
+ "modified",
3319
+ "unchanged"
3320
+ ].includes(String(value));
3321
+ }
3322
+ function invalidPlan(message) {
3323
+ throw new TypeError(`更新计划无效:${message}`);
3324
+ }
3325
+ // ../../packages/core/dist/apply-plans.js
3326
+ /**
3327
+ * 直接消费已保存的决定;不读取基线、不比较、不运行策略。
3328
+ * 显式选择语言时,越界计划整批拒绝;写入前后的复查也限定在所选语言。
3329
+ */
3330
+ async function applyUpdatePlan(plan, config, condition, options = {}) {
3331
+ const languages = resolveLanguageSelection(config.translations?.languages ?? [], options);
3332
+ validateUpdatePlan(plan);
3333
+ const validatedPlan = normalizeLegacyUpdatePlan(plan);
3334
+ if (options.languages !== void 0) assertUpdatePlanLanguages(validatedPlan, languages);
3335
+ const requests = [];
3336
+ const requestIndexes = [];
3337
+ for (const [index, item] of validatedPlan.items.entries()) if (item.action === "write" || item.action === "delete") {
3338
+ if (item.request === void 0) throw new TypeError(`更新计划第 ${index + 1} 项缺少写入请求。`);
3339
+ if (item.request.operation !== item.action) throw new TypeError(`更新计划第 ${index + 1} 项的操作与请求不匹配。`);
3340
+ requests.push(item);
3341
+ requestIndexes.push(index);
3342
+ } else if (item.request !== void 0) throw new TypeError(`更新计划第 ${index + 1} 项不应包含写入请求。`);
3343
+ const writes = requests.length === 0 ? { results: [] } : await writeTranslationRequests(requests.map(({ request }) => {
3344
+ if (request === void 0) throw new TypeError("更新计划写入项缺少请求。");
3345
+ return request;
3346
+ }), config, condition, options);
3347
+ const batchFailed = Object.hasOwn(writes, "batchError");
3348
+ const batchError = "batchError" in writes ? writes.batchError : void 0;
3349
+ const writesByPlanIndex = new Map(requestIndexes.map((planIndex, writeIndex) => [planIndex, writes.results[writeIndex]]));
3350
+ const results = validatedPlan.items.map((item, index) => {
3351
+ if (item.action === "write" || item.action === "delete") {
3352
+ const writeResult = writesByPlanIndex.get(index);
3353
+ if (writeResult === void 0) throw new TypeError(`更新计划第 ${index + 1} 项缺少写入结果。`);
3354
+ return {
3355
+ index,
3356
+ action: item.action,
3357
+ status: writeResult.status,
3358
+ ...writeResult.reason === void 0 ? {} : { reason: writeResult.reason },
3359
+ request: writeResult.request
3360
+ };
3361
+ }
3362
+ const status = item.action === "retain" ? "retained" : item.action;
3363
+ return {
3364
+ index,
3365
+ action: item.action,
3366
+ status,
3367
+ reason: item.reason
3368
+ };
3369
+ });
3370
+ return {
3371
+ status: batchFailed || results.some(({ status }) => status === "conflict" || status === "notWritable" || status === "writeFailed" || status === "writeUnconfirmed") ? "failed" : "completed",
3372
+ results,
3373
+ ...batchFailed ? { batchError } : {}
3374
+ };
3375
+ }
3376
+ /**
3377
+ * 正式更新入口默认只规划并执行资源修改;recordBaseline 显式组合全语言完整更新与基线记录。
3378
+ * options.condition 可为每次写入追加业务条件。
3379
+ */
3380
+ async function update(config, store, options = {}) {
3381
+ if (!isRecord(options)) throw new TypeError("update 的第三参数必须是选项对象;请通过 options.condition 传入附加写入条件。");
3382
+ if (options.recordBaseline !== void 0 && typeof options.recordBaseline !== "boolean") throw new TypeError("update 的 options.recordBaseline 必须是布尔值。");
3383
+ if (options.recordBaseline === true) {
3384
+ if (store === void 0) throw new TypeError("记录比较基线需要提供比较基线存储。");
3385
+ const configuredLanguages = [...new Set(config.translations?.languages ?? [])];
3386
+ if (resolveLanguageSelection(config.translations?.languages ?? [], options).length !== configuredLanguages.length) throw new TypeError("记录比较基线要求本次更新覆盖全部配置语言。");
3387
+ }
3388
+ const plan = await previewUpdate(config, store, options);
3389
+ const execution = await applyUpdatePlan(plan, config, options.condition, options);
3390
+ if (options.recordBaseline !== true) return {
3391
+ ...execution,
3392
+ plan
3393
+ };
3394
+ if (store === void 0) throw new TypeError("记录比较基线需要提供比较基线存储。");
3395
+ const baseline = await advanceBaselineAfterUpdate(config, store, plan, execution);
3396
+ return {
3397
+ ...execution,
3398
+ status: baseline.outcome === "saved" || baseline.outcome === "unchanged" ? execution.status : "failed",
3399
+ plan,
3400
+ baseline
3401
+ };
3402
+ }
3403
+ async function advanceBaselineAfterUpdate(config, store, plan, execution) {
3404
+ if (Object.hasOwn(execution, "batchError")) return {
3405
+ outcome: "notAdvanced",
3406
+ message: "批次写回发生异常;比较基线保留。"
3407
+ };
3408
+ if (execution.status !== "completed") return {
3409
+ outcome: "notAdvanced",
3410
+ message: "更新未完整成功;比较基线保留。"
3411
+ };
3412
+ if (!allUpdateChangesProcessed(plan, execution.results)) return {
3413
+ outcome: "notAdvanced",
3414
+ message: "仍有更新变化未处理或待复核;比较基线保留。"
3415
+ };
3416
+ let current;
3417
+ try {
3418
+ current = await readComparisonSnapshot(config);
3419
+ } catch (error) {
3420
+ return {
3421
+ outcome: "notAdvanced",
3422
+ message: `执行后完整回读失败;比较基线保留:${errorMessage(error)}`
3423
+ };
3424
+ }
3425
+ if (!isDeepStrictEqual(plan.current.source, current.source)) return {
3426
+ outcome: "notAdvanced",
3427
+ message: "执行后原文与本次更新依据不一致;比较基线保留。"
3428
+ };
3429
+ try {
3430
+ return { outcome: (await recordComparisonBaselineFromSnapshot(current, store)).outcome };
3431
+ } catch (error) {
3432
+ if (error instanceof ComparisonBaselineIncompleteSnapshotError) return {
3433
+ outcome: "notAdvanced",
3434
+ message: `${error.message}比较基线保留。`
3435
+ };
3436
+ return {
3437
+ outcome: "failed",
3438
+ message: `译文已写入,基线未推进:${errorMessage(error)}`
3439
+ };
3440
+ }
3441
+ }
3442
+ function allUpdateChangesProcessed(plan, results) {
3443
+ if (results.length !== plan.items.length || results.some(({ status }) => status !== "written" && status !== "retained")) return false;
3444
+ const sourceLanguagePairs = new Set(plan.items.flatMap(({ sourceKey, language, changes }) => {
3445
+ const key = sourceKey ?? changes.source?.key;
3446
+ return key === void 0 ? [] : [sourceLanguageKey(key, language)];
3447
+ }));
3448
+ const changedSourceKeys = new Set(plan.comparisons.sourceChanges.flatMap(({ key, status, current }) => status === "unchanged" || current === void 0 ? [] : [key]));
3449
+ for (const source of plan.current.source.units) for (const read of plan.current.translations.reads) {
3450
+ const association = plan.associations.current.find((item) => item.sourceKey === source.key && item.language === read.language);
3451
+ if ((changedSourceKeys.has(source.key) || association === void 0 || association.status !== "matched") && !sourceLanguagePairs.has(sourceLanguageKey(source.key, read.language))) return false;
3452
+ }
3453
+ const translationKeys = new Set(plan.items.flatMap(({ changes }) => changes.translations.map(({ identity }) => JSON.stringify([identity.language, identity.key]))));
3454
+ if (plan.comparisons.translationChanges.some(({ identity, status, current }) => status !== "unchanged" && current !== void 0 && !translationKeys.has(JSON.stringify([identity.language, identity.key])))) return false;
3455
+ return removedSourceTargetsAreProcessed(plan);
3456
+ }
3457
+ function sourceLanguageKey(sourceKey, language) {
3458
+ return JSON.stringify([sourceKey, language]);
3459
+ }
3460
+ function removedSourceTargetsAreProcessed(plan) {
3461
+ if (plan.previous === void 0) return true;
3462
+ const currentTargets = new Set(plan.current.translations.records.map(({ identity }) => JSON.stringify([identity.language, identity.key])));
3463
+ for (const sourceChange of plan.comparisons.sourceChanges) {
3464
+ if (sourceChange.status !== "removed") continue;
3465
+ for (const association of plan.associations.previous) {
3466
+ if (association.sourceKey !== sourceChange.key) continue;
3467
+ for (const index of association.translationIndexes) {
3468
+ const previous = plan.previous.translations.records[index];
3469
+ if (previous === void 0) return false;
3470
+ const key = JSON.stringify([previous.identity.language, previous.identity.key]);
3471
+ if (!currentTargets.has(key)) continue;
3472
+ if (!plan.items.some((item) => item.language === association.language && item.changes.translations.some(({ identity }) => JSON.stringify([identity.language, identity.key]) === key))) return false;
3473
+ }
3474
+ }
3475
+ }
3476
+ return true;
3477
+ }
3478
+ function errorMessage(error) {
3479
+ return error instanceof Error ? error.message : String(error);
3480
+ }
3481
+ // ../../packages/core/dist/index.js
3482
+ var DuplicateTranslationUnitKeyError = class extends Error {
3483
+ key;
3484
+ firstIndex;
3485
+ duplicateIndex;
3486
+ constructor(key, firstIndex, duplicateIndex) {
3487
+ super(`原文单元身份重复:${JSON.stringify(key)}(第 ${firstIndex + 1} 与第 ${duplicateIndex + 1} 个单元)`);
3488
+ this.name = "DuplicateTranslationUnitKeyError";
3489
+ this.key = key;
3490
+ this.firstIndex = firstIndex;
3491
+ this.duplicateIndex = duplicateIndex;
3492
+ }
3493
+ };
3494
+ function defineConfigImplementation(config) {
3495
+ return config;
3496
+ }
3497
+ /**
3498
+ * 声明宿主配置。显式业务泛型通过 withTypes 预先绑定,以便从配置内容推断检查项与分组。
3499
+ * 静态字面量 ID 保留精确选择类型;混入普通 string ID 会使检查项联合退化为 string,
3500
+ * 此时检查项、分组成员和运行选项依赖 QA 入口的运行时目录校验。
3501
+ */
3502
+ const defineConfig = Object.assign(defineConfigImplementation, { withTypes() {
3503
+ return (config) => defineConfigImplementation(config);
3504
+ } });
3505
+ function validateFrameworkConfig(value) {
3506
+ validateSourceConfig(value);
3507
+ }
3508
+ function validateSourceConfig(value) {
3509
+ if (!isRecord(value)) invalidFrameworkConfig("宿主配置必须是对象。");
3510
+ if (!isRecord(value.source) || typeof value.source.read !== "function") invalidFrameworkConfig("defineConfig 的 source.read 必须是函数。");
3511
+ if (!isStandardSchema(value.source.schema)) invalidFrameworkConfig("defineConfig 的 source.schema 必须符合 Standard Schema v1。");
3512
+ if (typeof value.keyOf !== "function") invalidFrameworkConfig("defineConfig 的 keyOf 必须是函数。");
3513
+ validateQualityConfiguration(value.quality);
3514
+ }
3515
+ function validateQualityConfiguration(value) {
3516
+ if (value === void 0) return;
3517
+ if (!isRecord(value)) invalidFrameworkConfig("defineConfig 的 quality 必须是对象。");
3518
+ if (Object.hasOwn(value, "prepare")) invalidFrameworkConfig("defineConfig 的 quality.prepare 已移除;请直接配置 quality.checks。");
3519
+ if (value.checks !== void 0 && !Array.isArray(value.checks)) invalidFrameworkConfig("defineConfig 的 quality.checks 必须是检查器数组。");
3520
+ if (Object.hasOwn(value, "buildCandidates")) invalidFrameworkConfig("defineConfig 的 quality.buildCandidates 已移除;请在 runQa 前构造 candidates。");
3521
+ if (value.relationships !== void 0 && !Array.isArray(value.relationships)) invalidFrameworkConfig("defineConfig 的 quality.relationships 必须是数组。");
3522
+ if (value.resultCache !== void 0 && (!isRecord(value.resultCache) || typeof value.resultCache.get !== "function" || typeof value.resultCache.set !== "function")) invalidFrameworkConfig("defineConfig 的 quality.resultCache 必须提供 get 与 set 函数。");
3523
+ if (value.suppressionStore !== void 0 && (!isRecord(value.suppressionStore) || typeof value.suppressionStore.load !== "function" || typeof value.suppressionStore.upsert !== "function")) invalidFrameworkConfig("defineConfig 的 quality.suppressionStore 必须提供 load 与 upsert 函数。");
3524
+ }
3525
+ function invalidFrameworkConfig(message) {
3526
+ throw new StandardSchemaContractError("defineConfig 配置", "schema-mismatch", message);
3527
+ }
3528
+ async function readSourceSnapshot(config) {
3529
+ validateSourceConfig(config);
3530
+ let read;
3531
+ let errorMessage;
3532
+ try {
3533
+ read = await config.source.read();
3534
+ } catch (error) {
3535
+ if (error instanceof StandardSchemaContractError) throw error;
3536
+ errorMessage = error instanceof Error ? error.message : String(error);
3537
+ }
3538
+ if (errorMessage === void 0) validateSourceRead(read);
3539
+ const firstIndexes = /* @__PURE__ */ new Map();
3540
+ const units = [];
3541
+ const scopes = read?.scopes ?? [];
3542
+ for (const [scopeIndex, scope] of scopes.entries()) for (const record of scope.records) {
3543
+ const index = units.length;
3544
+ const unit = await validateWithStandardSchema(config.source.schema, record.value, `原文单元 ${index + 1}`, {
3545
+ preserveValue: true,
3546
+ requireJson: true
3547
+ });
3548
+ const key = config.keyOf(unit);
3549
+ if (typeof key !== "string" || key.trim().length === 0) invalidFrameworkConfig("keyOf 必须返回非空的原文消息键。");
3550
+ const firstIndex = firstIndexes.get(key);
3551
+ if (firstIndex !== void 0) throw new DuplicateTranslationUnitKeyError(key, firstIndex, index);
3552
+ firstIndexes.set(key, index);
3553
+ units.push({
3554
+ key,
3555
+ unit,
3556
+ bodyAvailability: record.bodyAvailability,
3557
+ scopeIndex
3558
+ });
3559
+ }
3560
+ const scopeCoverage = scopes.map((scope) => ({
3561
+ range: scope.range,
3562
+ enumeration: scope.enumeration,
3563
+ recordCount: scope.records.length,
3564
+ ...scope.error === void 0 ? {} : { error: scope.error }
3565
+ }));
3566
+ const status = readStatus(scopeCoverage, errorMessage);
3567
+ const totalUnitCount = status === "complete" ? units.length : null;
3568
+ const readCoverage = {
3569
+ status,
3570
+ scopes: scopeCoverage,
3571
+ ...errorMessage === void 0 ? {} : { error: errorMessage }
3572
+ };
3573
+ return {
3574
+ version: snapshotVersion({
3575
+ read: readCoverage,
3576
+ units
3577
+ }),
3578
+ read: readCoverage,
3579
+ totalUnitCount,
3580
+ units
3581
+ };
3582
+ }
3583
+ /** 读取源、目标事实及读取依据,不计算源译关联或运行 QA。 */
3584
+ async function readComparisonSnapshot(config, options = {}) {
3585
+ validateFrameworkConfig(config);
3586
+ return await collectComparisonSnapshot(config, resolveLanguageSelection(config.translations?.languages ?? [], options));
3587
+ }
3588
+ async function collectComparisonSnapshot(config, languages) {
3589
+ const source = await readSourceSnapshot(config);
3590
+ const translations = await readTranslationSnapshot(config.translations, source.units, languages);
3591
+ return {
3592
+ version: snapshotVersion({
3593
+ source,
3594
+ translations
3595
+ }),
3596
+ source,
3597
+ translations
3598
+ };
3599
+ }
3600
+ async function readProjectSnapshot(config, options = {}) {
3601
+ validateFrameworkConfig(config);
3602
+ const translationAdapter = config.translations;
3603
+ const snapshot = await collectComparisonSnapshot(config, resolveLanguageSelection(translationAdapter?.languages ?? [], options));
3604
+ const associations = associateSnapshot(snapshot);
3605
+ const version = snapshotVersion({
3606
+ source: snapshot.source,
3607
+ translations: snapshot.translations,
3608
+ associations
3609
+ });
3610
+ return {
3611
+ ...snapshot,
3612
+ version,
3613
+ associations
3614
+ };
3615
+ }
3616
+ async function runQa(config, options = {}) {
3617
+ const profile = options.profiler === void 0 ? void 0 : beginQualityProfile(options.profiler);
3618
+ let completed = false;
3619
+ let stage = profile?.stage("configuration");
3620
+ try {
3621
+ validateFrameworkConfig(config);
3622
+ const quality = config.quality;
3623
+ const selectedChecks = resolveQualityCheckSelection(quality?.checks ?? [], quality?.groups, options);
3624
+ stage?.();
3625
+ stage = profile?.stage("suppressions");
3626
+ const suppressions = await loadQaSuppressions(config);
3627
+ stage?.();
3628
+ stage = profile?.stage("snapshot");
3629
+ const snapshot = await readProjectSnapshot(config, options);
3630
+ stage?.();
3631
+ const memo = options.memo ?? createMemoScope();
3632
+ const qualityData = createQualityDataReader();
3633
+ try {
3634
+ stage = profile?.stage("candidates");
3635
+ const isDraft = options.candidates !== void 0;
3636
+ assertReadableSnapshot(snapshot, { draft: isDraft });
3637
+ let selection;
3638
+ if (options.candidates !== void 0 || options.selectCandidates !== void 0) {
3639
+ const supplied = options.candidates === void 0 ? savedTranslationCandidates(snapshot) : options.candidates;
3640
+ if (!Array.isArray(supplied)) throw new TypeError("candidates 必须是译文候选数组。");
3641
+ const candidates = [];
3642
+ for (const candidate of supplied) candidates.push(freezeJsonValue(await validateTranslationCandidate(candidate, config)));
3643
+ validateQualityCandidateScope(snapshot, candidates);
3644
+ selection = candidates;
3645
+ if (options.selectCandidates !== void 0) {
3646
+ const selected = options.selectCandidates(Object.freeze(candidates));
3647
+ if (!Array.isArray(selected)) throw new TypeError("selectCandidates 必须返回候选数组。");
3648
+ const offered = new Set(candidates);
3649
+ if (selected.some((candidate) => !offered.has(candidate))) throw new TypeError("selectCandidates 只能筛选或重排传入的候选;请通过 candidates 提供候选。");
3650
+ validateQualityCandidateScope(snapshot, selected);
3651
+ selection = selected;
3652
+ }
3653
+ if (!isDraft) {
3654
+ const selectedIdentities = new Set(selection.map(({ sourceKey, language }) => JSON.stringify([sourceKey, language])));
3655
+ assertSelectedAssociationsComplete(snapshot, snapshot.associations.filter((association) => selectedIdentities.has(JSON.stringify([association.sourceKey, association.language]))));
3656
+ }
3657
+ }
3658
+ stage?.();
3659
+ stage = profile?.stage("checks");
3660
+ const result = await runQualityChecksWithQualityData(snapshot, {
3661
+ ...selection === void 0 ? {} : { candidates: selection },
3662
+ relationships: quality?.relationships ?? [],
3663
+ suppressions
3664
+ }, selectedChecks, {
3665
+ memo,
3666
+ includeCleanExecutions: true,
3667
+ ...profile === void 0 ? {} : { profile },
3668
+ ...quality?.resultCache === void 0 ? {} : { qualityCheckResultCache: quality.resultCache }
3669
+ }, qualityData);
3670
+ stage?.();
3671
+ const configuredChecks = quality?.checks ?? [];
3672
+ const reportedChecks = options.includeCleanExecutions === true ? result.checks : pruneCleanExecutions(result.checks);
3673
+ const report = {
3674
+ ...result,
3675
+ checks: reportedChecks,
3676
+ checkScope: {
3677
+ configuredCount: configuredChecks.length,
3678
+ selectedIds: selectedChecks.map(({ id }) => id),
3679
+ evaluatedCount: result.checkScope.evaluatedCount
3680
+ }
3681
+ };
3682
+ if (!(options.candidates === void 0 && options.selectCandidates === void 0 && selectedChecks.length === configuredChecks.length)) {
3683
+ completed = true;
3684
+ return report;
3685
+ }
3686
+ assertQaSuppressionBindings({
3687
+ suppressions,
3688
+ configuredCheckIds: configuredChecks.map(({ id }) => id),
3689
+ configuredLanguages: config.translations?.languages ?? [],
3690
+ completeSourceKeys: new Set(snapshot.source.units.map(({ key }) => key)),
3691
+ savedChecks: result.checks,
3692
+ ...options.languages === void 0 ? {} : { selectedLanguages: options.languages }
3693
+ });
3694
+ const activeExecutions = new Set(result.diagnostics.filter(({ handling }) => handling.status === "active").map(({ executionId }) => executionId));
3695
+ const remaining = /* @__PURE__ */ new Map();
3696
+ for (const check of result.checks) for (const { executionId, sourceKey, language } of check.executions) {
3697
+ if (!activeExecutions.has(executionId)) continue;
3698
+ let keys = remaining.get(language);
3699
+ if (!keys) {
3700
+ keys = /* @__PURE__ */ new Set();
3701
+ remaining.set(language, keys);
3702
+ }
3703
+ keys.add(sourceKey);
3704
+ }
3705
+ const total = snapshot.source.units.length;
3706
+ const progress = snapshot.translations.reads.map(({ language }) => {
3707
+ const finished = total - (remaining.get(language)?.size ?? 0);
3708
+ return {
3709
+ language,
3710
+ completed: finished,
3711
+ total,
3712
+ ...total === 0 ? {} : { percentage: 100 * finished / total }
3713
+ };
3714
+ });
3715
+ completed = true;
3716
+ return {
3717
+ ...report,
3718
+ progress
3719
+ };
3720
+ } finally {
3721
+ stage?.();
3722
+ stage = profile?.stage("cleanup");
3723
+ try {
3724
+ qualityData.dispose();
3725
+ if (options.memo === void 0) memo.dispose();
3726
+ } finally {
3727
+ stage?.();
3728
+ }
3729
+ }
3730
+ } finally {
3731
+ stage?.();
3732
+ profile?.finish(completed ? "completed" : "interrupted");
3733
+ }
3734
+ }
3735
+ function resolveQualityCheckSelection(checks, configuredGroups, options) {
3736
+ const checksById = /* @__PURE__ */ new Map();
3737
+ for (const check of checks) {
3738
+ if (typeof check.id !== "string" || check.id.trim() === "") throw new TypeError("QA 检查项必须提供非空 id。");
3739
+ if (checksById.has(check.id)) throw new TypeError(`QA 检查项 id ${check.id} 重复。`);
3740
+ checksById.set(check.id, check);
3741
+ }
3742
+ const groupsByName = /* @__PURE__ */ new Map();
3743
+ if (configuredGroups !== void 0) {
3744
+ if (!isPlainRecord(configuredGroups)) throw new TypeError("defineConfig 的 quality.groups 必须是对象。");
3745
+ for (const [groupName, members] of Object.entries(configuredGroups)) {
3746
+ if (!Array.isArray(members) || members.some((id) => typeof id !== "string")) throw new TypeError(`defineConfig 的 quality.groups.${groupName} 必须是检查项 ID 数组。`);
3747
+ for (const id of members) if (!checksById.has(id)) throw new TypeError(`质量检查分组 ${groupName} 引用了未配置的检查项 ${JSON.stringify(id)}。`);
3748
+ groupsByName.set(groupName, members);
3749
+ }
3750
+ }
3751
+ const { checkIds, groups } = options;
3752
+ if (checkIds !== void 0 && groups !== void 0) throw new TypeError("质量检查不能同时使用 checkIds 和 groups 选择。");
3753
+ let selectedIds;
3754
+ if (checkIds !== void 0) {
3755
+ if (!Array.isArray(checkIds) || checkIds.some((id) => typeof id !== "string")) throw new TypeError("checkIds 必须是检查项 ID 数组。");
3756
+ if (checkIds.length === 0) throw new TypeError("显式检查项选择不能为空。");
3757
+ selectedIds = /* @__PURE__ */ new Set();
3758
+ for (const id of checkIds) {
3759
+ if (!checksById.has(id)) throw new TypeError(`未配置质量检查项 ${JSON.stringify(id)}。`);
3760
+ selectedIds.add(id);
3761
+ }
3762
+ } else if (groups !== void 0) {
3763
+ if (!Array.isArray(groups) || groups.some((name) => typeof name !== "string")) throw new TypeError("groups 必须是分组名数组。");
3764
+ if (groups.length === 0) throw new TypeError("显式检查项分组选择不能为空。");
3765
+ selectedIds = /* @__PURE__ */ new Set();
3766
+ for (const name of groups) {
3767
+ const members = groupsByName.get(name);
3768
+ if (members === void 0) throw new TypeError(`未配置质量检查分组 ${JSON.stringify(name)}。`);
3769
+ for (const id of members) selectedIds.add(id);
3770
+ }
3771
+ if (selectedIds.size === 0) throw new TypeError("质量检查分组选择结果不能为空。");
3772
+ }
3773
+ if (selectedIds === void 0) return checks;
3774
+ return checks.filter(({ id }) => selectedIds.has(id));
3775
+ }
3776
+ async function loadQaSuppressions(config) {
3777
+ const store = config.quality?.suppressionStore;
3778
+ if (store === void 0) return [];
3779
+ const suppressions = await store.load();
3780
+ validateQaSuppressions(suppressions);
3781
+ return suppressions;
3782
+ }
3783
+ function validateSourceRead(value) {
3784
+ if (!isRecord(value) || !Array.isArray(value.scopes)) invalidReadStructure("source.read 必须返回包含 scopes 数组的读取结果。");
3785
+ for (const [scopeIndex, scope] of value.scopes.entries()) {
3786
+ if (!isRecord(scope) || !Array.isArray(scope.records) || scope.enumeration !== "complete" && scope.enumeration !== "partial" && scope.enumeration !== "failed" || scope.error !== void 0 && typeof scope.error !== "string") invalidReadStructure(`source.read 的第 ${scopeIndex + 1} 个范围结构无效。`);
3787
+ assertJsonValue(scope.range, `原文范围 ${scopeIndex + 1}`);
3788
+ for (const [recordIndex, record] of scope.records.entries()) if (!isRecord(record) || record.bodyAvailability !== "available" && record.bodyAvailability !== "unavailable") invalidReadStructure(`source.read 的第 ${scopeIndex + 1} 个范围中,第 ${recordIndex + 1} 条原文记录结构无效。`);
3789
+ }
3790
+ }
3791
+ function invalidReadStructure(message) {
3792
+ throw new StandardSchemaContractError("source.read", "schema-mismatch", message);
3793
+ }
3794
+ function snapshotVersion(value) {
3795
+ return `sha256:${createHash("sha256").update(JSON.stringify(value)).digest("hex")}`;
3796
+ }
3797
+ export { defineChecker as A, validateQaSuppressions as B, validateComparisonResult as C, TranslationIdentityContractError as D, writeTranslationRequests as E, QaSuppressionFormatError as F, MemoScopeClosedError as H, createQaSuppression as I, upsertQaSuppressionFromReport as L, stableStringify as M, StandardSchemaContractError as N, QualityCheckerContractError as O, assertJsonValue as P, validateQaSuppression as R, validateComparisonInput as S, validateTranslationWriteRequest as T, createMemoScope as U, isRecord as V, createQualityProfiler as W, replaceComparisonBaseline as _, readSourceSnapshot as a, compareSnapshots as b, applyUpdatePlan as c, defaultUpdatePolicy as d, previewUpdate as f, recordComparisonBaseline as g, ComparisonBaselineIncompleteSnapshotError as h, readProjectSnapshot as i, isCachedQualityFindings as j, QualityDataReaderContractError as k, update as l, ComparisonBaselineFormatError as m, defineConfig as n, runQa as o, validateUpdatePlan as p, readComparisonSnapshot as r, validateFrameworkConfig as s, DuplicateTranslationUnitKeyError as t, createUpdatePlan as u, validateComparisonBaseline as v, validateTranslationCandidate as w, defaultCompare as x, ComparisonContractError as y, validateQaSuppressionFile as z };