dsh-agent-team-ui-testing 0.0.0-stage → 0.1.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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +327 -2
  3. package/annotation-capture.js +111 -0
  4. package/banner.png +0 -0
  5. package/banner_zh.png +0 -0
  6. package/browser-safety.js +293 -0
  7. package/capture-p0.js +910 -0
  8. package/client.js +11302 -0
  9. package/context-menu.js +134 -0
  10. package/cordis.patch.yml +3 -0
  11. package/core/clock.js +88 -0
  12. package/core/config-store.js +566 -0
  13. package/core/config.js +892 -0
  14. package/core/contracts.js +240 -0
  15. package/core/errors.js +156 -0
  16. package/core/evidence.js +141 -0
  17. package/core/geometry.js +217 -0
  18. package/core/identity.js +180 -0
  19. package/core/index.js +24 -0
  20. package/core/p0.js +1101 -0
  21. package/core/readiness.js +175 -0
  22. package/core/registry.js +239 -0
  23. package/core/tab-access.js +1350 -0
  24. package/docs/adapters.md +160 -0
  25. package/docs/architecture.md +146 -0
  26. package/docs/capability-tiers.md +80 -0
  27. package/docs/capture-p0.md +90 -0
  28. package/docs/diagnose-reason-codes.md +157 -0
  29. package/docs/element-picker.md +143 -0
  30. package/docs/getting-started.md +136 -0
  31. package/docs/index.md +36 -0
  32. package/docs/multi-tab.md +162 -0
  33. package/docs/network-p0.md +117 -0
  34. package/docs/panel-context-menu.md +41 -0
  35. package/docs/t2-structured-gui.md +68 -0
  36. package/docs/t3-vision.md +84 -0
  37. package/docs/t4-dynamic-behavior.md +135 -0
  38. package/docs/tools.md +174 -0
  39. package/docs/verification.md +131 -0
  40. package/docs/viewport-control.md +94 -0
  41. package/dynamic-t4.js +5699 -0
  42. package/frame-push.js +508 -0
  43. package/frame-source.js +162 -0
  44. package/icon.png +0 -0
  45. package/index.js +23028 -0
  46. package/integration/cross-environment.js +1535 -0
  47. package/integration/diagnose.js +945 -0
  48. package/integration/tab-principal.js +493 -0
  49. package/locale/en.json +6 -0
  50. package/locale/zh.json +6 -0
  51. package/network-p0.js +4264 -0
  52. package/package.json +19 -4
  53. package/select-control.js +298 -0
  54. package/skills/ui-testing-common/SKILL.md +54 -0
  55. package/skills/ui-testing-fake/SKILL.md +43 -0
  56. package/skills/ui-testing-web/SKILL.md +520 -0
  57. package/skills/ui-testing-web/manifests/declared-capabilities.json +903 -0
  58. package/skills/ui-testing-web/references/contracts/capability.md +68 -0
  59. package/skills/ui-testing-web/references/contracts/evidence.md +41 -0
  60. package/skills/ui-testing-web/references/contracts/operation.md +44 -0
  61. package/skills/ui-testing-web/references/core/dynamic-visual.md +123 -0
  62. package/skills/ui-testing-web/references/core/fallback.md +83 -0
  63. package/skills/ui-testing-web/references/core/network-and-state.md +114 -0
  64. package/skills/ui-testing-web/references/core/page-identity.md +91 -0
  65. package/skills/ui-testing-web/references/core/report-template.md +144 -0
  66. package/skills/ui-testing-web/references/core/reporting.md +92 -0
  67. package/skills/ui-testing-web/references/core/safety.md +12 -0
  68. package/skills/ui-testing-web/references/core/selection.md +26 -0
  69. package/skills/ui-testing-web/references/core/tool-routing-and-limits.md +198 -0
  70. package/skills/ui-testing-web/references/core/verdict-examples.md +96 -0
  71. package/skills/ui-testing-web/references/core/verdict-gate.md +105 -0
  72. package/skills/ui-testing-web/references/core/verification.md +19 -0
  73. package/skills/ui-testing-web/references/core/workflow.md +16 -0
  74. package/skills/ui-testing-web/references/platforms/index.md +19 -0
  75. package/skills/ui-testing-web/references/platforms/web.md +17 -0
  76. package/skills/ui-testing-web/references/scenarios/annotations.md +104 -0
  77. package/skills/ui-testing-web/references/scenarios/functional.md +205 -0
  78. package/skills/ui-testing-web/references/scenarios/visual-motion.md +170 -0
  79. package/skills/ui-testing-web/references/tiers/t1-programmatic.md +25 -0
  80. package/skills/ui-testing-web/references/tiers/t2-structured.md +61 -0
  81. package/skills/ui-testing-web/references/tiers/t3-static-visual.md +45 -0
  82. package/skills/ui-testing-web/references/tiers/t4-dynamic-visual.md +58 -0
  83. package/skills/ui-testing-web/templates/capability-note.md +23 -0
  84. package/skills/ui-testing-web/templates/platform.md +30 -0
  85. package/skills/ui-testing-web/templates/regression-case.md +15 -0
  86. package/skills/ui-testing-web/templates/scenario.md +13 -0
  87. package/targets/fake/adapter.js +1163 -0
  88. package/targets/fake/fixtures.js +177 -0
  89. package/targets/web/adapter.js +1231 -0
  90. package/targets/web/provider.js +415 -0
  91. package/vision-baseline.js +1254 -0
  92. package/vision-t3.js +2657 -0
package/vision-t3.js ADDED
@@ -0,0 +1,2657 @@
1
+ /**
2
+ * vision-t3.js — WEB-T3 静态视觉的纯算法层(零 npm 依赖、无 CDP/浏览器代码)。
3
+ *
4
+ * 权威契约:docs/t3-vision.md(§1–§5、§9 的 U 类条目);
5
+ * 模块 API 见 docs/t3-vision.md。
6
+ *
7
+ * 设计约束:
8
+ * - 只依赖 node:crypto / node:zlib 与既有 capture-p0.js(inspectPng/crc32)、browser-safety.js(BrowserError)。
9
+ * - 不 import CDP、不启动浏览器、不写文件、不读环境变量、无全局可变状态。
10
+ * - 失败:参数/预算/取消/尺寸/空比较一律抛 BrowserError;PNG 解码把格式/结构错误作为
11
+ * `{ok:false,code,message}` 返回(契约 §2.1 decodePngToRgba 形状),由调用方转抛。
12
+ * - 每 65,536 像素/比较检查一次取消与 5,000ms 算法预算;`*Async` 变体在检查点 await
13
+ * 让出事件循环(同步变体在单次同步执行中无法投递 abort 事件,只能检查已 abort 的 signal
14
+ * 与墙钟预算,Host 有取消需求时用 Async 变体)。
15
+ * - PNG 解码在 inflate 前用预期扫描行字节数限制输出(防压缩炸弹),channel 1/2/3/4 正规化 RGBA8。
16
+ *
17
+ * 实现约定(契约未逐字规定、此处固定并供 Host/验收引用):
18
+ * - findInImage 返回的 candidates[].region / centroid 是**完整输入 image** 坐标(ROI 原点已回加)。
19
+ * - diffImages 返回 regions(≤100,id r1…)+ regionCount(过滤后总数)+ regionsTruncated;
20
+ * C=N-M=0 时抛 VISION_EMPTY_COMPARISON;highlight 是完整源图尺寸的 PNG Buffer。
21
+ * - VisionProductStore.pin() 找不到时返回 null(由调用方抛 VISION_SOURCE_NOT_FOUND);
22
+ * add() 在未提供 sha256 时自算编码字节 hash,不自算 rgbaSha256(store 不长期持有解码缓冲)。
23
+ * - AA 3×3 排除:Y 相等计数在边界初值 1、内部 0;第二层「两图各有 ≥3 个相等 RGBA 邻居」按
24
+ * 实际有效邻居计数(不再加初值),并列邻居按 y 后 x 升序取第一个。
25
+ * - 工作集预算在 diff 分配前按 16·W·H + 7·N + min(4·W·H, 32MiB) 估算(契约 §1.1 的
26
+ * 「同时存活缓冲」口径),超限抛 VISION_LIMIT_EXCEEDED;其它操作由像素/字节硬上限兜底。
27
+ */
28
+
29
+ import { createHash, randomBytes } from 'node:crypto';
30
+ import { constants as zlibConstants, deflateSync, inflateSync } from 'node:zlib';
31
+
32
+ import { BrowserError } from './browser-safety.js';
33
+ import { crc32, inspectPng } from './capture-p0.js';
34
+
35
+ /* ------------------------------------------------------------------ */
36
+ /* 常量 */
37
+ /* ------------------------------------------------------------------ */
38
+
39
+ export const VISION_ALGORITHM_VERSION = 't3-v1';
40
+
41
+ export const VISION_LIMITS = Object.freeze({
42
+ maxProducts: 16,
43
+ maxTotalBytes: 128 * 1024 * 1024,
44
+ maxProductBytes: 32 * 1024 * 1024,
45
+ maxProductPixels: 16000000,
46
+ maxWorkingSetBytes: 256 * 1024 * 1024,
47
+ maxTemplateComparisons: 50000000,
48
+ algorithmBudgetMs: 5000,
49
+ maxOutputPixels: 16000000,
50
+ maxOutputBytes: 32 * 1024 * 1024,
51
+ });
52
+
53
+ export const DEFAULT_DIFF_OPTIONS = Object.freeze({ threshold: 0.1, includeAA: false, minRegionPixels: 1 });
54
+ export const DEFAULT_THRESHOLDS = Object.freeze({ warnRatio: 0.001, failRatio: 0.01 });
55
+
56
+ export const WARNING_VOCABULARY = Object.freeze([
57
+ 'bitmap-upscaled',
58
+ 'mapping-incompatible',
59
+ 'advisory-only',
60
+ 'fact-unverified',
61
+ 'regions-truncated',
62
+ 'animation-not-evaluated',
63
+ ]);
64
+
65
+ /** 每 65,536 像素/比较检查一次取消与算法预算。 */
66
+ const CHECKPOINT_UNITS = 65536;
67
+
68
+ /** PNG 编码固定参数(契约 §4.1):RGBA8/type6、非交错、filter 0、level 9、单 IDAT、无 tIME。 */
69
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
70
+ const PNG_COLOR_TYPE_CHANNELS = Object.freeze({ 0: 1, 2: 3, 4: 2, 6: 4 });
71
+ const DEFLATE_OPTIONS = Object.freeze({
72
+ level: 9,
73
+ windowBits: 15,
74
+ memLevel: 8,
75
+ strategy: zlibConstants.Z_DEFAULT_STRATEGY,
76
+ });
77
+
78
+ const NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
79
+ const PRODUCT_ID_PATTERN = /^v1_[0-9a-f]{32}$/;
80
+
81
+ const DIGIT_BITMAPS = Object.freeze({
82
+ 0: ['111', '101', '101', '101', '111'],
83
+ 1: ['010', '110', '010', '010', '111'],
84
+ 2: ['111', '001', '111', '100', '111'],
85
+ 3: ['111', '001', '111', '001', '111'],
86
+ 4: ['101', '101', '111', '001', '001'],
87
+ 5: ['111', '100', '111', '001', '111'],
88
+ 6: ['111', '100', '111', '101', '111'],
89
+ 7: ['111', '001', '010', '010', '010'],
90
+ 8: ['111', '101', '111', '101', '111'],
91
+ 9: ['111', '101', '111', '001', '111'],
92
+ });
93
+
94
+ /* ------------------------------------------------------------------ */
95
+ /* 错误、操作上下文、生成器驱动 */
96
+ /* ------------------------------------------------------------------ */
97
+
98
+ function visionLimitExceeded(limit, actual, max, message) {
99
+ return new BrowserError('VISION_LIMIT_EXCEEDED', message || `vision 预算超限: ${limit}`, {
100
+ limit,
101
+ actual,
102
+ max,
103
+ });
104
+ }
105
+
106
+ function invalidArgument(path, reason, label) {
107
+ const parts = [label, path].filter((part) => typeof part === 'string' && part !== '');
108
+ const fullPath = parts.length ? parts.join('.') : 'value';
109
+ return new BrowserError('INVALID_ARGUMENT', `参数不合法: ${fullPath} (${reason})`, {
110
+ path: fullPath,
111
+ reason,
112
+ });
113
+ }
114
+
115
+ function createOpContext({ signal, budgetMs, startedAt } = {}) {
116
+ const budget = Number.isFinite(budgetMs) && budgetMs >= 0 ? budgetMs : VISION_LIMITS.algorithmBudgetMs;
117
+ return {
118
+ signal: signal || null,
119
+ budgetMs: budget,
120
+ startedAt: Number.isFinite(startedAt) ? startedAt : Date.now(),
121
+ check(operation) {
122
+ if (this.signal && this.signal.aborted) {
123
+ throw new BrowserError('ABORTED', 'vision 算法已取消', { operation });
124
+ }
125
+ const elapsedMs = Date.now() - this.startedAt;
126
+ if (elapsedMs > this.budgetMs) {
127
+ throw new BrowserError('VISION_TIMEOUT', 'vision 算法超出预算', {
128
+ operation,
129
+ budgetMs: this.budgetMs,
130
+ elapsedMs,
131
+ });
132
+ }
133
+ },
134
+ };
135
+ }
136
+
137
+ function driveSync(generator, ctx, operation) {
138
+ ctx.check(operation);
139
+ let step = generator.next();
140
+ while (!step.done) {
141
+ ctx.check(operation);
142
+ step = generator.next();
143
+ }
144
+ return step.value;
145
+ }
146
+
147
+ async function driveAsync(generator, ctx, operation) {
148
+ ctx.check(operation);
149
+ let step = generator.next();
150
+ while (!step.done) {
151
+ ctx.check(operation);
152
+ await new Promise((resolve) => setImmediate(resolve));
153
+ step = generator.next();
154
+ }
155
+ return step.value;
156
+ }
157
+
158
+ /* ------------------------------------------------------------------ */
159
+ /* 基础工具 */
160
+ /* ------------------------------------------------------------------ */
161
+
162
+ function clampByte(value) {
163
+ if (value < 0) return 0;
164
+ if (value > 255) return 255;
165
+ return value;
166
+ }
167
+
168
+ function clampInt(value, min, max) {
169
+ if (value < min) return min;
170
+ if (value > max) return max;
171
+ return value;
172
+ }
173
+
174
+ function isPlainObject(value) {
175
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
176
+ }
177
+
178
+ function hasOwn(object, key) {
179
+ return Object.prototype.hasOwnProperty.call(object, key);
180
+ }
181
+
182
+ function toBuffer(bytes) {
183
+ if (Buffer.isBuffer(bytes)) return bytes;
184
+ if (bytes instanceof Uint8Array) return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
185
+ if (bytes instanceof ArrayBuffer) return Buffer.from(bytes);
186
+ return null;
187
+ }
188
+
189
+ function sha256Hex(bytes) {
190
+ return createHash('sha256').update(bytes).digest('hex');
191
+ }
192
+
193
+ function assertImage(image, label = 'image') {
194
+ if (!isPlainObject(image)) throw invalidArgument('', 'invalid-image', label);
195
+ const { width, height, rgba } = image;
196
+ if (!Number.isInteger(width) || width <= 0) throw invalidArgument('width', 'invalid-dimensions', label);
197
+ if (!Number.isInteger(height) || height <= 0) throw invalidArgument('height', 'invalid-dimensions', label);
198
+ if (!(rgba instanceof Uint8Array)) throw invalidArgument('rgba', 'invalid-rgba-buffer', label);
199
+ if (rgba.length !== width * height * 4) throw invalidArgument('rgba', 'invalid-rgba-buffer', label);
200
+ return image;
201
+ }
202
+
203
+ function assertOutputPixels(pixels, label = 'image') {
204
+ if (pixels > VISION_LIMITS.maxOutputPixels) {
205
+ throw visionLimitExceeded(
206
+ 'maxOutputPixels',
207
+ pixels,
208
+ VISION_LIMITS.maxOutputPixels,
209
+ `${label}: 输出像素超限`,
210
+ );
211
+ }
212
+ }
213
+
214
+ /* ------------------------------------------------------------------ */
215
+ /* 参数校验 */
216
+ /* ------------------------------------------------------------------ */
217
+
218
+ function assertObject(value, label) {
219
+ if (!isPlainObject(value)) throw invalidArgument('', 'not-an-object', label);
220
+ return value;
221
+ }
222
+
223
+ function assertAllowedKeys(value, allowed, label) {
224
+ for (const key of Object.keys(value)) {
225
+ if (!allowed.includes(key)) throw invalidArgument(key, 'unknown-field', label);
226
+ }
227
+ }
228
+
229
+ function readNumber(value, key, label, options = {}) {
230
+ const { min, max, integer = false, required = false, fallback } = options;
231
+ if (!hasOwn(value, key)) {
232
+ if (required) throw invalidArgument(key, 'missing-required-field', label);
233
+ return fallback;
234
+ }
235
+ const raw = value[key];
236
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) {
237
+ throw invalidArgument(key, 'not-a-finite-number', label);
238
+ }
239
+ if (integer && !Number.isInteger(raw)) throw invalidArgument(key, 'not-an-integer', label);
240
+ if (min !== undefined && raw < min) throw invalidArgument(key, 'below-minimum', label);
241
+ if (max !== undefined && raw > max) throw invalidArgument(key, 'above-maximum', label);
242
+ return raw;
243
+ }
244
+
245
+ function readBoolean(value, key, label, fallback) {
246
+ if (!hasOwn(value, key)) return fallback;
247
+ const raw = value[key];
248
+ if (typeof raw !== 'boolean') throw invalidArgument(key, 'not-a-boolean', label);
249
+ return raw;
250
+ }
251
+
252
+ function readName(value, key, label) {
253
+ if (!hasOwn(value, key)) throw invalidArgument(key, 'missing-required-field', label);
254
+ const raw = value[key];
255
+ if (typeof raw !== 'string' || !NAME_PATTERN.test(raw)) throw invalidArgument(key, 'invalid-name', label);
256
+ return raw;
257
+ }
258
+
259
+ function readString(value, key, label, { required = false, fallback = null, maxBytes = 200 } = {}) {
260
+ if (!hasOwn(value, key)) {
261
+ if (required) throw invalidArgument(key, 'missing-required-field', label);
262
+ return fallback;
263
+ }
264
+ const raw = value[key];
265
+ if (typeof raw !== 'string') throw invalidArgument(key, 'not-a-string', label);
266
+ if (raw === '' || raw.trim() === '') throw invalidArgument(key, 'empty-string', label);
267
+ if (Buffer.byteLength(raw, 'utf8') > maxBytes) throw invalidArgument(key, 'string-too-long', label);
268
+ if (raw.includes('\0')) throw invalidArgument(key, 'string-has-nul', label);
269
+ return raw;
270
+ }
271
+
272
+ function readColorArray(value, key, label, length) {
273
+ if (!hasOwn(value, key)) throw invalidArgument(key, 'missing-required-field', label);
274
+ const raw = value[key];
275
+ if (!Array.isArray(raw) || raw.length !== length) {
276
+ throw invalidArgument(key, `expected-rgba-array-${length}`, label);
277
+ }
278
+ const out = new Array(length);
279
+ for (let index = 0; index < length; index += 1) {
280
+ const channel = raw[index];
281
+ if (!Number.isInteger(channel) || channel < 0 || channel > 255) {
282
+ throw invalidArgument(`${key}[${index}]`, 'invalid-color-channel', label);
283
+ }
284
+ out[index] = channel;
285
+ }
286
+ return out;
287
+ }
288
+
289
+ function readOptionalColorArray(value, key, label, length, fallback) {
290
+ if (!hasOwn(value, key)) return fallback;
291
+ const raw = value[key];
292
+ if (!Array.isArray(raw) || raw.length !== length) {
293
+ throw invalidArgument(key, `expected-rgba-array-${length}`, label);
294
+ }
295
+ const out = new Array(length);
296
+ for (let index = 0; index < length; index += 1) {
297
+ const channel = raw[index];
298
+ if (!Number.isInteger(channel) || channel < 0 || channel > 255) {
299
+ throw invalidArgument(`${key}[${index}]`, 'invalid-color-channel', label);
300
+ }
301
+ out[index] = channel;
302
+ }
303
+ return out;
304
+ }
305
+
306
+ function validatePixelPoint(value, label) {
307
+ const point = assertObject(value, label);
308
+ assertAllowedKeys(point, ['x', 'y'], label);
309
+ const x = readNumber(point, 'x', label, { min: 0, integer: true, required: true });
310
+ const y = readNumber(point, 'y', label, { min: 0, integer: true, required: true });
311
+ return { x, y };
312
+ }
313
+
314
+ export function validatePixelRect(value, label = 'rect') {
315
+ const rect = assertObject(value, label);
316
+ assertAllowedKeys(rect, ['x', 'y', 'width', 'height'], label);
317
+ const x = readNumber(rect, 'x', label, { min: 0, integer: true, required: true });
318
+ const y = readNumber(rect, 'y', label, { min: 0, integer: true, required: true });
319
+ const width = readNumber(rect, 'width', label, { min: 1, integer: true, required: true });
320
+ const height = readNumber(rect, 'height', label, { min: 1, integer: true, required: true });
321
+ return { x, y, width, height };
322
+ }
323
+
324
+ export function validateCssRect(value, label = 'rect') {
325
+ const rect = assertObject(value, label);
326
+ assertAllowedKeys(rect, ['x', 'y', 'width', 'height'], label);
327
+ const x = readNumber(rect, 'x', label, { min: 0, required: true });
328
+ const y = readNumber(rect, 'y', label, { min: 0, required: true });
329
+ const width = readNumber(rect, 'width', label, { min: 1, required: true });
330
+ const height = readNumber(rect, 'height', label, { min: 1, required: true });
331
+ return { x, y, width, height };
332
+ }
333
+
334
+ /**
335
+ * `Source.live.region` 的 canvas 空间校验:允许负 x/y(视口外/内容外即 blank,docs/
336
+ * canvas-viewport.md §6.2)。有限性与 width/height ≥ 1 与文档矩形一致;O=0 时 Host 仍会拒绝
337
+ * 负坐标(旧语义不变),这里只负责语法层。
338
+ */
339
+ function validateSourceRegion(value, label = 'region') {
340
+ const rect = assertObject(value, label);
341
+ assertAllowedKeys(rect, ['x', 'y', 'width', 'height'], label);
342
+ const x = readNumber(rect, 'x', label, { required: true });
343
+ const y = readNumber(rect, 'y', label, { required: true });
344
+ const width = readNumber(rect, 'width', label, { min: 1, required: true });
345
+ const height = readNumber(rect, 'height', label, { min: 1, required: true });
346
+ return { x, y, width, height };
347
+ }
348
+
349
+ export function validatePoint(value, label = 'point') {
350
+ const point = assertObject(value, label);
351
+ assertAllowedKeys(point, ['x', 'y'], label);
352
+ const x = readNumber(point, 'x', label, { min: 0, required: true });
353
+ const y = readNumber(point, 'y', label, { min: 0, required: true });
354
+ return { x, y };
355
+ }
356
+
357
+ /**
358
+ * `Source` 校验(契约 §1.1)。
359
+ *
360
+ * `scale` **保留“省略”**:省略时规范化结果里没有 `scale` 字段,由 Host 在本次调用的队列内
361
+ * 解析一次当前 `view.scale`(cold 时 1)。这里绝不能填 1,否则 Host 无法区分“调用方显式要 1”
362
+ * 与“调用方没说话”,默认截图比例就永远跟着固定值而不是共享视口(docs/viewport-control.md,
363
+ * Lead 冻结 2026-11-01)。显式 scale 的合法范围同步扩到下界 0.1。
364
+ */
365
+ export function validateSource(value, label = 'source') {
366
+ if (value === undefined) return { kind: 'live' };
367
+ const source = assertObject(value, label);
368
+ const kind = source.kind;
369
+ if (kind !== 'live' && kind !== 'product' && kind !== 'baseline') {
370
+ throw invalidArgument('kind', hasOwn(source, 'kind') ? 'invalid-enum' : 'missing-required-field', label);
371
+ }
372
+ if (kind === 'live') {
373
+ assertAllowedKeys(source, ['kind', 'scale', 'region'], label);
374
+ const scale = readNumber(source, 'scale', label, { min: 0.1, max: 4 });
375
+ const normalized = { kind: 'live' };
376
+ if (scale !== undefined) normalized.scale = scale;
377
+ if (hasOwn(source, 'region')) normalized.region = validateSourceRegion(source.region, `${label}.region`);
378
+ return normalized;
379
+ }
380
+ if (kind === 'product') {
381
+ assertAllowedKeys(source, ['kind', 'productId'], label);
382
+ if (!hasOwn(source, 'productId')) throw invalidArgument('productId', 'missing-required-field', label);
383
+ const productId = source.productId;
384
+ if (typeof productId !== 'string' || !PRODUCT_ID_PATTERN.test(productId)) {
385
+ throw invalidArgument('productId', 'invalid-product-id', label);
386
+ }
387
+ return { kind: 'product', productId };
388
+ }
389
+ assertAllowedKeys(source, ['kind', 'name', 'revision'], label);
390
+ const name = readName(source, 'name', label);
391
+ const normalized = { kind: 'baseline', name };
392
+ if (hasOwn(source, 'revision')) {
393
+ normalized.revision = readNumber(source, 'revision', label, {
394
+ min: 1,
395
+ max: 9999999999,
396
+ integer: true,
397
+ required: true,
398
+ });
399
+ }
400
+ return normalized;
401
+ }
402
+
403
+ export function validateQuery(value, label = 'query') {
404
+ const query = assertObject(value, label);
405
+ const method = query.method;
406
+ const METHODS = ['color', 'components', 'edges', 'template'];
407
+ if (!METHODS.includes(method)) {
408
+ throw invalidArgument('method', hasOwn(query, 'method') ? 'invalid-enum' : 'missing-required-field', label);
409
+ }
410
+ const maxResults = readNumber(query, 'maxResults', label, { min: 1, max: 100, integer: true, fallback: 20 });
411
+ if (method === 'template') {
412
+ assertAllowedKeys(query, ['method', 'maxResults', 'template', 'minScore', 'stride'], label);
413
+ if (!hasOwn(query, 'template')) throw invalidArgument('template', 'missing-required-field', label);
414
+ const template = validateSource(query.template, `${label}.template`);
415
+ if (template.kind === 'live') {
416
+ throw invalidArgument('template', 'template-source-must-be-product-or-baseline', label);
417
+ }
418
+ const minScore = readNumber(query, 'minScore', label, { min: 0, max: 1, fallback: 0.95 });
419
+ const stride = readNumber(query, 'stride', label, { min: 1, max: 16, integer: true, fallback: 1 });
420
+ return { method, maxResults, template, minScore, stride };
421
+ }
422
+ assertAllowedKeys(query, ['method', 'minArea', 'maxResults', 'color', 'tolerance', 'background', 'edgeThreshold'], label);
423
+ const minArea = readNumber(query, 'minArea', label, { min: 1, max: 16000000, integer: true, fallback: 4 });
424
+ if (method === 'color') {
425
+ assertAllowedKeys(query, ['method', 'minArea', 'maxResults', 'color', 'tolerance'], label);
426
+ const color = readColorArray(query, 'color', label, 3);
427
+ const tolerance = readNumber(query, 'tolerance', label, { min: 0, max: 255, integer: true, fallback: 16 });
428
+ return { method, minArea, maxResults, color, tolerance };
429
+ }
430
+ if (method === 'components') {
431
+ assertAllowedKeys(query, ['method', 'minArea', 'maxResults', 'background', 'tolerance'], label);
432
+ const background = readOptionalColorArray(query, 'background', label, 3, [255, 255, 255]);
433
+ const tolerance = readNumber(query, 'tolerance', label, { min: 0, max: 255, integer: true, fallback: 16 });
434
+ return { method, minArea, maxResults, background, tolerance };
435
+ }
436
+ assertAllowedKeys(query, ['method', 'minArea', 'maxResults', 'edgeThreshold'], label);
437
+ const edgeThreshold = readNumber(query, 'edgeThreshold', label, {
438
+ min: 0,
439
+ max: 255,
440
+ integer: true,
441
+ fallback: 32,
442
+ });
443
+ return { method, minArea, maxResults, edgeThreshold };
444
+ }
445
+
446
+ export function validateDiffOptions(value, label = 'options') {
447
+ if (value === undefined) return { ...DEFAULT_DIFF_OPTIONS };
448
+ const options = assertObject(value, label);
449
+ assertAllowedKeys(options, ['threshold', 'includeAA', 'minRegionPixels'], label);
450
+ const threshold = readNumber(options, 'threshold', label, {
451
+ min: 0,
452
+ max: 1,
453
+ fallback: DEFAULT_DIFF_OPTIONS.threshold,
454
+ });
455
+ const includeAA = readBoolean(options, 'includeAA', label, DEFAULT_DIFF_OPTIONS.includeAA);
456
+ const minRegionPixels = readNumber(options, 'minRegionPixels', label, {
457
+ min: 1,
458
+ max: 16000000,
459
+ integer: true,
460
+ fallback: DEFAULT_DIFF_OPTIONS.minRegionPixels,
461
+ });
462
+ return { threshold, includeAA, minRegionPixels };
463
+ }
464
+
465
+ export function validateThresholds(value, label = 'thresholds') {
466
+ if (value === undefined) return { ...DEFAULT_THRESHOLDS };
467
+ const thresholds = assertObject(value, label);
468
+ assertAllowedKeys(thresholds, ['warnRatio', 'failRatio'], label);
469
+ const warnRatio = readNumber(thresholds, 'warnRatio', label, {
470
+ min: 0,
471
+ max: 1,
472
+ fallback: DEFAULT_THRESHOLDS.warnRatio,
473
+ });
474
+ const failRatio = readNumber(thresholds, 'failRatio', label, {
475
+ min: 0,
476
+ max: 1,
477
+ fallback: DEFAULT_THRESHOLDS.failRatio,
478
+ });
479
+ if (warnRatio > failRatio) throw invalidArgument('failRatio', 'warn-ratio-greater-than-fail-ratio', label);
480
+ return { warnRatio, failRatio };
481
+ }
482
+
483
+ export function validateMasks(value, label = 'masks') {
484
+ if (value === undefined) return [];
485
+ if (!Array.isArray(value)) throw invalidArgument('', 'not-an-array', label);
486
+ if (value.length > 64) throw invalidArgument('', 'too-many-items', label);
487
+ const seen = new Set();
488
+ const masks = [];
489
+ for (let index = 0; index < value.length; index += 1) {
490
+ const itemLabel = `${label}[${index}]`;
491
+ const mask = assertObject(value[index], itemLabel);
492
+ assertAllowedKeys(mask, ['id', 'region'], itemLabel);
493
+ const id = readName(mask, 'id', itemLabel);
494
+ if (seen.has(id)) throw invalidArgument('id', 'duplicate-id', itemLabel);
495
+ seen.add(id);
496
+ if (!hasOwn(mask, 'region')) throw invalidArgument('region', 'missing-required-field', itemLabel);
497
+ const region = validatePixelRect(mask.region, `${itemLabel}.region`);
498
+ masks.push({ id, region });
499
+ }
500
+ return masks;
501
+ }
502
+
503
+ export function validateAnnotations(value, label = 'annotations') {
504
+ if (value === undefined) return [];
505
+ if (!Array.isArray(value)) throw invalidArgument('', 'not-an-array', label);
506
+ if (value.length > 64) throw invalidArgument('', 'too-many-items', label);
507
+ const annotations = [];
508
+ for (let index = 0; index < value.length; index += 1) {
509
+ const itemLabel = `${label}[${index}]`;
510
+ const item = assertObject(value[index], itemLabel);
511
+ const kind = item.kind;
512
+ if (kind !== 'rect' && kind !== 'cross' && kind !== 'number' && kind !== 'arrow') {
513
+ throw invalidArgument('kind', hasOwn(item, 'kind') ? 'invalid-enum' : 'missing-required-field', itemLabel);
514
+ }
515
+ const color = readOptionalColorArray(item, 'color', itemLabel, 4, [255, 0, 0, 255]);
516
+ const thickness = readNumber(item, 'thickness', itemLabel, { min: 1, max: 8, integer: true, fallback: 2 });
517
+ if (kind === 'rect') {
518
+ assertAllowedKeys(item, ['kind', 'color', 'thickness', 'region'], itemLabel);
519
+ if (!hasOwn(item, 'region')) throw invalidArgument('region', 'missing-required-field', itemLabel);
520
+ const region = validatePixelRect(item.region, `${itemLabel}.region`);
521
+ annotations.push({ kind, color, thickness, region });
522
+ } else if (kind === 'cross') {
523
+ assertAllowedKeys(item, ['kind', 'color', 'thickness', 'point', 'size'], itemLabel);
524
+ if (!hasOwn(item, 'point')) throw invalidArgument('point', 'missing-required-field', itemLabel);
525
+ const point = validatePixelPoint(item.point, `${itemLabel}.point`);
526
+ const size = readNumber(item, 'size', itemLabel, { min: 3, max: 63, integer: true, fallback: 9 });
527
+ annotations.push({ kind, color, thickness, point, size });
528
+ } else if (kind === 'number') {
529
+ assertAllowedKeys(item, ['kind', 'color', 'thickness', 'point', 'number'], itemLabel);
530
+ if (!hasOwn(item, 'point')) throw invalidArgument('point', 'missing-required-field', itemLabel);
531
+ const point = validatePixelPoint(item.point, `${itemLabel}.point`);
532
+ const number = readNumber(item, 'number', itemLabel, { min: 1, max: 999, integer: true, required: true });
533
+ annotations.push({ kind, color, thickness, point, number });
534
+ } else {
535
+ assertAllowedKeys(item, ['kind', 'color', 'thickness', 'point', 'to'], itemLabel);
536
+ if (!hasOwn(item, 'point')) throw invalidArgument('point', 'missing-required-field', itemLabel);
537
+ if (!hasOwn(item, 'to')) throw invalidArgument('to', 'missing-required-field', itemLabel);
538
+ const point = validatePixelPoint(item.point, `${itemLabel}.point`);
539
+ const to = validatePixelPoint(item.to, `${itemLabel}.to`);
540
+ annotations.push({ kind, color, thickness, point, to });
541
+ }
542
+ }
543
+ return annotations;
544
+ }
545
+
546
+ export function validatePreprocess(value, label = 'preprocess') {
547
+ if (value === undefined) return [];
548
+ if (!Array.isArray(value)) throw invalidArgument('', 'not-an-array', label);
549
+ if (value.length > 8) throw invalidArgument('', 'too-many-items', label);
550
+ const ops = [];
551
+ for (let index = 0; index < value.length; index += 1) {
552
+ const itemLabel = `${label}[${index}]`;
553
+ const item = assertObject(value[index], itemLabel);
554
+ const op = item.op;
555
+ if (op !== 'grayscale' && op !== 'blur' && op !== 'normalize' && op !== 'threshold' && op !== 'channels') {
556
+ throw invalidArgument('op', hasOwn(item, 'op') ? 'invalid-enum' : 'missing-required-field', itemLabel);
557
+ }
558
+ if (op === 'blur') {
559
+ assertAllowedKeys(item, ['op', 'radius'], itemLabel);
560
+ const radius = readNumber(item, 'radius', itemLabel, { min: 1, max: 3, integer: true, fallback: 1 });
561
+ ops.push({ op, radius });
562
+ } else if (op === 'threshold') {
563
+ assertAllowedKeys(item, ['op', 'value'], itemLabel);
564
+ const thresholdValue = readNumber(item, 'value', itemLabel, { min: 0, max: 255, integer: true, fallback: 128 });
565
+ ops.push({ op, value: thresholdValue });
566
+ } else if (op === 'channels') {
567
+ assertAllowedKeys(item, ['op', 'order'], itemLabel);
568
+ const order = hasOwn(item, 'order') ? item.order : 'rgba';
569
+ if (order !== 'rgba' && order !== 'bgra' && order !== 'argb') {
570
+ throw invalidArgument('order', 'invalid-enum', itemLabel);
571
+ }
572
+ ops.push({ op, order });
573
+ } else {
574
+ assertAllowedKeys(item, ['op'], itemLabel);
575
+ ops.push({ op });
576
+ }
577
+ }
578
+ return ops;
579
+ }
580
+
581
+ export function validateOutput(value, label = 'output') {
582
+ if (value === undefined) return { persist: false };
583
+ const output = assertObject(value, label);
584
+ assertAllowedKeys(output, ['persist', 'out'], label);
585
+ const persist = readBoolean(output, 'persist', label, false);
586
+ const normalized = { persist };
587
+ if (hasOwn(output, 'out')) {
588
+ normalized.out = readString(output, 'out', label, { required: true, maxBytes: 200 });
589
+ }
590
+ return normalized;
591
+ }
592
+
593
+ /* ------------------------------------------------------------------ */
594
+ /* PNG 解码(8-bit、color type 0/2/4/6、非交错,正规化 RGBA8) */
595
+ /* ------------------------------------------------------------------ */
596
+
597
+ function pngFailure(code, message, details) {
598
+ return details ? { ok: false, code, message, details } : { ok: false, code, message };
599
+ }
600
+
601
+ function paethPredictor(a, b, c) {
602
+ const p = a + b - c;
603
+ const pa = Math.abs(p - a);
604
+ const pb = Math.abs(p - b);
605
+ const pc = Math.abs(p - c);
606
+ if (pa <= pb && pa <= pc) return a;
607
+ if (pb <= pc) return b;
608
+ return c;
609
+ }
610
+
611
+ function* decodePngSteps(bytes, ctx) {
612
+ const inspected = inspectPng(bytes);
613
+ if (!inspected.ok) return pngFailure('INVALID_PNG', 'PNG 结构或 CRC 校验失败');
614
+ const buf = toBuffer(bytes);
615
+ if (!buf) return pngFailure('INVALID_PNG', 'PNG 字节不可读');
616
+ const bitDepth = buf[24];
617
+ const colorType = buf[25];
618
+ const compressionMethod = buf[26];
619
+ const filterMethod = buf[27];
620
+ const interlace = buf[28];
621
+ if (bitDepth !== 8) {
622
+ return pngFailure('VISION_FORMAT_UNSUPPORTED', 'PNG 位深不受支持(仅 8-bit)');
623
+ }
624
+ const channels = PNG_COLOR_TYPE_CHANNELS[colorType];
625
+ if (!channels) {
626
+ return pngFailure('VISION_FORMAT_UNSUPPORTED', 'PNG color type 不受支持(仅 0/2/4/6)');
627
+ }
628
+ if (interlace !== 0) return pngFailure('VISION_FORMAT_UNSUPPORTED', 'PNG 交错模式不受支持');
629
+ if (compressionMethod !== 0 || filterMethod !== 0) {
630
+ return pngFailure('VISION_FORMAT_UNSUPPORTED', 'PNG 压缩/滤波方法不受支持');
631
+ }
632
+
633
+ const width = inspected.width;
634
+ const height = inspected.height;
635
+ const pixels = width * height;
636
+ if (pixels > VISION_LIMITS.maxProductPixels) {
637
+ return pngFailure('VISION_LIMIT_EXCEEDED', 'PNG 像素数超过 product 上限', {
638
+ limit: 'maxProductPixels',
639
+ actual: pixels,
640
+ max: VISION_LIMITS.maxProductPixels,
641
+ });
642
+ }
643
+
644
+ const idatParts = [];
645
+ let offset = 8;
646
+ while (offset + 8 <= buf.length) {
647
+ const length = buf.readUInt32BE(offset);
648
+ const type = buf.toString('latin1', offset + 4, offset + 8);
649
+ if (type === 'tRNS') {
650
+ // 不支持调色板/透明块:不能忽略后把非 alpha 通道当不透明图分析。
651
+ return pngFailure('VISION_FORMAT_UNSUPPORTED', 'PNG tRNS 透明度块不受支持');
652
+ }
653
+ if (type === 'IDAT') idatParts.push(buf.subarray(offset + 8, offset + 8 + length));
654
+ offset += 8 + length + 4;
655
+ if (type === 'IEND') break;
656
+ }
657
+ if (!idatParts.length) return pngFailure('INVALID_PNG', 'PNG 缺少 IDAT');
658
+
659
+ const stride = width * channels;
660
+ const expectedLength = (stride + 1) * height;
661
+ let raw;
662
+ try {
663
+ raw = inflateSync(Buffer.concat(idatParts), { maxOutputLength: expectedLength });
664
+ } catch {
665
+ return pngFailure('INVALID_PNG', 'PNG IDAT 解压失败或超过预期扫描行长度(疑似压缩炸弹)');
666
+ }
667
+ if (raw.length !== expectedLength) {
668
+ return pngFailure('INVALID_PNG', 'PNG 扫描行字节数与 IHDR 不一致');
669
+ }
670
+
671
+ const rgba = new Uint8Array(pixels * 4);
672
+ let prev = new Uint8Array(stride);
673
+ let cur = new Uint8Array(stride);
674
+ let nextCheckpoint = CHECKPOINT_UNITS;
675
+ for (let y = 0; y < height; y += 1) {
676
+ const rowStart = y * (stride + 1);
677
+ const filter = raw[rowStart];
678
+ if (filter > 4) return pngFailure('INVALID_PNG', 'PNG 行 filter 类型非法');
679
+ const inStart = rowStart + 1;
680
+ for (let i = 0; i < stride; i += 1) {
681
+ const x = raw[inStart + i];
682
+ const left = i >= channels ? cur[i - channels] : 0;
683
+ const up = y > 0 ? prev[i] : 0;
684
+ const upLeft = y > 0 && i >= channels ? prev[i - channels] : 0;
685
+ let value;
686
+ switch (filter) {
687
+ case 0: value = x; break;
688
+ case 1: value = x + left; break;
689
+ case 2: value = x + up; break;
690
+ case 3: value = x + ((left + up) >> 1); break;
691
+ default: value = x + paethPredictor(left, up, upLeft); break;
692
+ }
693
+ cur[i] = value & 0xff;
694
+ }
695
+ const outBase = y * width * 4;
696
+ if (channels === 4) {
697
+ rgba.set(cur, outBase);
698
+ } else if (channels === 1) {
699
+ for (let x = 0; x < width; x += 1) {
700
+ const gray = cur[x];
701
+ const out = outBase + x * 4;
702
+ rgba[out] = gray;
703
+ rgba[out + 1] = gray;
704
+ rgba[out + 2] = gray;
705
+ rgba[out + 3] = 255;
706
+ }
707
+ } else if (channels === 2) {
708
+ for (let x = 0; x < width; x += 1) {
709
+ const gray = cur[x * 2];
710
+ const out = outBase + x * 4;
711
+ rgba[out] = gray;
712
+ rgba[out + 1] = gray;
713
+ rgba[out + 2] = gray;
714
+ rgba[out + 3] = cur[x * 2 + 1];
715
+ }
716
+ } else {
717
+ for (let x = 0; x < width; x += 1) {
718
+ const out = outBase + x * 4;
719
+ const src = x * 3;
720
+ rgba[out] = cur[src];
721
+ rgba[out + 1] = cur[src + 1];
722
+ rgba[out + 2] = cur[src + 2];
723
+ rgba[out + 3] = 255;
724
+ }
725
+ }
726
+ const tmp = prev;
727
+ prev = cur;
728
+ cur = tmp;
729
+ const done = (y + 1) * width;
730
+ if (done >= nextCheckpoint) {
731
+ nextCheckpoint += CHECKPOINT_UNITS;
732
+ yield;
733
+ }
734
+ }
735
+ return { ok: true, width, height, rgba };
736
+ }
737
+
738
+ /** 解码 PNG 为 RGBA8:`{ok:true,width,height,rgba}` 或 `{ok:false,code,message[,details]}`。 */
739
+ export function decodePngToRgba(bytes, options = {}) {
740
+ const ctx = createOpContext(options);
741
+ return driveSync(decodePngSteps(bytes, ctx), ctx, 'decode');
742
+ }
743
+
744
+ /** decodePngToRgba 的让出事件循环版本(每 65,536 像素)。 */
745
+ export async function decodePngToRgbaAsync(bytes, options = {}) {
746
+ const ctx = createOpContext(options);
747
+ return driveAsync(decodePngSteps(bytes, ctx), ctx, 'decode');
748
+ }
749
+
750
+ /* ------------------------------------------------------------------ */
751
+ /* PNG 编码(RGBA8/type6、非交错、filter 0、level 9、单 IDAT、无 tIME) */
752
+ /* ------------------------------------------------------------------ */
753
+
754
+ function pngChunk(type, data) {
755
+ const length = Buffer.alloc(4);
756
+ length.writeUInt32BE(data.length, 0);
757
+ const typeBytes = Buffer.from(type, 'latin1');
758
+ const body = Buffer.concat([typeBytes, data]);
759
+ const crc = Buffer.alloc(4);
760
+ crc.writeUInt32BE(crc32(body) >>> 0, 0);
761
+ return Buffer.concat([length, body, crc]);
762
+ }
763
+
764
+ function* encodePngSteps(image, ctx) {
765
+ if (!isPlainObject(image)) throw invalidArgument('', 'invalid-image', 'image');
766
+ const width = image.width;
767
+ const height = image.height;
768
+ if (!Number.isInteger(width) || width <= 0) throw invalidArgument('width', 'invalid-dimensions', 'image');
769
+ if (!Number.isInteger(height) || height <= 0) throw invalidArgument('height', 'invalid-dimensions', 'image');
770
+ const pixels = width * height;
771
+ if (pixels > VISION_LIMITS.maxOutputPixels) {
772
+ throw visionLimitExceeded(
773
+ 'maxOutputPixels',
774
+ pixels,
775
+ VISION_LIMITS.maxOutputPixels,
776
+ 'PNG 编码输出像素超限',
777
+ );
778
+ }
779
+ const rgba = image.rgba;
780
+ if (!(rgba instanceof Uint8Array) || rgba.length !== pixels * 4) {
781
+ throw invalidArgument('rgba', 'invalid-rgba-buffer', 'image');
782
+ }
783
+
784
+ const rowBytes = width * 4;
785
+ const raw = Buffer.allocUnsafe((rowBytes + 1) * height);
786
+ let out = 0;
787
+ let nextCheckpoint = CHECKPOINT_UNITS;
788
+ for (let y = 0; y < height; y += 1) {
789
+ raw[out] = 0;
790
+ out += 1;
791
+ raw.set(rgba.subarray(y * rowBytes, (y + 1) * rowBytes), out);
792
+ out += rowBytes;
793
+ const done = (y + 1) * width;
794
+ if (done >= nextCheckpoint) {
795
+ nextCheckpoint += CHECKPOINT_UNITS;
796
+ yield;
797
+ }
798
+ }
799
+ const compressed = deflateSync(raw, DEFLATE_OPTIONS);
800
+ const ihdr = Buffer.alloc(13);
801
+ ihdr.writeUInt32BE(width, 0);
802
+ ihdr.writeUInt32BE(height, 4);
803
+ ihdr[8] = 8;
804
+ ihdr[9] = 6;
805
+ ihdr[10] = 0;
806
+ ihdr[11] = 0;
807
+ ihdr[12] = 0;
808
+ const png = Buffer.concat([
809
+ PNG_SIGNATURE,
810
+ pngChunk('IHDR', ihdr),
811
+ pngChunk('IDAT', compressed),
812
+ pngChunk('IEND', Buffer.alloc(0)),
813
+ ]);
814
+ if (png.length > VISION_LIMITS.maxOutputBytes) {
815
+ throw visionLimitExceeded('maxOutputBytes', png.length, VISION_LIMITS.maxOutputBytes, 'PNG 编码字节超限');
816
+ }
817
+ return png;
818
+ }
819
+
820
+ /** 编码 RGBA8 为确定性 PNG(固定 filter0/level9/单 IDAT/无 tIME),返回 Buffer。 */
821
+ export function encodePngRgba(image, options = {}) {
822
+ const ctx = createOpContext(options);
823
+ return driveSync(encodePngSteps(image, ctx), ctx, 'encode');
824
+ }
825
+
826
+ /** encodePngRgba 的让出事件循环版本。 */
827
+ export async function encodePngRgbaAsync(image, options = {}) {
828
+ const ctx = createOpContext(options);
829
+ return driveAsync(encodePngSteps(image, ctx), ctx, 'encode');
830
+ }
831
+
832
+ /* ------------------------------------------------------------------ */
833
+ /* 裁剪 / 缩放 */
834
+ /* ------------------------------------------------------------------ */
835
+
836
+ function* cropSteps(image, rect, ctx) {
837
+ assertImage(image, 'image');
838
+ const region = validatePixelRect(rect, 'rect');
839
+ if (region.x + region.width > image.width || region.y + region.height > image.height) {
840
+ throw invalidArgument('rect', 'out-of-bounds', 'cropImage');
841
+ }
842
+ const pixels = region.width * region.height;
843
+ assertOutputPixels(pixels, 'cropImage');
844
+ const out = new Uint8Array(pixels * 4);
845
+ const rowBytes = region.width * 4;
846
+ let nextCheckpoint = CHECKPOINT_UNITS;
847
+ for (let y = 0; y < region.height; y += 1) {
848
+ const srcStart = ((region.y + y) * image.width + region.x) * 4;
849
+ out.set(image.rgba.subarray(srcStart, srcStart + rowBytes), y * rowBytes);
850
+ const done = (y + 1) * region.width;
851
+ if (done >= nextCheckpoint) {
852
+ nextCheckpoint += CHECKPOINT_UNITS;
853
+ yield;
854
+ }
855
+ }
856
+ return { width: region.width, height: region.height, rgba: out };
857
+ }
858
+
859
+ /** 裁剪(rect 必须完全在图内,左闭右开)。 */
860
+ export function cropImage(image, rect, options = {}) {
861
+ const ctx = createOpContext(options);
862
+ return driveSync(cropSteps(image, rect, ctx), ctx, 'crop');
863
+ }
864
+
865
+ /** cropImage 的让出事件循环版本。 */
866
+ export async function cropImageAsync(image, rect, options = {}) {
867
+ const ctx = createOpContext(options);
868
+ return driveAsync(cropSteps(image, rect, ctx), ctx, 'crop');
869
+ }
870
+
871
+ function readResizeFactor(factor) {
872
+ if (typeof factor !== 'number' || !Number.isFinite(factor)) {
873
+ throw invalidArgument('factor', 'not-a-finite-number', 'resize');
874
+ }
875
+ if (factor < 1 || factor > 4) throw invalidArgument('factor', 'out-of-range', 'resize');
876
+ return factor;
877
+ }
878
+
879
+ function readResizeMethod(method) {
880
+ if (method === undefined || method === null) return 'nearest';
881
+ if (method !== 'nearest' && method !== 'bilinear') throw invalidArgument('method', 'invalid-enum', 'resize');
882
+ return method;
883
+ }
884
+
885
+ function* resizeSteps(image, factor, method, ctx) {
886
+ assertImage(image, 'image');
887
+ const scale = readResizeFactor(factor);
888
+ const algorithm = readResizeMethod(method);
889
+ const widthOut = Math.round(image.width * scale);
890
+ const heightOut = Math.round(image.height * scale);
891
+ if (widthOut < 1 || heightOut < 1) throw invalidArgument('factor', 'empty-output', 'resize');
892
+ assertOutputPixels(widthOut * heightOut, 'resizeImage');
893
+ const out = new Uint8Array(widthOut * heightOut * 4);
894
+ const widthIn = image.width;
895
+ const heightIn = image.height;
896
+ const rgba = image.rgba;
897
+ let nextCheckpoint = CHECKPOINT_UNITS;
898
+
899
+ if (algorithm === 'nearest') {
900
+ for (let oy = 0; oy < heightOut; oy += 1) {
901
+ const iy = Math.min(heightIn - 1, Math.floor(((oy + 0.5) * heightIn) / heightOut));
902
+ const srcRow = iy * widthIn * 4;
903
+ const dstRow = oy * widthOut * 4;
904
+ for (let ox = 0; ox < widthOut; ox += 1) {
905
+ const ix = Math.min(widthIn - 1, Math.floor(((ox + 0.5) * widthIn) / widthOut));
906
+ const src = srcRow + ix * 4;
907
+ const dst = dstRow + ox * 4;
908
+ out[dst] = rgba[src];
909
+ out[dst + 1] = rgba[src + 1];
910
+ out[dst + 2] = rgba[src + 2];
911
+ out[dst + 3] = rgba[src + 3];
912
+ }
913
+ const done = (oy + 1) * widthOut;
914
+ if (done >= nextCheckpoint) {
915
+ nextCheckpoint += CHECKPOINT_UNITS;
916
+ yield;
917
+ }
918
+ }
919
+ return { width: widthOut, height: heightOut, rgba: out };
920
+ }
921
+
922
+ // bilinear:u=(ox+0.5)*Win/Wout-0.5,四个相邻 clamp 像素按距离权重插值预乘 alpha。
923
+ const x0 = new Int32Array(widthOut);
924
+ const x1 = new Int32Array(widthOut);
925
+ const fx = new Float64Array(widthOut);
926
+ for (let ox = 0; ox < widthOut; ox += 1) {
927
+ const u = ((ox + 0.5) * widthIn) / widthOut - 0.5;
928
+ const base = Math.floor(u);
929
+ x0[ox] = clampInt(base, 0, widthIn - 1);
930
+ x1[ox] = clampInt(base + 1, 0, widthIn - 1);
931
+ fx[ox] = u - base;
932
+ }
933
+ const y0 = new Int32Array(heightOut);
934
+ const y1 = new Int32Array(heightOut);
935
+ const fy = new Float64Array(heightOut);
936
+ for (let oy = 0; oy < heightOut; oy += 1) {
937
+ const v = ((oy + 0.5) * heightIn) / heightOut - 0.5;
938
+ const base = Math.floor(v);
939
+ y0[oy] = clampInt(base, 0, heightIn - 1);
940
+ y1[oy] = clampInt(base + 1, 0, heightIn - 1);
941
+ fy[oy] = v - base;
942
+ }
943
+ for (let oy = 0; oy < heightOut; oy += 1) {
944
+ const row0 = y0[oy] * widthIn * 4;
945
+ const row1 = y1[oy] * widthIn * 4;
946
+ const wy1 = fy[oy];
947
+ const wy0 = 1 - wy1;
948
+ const dstRow = oy * widthOut * 4;
949
+ for (let ox = 0; ox < widthOut; ox += 1) {
950
+ const col0 = x0[ox] * 4;
951
+ const col1 = x1[ox] * 4;
952
+ const wx1 = fx[ox];
953
+ const wx0 = 1 - wx1;
954
+ const p00 = row0 + col0;
955
+ const p01 = row0 + col1;
956
+ const p10 = row1 + col0;
957
+ const p11 = row1 + col1;
958
+ const w00 = wx0 * wy0;
959
+ const w01 = wx1 * wy0;
960
+ const w10 = wx0 * wy1;
961
+ const w11 = wx1 * wy1;
962
+ const a00 = rgba[p00 + 3];
963
+ const a01 = rgba[p01 + 3];
964
+ const a10 = rgba[p10 + 3];
965
+ const a11 = rgba[p11 + 3];
966
+ const aSum = w00 * a00 + w01 * a01 + w10 * a10 + w11 * a11;
967
+ const dst = dstRow + ox * 4;
968
+ if (aSum <= 0) {
969
+ out[dst] = 0;
970
+ out[dst + 1] = 0;
971
+ out[dst + 2] = 0;
972
+ out[dst + 3] = 0;
973
+ } else {
974
+ out[dst] = clampByte(Math.round(
975
+ (w00 * a00 * rgba[p00] + w01 * a01 * rgba[p01] + w10 * a10 * rgba[p10] + w11 * a11 * rgba[p11]) / aSum,
976
+ ));
977
+ out[dst + 1] = clampByte(Math.round(
978
+ (w00 * a00 * rgba[p00 + 1] + w01 * a01 * rgba[p01 + 1] + w10 * a10 * rgba[p10 + 1] + w11 * a11 * rgba[p11 + 1]) / aSum,
979
+ ));
980
+ out[dst + 2] = clampByte(Math.round(
981
+ (w00 * a00 * rgba[p00 + 2] + w01 * a01 * rgba[p01 + 2] + w10 * a10 * rgba[p10 + 2] + w11 * a11 * rgba[p11 + 2]) / aSum,
982
+ ));
983
+ out[dst + 3] = clampByte(Math.round(aSum));
984
+ }
985
+ }
986
+ const done = (oy + 1) * widthOut;
987
+ if (done >= nextCheckpoint) {
988
+ nextCheckpoint += CHECKPOINT_UNITS;
989
+ yield;
990
+ }
991
+ }
992
+ return { width: widthOut, height: heightOut, rgba: out };
993
+ }
994
+
995
+ /** 位图缩放:factor∈[1,4],method 'nearest'|'bilinear'(bilinear 预乘 alpha)。 */
996
+ export function resizeImage(image, factor, method, options = {}) {
997
+ const ctx = createOpContext(options);
998
+ return driveSync(resizeSteps(image, factor, method, ctx), ctx, 'resize');
999
+ }
1000
+
1001
+ /** resizeImage 的让出事件循环版本。 */
1002
+ export async function resizeImageAsync(image, factor, method, options = {}) {
1003
+ const ctx = createOpContext(options);
1004
+ return driveAsync(resizeSteps(image, factor, method, ctx), ctx, 'resize');
1005
+ }
1006
+
1007
+ /* ------------------------------------------------------------------ */
1008
+ /* 预处理(grayscale/blur/normalize/threshold/channels,按列表顺序) */
1009
+ /* ------------------------------------------------------------------ */
1010
+
1011
+ function* grayscaleInPlace(rgba, pixels, ctx) {
1012
+ let nextCheckpoint = CHECKPOINT_UNITS;
1013
+ for (let index = 0; index < pixels; index += 1) {
1014
+ const offset = index * 4;
1015
+ const gray = clampByte(Math.round(0.299 * rgba[offset] + 0.587 * rgba[offset + 1] + 0.114 * rgba[offset + 2]));
1016
+ rgba[offset] = gray;
1017
+ rgba[offset + 1] = gray;
1018
+ rgba[offset + 2] = gray;
1019
+ if (index + 1 >= nextCheckpoint) {
1020
+ nextCheckpoint += CHECKPOINT_UNITS;
1021
+ yield;
1022
+ }
1023
+ }
1024
+ }
1025
+
1026
+ function* blurInPlace(rgba, width, height, radius, ctx) {
1027
+ const src = new Uint8Array(rgba);
1028
+ const windowCount = (2 * radius + 1) * (2 * radius + 1);
1029
+ let nextCheckpoint = CHECKPOINT_UNITS;
1030
+ for (let y = 0; y < height; y += 1) {
1031
+ for (let x = 0; x < width; x += 1) {
1032
+ let sumA = 0;
1033
+ let sumR = 0;
1034
+ let sumG = 0;
1035
+ let sumB = 0;
1036
+ for (let dy = -radius; dy <= radius; dy += 1) {
1037
+ const sy = clampInt(y + dy, 0, height - 1);
1038
+ for (let dx = -radius; dx <= radius; dx += 1) {
1039
+ const sx = clampInt(x + dx, 0, width - 1);
1040
+ const offset = (sy * width + sx) * 4;
1041
+ const alpha = src[offset + 3];
1042
+ sumA += alpha;
1043
+ sumR += src[offset] * alpha;
1044
+ sumG += src[offset + 1] * alpha;
1045
+ sumB += src[offset + 2] * alpha;
1046
+ }
1047
+ }
1048
+ const offset = (y * width + x) * 4;
1049
+ if (sumA <= 0) {
1050
+ rgba[offset] = 0;
1051
+ rgba[offset + 1] = 0;
1052
+ rgba[offset + 2] = 0;
1053
+ rgba[offset + 3] = 0;
1054
+ } else {
1055
+ rgba[offset] = clampByte(Math.round(sumR / sumA));
1056
+ rgba[offset + 1] = clampByte(Math.round(sumG / sumA));
1057
+ rgba[offset + 2] = clampByte(Math.round(sumB / sumA));
1058
+ rgba[offset + 3] = clampByte(Math.round(sumA / windowCount));
1059
+ }
1060
+ }
1061
+ const done = (y + 1) * width;
1062
+ if (done >= nextCheckpoint) {
1063
+ nextCheckpoint += CHECKPOINT_UNITS;
1064
+ yield;
1065
+ }
1066
+ }
1067
+ }
1068
+
1069
+ function* normalizeInPlace(rgba, pixels, ctx) {
1070
+ let minR = 255;
1071
+ let maxR = 0;
1072
+ let minG = 255;
1073
+ let maxG = 0;
1074
+ let minB = 255;
1075
+ let maxB = 0;
1076
+ let anyOpaque = false;
1077
+ for (let index = 0; index < pixels; index += 1) {
1078
+ const offset = index * 4;
1079
+ if (rgba[offset + 3] === 0) continue;
1080
+ anyOpaque = true;
1081
+ const r = rgba[offset];
1082
+ const g = rgba[offset + 1];
1083
+ const b = rgba[offset + 2];
1084
+ if (r < minR) minR = r;
1085
+ if (r > maxR) maxR = r;
1086
+ if (g < minG) minG = g;
1087
+ if (g > maxG) maxG = g;
1088
+ if (b < minB) minB = b;
1089
+ if (b > maxB) maxB = b;
1090
+ }
1091
+ if (!anyOpaque) return;
1092
+ const rangeR = maxR - minR;
1093
+ const rangeG = maxG - minG;
1094
+ const rangeB = maxB - minB;
1095
+ let nextCheckpoint = CHECKPOINT_UNITS;
1096
+ for (let index = 0; index < pixels; index += 1) {
1097
+ const offset = index * 4;
1098
+ if (rgba[offset + 3] !== 0) {
1099
+ if (rangeR !== 0) rgba[offset] = clampByte(Math.round((255 * (rgba[offset] - minR)) / rangeR));
1100
+ if (rangeG !== 0) rgba[offset + 1] = clampByte(Math.round((255 * (rgba[offset + 1] - minG)) / rangeG));
1101
+ if (rangeB !== 0) rgba[offset + 2] = clampByte(Math.round((255 * (rgba[offset + 2] - minB)) / rangeB));
1102
+ }
1103
+ if (index + 1 >= nextCheckpoint) {
1104
+ nextCheckpoint += CHECKPOINT_UNITS;
1105
+ yield;
1106
+ }
1107
+ }
1108
+ }
1109
+
1110
+ function* thresholdInPlace(rgba, pixels, value, ctx) {
1111
+ let nextCheckpoint = CHECKPOINT_UNITS;
1112
+ for (let index = 0; index < pixels; index += 1) {
1113
+ const offset = index * 4;
1114
+ const gray = Math.round(0.299 * rgba[offset] + 0.587 * rgba[offset + 1] + 0.114 * rgba[offset + 2]);
1115
+ const binary = gray >= value ? 255 : 0;
1116
+ rgba[offset] = binary;
1117
+ rgba[offset + 1] = binary;
1118
+ rgba[offset + 2] = binary;
1119
+ if (index + 1 >= nextCheckpoint) {
1120
+ nextCheckpoint += CHECKPOINT_UNITS;
1121
+ yield;
1122
+ }
1123
+ }
1124
+ }
1125
+
1126
+ function* channelsInPlace(rgba, pixels, order, ctx) {
1127
+ if (order === 'rgba') return;
1128
+ let nextCheckpoint = CHECKPOINT_UNITS;
1129
+ for (let index = 0; index < pixels; index += 1) {
1130
+ const offset = index * 4;
1131
+ const r = rgba[offset];
1132
+ const g = rgba[offset + 1];
1133
+ const b = rgba[offset + 2];
1134
+ const a = rgba[offset + 3];
1135
+ if (order === 'bgra') {
1136
+ rgba[offset] = b;
1137
+ rgba[offset + 1] = g;
1138
+ rgba[offset + 2] = r;
1139
+ rgba[offset + 3] = a;
1140
+ } else {
1141
+ // argb: 输出 [a,r,g,b]
1142
+ rgba[offset] = a;
1143
+ rgba[offset + 1] = r;
1144
+ rgba[offset + 2] = g;
1145
+ rgba[offset + 3] = b;
1146
+ }
1147
+ if (index + 1 >= nextCheckpoint) {
1148
+ nextCheckpoint += CHECKPOINT_UNITS;
1149
+ yield;
1150
+ }
1151
+ }
1152
+ }
1153
+
1154
+ function* preprocessSteps(image, ops, ctx) {
1155
+ assertImage(image, 'image');
1156
+ const list = validatePreprocess(ops === null ? undefined : ops, 'preprocess');
1157
+ const width = image.width;
1158
+ const height = image.height;
1159
+ const pixels = width * height;
1160
+ const rgba = new Uint8Array(image.rgba);
1161
+ for (const op of list) {
1162
+ if (op.op === 'grayscale') yield* grayscaleInPlace(rgba, pixels, ctx);
1163
+ else if (op.op === 'blur') yield* blurInPlace(rgba, width, height, op.radius, ctx);
1164
+ else if (op.op === 'normalize') yield* normalizeInPlace(rgba, pixels, ctx);
1165
+ else if (op.op === 'threshold') yield* thresholdInPlace(rgba, pixels, op.value, ctx);
1166
+ else yield* channelsInPlace(rgba, pixels, op.order, ctx);
1167
+ }
1168
+ return { width, height, rgba };
1169
+ }
1170
+
1171
+ /** 预处理:ops 顺序生效,返回新 Image(不修改输入)。 */
1172
+ export function preprocessImage(image, ops, options = {}) {
1173
+ const ctx = createOpContext(options);
1174
+ return driveSync(preprocessSteps(image, ops, ctx), ctx, 'preprocess');
1175
+ }
1176
+
1177
+ /** preprocessImage 的让出事件循环版本。 */
1178
+ export async function preprocessImageAsync(image, ops, options = {}) {
1179
+ const ctx = createOpContext(options);
1180
+ return driveAsync(preprocessSteps(image, ops, ctx), ctx, 'preprocess');
1181
+ }
1182
+
1183
+ /* ------------------------------------------------------------------ */
1184
+ /* 标注(rect/cross/number/arrow,整数像素 raster,无字体依赖) */
1185
+ /* ------------------------------------------------------------------ */
1186
+
1187
+ function compositeSourceOver(rgba, offset, color) {
1188
+ const srcA = color[3] / 255;
1189
+ const dstA = rgba[offset + 3] / 255;
1190
+ const outA = srcA + dstA * (1 - srcA);
1191
+ if (outA <= 0) {
1192
+ rgba[offset] = 0;
1193
+ rgba[offset + 1] = 0;
1194
+ rgba[offset + 2] = 0;
1195
+ rgba[offset + 3] = 0;
1196
+ return;
1197
+ }
1198
+ rgba[offset] = clampByte(Math.round((color[0] * srcA + rgba[offset] * dstA * (1 - srcA)) / outA));
1199
+ rgba[offset + 1] = clampByte(Math.round((color[1] * srcA + rgba[offset + 1] * dstA * (1 - srcA)) / outA));
1200
+ rgba[offset + 2] = clampByte(Math.round((color[2] * srcA + rgba[offset + 2] * dstA * (1 - srcA)) / outA));
1201
+ rgba[offset + 3] = clampByte(Math.round(outA * 255));
1202
+ }
1203
+
1204
+ function brushOffsets(thickness) {
1205
+ const negative = Math.floor((thickness - 1) / 2);
1206
+ const positive = thickness - 1 - negative;
1207
+ return { negative, positive };
1208
+ }
1209
+
1210
+ function* annotateSteps(image, annotations, ctx) {
1211
+ assertImage(image, 'image');
1212
+ const list = validateAnnotations(annotations === null ? undefined : annotations, 'annotations');
1213
+ const width = image.width;
1214
+ const height = image.height;
1215
+ const rgba = new Uint8Array(image.rgba);
1216
+ if (!list.length) return { width, height, rgba };
1217
+
1218
+ const mask = new Uint8Array(width * height);
1219
+ const touched = [];
1220
+ let paintedSinceCheck = 0;
1221
+
1222
+ const paint = (x, y) => {
1223
+ if (x < 0 || y < 0 || x >= width || y >= height) return;
1224
+ const index = y * width + x;
1225
+ if (mask[index]) return;
1226
+ mask[index] = 1;
1227
+ touched.push(index);
1228
+ paintedSinceCheck += 1;
1229
+ };
1230
+
1231
+ for (const annotation of list) {
1232
+ const { negative, positive } = brushOffsets(annotation.thickness);
1233
+ touched.length = 0;
1234
+ paintedSinceCheck = 0;
1235
+
1236
+ // 方形笔刷:以线中心向两侧扩张,偶数厚度多余像素放正方向(x/y 两个轴同规则)。
1237
+ const paintBrush = (x, y) => {
1238
+ for (let by = -negative; by <= positive; by += 1) {
1239
+ for (let bx = -negative; bx <= positive; bx += 1) paint(x + bx, y + by);
1240
+ }
1241
+ };
1242
+
1243
+ if (annotation.kind === 'rect') {
1244
+ const region = annotation.region;
1245
+ if (region.x + region.width > width || region.y + region.height > height) {
1246
+ throw invalidArgument('region', 'out-of-bounds', 'annotateImage');
1247
+ }
1248
+ const right = region.x + region.width - 1;
1249
+ const bottom = region.y + region.height - 1;
1250
+ for (let x = region.x; x <= right; x += 1) {
1251
+ paintBrush(x, region.y);
1252
+ paintBrush(x, bottom);
1253
+ if (paintedSinceCheck >= CHECKPOINT_UNITS) {
1254
+ paintedSinceCheck = 0;
1255
+ yield;
1256
+ }
1257
+ }
1258
+ for (let y = region.y; y <= bottom; y += 1) {
1259
+ paintBrush(region.x, y);
1260
+ paintBrush(right, y);
1261
+ if (paintedSinceCheck >= CHECKPOINT_UNITS) {
1262
+ paintedSinceCheck = 0;
1263
+ yield;
1264
+ }
1265
+ }
1266
+ } else if (annotation.kind === 'cross') {
1267
+ const point = annotation.point;
1268
+ if (point.x >= width || point.y >= height) {
1269
+ throw invalidArgument('point', 'out-of-bounds', 'annotateImage');
1270
+ }
1271
+ const half = Math.floor((annotation.size - 1) / 2);
1272
+ const startX = point.x - half;
1273
+ const endX = startX + annotation.size - 1;
1274
+ const startY = point.y - half;
1275
+ const endY = startY + annotation.size - 1;
1276
+ for (let x = startX; x <= endX; x += 1) {
1277
+ paintBrush(x, point.y);
1278
+ if (paintedSinceCheck >= CHECKPOINT_UNITS) {
1279
+ paintedSinceCheck = 0;
1280
+ yield;
1281
+ }
1282
+ }
1283
+ for (let y = startY; y <= endY; y += 1) {
1284
+ paintBrush(point.x, y);
1285
+ if (paintedSinceCheck >= CHECKPOINT_UNITS) {
1286
+ paintedSinceCheck = 0;
1287
+ yield;
1288
+ }
1289
+ }
1290
+ } else if (annotation.kind === 'number') {
1291
+ const point = annotation.point;
1292
+ if (point.x >= width || point.y >= height) {
1293
+ throw invalidArgument('point', 'out-of-bounds', 'annotateImage');
1294
+ }
1295
+ const digits = String(annotation.number);
1296
+ for (let digitIndex = 0; digitIndex < digits.length; digitIndex += 1) {
1297
+ const bitmap = DIGIT_BITMAPS[digits[digitIndex]];
1298
+ const originX = point.x + digitIndex * 7; // 3×5 位图 2 倍 nearest = 6px,字间 1px
1299
+ for (let row = 0; row < 5; row += 1) {
1300
+ for (let col = 0; col < 3; col += 1) {
1301
+ if (bitmap[row][col] !== '1') continue;
1302
+ const px = originX + col * 2;
1303
+ const py = point.y + row * 2;
1304
+ paint(px, py);
1305
+ paint(px + 1, py);
1306
+ paint(px, py + 1);
1307
+ paint(px + 1, py + 1);
1308
+ }
1309
+ }
1310
+ }
1311
+ } else {
1312
+ const point = annotation.point;
1313
+ const to = annotation.to;
1314
+ if (point.x >= width || point.y >= height || to.x >= width || to.y >= height) {
1315
+ throw invalidArgument('to', 'out-of-bounds', 'annotateImage');
1316
+ }
1317
+ const drawLine = function* drawLine(x0, y0, x1, y1) {
1318
+ let cx = x0;
1319
+ let cy = y0;
1320
+ const dx = Math.abs(x1 - x0);
1321
+ const sx = x0 < x1 ? 1 : -1;
1322
+ const dy = -Math.abs(y1 - y0);
1323
+ const sy = y0 < y1 ? 1 : -1;
1324
+ let err = dx + dy;
1325
+ for (;;) {
1326
+ paintBrush(cx, cy);
1327
+ if (paintedSinceCheck >= CHECKPOINT_UNITS) {
1328
+ paintedSinceCheck = 0;
1329
+ yield;
1330
+ }
1331
+ if (cx === x1 && cy === y1) break;
1332
+ const e2 = 2 * err;
1333
+ if (e2 >= dy) {
1334
+ err += dy;
1335
+ cx += sx;
1336
+ }
1337
+ if (e2 <= dx) {
1338
+ err += dx;
1339
+ cy += sy;
1340
+ }
1341
+ }
1342
+ };
1343
+ yield* drawLine(point.x, point.y, to.x, to.y);
1344
+ const dx = to.x - point.x;
1345
+ const dy = to.y - point.y;
1346
+ const length = Math.hypot(dx, dy);
1347
+ if (length > 0) {
1348
+ const ux = dx / length;
1349
+ const uy = dy / length;
1350
+ const cos45 = Math.SQRT1_2;
1351
+ const sin45 = Math.SQRT1_2;
1352
+ // 箭翼从端点向主线反方向张开 ±45°、长度 6(端点 round 后 clamp)。
1353
+ const wingDirs = [
1354
+ [-ux * cos45 + uy * sin45, -ux * sin45 - uy * cos45],
1355
+ [-ux * cos45 - uy * sin45, ux * sin45 - uy * cos45],
1356
+ ];
1357
+ for (const [wx, wy] of wingDirs) {
1358
+ const endX = clampInt(Math.round(to.x + 6 * wx), 0, width - 1);
1359
+ const endY = clampInt(Math.round(to.y + 6 * wy), 0, height - 1);
1360
+ yield* drawLine(to.x, to.y, endX, endY);
1361
+ }
1362
+ }
1363
+ }
1364
+
1365
+ for (const index of touched) {
1366
+ compositeSourceOver(rgba, index * 4, annotation.color);
1367
+ mask[index] = 0;
1368
+ }
1369
+ touched.length = 0;
1370
+ // 单个 annotation 的绘制受图幅/厚度约束;每个 annotation 结束检查一次取消与预算。
1371
+ yield;
1372
+ }
1373
+ return { width, height, rgba };
1374
+ }
1375
+
1376
+ /** 标注:四类确定性 raster,返回新 Image(不修改输入)。 */
1377
+ export function annotateImage(image, annotations, options = {}) {
1378
+ const ctx = createOpContext(options);
1379
+ return driveSync(annotateSteps(image, annotations, ctx), ctx, 'annotate');
1380
+ }
1381
+
1382
+ /** annotateImage 的让出事件循环版本。 */
1383
+ export async function annotateImageAsync(image, annotations, options = {}) {
1384
+ const ctx = createOpContext(options);
1385
+ return driveAsync(annotateSteps(image, annotations, ctx), ctx, 'annotate');
1386
+ }
1387
+
1388
+ /* ------------------------------------------------------------------ */
1389
+ /* 灰度 / Sobel 边缘 */
1390
+ /* ------------------------------------------------------------------ */
1391
+
1392
+ function whiteCompositedLuma(rgba, offset) {
1393
+ const alpha = rgba[offset + 3];
1394
+ const r = 255 + (rgba[offset] - 255) * (alpha / 255);
1395
+ const g = 255 + (rgba[offset + 1] - 255) * (alpha / 255);
1396
+ const b = 255 + (rgba[offset + 2] - 255) * (alpha / 255);
1397
+ return 0.29889531 * r + 0.58662247 * g + 0.11448223 * b;
1398
+ }
1399
+
1400
+ function whiteCompositedGray(rgba, offset) {
1401
+ const alpha = rgba[offset + 3];
1402
+ const r = 255 + (rgba[offset] - 255) * (alpha / 255);
1403
+ const g = 255 + (rgba[offset + 1] - 255) * (alpha / 255);
1404
+ const b = 255 + (rgba[offset + 2] - 255) * (alpha / 255);
1405
+ return Math.round(0.299 * r + 0.587 * g + 0.114 * b);
1406
+ }
1407
+
1408
+ function* edgeMaskSteps(image, threshold, ctx) {
1409
+ const width = image.width;
1410
+ const height = image.height;
1411
+ const rgba = image.rgba;
1412
+ const edges = new Uint8Array(width * height);
1413
+ if (width < 3 || height < 3) return edges;
1414
+ let rowA = new Uint8Array(width);
1415
+ let rowB = new Uint8Array(width);
1416
+ let rowC = new Uint8Array(width);
1417
+ const fillRow = (y, target) => {
1418
+ const base = y * width * 4;
1419
+ for (let x = 0; x < width; x += 1) target[x] = whiteCompositedGray(rgba, base + x * 4);
1420
+ };
1421
+ fillRow(0, rowA);
1422
+ fillRow(1, rowB);
1423
+ let nextCheckpoint = CHECKPOINT_UNITS;
1424
+ for (let y = 1; y < height - 1; y += 1) {
1425
+ fillRow(y + 1, rowC);
1426
+ const rowOut = y * width;
1427
+ for (let x = 1; x < width - 1; x += 1) {
1428
+ const gx = (rowC[x + 1] + 2 * rowC[x] + rowC[x - 1]) - (rowA[x + 1] + 2 * rowA[x] + rowA[x - 1]);
1429
+ const gy = (rowA[x - 1] + 2 * rowB[x - 1] + rowC[x - 1]) - (rowA[x + 1] + 2 * rowB[x + 1] + rowC[x + 1]);
1430
+ const magnitude = Math.min(255, Math.round((Math.abs(gx) + Math.abs(gy)) / 8));
1431
+ if (magnitude >= threshold && magnitude > 0) edges[rowOut + x] = 1;
1432
+ }
1433
+ const tmp = rowA;
1434
+ rowA = rowB;
1435
+ rowB = rowC;
1436
+ rowC = tmp;
1437
+ if ((y + 1) * width >= nextCheckpoint) {
1438
+ nextCheckpoint += CHECKPOINT_UNITS;
1439
+ yield;
1440
+ }
1441
+ }
1442
+ return edges;
1443
+ }
1444
+
1445
+ /** Sobel 边缘 mask(白底合成灰度,边界一圈为 0),1=edge。 */
1446
+ export function edgeMask(image, threshold = 32, options = {}) {
1447
+ assertImage(image, 'image');
1448
+ if (!Number.isInteger(threshold) || threshold < 0 || threshold > 255) {
1449
+ throw invalidArgument('threshold', 'invalid-threshold', 'edgeMask');
1450
+ }
1451
+ const ctx = createOpContext(options);
1452
+ return driveSync(edgeMaskSteps(image, threshold, ctx), ctx, 'edgeMask');
1453
+ }
1454
+
1455
+ /** edgeMask 的让出事件循环版本。 */
1456
+ export async function edgeMaskAsync(image, threshold = 32, options = {}) {
1457
+ assertImage(image, 'image');
1458
+ if (!Number.isInteger(threshold) || threshold < 0 || threshold > 255) {
1459
+ throw invalidArgument('threshold', 'invalid-threshold', 'edgeMask');
1460
+ }
1461
+ const ctx = createOpContext(options);
1462
+ return driveAsync(edgeMaskSteps(image, threshold, ctx), ctx, 'edgeMask');
1463
+ }
1464
+
1465
+ /* ------------------------------------------------------------------ */
1466
+ /* 全量统计 */
1467
+ /* ------------------------------------------------------------------ */
1468
+
1469
+ function* analyzeSteps(image, ctx) {
1470
+ assertImage(image, 'image');
1471
+ const width = image.width;
1472
+ const height = image.height;
1473
+ const pixels = width * height;
1474
+ const rgba = image.rgba;
1475
+ let transparentPixels = 0;
1476
+ let opaquePixels = 0;
1477
+ let sumR = 0;
1478
+ let sumG = 0;
1479
+ let sumB = 0;
1480
+ let sumA = 0;
1481
+ let minR = 255;
1482
+ let minG = 255;
1483
+ let minB = 255;
1484
+ let minA = 255;
1485
+ let maxR = 0;
1486
+ let maxG = 0;
1487
+ let maxB = 0;
1488
+ let maxA = 0;
1489
+ let uniform = true;
1490
+ const first = [rgba[0], rgba[1], rgba[2], rgba[3]];
1491
+ const buckets = new Map();
1492
+ let nextCheckpoint = CHECKPOINT_UNITS;
1493
+ for (let index = 0; index < pixels; index += 1) {
1494
+ const offset = index * 4;
1495
+ const r = rgba[offset];
1496
+ const g = rgba[offset + 1];
1497
+ const b = rgba[offset + 2];
1498
+ const a = rgba[offset + 3];
1499
+ if (a === 0) transparentPixels += 1;
1500
+ else if (a === 255) opaquePixels += 1;
1501
+ sumR += r;
1502
+ sumG += g;
1503
+ sumB += b;
1504
+ sumA += a;
1505
+ if (r < minR) minR = r;
1506
+ if (g < minG) minG = g;
1507
+ if (b < minB) minB = b;
1508
+ if (a < minA) minA = a;
1509
+ if (r > maxR) maxR = r;
1510
+ if (g > maxG) maxG = g;
1511
+ if (b > maxB) maxB = b;
1512
+ if (a > maxA) maxA = a;
1513
+ if (uniform && (r !== first[0] || g !== first[1] || b !== first[2] || a !== first[3])) {
1514
+ uniform = false;
1515
+ }
1516
+ const qr = Math.floor(r / 16) * 16;
1517
+ const qg = Math.floor(g / 16) * 16;
1518
+ const qb = Math.floor(b / 16) * 16;
1519
+ const qa = Math.floor(a / 16) * 16;
1520
+ const key = (((qr << 12) | (qg << 8) | (qb << 4) | (qa >> 4)) >>> 0);
1521
+ const bucket = buckets.get(key);
1522
+ if (bucket) bucket.count += 1;
1523
+ else buckets.set(key, { rgba: [qr, qg, qb, qa], count: 1 });
1524
+ if (index + 1 >= nextCheckpoint) {
1525
+ nextCheckpoint += CHECKPOINT_UNITS;
1526
+ yield;
1527
+ }
1528
+ }
1529
+
1530
+ const dominantColors = [...buckets.values()]
1531
+ .sort((left, right) => {
1532
+ if (right.count !== left.count) return right.count - left.count;
1533
+ for (let channel = 0; channel < 4; channel += 1) {
1534
+ if (left.rgba[channel] !== right.rgba[channel]) return left.rgba[channel] - right.rgba[channel];
1535
+ }
1536
+ return 0;
1537
+ })
1538
+ .slice(0, 8)
1539
+ .map((bucket) => ({
1540
+ rgba: bucket.rgba,
1541
+ count: bucket.count,
1542
+ fraction: bucket.count / pixels,
1543
+ }));
1544
+
1545
+ const edges = yield* edgeMaskSteps(image, 32, ctx);
1546
+ let edgePixels = 0;
1547
+ for (let index = 0; index < pixels; index += 1) {
1548
+ if (edges[index]) edgePixels += 1;
1549
+ if ((index + 1) % CHECKPOINT_UNITS === 0) yield;
1550
+ }
1551
+
1552
+ return {
1553
+ pixelCount: pixels,
1554
+ transparentPixels,
1555
+ opaquePixels,
1556
+ averageRgba: [sumR / pixels, sumG / pixels, sumB / pixels, sumA / pixels],
1557
+ minRgba: [minR, minG, minB, minA],
1558
+ maxRgba: [maxR, maxG, maxB, maxA],
1559
+ uniform,
1560
+ dominantColors,
1561
+ edgePixels,
1562
+ edgeRatio: edgePixels / pixels,
1563
+ };
1564
+ }
1565
+
1566
+ /** 全量统计(契约 §2.2 Analysis)。 */
1567
+ export function analyzeImage(image, options = {}) {
1568
+ const ctx = createOpContext(options);
1569
+ return driveSync(analyzeSteps(image, ctx), ctx, 'analyze');
1570
+ }
1571
+
1572
+ /** analyzeImage 的让出事件循环版本。 */
1573
+ export async function analyzeImageAsync(image, options = {}) {
1574
+ const ctx = createOpContext(options);
1575
+ return driveAsync(analyzeSteps(image, ctx), ctx, 'analyze');
1576
+ }
1577
+
1578
+ /* ------------------------------------------------------------------ */
1579
+ /* YIQ 差异(yiq-v1) */
1580
+ /* ------------------------------------------------------------------ */
1581
+
1582
+ const YIQ_DELTA_SCALE = 35215;
1583
+
1584
+ function yiqDeltaAt(beforeRgba, afterRgba, offset) {
1585
+ const aBefore = beforeRgba[offset + 3];
1586
+ const aAfter = afterRgba[offset + 3];
1587
+ const r1 = 255 + (beforeRgba[offset] - 255) * (aBefore / 255);
1588
+ const g1 = 255 + (beforeRgba[offset + 1] - 255) * (aBefore / 255);
1589
+ const b1 = 255 + (beforeRgba[offset + 2] - 255) * (aBefore / 255);
1590
+ const r2 = 255 + (afterRgba[offset] - 255) * (aAfter / 255);
1591
+ const g2 = 255 + (afterRgba[offset + 1] - 255) * (aAfter / 255);
1592
+ const b2 = 255 + (afterRgba[offset + 2] - 255) * (aAfter / 255);
1593
+ const dR = r1 - r2;
1594
+ const dG = g1 - g2;
1595
+ const dB = b1 - b2;
1596
+ const y = 0.29889531 * dR + 0.58662247 * dG + 0.11448223 * dB;
1597
+ const i = 0.59597799 * dR - 0.27417610 * dG - 0.32180189 * dB;
1598
+ const q = 0.21147017 * dR - 0.52261711 * dG + 0.31114694 * dB;
1599
+ return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
1600
+ }
1601
+
1602
+ function countEqualRgbaNeighbors(rgba, width, height, x, y) {
1603
+ const offset = (y * width + x) * 4;
1604
+ const r = rgba[offset];
1605
+ const g = rgba[offset + 1];
1606
+ const b = rgba[offset + 2];
1607
+ const a = rgba[offset + 3];
1608
+ let count = 0;
1609
+ const yStart = Math.max(0, y - 1);
1610
+ const yEnd = Math.min(height - 1, y + 1);
1611
+ const xStart = Math.max(0, x - 1);
1612
+ const xEnd = Math.min(width - 1, x + 1);
1613
+ for (let ny = yStart; ny <= yEnd; ny += 1) {
1614
+ for (let nx = xStart; nx <= xEnd; nx += 1) {
1615
+ if (nx === x && ny === y) continue;
1616
+ const other = (ny * width + nx) * 4;
1617
+ if (rgba[other] === r && rgba[other + 1] === g && rgba[other + 2] === b && rgba[other + 3] === a) {
1618
+ count += 1;
1619
+ }
1620
+ }
1621
+ }
1622
+ return count;
1623
+ }
1624
+
1625
+ function aaForImage(rgba, otherRgba, width, height, x, y) {
1626
+ const centerLuma = whiteCompositedLuma(rgba, (y * width + x) * 4);
1627
+ const onBorder = x === 0 || y === 0 || x === width - 1 || y === height - 1;
1628
+ let equal = onBorder ? 1 : 0;
1629
+ let minLuma = Infinity;
1630
+ let maxLuma = -Infinity;
1631
+ let minPos = null;
1632
+ let maxPos = null;
1633
+ const yStart = Math.max(0, y - 1);
1634
+ const yEnd = Math.min(height - 1, y + 1);
1635
+ const xStart = Math.max(0, x - 1);
1636
+ const xEnd = Math.min(width - 1, x + 1);
1637
+ for (let ny = yStart; ny <= yEnd; ny += 1) {
1638
+ for (let nx = xStart; nx <= xEnd; nx += 1) {
1639
+ if (nx === x && ny === y) continue;
1640
+ const luma = whiteCompositedLuma(rgba, (ny * width + nx) * 4);
1641
+ if (luma === centerLuma) {
1642
+ equal += 1;
1643
+ if (equal > 2) return false;
1644
+ } else if (luma < centerLuma) {
1645
+ if (luma < minLuma) {
1646
+ minLuma = luma;
1647
+ minPos = { x: nx, y: ny };
1648
+ }
1649
+ } else if (luma > maxLuma) {
1650
+ maxLuma = luma;
1651
+ maxPos = { x: nx, y: ny };
1652
+ }
1653
+ }
1654
+ }
1655
+ if (!minPos || !maxPos) return false;
1656
+ for (const position of [minPos, maxPos]) {
1657
+ if (countEqualRgbaNeighbors(rgba, width, height, position.x, position.y) >= 3
1658
+ && countEqualRgbaNeighbors(otherRgba, width, height, position.x, position.y) >= 3) {
1659
+ return true;
1660
+ }
1661
+ }
1662
+ return false;
1663
+ }
1664
+
1665
+ function isAntialiasedPair(before, after, width, height, x, y) {
1666
+ return aaForImage(before.rgba, after.rgba, width, height, x, y)
1667
+ || aaForImage(after.rgba, before.rgba, width, height, x, y);
1668
+ }
1669
+
1670
+ /** 区域排序:area 降序、y 升序、x 升序、height 升序、width 升序(<0 表示 left 更靠前)。 */
1671
+ function compareRegions(left, right) {
1672
+ if (right.area !== left.area) return right.area - left.area;
1673
+ if (left.y !== right.y) return left.y - right.y;
1674
+ if (left.x !== right.x) return left.x - right.x;
1675
+ if (left.height !== right.height) return left.height - right.height;
1676
+ return left.width - right.width;
1677
+ }
1678
+
1679
+ /** 只保留排序最前的 100 个区域(流式插入),避免病态差异图撑爆内存。 */
1680
+ function insertTopRegion(top, candidate) {
1681
+ const LIMIT = 100;
1682
+ if (top.length >= LIMIT && compareRegions(candidate, top[top.length - 1]) >= 0) return;
1683
+ let low = 0;
1684
+ let high = top.length >= LIMIT ? top.length - 1 : top.length;
1685
+ while (low < high) {
1686
+ const mid = (low + high) >> 1;
1687
+ if (compareRegions(candidate, top[mid]) < 0) high = mid;
1688
+ else low = mid + 1;
1689
+ }
1690
+ top.splice(low, 0, candidate);
1691
+ if (top.length > LIMIT) top.pop();
1692
+ }
1693
+
1694
+ function* diffRegionSteps(diffMap, region, minRegionPixels, ctx) {
1695
+ const width = region.width;
1696
+ const height = region.height;
1697
+ const total = width * height;
1698
+ const visited = new Uint8Array(total);
1699
+ let stack = new Int32Array(4096);
1700
+ const found = [];
1701
+ let regionCount = 0;
1702
+ let sinceCheckpoint = 0;
1703
+ for (let index = 0; index < total; index += 1) {
1704
+ if (diffMap[index] !== 1 || visited[index]) {
1705
+ sinceCheckpoint += 1;
1706
+ if (sinceCheckpoint >= CHECKPOINT_UNITS) {
1707
+ sinceCheckpoint = 0;
1708
+ yield;
1709
+ }
1710
+ continue;
1711
+ }
1712
+ let top = 0;
1713
+ stack[top] = index;
1714
+ top += 1;
1715
+ visited[index] = 1;
1716
+ let area = 0;
1717
+ let minX = width;
1718
+ let minY = height;
1719
+ let maxX = -1;
1720
+ let maxY = -1;
1721
+ while (top > 0) {
1722
+ top -= 1;
1723
+ const current = stack[top];
1724
+ const localX = current % width;
1725
+ const localY = (current - localX) / width;
1726
+ area += 1;
1727
+ if (localX < minX) minX = localX;
1728
+ if (localX > maxX) maxX = localX;
1729
+ if (localY < minY) minY = localY;
1730
+ if (localY > maxY) maxY = localY;
1731
+ for (let dy = -1; dy <= 1; dy += 1) {
1732
+ const ny = localY + dy;
1733
+ if (ny < 0 || ny >= height) continue;
1734
+ for (let dx = -1; dx <= 1; dx += 1) {
1735
+ if (dx === 0 && dy === 0) continue;
1736
+ const nx = localX + dx;
1737
+ if (nx < 0 || nx >= width) continue;
1738
+ const neighbor = ny * width + nx;
1739
+ if (diffMap[neighbor] === 1 && !visited[neighbor]) {
1740
+ visited[neighbor] = 1;
1741
+ if (top >= stack.length) {
1742
+ const grown = new Int32Array(stack.length * 2);
1743
+ grown.set(stack);
1744
+ stack = grown;
1745
+ }
1746
+ stack[top] = neighbor;
1747
+ top += 1;
1748
+ }
1749
+ }
1750
+ }
1751
+ sinceCheckpoint += 1;
1752
+ if (sinceCheckpoint >= CHECKPOINT_UNITS) {
1753
+ sinceCheckpoint = 0;
1754
+ yield;
1755
+ }
1756
+ }
1757
+ if (area >= minRegionPixels) {
1758
+ regionCount += 1;
1759
+ insertTopRegion(found, {
1760
+ area,
1761
+ x: region.x + minX,
1762
+ y: region.y + minY,
1763
+ width: maxX - minX + 1,
1764
+ height: maxY - minY + 1,
1765
+ });
1766
+ }
1767
+ sinceCheckpoint += 1;
1768
+ if (sinceCheckpoint >= CHECKPOINT_UNITS) {
1769
+ sinceCheckpoint = 0;
1770
+ yield;
1771
+ }
1772
+ }
1773
+ return { regions: found, count: regionCount };
1774
+ }
1775
+
1776
+ function* diffSteps(beforeImage, afterImage, params, ctx) {
1777
+ assertImage(beforeImage, 'before');
1778
+ assertImage(afterImage, 'after');
1779
+ const width = beforeImage.width;
1780
+ const height = beforeImage.height;
1781
+ if (afterImage.width !== width || afterImage.height !== height) {
1782
+ throw new BrowserError('VISION_SIZE_MISMATCH', 'compare 两图像素尺寸不一致', {
1783
+ before: { width, height },
1784
+ after: { width: afterImage.width, height: afterImage.height },
1785
+ });
1786
+ }
1787
+ const region = params.region === undefined || params.region === null
1788
+ ? { x: 0, y: 0, width, height }
1789
+ : validatePixelRect(params.region, 'region');
1790
+ if (region.x + region.width > width || region.y + region.height > height) {
1791
+ throw invalidArgument('region', 'out-of-bounds', 'diffImages');
1792
+ }
1793
+ const masks = params.masks === undefined || params.masks === null ? [] : validateMasks(params.masks, 'masks');
1794
+ for (let index = 0; index < masks.length; index += 1) {
1795
+ const maskRegion = masks[index].region;
1796
+ if (maskRegion.x + maskRegion.width > width || maskRegion.y + maskRegion.height > height) {
1797
+ throw invalidArgument(`masks[${index}].region`, 'out-of-bounds', 'diffImages');
1798
+ }
1799
+ }
1800
+ const options = validateDiffOptions(params.options === null ? undefined : params.options, 'options');
1801
+
1802
+ const roiPixels = region.width * region.height;
1803
+ const estimate = 16 * width * height + 7 * roiPixels
1804
+ + Math.min(4 * width * height, VISION_LIMITS.maxOutputBytes);
1805
+ if (estimate > VISION_LIMITS.maxWorkingSetBytes) {
1806
+ throw visionLimitExceeded(
1807
+ 'maxWorkingSetBytes',
1808
+ estimate,
1809
+ VISION_LIMITS.maxWorkingSetBytes,
1810
+ 'compare 工作集超限',
1811
+ );
1812
+ }
1813
+
1814
+ const maskMap = new Uint8Array(roiPixels);
1815
+ let maskedPixels = 0;
1816
+ let maskWork = 0;
1817
+ for (const mask of masks) {
1818
+ const startX = Math.max(mask.region.x, region.x);
1819
+ const startY = Math.max(mask.region.y, region.y);
1820
+ const endX = Math.min(mask.region.x + mask.region.width, region.x + region.width);
1821
+ const endY = Math.min(mask.region.y + mask.region.height, region.y + region.height);
1822
+ for (let gy = startY; gy < endY; gy += 1) {
1823
+ for (let gx = startX; gx < endX; gx += 1) {
1824
+ const roiIndex = (gy - region.y) * region.width + (gx - region.x);
1825
+ if (!maskMap[roiIndex]) {
1826
+ maskMap[roiIndex] = 1;
1827
+ maskedPixels += 1;
1828
+ }
1829
+ }
1830
+ maskWork += endX - startX;
1831
+ if (maskWork >= CHECKPOINT_UNITS) {
1832
+ maskWork = 0;
1833
+ yield;
1834
+ }
1835
+ }
1836
+ }
1837
+
1838
+ const beforeRgba = beforeImage.rgba;
1839
+ const afterRgba = afterImage.rgba;
1840
+ const highlight = new Uint8Array(width * height * 4);
1841
+ const diffMap = new Uint8Array(roiPixels);
1842
+ const aaMap = new Uint8Array(roiPixels);
1843
+ const thresholdSquared = YIQ_DELTA_SCALE * options.threshold * options.threshold;
1844
+ let diffPixels = 0;
1845
+ let aaPixels = 0;
1846
+ let nextCheckpoint = CHECKPOINT_UNITS;
1847
+
1848
+ for (let y = 0; y < height; y += 1) {
1849
+ const rowBase = y * width * 4;
1850
+ for (let x = 0; x < width; x += 1) {
1851
+ const offset = rowBase + x * 4;
1852
+ const out = offset;
1853
+ const lumaBefore = whiteCompositedLuma(beforeRgba, offset);
1854
+ const gray = clampByte(Math.round(255 * 0.9 + lumaBefore * 0.1));
1855
+ highlight[out] = gray;
1856
+ highlight[out + 1] = gray;
1857
+ highlight[out + 2] = gray;
1858
+ highlight[out + 3] = 255;
1859
+ if (x < region.x || x >= region.x + region.width || y < region.y || y >= region.y + region.height) {
1860
+ continue;
1861
+ }
1862
+ const roiIndex = (y - region.y) * region.width + (x - region.x);
1863
+ if (maskMap[roiIndex]) {
1864
+ highlight[out] = 128;
1865
+ highlight[out + 1] = 128;
1866
+ highlight[out + 2] = 128;
1867
+ continue;
1868
+ }
1869
+ if (beforeRgba[offset] === afterRgba[offset]
1870
+ && beforeRgba[offset + 1] === afterRgba[offset + 1]
1871
+ && beforeRgba[offset + 2] === afterRgba[offset + 2]
1872
+ && beforeRgba[offset + 3] === afterRgba[offset + 3]) {
1873
+ continue;
1874
+ }
1875
+ const delta = yiqDeltaAt(beforeRgba, afterRgba, offset);
1876
+ if (!(delta > thresholdSquared)) continue;
1877
+ if (!options.includeAA && isAntialiasedPair(beforeImage, afterImage, width, height, x, y)) {
1878
+ aaPixels += 1;
1879
+ aaMap[roiIndex] = 1;
1880
+ highlight[out] = 255;
1881
+ highlight[out + 1] = 255;
1882
+ highlight[out + 2] = 0;
1883
+ continue;
1884
+ }
1885
+ diffPixels += 1;
1886
+ diffMap[roiIndex] = 1;
1887
+ highlight[out] = 255;
1888
+ highlight[out + 1] = 0;
1889
+ highlight[out + 2] = 0;
1890
+ }
1891
+ if ((y + 1) * width >= nextCheckpoint) {
1892
+ nextCheckpoint += CHECKPOINT_UNITS;
1893
+ yield;
1894
+ }
1895
+ }
1896
+
1897
+ const totalPixels = roiPixels;
1898
+ const comparedPixels = totalPixels - maskedPixels;
1899
+ if (comparedPixels <= 0) {
1900
+ throw new BrowserError('VISION_EMPTY_COMPARISON', 'ROI 内所有像素都被 mask 排除,无法比较');
1901
+ }
1902
+
1903
+ const found = yield* diffRegionSteps(diffMap, region, options.minRegionPixels, ctx);
1904
+ const regionCount = found.count;
1905
+ const regionsTruncated = regionCount > 100;
1906
+ const selected = found.regions;
1907
+
1908
+ // 高亮 bbox 内边框(1px,按排序绘制;统计已在绘制前完成)。
1909
+ for (const item of selected) {
1910
+ const right = item.x + item.width - 1;
1911
+ const bottom = item.y + item.height - 1;
1912
+ for (let x = item.x; x <= right; x += 1) {
1913
+ const topOffset = (item.y * width + x) * 4;
1914
+ highlight[topOffset] = 0;
1915
+ highlight[topOffset + 1] = 128;
1916
+ highlight[topOffset + 2] = 255;
1917
+ highlight[topOffset + 3] = 255;
1918
+ const bottomOffset = (bottom * width + x) * 4;
1919
+ highlight[bottomOffset] = 0;
1920
+ highlight[bottomOffset + 1] = 128;
1921
+ highlight[bottomOffset + 2] = 255;
1922
+ highlight[bottomOffset + 3] = 255;
1923
+ }
1924
+ for (let y = item.y; y <= bottom; y += 1) {
1925
+ const leftOffset = (y * width + item.x) * 4;
1926
+ highlight[leftOffset] = 0;
1927
+ highlight[leftOffset + 1] = 128;
1928
+ highlight[leftOffset + 2] = 255;
1929
+ highlight[leftOffset + 3] = 255;
1930
+ const rightOffset = (y * width + right) * 4;
1931
+ highlight[rightOffset] = 0;
1932
+ highlight[rightOffset + 1] = 128;
1933
+ highlight[rightOffset + 2] = 255;
1934
+ highlight[rightOffset + 3] = 255;
1935
+ }
1936
+ }
1937
+
1938
+ const highlightPng = yield* encodePngSteps({ width, height, rgba: highlight }, ctx);
1939
+ const regions = selected.map((item, index) => ({
1940
+ id: `r${index + 1}`,
1941
+ area: item.area,
1942
+ imagePixels: { x: item.x, y: item.y, width: item.width, height: item.height },
1943
+ }));
1944
+
1945
+ return {
1946
+ metrics: {
1947
+ totalPixels,
1948
+ maskedPixels,
1949
+ comparedPixels,
1950
+ diffPixels,
1951
+ aaPixels,
1952
+ diffRatio: diffPixels / comparedPixels,
1953
+ similarity: 1 - diffPixels / comparedPixels,
1954
+ },
1955
+ regions,
1956
+ regionCount,
1957
+ regionsTruncated,
1958
+ highlight: highlightPng,
1959
+ };
1960
+ }
1961
+
1962
+ /**
1963
+ * YIQ 差异(yiq-v1):白底合成、严格 >、AA 3×3 排除、mask 并集、分母 C=N-M、
1964
+ * 8 邻接连通域、完整尺寸 annotated diff PNG。
1965
+ */
1966
+ export function diffImages(beforeImage, afterImage, params = {}) {
1967
+ const ctx = createOpContext(params);
1968
+ return driveSync(diffSteps(beforeImage, afterImage, params, ctx), ctx, 'diff');
1969
+ }
1970
+
1971
+ /** diffImages 的让出事件循环版本。 */
1972
+ export async function diffImagesAsync(beforeImage, afterImage, params = {}) {
1973
+ const ctx = createOpContext(params);
1974
+ return driveAsync(diffSteps(beforeImage, afterImage, params, ctx), ctx, 'diff');
1975
+ }
1976
+
1977
+ /* ------------------------------------------------------------------ */
1978
+ /* 识别(color/components/edges/template) */
1979
+ /* ------------------------------------------------------------------ */
1980
+
1981
+ function* componentSteps(foreground, width, height, minArea, ctx) {
1982
+ const total = width * height;
1983
+ let stack = new Int32Array(4096);
1984
+ const found = [];
1985
+ let sinceCheckpoint = 0;
1986
+ for (let index = 0; index < total; index += 1) {
1987
+ if (foreground[index] !== 1) {
1988
+ sinceCheckpoint += 1;
1989
+ if (sinceCheckpoint >= CHECKPOINT_UNITS) {
1990
+ sinceCheckpoint = 0;
1991
+ yield;
1992
+ }
1993
+ continue;
1994
+ }
1995
+ let top = 0;
1996
+ stack[top] = index;
1997
+ top += 1;
1998
+ foreground[index] = 2;
1999
+ let area = 0;
2000
+ let minX = width;
2001
+ let minY = height;
2002
+ let maxX = -1;
2003
+ let maxY = -1;
2004
+ let sumX = 0;
2005
+ let sumY = 0;
2006
+ while (top > 0) {
2007
+ top -= 1;
2008
+ const current = stack[top];
2009
+ const localX = current % width;
2010
+ const localY = (current - localX) / width;
2011
+ area += 1;
2012
+ sumX += localX;
2013
+ sumY += localY;
2014
+ if (localX < minX) minX = localX;
2015
+ if (localX > maxX) maxX = localX;
2016
+ if (localY < minY) minY = localY;
2017
+ if (localY > maxY) maxY = localY;
2018
+ for (let dy = -1; dy <= 1; dy += 1) {
2019
+ const ny = localY + dy;
2020
+ if (ny < 0 || ny >= height) continue;
2021
+ for (let dx = -1; dx <= 1; dx += 1) {
2022
+ if (dx === 0 && dy === 0) continue;
2023
+ const nx = localX + dx;
2024
+ if (nx < 0 || nx >= width) continue;
2025
+ const neighbor = ny * width + nx;
2026
+ if (foreground[neighbor] === 1) {
2027
+ foreground[neighbor] = 2;
2028
+ if (top >= stack.length) {
2029
+ const grown = new Int32Array(stack.length * 2);
2030
+ grown.set(stack);
2031
+ stack = grown;
2032
+ }
2033
+ stack[top] = neighbor;
2034
+ top += 1;
2035
+ }
2036
+ }
2037
+ }
2038
+ sinceCheckpoint += 1;
2039
+ if (sinceCheckpoint >= CHECKPOINT_UNITS) {
2040
+ sinceCheckpoint = 0;
2041
+ yield;
2042
+ }
2043
+ }
2044
+ if (area >= minArea) {
2045
+ found.push({ area, minX, minY, maxX, maxY, sumX, sumY });
2046
+ }
2047
+ sinceCheckpoint += 1;
2048
+ if (sinceCheckpoint >= CHECKPOINT_UNITS) {
2049
+ sinceCheckpoint = 0;
2050
+ yield;
2051
+ }
2052
+ }
2053
+ return found;
2054
+ }
2055
+
2056
+ function buildCandidates(components, roi, maxResults, signal) {
2057
+ const mapped = components.map((component) => {
2058
+ const x = roi.x + component.minX;
2059
+ const y = roi.y + component.minY;
2060
+ const width = component.maxX - component.minX + 1;
2061
+ const height = component.maxY - component.minY + 1;
2062
+ const centroidX = roi.x + component.sumX / component.area + 0.5;
2063
+ const centroidY = roi.y + component.sumY / component.area + 0.5;
2064
+ return {
2065
+ region: { x, y, width, height },
2066
+ centroid: { x: centroidX, y: centroidY },
2067
+ area: component.area,
2068
+ score: component.area / (width * height),
2069
+ signal,
2070
+ };
2071
+ });
2072
+ mapped.sort((left, right) => {
2073
+ if (right.area !== left.area) return right.area - left.area;
2074
+ if (left.region.y !== right.region.y) return left.region.y - right.region.y;
2075
+ if (left.region.x !== right.region.x) return left.region.x - right.region.x;
2076
+ if (left.region.height !== right.region.height) return left.region.height - right.region.height;
2077
+ return left.region.width - right.region.width;
2078
+ });
2079
+ const totalCandidates = mapped.length;
2080
+ const truncated = totalCandidates > maxResults;
2081
+ const candidates = mapped.slice(0, maxResults).map((item, index) => ({
2082
+ id: `c${index + 1}`,
2083
+ region: item.region,
2084
+ documentCss: null,
2085
+ centroid: item.centroid,
2086
+ area: item.area,
2087
+ score: item.score,
2088
+ signal: item.signal,
2089
+ semanticName: null,
2090
+ }));
2091
+ return { candidates, totalCandidates, truncated };
2092
+ }
2093
+
2094
+ function iouOfBoxes(left, right, width, height) {
2095
+ const leftX = Math.max(left.x, right.x);
2096
+ const leftY = Math.max(left.y, right.y);
2097
+ const rightX = Math.min(left.x + width, right.x + width);
2098
+ const rightY = Math.min(left.y + height, right.y + height);
2099
+ if (rightX <= leftX || rightY <= leftY) return 0;
2100
+ const intersection = (rightX - leftX) * (rightY - leftY);
2101
+ const union = 2 * width * height - intersection;
2102
+ return intersection / union;
2103
+ }
2104
+
2105
+ function* templateSearchSteps(image, templateImage, roi, query, ctx) {
2106
+ const templateWidth = templateImage.width;
2107
+ const templateHeight = templateImage.height;
2108
+ const stride = query.stride;
2109
+ const positionsX = Math.floor((roi.width - templateWidth) / stride) + 1;
2110
+ const positionsY = Math.floor((roi.height - templateHeight) / stride) + 1;
2111
+ const positions = positionsX * positionsY;
2112
+ const templatePixels = templateWidth * templateHeight;
2113
+ const comparisons = positions * templatePixels;
2114
+ if (comparisons > VISION_LIMITS.maxTemplateComparisons) {
2115
+ throw visionLimitExceeded(
2116
+ 'maxTemplateComparisons',
2117
+ comparisons,
2118
+ VISION_LIMITS.maxTemplateComparisons,
2119
+ '模板候选像素比较次数超限',
2120
+ );
2121
+ }
2122
+
2123
+ const templateR = new Float64Array(templatePixels);
2124
+ const templateG = new Float64Array(templatePixels);
2125
+ const templateB = new Float64Array(templatePixels);
2126
+ for (let index = 0; index < templatePixels; index += 1) {
2127
+ const offset = index * 4;
2128
+ const alpha = templateImage.rgba[offset + 3];
2129
+ templateR[index] = 255 + (templateImage.rgba[offset] - 255) * (alpha / 255);
2130
+ templateG[index] = 255 + (templateImage.rgba[offset + 1] - 255) * (alpha / 255);
2131
+ templateB[index] = 255 + (templateImage.rgba[offset + 2] - 255) * (alpha / 255);
2132
+ }
2133
+ const denominator = 255 * 3 * templatePixels;
2134
+ const rgba = image.rgba;
2135
+ const imageWidth = image.width;
2136
+ const matches = [];
2137
+ const maxMatchEntries = 1000000;
2138
+ let comparisonsSinceCheck = 0;
2139
+ for (let py = 0; py < positionsY; py += 1) {
2140
+ const originY = roi.y + py * stride;
2141
+ for (let px = 0; px < positionsX; px += 1) {
2142
+ const originX = roi.x + px * stride;
2143
+ let sum = 0;
2144
+ for (let ty = 0; ty < templateHeight; ty += 1) {
2145
+ const rowBase = ((originY + ty) * imageWidth + originX) * 4;
2146
+ const templateRow = ty * templateWidth;
2147
+ for (let tx = 0; tx < templateWidth; tx += 1) {
2148
+ const offset = rowBase + tx * 4;
2149
+ const alpha = rgba[offset + 3];
2150
+ const r = 255 + (rgba[offset] - 255) * (alpha / 255);
2151
+ const g = 255 + (rgba[offset + 1] - 255) * (alpha / 255);
2152
+ const b = 255 + (rgba[offset + 2] - 255) * (alpha / 255);
2153
+ const templateIndex = templateRow + tx;
2154
+ sum += Math.abs(r - templateR[templateIndex])
2155
+ + Math.abs(g - templateG[templateIndex])
2156
+ + Math.abs(b - templateB[templateIndex]);
2157
+ }
2158
+ comparisonsSinceCheck += templateWidth;
2159
+ if (comparisonsSinceCheck >= CHECKPOINT_UNITS) {
2160
+ comparisonsSinceCheck = 0;
2161
+ yield;
2162
+ }
2163
+ }
2164
+ const score = 1 - sum / denominator;
2165
+ if (score >= query.minScore) {
2166
+ matches.push({ x: originX, y: originY, score });
2167
+ if (matches.length > maxMatchEntries) {
2168
+ throw visionLimitExceeded(
2169
+ 'maxTemplateMatches',
2170
+ matches.length,
2171
+ maxMatchEntries,
2172
+ '模板命中的候选位置超出工作集预算,请提高 minScore 或缩小 ROI',
2173
+ );
2174
+ }
2175
+ }
2176
+ }
2177
+ }
2178
+
2179
+ matches.sort((left, right) => {
2180
+ if (right.score !== left.score) return right.score - left.score;
2181
+ if (left.y !== right.y) return left.y - right.y;
2182
+ return left.x - right.x;
2183
+ });
2184
+ const kept = [];
2185
+ for (const match of matches) {
2186
+ let suppressed = false;
2187
+ for (const survivor of kept) {
2188
+ if (iouOfBoxes(match, survivor, templateWidth, templateHeight) > 0.3) {
2189
+ suppressed = true;
2190
+ break;
2191
+ }
2192
+ }
2193
+ if (!suppressed) kept.push(match);
2194
+ }
2195
+ const totalCandidates = kept.length;
2196
+ const truncated = totalCandidates > query.maxResults;
2197
+ const candidates = kept.slice(0, query.maxResults).map((match, index) => ({
2198
+ id: `c${index + 1}`,
2199
+ region: { x: match.x, y: match.y, width: templateWidth, height: templateHeight },
2200
+ documentCss: null,
2201
+ centroid: { x: match.x + templateWidth / 2, y: match.y + templateHeight / 2 },
2202
+ area: templatePixels,
2203
+ score: match.score,
2204
+ signal: 'template',
2205
+ semanticName: null,
2206
+ }));
2207
+ return {
2208
+ candidates,
2209
+ totalCandidates,
2210
+ truncated,
2211
+ metrics: {
2212
+ foregroundPixels: null,
2213
+ evaluatedPositions: positions,
2214
+ pixelComparisons: comparisons,
2215
+ algorithm: 'template-v1',
2216
+ },
2217
+ };
2218
+ }
2219
+
2220
+ function* findSteps(image, query, params, ctx) {
2221
+ assertImage(image, 'image');
2222
+ const parsed = validateQuery(query, 'query');
2223
+ const width = image.width;
2224
+ const height = image.height;
2225
+ const roi = params.roi === undefined || params.roi === null
2226
+ ? { x: 0, y: 0, width, height }
2227
+ : validatePixelRect(params.roi, 'roi');
2228
+ if (roi.x + roi.width > width || roi.y + roi.height > height) {
2229
+ throw invalidArgument('roi', 'out-of-bounds', 'findInImage');
2230
+ }
2231
+ if (parsed.method === 'template') {
2232
+ const templateImage = params.templateImage;
2233
+ assertImage(templateImage, 'template');
2234
+ if (templateImage.width > roi.width || templateImage.height > roi.height) {
2235
+ throw invalidArgument('template', 'template-larger-than-roi', 'findInImage');
2236
+ }
2237
+ return yield* templateSearchSteps(image, templateImage, roi, parsed, ctx);
2238
+ }
2239
+
2240
+ const roiPixels = roi.width * roi.height;
2241
+ const foreground = new Uint8Array(roiPixels);
2242
+ let foregroundPixels = 0;
2243
+ if (parsed.method === 'edges') {
2244
+ const edges = yield* edgeMaskSteps(image, parsed.edgeThreshold, ctx);
2245
+ let nextCheckpoint = CHECKPOINT_UNITS;
2246
+ for (let y = 0; y < roi.height; y += 1) {
2247
+ const edgeRow = (roi.y + y) * width;
2248
+ const outRow = y * roi.width;
2249
+ for (let x = 0; x < roi.width; x += 1) {
2250
+ if (edges[edgeRow + roi.x + x]) {
2251
+ foreground[outRow + x] = 1;
2252
+ foregroundPixels += 1;
2253
+ }
2254
+ }
2255
+ if ((y + 1) * roi.width >= nextCheckpoint) {
2256
+ nextCheckpoint += CHECKPOINT_UNITS;
2257
+ yield;
2258
+ }
2259
+ }
2260
+ } else {
2261
+ const rgba = image.rgba;
2262
+ const isColor = parsed.method === 'color';
2263
+ const target = isColor ? parsed.color : parsed.background;
2264
+ const tolerance = parsed.tolerance;
2265
+ let nextCheckpoint = CHECKPOINT_UNITS;
2266
+ for (let y = 0; y < roi.height; y += 1) {
2267
+ const sourceRow = (roi.y + y) * width;
2268
+ const outRow = y * roi.width;
2269
+ for (let x = 0; x < roi.width; x += 1) {
2270
+ const offset = (sourceRow + roi.x + x) * 4;
2271
+ const alpha = rgba[offset + 3];
2272
+ if (alpha === 0) continue;
2273
+ const dR = Math.abs(rgba[offset] - target[0]);
2274
+ const dG = Math.abs(rgba[offset + 1] - target[1]);
2275
+ const dB = Math.abs(rgba[offset + 2] - target[2]);
2276
+ const maxDelta = Math.max(dR, dG, dB);
2277
+ const isForeground = isColor ? maxDelta <= tolerance : maxDelta > tolerance;
2278
+ if (isForeground) {
2279
+ foreground[outRow + x] = 1;
2280
+ foregroundPixels += 1;
2281
+ }
2282
+ }
2283
+ if ((y + 1) * roi.width >= nextCheckpoint) {
2284
+ nextCheckpoint += CHECKPOINT_UNITS;
2285
+ yield;
2286
+ }
2287
+ }
2288
+ }
2289
+
2290
+ const components = yield* componentSteps(foreground, roi.width, roi.height, parsed.minArea, ctx);
2291
+ const signal = parsed.method === 'color' ? 'color' : parsed.method === 'components' ? 'component' : 'edge';
2292
+ const built = buildCandidates(components, roi, parsed.maxResults, signal);
2293
+ return {
2294
+ candidates: built.candidates,
2295
+ totalCandidates: built.totalCandidates,
2296
+ truncated: built.truncated,
2297
+ metrics: {
2298
+ foregroundPixels,
2299
+ evaluatedPositions: null,
2300
+ pixelComparisons: roiPixels,
2301
+ algorithm: `${parsed.method}-v1`,
2302
+ },
2303
+ };
2304
+ }
2305
+
2306
+ /**
2307
+ * 确定性识别:color/components/edges/template。
2308
+ * 返回 `{candidates,totalCandidates,truncated,metrics}`;候选坐标为完整输入图坐标。
2309
+ */
2310
+ export function findInImage(image, query, params = {}) {
2311
+ const ctx = createOpContext(params);
2312
+ return driveSync(findSteps(image, query, params, ctx), ctx, 'find');
2313
+ }
2314
+
2315
+ /** findInImage 的让出事件循环版本。 */
2316
+ export async function findInImageAsync(image, query, params = {}) {
2317
+ const ctx = createOpContext(params);
2318
+ return driveAsync(findSteps(image, query, params, ctx), ctx, 'find');
2319
+ }
2320
+
2321
+ /* ------------------------------------------------------------------ */
2322
+ /* 几何映射(image px → document CSS;viewport 由 Host 减现场 scroll) */
2323
+ /* ------------------------------------------------------------------ */
2324
+
2325
+ function isMapping(value) {
2326
+ return isPlainObject(value)
2327
+ && isPlainObject(value.originCss)
2328
+ && isPlainObject(value.cssPerPixel)
2329
+ && Number.isFinite(value.originCss.x)
2330
+ && Number.isFinite(value.originCss.y)
2331
+ && Number.isFinite(value.cssPerPixel.x)
2332
+ && Number.isFinite(value.cssPerPixel.y)
2333
+ && value.cssPerPixel.x > 0
2334
+ && value.cssPerPixel.y > 0;
2335
+ }
2336
+
2337
+ /** 图像点 → document CSS 点;无 mapping 返回 null。 */
2338
+ export function mapImagePointToDocument(mapping, point) {
2339
+ if (!isMapping(mapping) || !isPlainObject(point)) return null;
2340
+ const { x, y } = point;
2341
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
2342
+ return {
2343
+ x: mapping.originCss.x + x * mapping.cssPerPixel.x,
2344
+ y: mapping.originCss.y + y * mapping.cssPerPixel.y,
2345
+ };
2346
+ }
2347
+
2348
+ /** 图像矩形 → document CSS 矩形(区域用边缘而非像素中心);无 mapping 返回 null。 */
2349
+ export function mapImageRectToDocument(mapping, rect) {
2350
+ if (!isMapping(mapping) || !isPlainObject(rect)) return null;
2351
+ const { x, y, width, height } = rect;
2352
+ if (![x, y, width, height].every((value) => Number.isFinite(value))) return null;
2353
+ const left = mapping.originCss.x + x * mapping.cssPerPixel.x;
2354
+ const top = mapping.originCss.y + y * mapping.cssPerPixel.y;
2355
+ const right = mapping.originCss.x + (x + width) * mapping.cssPerPixel.x;
2356
+ const bottom = mapping.originCss.y + (y + height) * mapping.cssPerPixel.y;
2357
+ return { x: left, y: top, width: right - left, height: bottom - top };
2358
+ }
2359
+
2360
+ /** 两个 mapping 是否兼容(coordinateSpace + originCss/cssPerPixel/capturedCssRect 逐轴差 ≤1e-9)。 */
2361
+ export function mappingCompatible(left, right) {
2362
+ if (!isMapping(left) || !isMapping(right)) return false;
2363
+ if (left.coordinateSpace !== right.coordinateSpace) return false;
2364
+ const epsilon = 1e-9;
2365
+ const near = (a, b) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= epsilon;
2366
+ if (!near(left.originCss.x, right.originCss.x) || !near(left.originCss.y, right.originCss.y)) return false;
2367
+ if (!near(left.cssPerPixel.x, right.cssPerPixel.x) || !near(left.cssPerPixel.y, right.cssPerPixel.y)) return false;
2368
+ const leftRect = left.capturedCssRect;
2369
+ const rightRect = right.capturedCssRect;
2370
+ if (!isPlainObject(leftRect) || !isPlainObject(rightRect)) return false;
2371
+ return near(leftRect.x, rightRect.x)
2372
+ && near(leftRect.y, rightRect.y)
2373
+ && near(leftRect.width, rightRect.width)
2374
+ && near(leftRect.height, rightRect.height);
2375
+ }
2376
+
2377
+ /** 两个 CSS 矩形的交集(右下开区间;无交集为 0 尺寸)。 */
2378
+ function intersectCssRect(a, b) {
2379
+ const left = Math.max(a.x, b.x);
2380
+ const top = Math.max(a.y, b.y);
2381
+ const right = Math.min(a.x + a.width, b.x + b.width);
2382
+ const bottom = Math.min(a.y + a.height, b.y + b.height);
2383
+ return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) };
2384
+ }
2385
+
2386
+ /** 裁剪后的派生 mapping:原点加 crop 偏移,cssPerPixel 不变。 */
2387
+ export function mappingAfterCrop(mapping, rect) {
2388
+ if (!isMapping(mapping) || !isPlainObject(rect)) return null;
2389
+ const { x, y, width, height } = rect;
2390
+ if (![x, y, width, height].every((value) => Number.isFinite(value))) return null;
2391
+ const originCss = {
2392
+ x: mapping.originCss.x + x * mapping.cssPerPixel.x,
2393
+ y: mapping.originCss.y + y * mapping.cssPerPixel.y,
2394
+ };
2395
+ const capturedCssRect = isPlainObject(mapping.capturedCssRect)
2396
+ ? {
2397
+ x: originCss.x,
2398
+ y: originCss.y,
2399
+ width: width * mapping.cssPerPixel.x,
2400
+ height: height * mapping.cssPerPixel.y,
2401
+ }
2402
+ : null;
2403
+ const derived = {
2404
+ ...mapping,
2405
+ originCss,
2406
+ imagePixels: { width, height },
2407
+ capturedCssRect,
2408
+ };
2409
+ // Canvas-space mappings (docs/viewport-control.md): a crop moves the canvas origin; the
2410
+ // content box stays anchored at (0,0), so the derived content intersection must be recomputed.
2411
+ if (isPlainObject(mapping.canvas) && capturedCssRect
2412
+ && Number.isFinite(mapping.canvas.contentWidth) && Number.isFinite(mapping.canvas.contentHeight)) {
2413
+ derived.canvas = {
2414
+ ...mapping.canvas,
2415
+ x: originCss.x,
2416
+ y: originCss.y,
2417
+ offsetX: originCss.x - mapping.canvas.scrollX,
2418
+ offsetY: originCss.y - mapping.canvas.scrollY,
2419
+ };
2420
+ derived.contentRect = intersectCssRect(capturedCssRect, {
2421
+ x: 0, y: 0, width: mapping.canvas.contentWidth, height: mapping.canvas.contentHeight,
2422
+ });
2423
+ }
2424
+ return derived;
2425
+ }
2426
+
2427
+ /** 缩放后的派生 mapping:cssPerPixel 按实际 sx=Wout/Win、sy=Hout/Hin 缩小。 */
2428
+ export function mappingAfterResize(mapping, width, height) {
2429
+ if (!isMapping(mapping) || !Number.isFinite(width) || !Number.isFinite(height)) return null;
2430
+ if (width <= 0 || height <= 0) return null;
2431
+ const sourceWidth = isPlainObject(mapping.imagePixels) ? mapping.imagePixels.width : null;
2432
+ const sourceHeight = isPlainObject(mapping.imagePixels) ? mapping.imagePixels.height : null;
2433
+ if (!Number.isFinite(sourceWidth) || !Number.isFinite(sourceHeight) || sourceWidth <= 0 || sourceHeight <= 0) {
2434
+ return null;
2435
+ }
2436
+ const sx = width / sourceWidth;
2437
+ const sy = height / sourceHeight;
2438
+ return {
2439
+ ...mapping,
2440
+ cssPerPixel: { x: mapping.cssPerPixel.x / sx, y: mapping.cssPerPixel.y / sy },
2441
+ imagePixels: { width, height },
2442
+ };
2443
+ }
2444
+
2445
+ /* ------------------------------------------------------------------ */
2446
+ /* 阈值判定 helper(compare/check 共用;相等按较低等级) */
2447
+ /* ------------------------------------------------------------------ */
2448
+
2449
+ /** diffRatio → 'PASS'|'WARN'|'FAIL'(严格 >,相等按较低等级)。 */
2450
+ export function ratioVerdict(diffRatio, thresholds = DEFAULT_THRESHOLDS) {
2451
+ if (!Number.isFinite(diffRatio)) throw invalidArgument('diffRatio', 'not-a-finite-number', 'ratioVerdict');
2452
+ const parsed = validateThresholds(thresholds, 'thresholds');
2453
+ if (diffRatio > parsed.failRatio) return 'FAIL';
2454
+ if (diffRatio > parsed.warnRatio) return 'WARN';
2455
+ return 'PASS';
2456
+ }
2457
+
2458
+ /* ------------------------------------------------------------------ */
2459
+ /* Product store */
2460
+ /* ------------------------------------------------------------------ */
2461
+
2462
+ function productKind(kind) {
2463
+ if (kind === 'capture' || kind === 'derived' || kind === 'diff' || kind === 'baseline') return kind;
2464
+ throw invalidArgument('kind', 'invalid-enum', 'product');
2465
+ }
2466
+
2467
+ /**
2468
+ * 每 scope 的 product store(契约 §1.1):16 项 / 128MiB 编码字节 / 单张 32MiB / 单图 16M px;
2469
+ * `v1_<32hex>` ID、LRU 读刷新、pin 不可淘汰、clear/stats。只保存编码字节与 lineage,
2470
+ * 不长期持有解码缓冲。
2471
+ */
2472
+ export class VisionProductStore {
2473
+ constructor({ now } = {}) {
2474
+ this._now = typeof now === 'function' ? now : () => Date.now();
2475
+ this._entries = new Map();
2476
+ this._totalBytes = 0;
2477
+ this._tick = 0;
2478
+ }
2479
+
2480
+ _touch(record) {
2481
+ this._tick += 1;
2482
+ record.lastAccess = this._tick;
2483
+ }
2484
+
2485
+ _view(record) {
2486
+ return {
2487
+ productId: record.productId,
2488
+ width: record.width,
2489
+ height: record.height,
2490
+ bytes: record.bytes,
2491
+ sha256: record.sha256,
2492
+ rgbaSha256: record.rgbaSha256,
2493
+ kind: record.kind,
2494
+ mapping: record.mapping,
2495
+ actionable: record.actionable,
2496
+ parentIds: record.parentIds,
2497
+ operations: record.operations,
2498
+ createdAt: record.createdAt,
2499
+ capturedAt: record.capturedAt,
2500
+ pinned: record.pins > 0,
2501
+ };
2502
+ }
2503
+
2504
+ _evictOne() {
2505
+ let victim = null;
2506
+ for (const record of this._entries.values()) {
2507
+ if (record.pins > 0) continue;
2508
+ if (!victim || record.lastAccess < victim.lastAccess) victim = record;
2509
+ }
2510
+ if (!victim) return false;
2511
+ this._entries.delete(victim.productId);
2512
+ this._totalBytes -= victim.bytes.length;
2513
+ return true;
2514
+ }
2515
+
2516
+ _newProductId() {
2517
+ for (;;) {
2518
+ const productId = `v1_${randomBytes(16).toString('hex')}`;
2519
+ if (!this._entries.has(productId)) return productId;
2520
+ }
2521
+ }
2522
+
2523
+ add(entry) {
2524
+ const input = assertObject(entry, 'product');
2525
+ const bytes = toBuffer(input.bytes);
2526
+ if (!bytes || bytes.length === 0) throw invalidArgument('bytes', 'invalid-bytes', 'product');
2527
+ if (bytes.length > VISION_LIMITS.maxProductBytes) {
2528
+ throw visionLimitExceeded('maxProductBytes', bytes.length, VISION_LIMITS.maxProductBytes, '单张 product 编码字节超限');
2529
+ }
2530
+ const width = input.width;
2531
+ const height = input.height;
2532
+ if (!Number.isInteger(width) || width <= 0) throw invalidArgument('width', 'invalid-dimensions', 'product');
2533
+ if (!Number.isInteger(height) || height <= 0) throw invalidArgument('height', 'invalid-dimensions', 'product');
2534
+ const pixels = width * height;
2535
+ if (pixels > VISION_LIMITS.maxProductPixels) {
2536
+ throw visionLimitExceeded('maxProductPixels', pixels, VISION_LIMITS.maxProductPixels, '单张 product 像素超限');
2537
+ }
2538
+ const kind = productKind(input.kind);
2539
+ const actionable = input.actionable === undefined ? false : input.actionable;
2540
+ if (typeof actionable !== 'boolean') throw invalidArgument('actionable', 'not-a-boolean', 'product');
2541
+ const createdAt = input.createdAt === undefined ? this._now() : input.createdAt;
2542
+ if (!Number.isFinite(createdAt) || createdAt < 0) throw invalidArgument('createdAt', 'invalid-epoch-ms', 'product');
2543
+ const capturedAt = input.capturedAt === undefined ? null : input.capturedAt;
2544
+ if (capturedAt !== null && (!Number.isFinite(capturedAt) || capturedAt < 0)) {
2545
+ throw invalidArgument('capturedAt', 'invalid-epoch-ms', 'product');
2546
+ }
2547
+ let sha256 = input.sha256;
2548
+ if (sha256 === undefined || sha256 === null) {
2549
+ sha256 = sha256Hex(bytes);
2550
+ } else if (typeof sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(sha256)) {
2551
+ throw invalidArgument('sha256', 'invalid-sha256', 'product');
2552
+ }
2553
+ let rgbaSha256 = input.rgbaSha256 === undefined ? null : input.rgbaSha256;
2554
+ if (rgbaSha256 !== null && (typeof rgbaSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(rgbaSha256))) {
2555
+ throw invalidArgument('rgbaSha256', 'invalid-sha256', 'product');
2556
+ }
2557
+ const mapping = input.mapping === undefined ? null : input.mapping;
2558
+ if (mapping !== null && !isPlainObject(mapping)) throw invalidArgument('mapping', 'invalid-mapping', 'product');
2559
+ const parentIds = input.parentIds === undefined ? [] : input.parentIds;
2560
+ if (!Array.isArray(parentIds) || parentIds.some((id) => typeof id !== 'string')) {
2561
+ throw invalidArgument('parentIds', 'invalid-string-list', 'product');
2562
+ }
2563
+ const operations = input.operations === undefined ? [] : input.operations;
2564
+ if (!Array.isArray(operations)) throw invalidArgument('operations', 'not-an-array', 'product');
2565
+
2566
+ while (this._entries.size >= VISION_LIMITS.maxProducts) {
2567
+ if (!this._evictOne()) {
2568
+ throw visionLimitExceeded(
2569
+ 'maxProducts',
2570
+ this._entries.size + 1,
2571
+ VISION_LIMITS.maxProducts,
2572
+ 'product store 数量超限且无可淘汰项',
2573
+ );
2574
+ }
2575
+ }
2576
+ while (this._totalBytes + bytes.length > VISION_LIMITS.maxTotalBytes) {
2577
+ if (!this._evictOne()) {
2578
+ throw visionLimitExceeded(
2579
+ 'maxTotalBytes',
2580
+ this._totalBytes + bytes.length,
2581
+ VISION_LIMITS.maxTotalBytes,
2582
+ 'product store 总字节超限且无可淘汰项',
2583
+ );
2584
+ }
2585
+ }
2586
+
2587
+ const record = {
2588
+ productId: this._newProductId(),
2589
+ width,
2590
+ height,
2591
+ bytes,
2592
+ sha256,
2593
+ rgbaSha256,
2594
+ kind,
2595
+ mapping,
2596
+ actionable,
2597
+ parentIds: [...parentIds],
2598
+ operations: [...operations],
2599
+ createdAt,
2600
+ capturedAt,
2601
+ pins: 0,
2602
+ lastAccess: 0,
2603
+ };
2604
+ this._entries.set(record.productId, record);
2605
+ this._totalBytes += bytes.length;
2606
+ this._touch(record);
2607
+ return {
2608
+ productId: record.productId,
2609
+ width: record.width,
2610
+ height: record.height,
2611
+ bytes: record.bytes.length,
2612
+ sha256: record.sha256,
2613
+ rgbaSha256: record.rgbaSha256,
2614
+ createdAt: record.createdAt,
2615
+ capturedAt: record.capturedAt,
2616
+ kind: record.kind,
2617
+ mapping: record.mapping,
2618
+ actionable: record.actionable,
2619
+ parentIds: [...record.parentIds],
2620
+ operations: [...record.operations],
2621
+ };
2622
+ }
2623
+
2624
+ get(productId) {
2625
+ if (typeof productId !== 'string') return null;
2626
+ const record = this._entries.get(productId);
2627
+ if (!record) return null;
2628
+ this._touch(record);
2629
+ return this._view(record);
2630
+ }
2631
+
2632
+ pin(productId) {
2633
+ if (typeof productId !== 'string') return null;
2634
+ const record = this._entries.get(productId);
2635
+ if (!record) return null;
2636
+ record.pins += 1;
2637
+ this._touch(record);
2638
+ return this._view(record);
2639
+ }
2640
+
2641
+ release(productId) {
2642
+ if (typeof productId !== 'string') return;
2643
+ const record = this._entries.get(productId);
2644
+ if (record && record.pins > 0) record.pins -= 1;
2645
+ }
2646
+
2647
+ clear() {
2648
+ this._entries.clear();
2649
+ this._totalBytes = 0;
2650
+ }
2651
+
2652
+ stats() {
2653
+ let pinned = 0;
2654
+ for (const record of this._entries.values()) if (record.pins > 0) pinned += 1;
2655
+ return { count: this._entries.size, bytes: this._totalBytes, pinned };
2656
+ }
2657
+ }