dsh-desktop-kit 2.24.0 → 2.30.0

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 (76) hide show
  1. package/CHANGELOG.md +74 -6
  2. package/README.md +192 -291
  3. package/client.js +1 -1
  4. package/cordis.patch.yml +5 -151
  5. package/docs/ARCHITECTURE.md +10 -16
  6. package/docs/COMPATIBILITY.md +1 -1
  7. package/docs/DEVELOPMENT.md +0 -1
  8. package/docs/PROPOSAL-2.25-quality-pipeline.md +435 -0
  9. package/docs/PROPOSAL-NEXUM-FINDINGS.md +259 -0
  10. package/docs/TEST-2.24.1.md +66 -0
  11. package/docs/TEST-2.30.0.md +83 -0
  12. package/docs/images/capability-map-2.30.png +0 -0
  13. package/docs/images/hero-2.30.png +0 -0
  14. package/docs/images/quality-pipeline-2.30.png +0 -0
  15. package/docs/preview/capability-map-2.30.html +106 -0
  16. package/docs/preview/hero-2.30.html +133 -0
  17. package/docs/preview/quality-pipeline-2.30.html +142 -0
  18. package/docs/preview/readme-visuals.css +111 -0
  19. package/index.js +6 -0
  20. package/package.json +11 -4
  21. package/plugins/dsh-agent-extensions/lib/routing.js +4 -0
  22. package/plugins/dsh-agent-extensions/lib/scaffold.js +152 -27
  23. package/plugins/dsh-agent-extensions/lib/settings.js +19 -0
  24. package/plugins/dsh-agent-extensions/lib/swarm.js +6 -2
  25. package/plugins/dsh-browser-qa/index.js +202 -9
  26. package/plugins/dsh-browser-qa/lib/design-more.js +688 -0
  27. package/plugins/dsh-browser-qa/lib/extras.js +1313 -0
  28. package/plugins/dsh-browser-qa/lib/pages.js +4 -3
  29. package/plugins/dsh-browser-qa/lib/png.js +190 -0
  30. package/plugins/dsh-browser-qa/lib/ui-gate.js +171 -31
  31. package/plugins/dsh-i18n/README.md +36 -0
  32. package/plugins/dsh-i18n/cordis.patch.yml +3 -0
  33. package/plugins/dsh-i18n/index.js +294 -0
  34. package/plugins/dsh-i18n/lib/lang.js +179 -0
  35. package/plugins/dsh-i18n/package.json +29 -0
  36. package/plugins/dsh-quality-pipeline/README.md +53 -0
  37. package/plugins/dsh-quality-pipeline/cordis.patch.yml +3 -0
  38. package/plugins/dsh-quality-pipeline/index.js +647 -0
  39. package/plugins/dsh-quality-pipeline/lib/acceptance.js +132 -0
  40. package/plugins/dsh-quality-pipeline/lib/autostart.js +159 -0
  41. package/plugins/dsh-quality-pipeline/lib/design.js +123 -0
  42. package/plugins/dsh-quality-pipeline/lib/machine.js +312 -0
  43. package/plugins/dsh-quality-pipeline/lib/prework.js +215 -0
  44. package/plugins/dsh-quality-pipeline/lib/release.js +53 -0
  45. package/plugins/dsh-quality-pipeline/lib/schema.js +256 -0
  46. package/plugins/dsh-quality-pipeline/lib/store.js +114 -0
  47. package/plugins/dsh-quality-pipeline/lib/text.js +109 -0
  48. package/plugins/dsh-quality-pipeline/package.json +33 -0
  49. package/plugins/dsh-remote-ops/README.md +38 -0
  50. package/plugins/dsh-remote-ops/cordis.patch.yml +3 -0
  51. package/plugins/dsh-remote-ops/index.js +268 -0
  52. package/plugins/dsh-remote-ops/lib/hosts.js +118 -0
  53. package/plugins/dsh-remote-ops/lib/ssh.js +96 -0
  54. package/plugins/dsh-remote-ops/lib/state.js +66 -0
  55. package/plugins/dsh-remote-ops/package.json +31 -0
  56. package/plugins/dsh-skill-autopilot/index.js +204 -15
  57. package/skills/a11y-audit/SKILL.md +67 -0
  58. package/skills/cms-ops/SKILL.md +74 -0
  59. package/skills/design-system/SKILL.md +100 -0
  60. package/skills/legal-ru-web/SKILL.md +68 -0
  61. package/skills/manifest.json +38 -18
  62. package/skills/release-pipeline/SKILL.md +67 -0
  63. package/skills/ui-batch/SKILL.md +60 -0
  64. package/skills/web-build/SKILL.md +106 -0
  65. package/skills/web-build/recipes/form.md +16 -0
  66. package/skills/web-build/recipes/payment.md +16 -0
  67. package/skills/web-build/recipes/review.md +16 -0
  68. package/skills-baseline.json +192 -0
  69. package/docs/TEST-2.24.0.md +0 -123
  70. package/skills/ui-design-system/references/accessibility-and-responsive.md +0 -50
  71. package/skills/ui-design-system/references/tokens-and-components.md +0 -67
  72. package/skills/ui-design-system/references/visual-qa.md +0 -44
  73. package/skills/visual-qa/references/commands.md +0 -32
  74. /package/skills/{ui-craft/SKILL.md → design-system/references/ui-craft.md} +0 -0
  75. /package/skills/{ui-design-system/SKILL.md → design-system/references/ui-design-system.md} +0 -0
  76. /package/skills/{visual-qa/SKILL.md → ui-batch/references/visual-qa.md} +0 -0
@@ -0,0 +1,1313 @@
1
+ /**
2
+ * Extra browser_qa checks: accessibility, interaction scenarios, performance
3
+ * and link probing.
4
+ *
5
+ * Everything runs through the same DevTools session as `audit`/`shot`, so the
6
+ * plugin still has zero npm dependencies. In-page probes are real functions
7
+ * stringified into the page — the same pattern as `OVERFLOW_EXPRESSION`.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+
12
+ import { PageSession, withSession } from "./pages.js";
13
+ import { compareImages, decodePng, encodePng } from "./png.js";
14
+ import { abortError, formatBytes, normalizeTarget, normalizeViewport, resolveOutDir, screenshotFileName, slugForTarget } from "./qa.js";
15
+
16
+ /* ------------------------------------------------------------------ */
17
+ /* accessibility probe (static checks inside the page) */
18
+ /* ------------------------------------------------------------------ */
19
+
20
+ function a11yProbe() {
21
+ const issues = [];
22
+ const MAX = 300;
23
+ const push = (rule, severity, node, detail) => {
24
+ if (issues.length >= MAX) return;
25
+ issues.push({ rule, severity, node, detail });
26
+ };
27
+
28
+ const pathOf = (el) => {
29
+ if (!el || el.nodeType !== 1) return "(none)";
30
+ const parts = [];
31
+ let node = el;
32
+ while (node && node.nodeType === 1 && parts.length < 5) {
33
+ let part = node.tagName.toLowerCase();
34
+ if (node.id) {
35
+ part += `#${node.id}`;
36
+ parts.unshift(part);
37
+ break;
38
+ }
39
+ const cls = (node.getAttribute("class") || "").trim().split(/\s+/u).filter(Boolean).slice(0, 2);
40
+ if (cls.length > 0) part += `.${cls.join(".")}`;
41
+ const parent = node.parentElement;
42
+ if (parent) {
43
+ const same = [...parent.children].filter((child) => child.tagName === node.tagName);
44
+ if (same.length > 1) part += `:nth-of-type(${same.indexOf(node) + 1})`;
45
+ }
46
+ parts.unshift(part);
47
+ node = node.parentElement;
48
+ }
49
+ return parts.join(" > ");
50
+ };
51
+
52
+ const visible = (el) => {
53
+ if (!el || el.nodeType !== 1) return false;
54
+ const style = getComputedStyle(el);
55
+ if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
56
+ const rect = el.getBoundingClientRect();
57
+ if (rect.width < 1 || rect.height < 1) return false;
58
+ if (el.closest("[hidden], [aria-hidden='true']")) return false;
59
+ return true;
60
+ };
61
+
62
+ const nameOf = (el) => {
63
+ const aria = el.getAttribute("aria-label");
64
+ if (aria && aria.trim()) return aria.trim();
65
+ const labelledBy = el.getAttribute("aria-labelledby");
66
+ if (labelledBy) {
67
+ const text = labelledBy
68
+ .split(/\s+/u)
69
+ .map((id) => document.getElementById(id)?.textContent || "")
70
+ .join(" ")
71
+ .trim();
72
+ if (text) return text;
73
+ }
74
+ const text = (el.textContent || "").replace(/\s+/gu, " ").trim();
75
+ if (text) return text;
76
+ const img = el.querySelector("img[alt]");
77
+ if (img && img.getAttribute("alt").trim()) return img.getAttribute("alt").trim();
78
+ const title = el.getAttribute("title");
79
+ return title ? title.trim() : "";
80
+ };
81
+
82
+ const parseColor = (value) => {
83
+ const match = String(value || "").match(/rgba?\(([^)]+)\)/u);
84
+ if (!match) return null;
85
+ const parts = match[1].split(",").map((item) => Number.parseFloat(item.trim()));
86
+ if (parts.length < 3 || parts.some((item) => Number.isNaN(item))) return null;
87
+ return [parts[0], parts[1], parts[2], parts.length > 3 ? parts[3] : 1];
88
+ };
89
+ const channel = (value) => {
90
+ const v = value / 255;
91
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
92
+ };
93
+ const luminance = (rgb) => 0.2126 * channel(rgb[0]) + 0.7152 * channel(rgb[1]) + 0.0722 * channel(rgb[2]);
94
+ const blend = (fg, bg) => {
95
+ const a = fg[3];
96
+ return [fg[0] * a + bg[0] * (1 - a), fg[1] * a + bg[1] * (1 - a), fg[2] * a + bg[2] * (1 - a), 1];
97
+ };
98
+ const backdrop = (el) => {
99
+ const layers = [];
100
+ let node = el;
101
+ let hasImage = false;
102
+ while (node && node.nodeType === 1) {
103
+ const style = getComputedStyle(node);
104
+ if (style.backgroundImage && style.backgroundImage !== "none") hasImage = true;
105
+ const color = parseColor(style.backgroundColor);
106
+ if (color && color[3] > 0) {
107
+ layers.push(color);
108
+ if (color[3] >= 0.999) break;
109
+ }
110
+ node = node.parentElement;
111
+ }
112
+ let acc = [255, 255, 255, 1];
113
+ for (let index = layers.length - 1; index >= 0; index -= 1) acc = blend(layers[index], acc);
114
+ return { rgb: acc, hasImage };
115
+ };
116
+
117
+ const html = document.documentElement;
118
+ if (!html.getAttribute("lang")) push("html-lang", "serious", "html", "у <html> нет атрибута lang");
119
+ if (!document.title || !document.title.trim()) push("document-title", "serious", "head > title", "пустой <title>");
120
+ const viewportMeta = document.querySelector('meta[name="viewport"]');
121
+ const viewportContent = viewportMeta ? viewportMeta.getAttribute("content") || "" : "";
122
+ if (!viewportMeta) push("viewport-meta", "moderate", "head", "нет meta viewport");
123
+ else if (/user-scalable\s*=\s*no/iu.test(viewportContent)) push("zoom-lock", "serious", 'meta[name="viewport"]', "user-scalable=no запрещает масштабирование");
124
+ else {
125
+ const maxScale = viewportContent.match(/maximum-scale\s*=\s*([\d.]+)/iu);
126
+ if (maxScale && Number(maxScale[1]) < 5) push("zoom-lock", "serious", 'meta[name="viewport"]', `maximum-scale=${maxScale[1]} ограничивает зум`);
127
+ }
128
+
129
+ const images = [...document.querySelectorAll("img")];
130
+ for (const img of images) {
131
+ if (!visible(img)) continue;
132
+ const decorative = img.getAttribute("role") === "presentation" || img.getAttribute("role") === "none" || img.getAttribute("aria-hidden") === "true";
133
+ if (decorative) continue;
134
+ if (img.getAttribute("alt") === null) push("img-alt", "serious", pathOf(img), `нет alt: ${(img.currentSrc || img.src || "").slice(-60)}`);
135
+ }
136
+
137
+ for (const svg of document.querySelectorAll("svg[role='img']")) {
138
+ if (!visible(svg)) continue;
139
+ if (!svg.querySelector("title") && !svg.getAttribute("aria-label")) push("svg-name", "moderate", pathOf(svg), "svg role=img без title/aria-label");
140
+ }
141
+
142
+ for (const link of document.querySelectorAll("a[href]")) {
143
+ if (!visible(link)) continue;
144
+ if (!nameOf(link)) push("link-name", "serious", pathOf(link), `ссылка без доступного имени: ${link.getAttribute("href")}`);
145
+ const href = (link.getAttribute("href") || "").trim();
146
+ if (href === "#" || /^javascript:/iu.test(href)) push("link-href", "moderate", pathOf(link), `пустая ссылка: ${href}`);
147
+ }
148
+
149
+ for (const button of document.querySelectorAll("button, [role='button'], input[type='submit'], input[type='button']")) {
150
+ if (!visible(button)) continue;
151
+ const value = button.tagName === "INPUT" ? button.value : "";
152
+ if (!nameOf(button) && !value) push("button-name", "serious", pathOf(button), "кнопка без доступного имени");
153
+ }
154
+
155
+ const labels = [...document.querySelectorAll("label")];
156
+ for (const field of document.querySelectorAll("input, select, textarea")) {
157
+ const type = (field.getAttribute("type") || "").toLowerCase();
158
+ if (["hidden", "submit", "button", "reset", "image"].includes(type)) continue;
159
+ if (!visible(field)) continue;
160
+ const id = field.getAttribute("id");
161
+ const labelled = (id && labels.some((label) => label.getAttribute("for") === id)) || field.closest("label") || field.getAttribute("aria-label") || field.getAttribute("aria-labelledby") || field.getAttribute("title");
162
+ if (!labelled) push("field-label", "serious", pathOf(field), "поле без label/aria-label");
163
+ if (field.getAttribute("placeholder") && !labelled) push("placeholder-only", "moderate", pathOf(field), "placeholder вместо подписи");
164
+ }
165
+
166
+ let previous = 0;
167
+ let h1 = 0;
168
+ for (const heading of document.querySelectorAll("h1, h2, h3, h4, h5, h6")) {
169
+ if (!visible(heading)) continue;
170
+ const level = Number(heading.tagName.slice(1));
171
+ if (level === 1) h1 += 1;
172
+ if (previous > 0 && level > previous + 1) push("heading-order", "moderate", pathOf(heading), `прыжок h${previous} → h${level}`);
173
+ previous = level;
174
+ }
175
+ if (h1 === 0) push("h1-missing", "moderate", "main", "на странице нет h1");
176
+ if (h1 > 1) push("h1-many", "minor", "main", `h1 встречается ${h1} раз`);
177
+
178
+ const seen = new Map();
179
+ for (const el of document.querySelectorAll("[id]")) {
180
+ const id = el.getAttribute("id");
181
+ if (!id) continue;
182
+ seen.set(id, (seen.get(id) || 0) + 1);
183
+ }
184
+ for (const [id, count] of seen) {
185
+ if (count > 1) push("duplicate-id", "moderate", `#${id}`, `id повторяется ${count} раз`);
186
+ }
187
+
188
+ for (const el of document.querySelectorAll("[tabindex]")) {
189
+ const value = Number(el.getAttribute("tabindex"));
190
+ if (value > 0) push("tabindex-positive", "moderate", pathOf(el), `tabindex=${value} ломает порядок фокуса`);
191
+ }
192
+
193
+ for (const el of document.querySelectorAll("[aria-hidden='true']")) {
194
+ const focusable = el.querySelector("a[href], button, input, select, textarea, [tabindex]:not([tabindex='-1'])");
195
+ if (focusable) push("aria-hidden-focusable", "serious", pathOf(el), "aria-hidden=true содержит фокусируемый элемент");
196
+ }
197
+
198
+ for (const frame of document.querySelectorAll("iframe")) {
199
+ if (!frame.getAttribute("title")) push("iframe-title", "moderate", pathOf(frame), "iframe без title");
200
+ }
201
+
202
+ let checkedText = 0;
203
+ let contrastChecked = 0;
204
+ const contrastViolations = [];
205
+ for (const el of document.querySelectorAll("body *")) {
206
+ if (checkedText >= 500) break;
207
+ const own = [...el.childNodes].filter((node) => node.nodeType === 3 && node.textContent.trim().length > 1);
208
+ if (own.length === 0) continue;
209
+ if (!visible(el)) continue;
210
+ checkedText += 1;
211
+ const style = getComputedStyle(el);
212
+ const fg = parseColor(style.color);
213
+ if (!fg) continue;
214
+ const bg = backdrop(el);
215
+ if (bg.hasImage) continue;
216
+ const fgBlended = blend(fg, bg.rgb);
217
+ const ratio = (Math.max(luminance(fgBlended), luminance(bg.rgb)) + 0.05) / (Math.min(luminance(fgBlended), luminance(bg.rgb)) + 0.05);
218
+ const size = Number.parseFloat(style.fontSize) || 16;
219
+ const weight = Number(style.fontWeight) || 400;
220
+ const large = size >= 24 || (size >= 18.66 && weight >= 700);
221
+ const required = large ? 3 : 4.5;
222
+ contrastChecked += 1;
223
+ if (ratio + 0.05 < required) {
224
+ contrastViolations.push({ node: pathOf(el), ratio: Math.round(ratio * 100) / 100, required, text: (el.textContent || "").trim().slice(0, 40) });
225
+ }
226
+ }
227
+ for (const item of contrastViolations.slice(0, 25)) {
228
+ push("contrast", item.ratio < 3 ? "serious" : "moderate", item.node, `контраст ${item.ratio}:1 < ${item.required}:1 — «${item.text}»`);
229
+ }
230
+
231
+ const tap = { below24: [], below44: [], total: 0 };
232
+ for (const el of document.querySelectorAll("a[href], button, [role='button'], input[type='submit'], summary")) {
233
+ if (!visible(el)) continue;
234
+ const rect = el.getBoundingClientRect();
235
+ const style = getComputedStyle(el);
236
+ const inline = style.display === "inline" && el.closest("p, li, td, span");
237
+ if (inline) continue;
238
+ tap.total += 1;
239
+ const box = Math.min(rect.width, rect.height);
240
+ if (box < 24) tap.below24.push({ node: pathOf(el), size: Math.round(box) });
241
+ else if (box < 44) tap.below44.push({ node: pathOf(el), size: Math.round(box) });
242
+ }
243
+ for (const item of tap.below24.slice(0, 15)) push("tap-target-24", "moderate", item.node, `тап-таргет ${item.size}px < 24px (WCAG 2.2 AA 2.5.8; исключение — достаточный отступ между целями, проверьте глазами)`);
244
+ for (const item of tap.below44.slice(0, 10)) push("tap-target-44", "minor", item.node, `тап-таргет ${item.size}px < 44px (рекомендация, не AA)`);
245
+
246
+ const counts = { serious: 0, moderate: 0, minor: 0 };
247
+ for (const issue of issues) counts[issue.severity] = (counts[issue.severity] || 0) + 1;
248
+
249
+ return {
250
+ url: location.href,
251
+ title: document.title,
252
+ counts,
253
+ issues,
254
+ stats: { images: images.length, contrastChecked, checkedText, tapTargets: tap.total, tapBelow24: tap.below24.length, tapBelow44: tap.below44.length },
255
+ };
256
+ }
257
+
258
+ export const A11Y_EXPRESSION = `(${a11yProbe.toString()})()`;
259
+
260
+ const FOCUS_PROBE = `(() => {
261
+ const all = [...document.querySelectorAll("a[href], button, input, select, textarea, [tabindex]:not([tabindex='-1'])")]
262
+ .filter((el) => {
263
+ const style = getComputedStyle(el);
264
+ const rect = el.getBoundingClientRect();
265
+ return style.display !== "none" && style.visibility !== "hidden" && rect.width >= 1 && rect.height >= 1 && !el.disabled;
266
+ })
267
+ .slice(0, Number(window.__qaFocusLimit || 12));
268
+ return all.map((el, index) => {
269
+ el.setAttribute("data-qa-focus", String(index));
270
+ return { index, tag: el.tagName.toLowerCase(), label: (el.getAttribute("aria-label") || el.textContent || "").replace(/\\s+/gu, " ").trim().slice(0, 40) };
271
+ });
272
+ })()`;
273
+
274
+ const FOCUS_STATE = `(() => {
275
+ const el = document.activeElement;
276
+ if (!el || el === document.body) return { found: false };
277
+ const style = getComputedStyle(el);
278
+ const rect = el.getBoundingClientRect();
279
+ const cx = Math.min(Math.max(rect.left + rect.width / 2, 0), window.innerWidth - 1);
280
+ const cy = Math.min(Math.max(rect.top + rect.height / 2, 0), window.innerHeight - 1);
281
+ const top = document.elementFromPoint(cx, cy);
282
+ return {
283
+ found: true,
284
+ index: Number(el.getAttribute("data-qa-focus") ?? -1),
285
+ tag: el.tagName.toLowerCase(),
286
+ focusVisible: typeof el.matches === "function" ? el.matches(":focus-visible") : false,
287
+ outlineStyle: style.outlineStyle,
288
+ outlineWidth: Number.parseFloat(style.outlineWidth) || 0,
289
+ boxShadow: style.boxShadow,
290
+ obscured: !(top === el || el.contains(top)),
291
+ topTag: top ? top.tagName.toLowerCase() : "",
292
+ topClass: top && top.getAttribute ? (top.getAttribute("class") || "").slice(0, 60) : "",
293
+ };
294
+ })()`;
295
+
296
+ /* ------------------------------------------------------------------ */
297
+ /* interaction flow */
298
+ /* ------------------------------------------------------------------ */
299
+
300
+ function clickProbe(selector) {
301
+ const el = document.querySelector(selector);
302
+ if (!el) return { ok: false, reason: "element not found" };
303
+ el.scrollIntoView({ block: "center", inline: "center" });
304
+ const rect = el.getBoundingClientRect();
305
+ const x = Math.min(Math.max(rect.left + rect.width / 2, 0), window.innerWidth - 1);
306
+ const y = Math.min(Math.max(rect.top + rect.height / 2, 0), window.innerHeight - 1);
307
+ const top = document.elementFromPoint(x, y);
308
+ const hit = top === el || el.contains(top);
309
+ const style = getComputedStyle(el);
310
+ const disabled = el.disabled === true || el.getAttribute("aria-disabled") === "true" || style.pointerEvents === "none";
311
+ const info = {
312
+ ok: true,
313
+ hit,
314
+ disabled,
315
+ rect: { x: Math.round(x), y: Math.round(y), w: Math.round(rect.width), h: Math.round(rect.height) },
316
+ top: top ? `${top.tagName.toLowerCase()}${top.id ? `#${top.id}` : ""}.${(top.getAttribute("class") || "").split(/\\s+/u)[0] || ""}` : "",
317
+ visible: style.display !== "none" && style.visibility !== "hidden" && rect.width >= 1 && rect.height >= 1,
318
+ };
319
+ if (!disabled) el.click();
320
+ return info;
321
+ }
322
+
323
+ function fillProbe(selector, value) {
324
+ const el = document.querySelector(selector);
325
+ if (!el) return { ok: false, reason: "element not found" };
326
+ const prototype = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
327
+ const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
328
+ el.focus();
329
+ if (setter) setter.call(el, value);
330
+ else el.value = value;
331
+ el.dispatchEvent(new Event("input", { bubbles: true }));
332
+ el.dispatchEvent(new Event("change", { bubbles: true }));
333
+ el.dispatchEvent(new Event("blur", { bubbles: true }));
334
+ return { ok: true, value: el.value };
335
+ }
336
+
337
+ function expectProbe(spec) {
338
+ const nodes = spec.selector ? [...document.querySelectorAll(spec.selector)] : [];
339
+ const first = nodes[0];
340
+ const style = first ? getComputedStyle(first) : null;
341
+ const rect = first ? first.getBoundingClientRect() : null;
342
+ const visible = Boolean(first) && style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) > 0 && rect.width >= 1 && rect.height >= 1;
343
+ const text = first ? (first.textContent || "").replace(/\s+/gu, " ").trim() : "";
344
+ const enabled = first ? !(first.disabled === true || first.getAttribute("aria-disabled") === "true") : false;
345
+ return {
346
+ count: nodes.length,
347
+ visible,
348
+ enabled,
349
+ text: text.slice(0, 200),
350
+ rect: rect ? { w: Math.round(rect.width), h: Math.round(rect.height) } : null,
351
+ };
352
+ }
353
+
354
+ export function parseSteps(raw) {
355
+ if (!Array.isArray(raw)) return { ok: false, reason: "steps must be an array", steps: [] };
356
+ const steps = [];
357
+ for (const [index, item] of raw.entries()) {
358
+ if (!item || typeof item !== "object") return { ok: false, reason: `step ${index + 1}: not an object`, steps: [] };
359
+ const type = String(item.type ?? "click").toLowerCase();
360
+ if (!["click", "fill", "press", "wait", "expect", "eval", "shot", "reload"].includes(type)) {
361
+ return { ok: false, reason: `step ${index + 1}: unknown type ${type}`, steps: [] };
362
+ }
363
+ if ((type === "click" || type === "fill" || type === "expect") && typeof item.selector !== "string") {
364
+ return { ok: false, reason: `step ${index + 1}: selector is required`, steps: [] };
365
+ }
366
+ steps.push({ ...item, type, index });
367
+ }
368
+ if (steps.length === 0) return { ok: false, reason: "steps are empty", steps: [] };
369
+ if (steps.length > 40) return { ok: false, reason: "at most 40 steps", steps: [] };
370
+ return { ok: true, reason: "", steps };
371
+ }
372
+
373
+ async function pressKey(page, key) {
374
+ const map = { Enter: 13, Tab: 9, Escape: 27, ArrowDown: 40, ArrowUp: 38, " ": 32 };
375
+ const code = map[key] ?? 0;
376
+ const common = { key, windowsVirtualKeyCode: code, nativeVirtualKeyCode: code };
377
+ await page.cdp.send("Input.dispatchKeyEvent", { type: "keyDown", ...common }, 5_000);
378
+ await page.cdp.send("Input.dispatchKeyEvent", { type: "keyUp", ...common }, 5_000);
379
+ }
380
+
381
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
382
+
383
+ /**
384
+ * Run an interaction scenario at one viewport. A step fails when the target is
385
+ * missing, covered by another element (the classic "dead zone"), disabled, or
386
+ * when an expectation is not met.
387
+ */
388
+ export async function runFlow(options = {}) {
389
+ const parsed = parseSteps(options.steps);
390
+ if (!parsed.ok) throw new Error(`flow: ${parsed.reason}`);
391
+ const viewport = normalizeViewport(options);
392
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
393
+ const timeoutMs = options.timeoutMs ?? 30_000;
394
+ const outDir = typeof options.outDir === "string" && options.outDir.length > 0 ? resolveOutDir(options.outDir, options.cwd ?? process.cwd()) : null;
395
+ if (outDir) fs.mkdirSync(outDir, { recursive: true });
396
+ return withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
397
+ const startedAt = Date.now();
398
+ await page.setViewport(viewport.width, viewport.height);
399
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
400
+ const steps = [];
401
+ for (const step of parsed.steps) {
402
+ if (options.signal?.aborted) throw abortError();
403
+ const stepStart = Date.now();
404
+ try {
405
+ if (step.type === "click") {
406
+ const result = await page.evaluate(`(${clickProbe.toString()})(${JSON.stringify(step.selector)})`);
407
+ const ok = result?.ok === true && result.visible === true && result.disabled === false && result.hit === true;
408
+ const reason = result?.ok !== true
409
+ ? "элемент не найден"
410
+ : result.disabled
411
+ ? "элемент выключен"
412
+ : result.visible !== true
413
+ ? "элемент невидим"
414
+ : result.hit !== true
415
+ ? `элемент перекрыт: ${result.top}`
416
+ : "";
417
+ steps.push({ index: step.index, type: step.type, selector: step.selector, ok, reason, detail: result });
418
+ } else if (step.type === "fill") {
419
+ const result = await page.evaluate(`(${fillProbe.toString()})(${JSON.stringify(step.selector)}, ${JSON.stringify(String(step.value ?? ""))})`);
420
+ steps.push({ index: step.index, type: step.type, selector: step.selector, ok: result?.ok === true, reason: result?.ok ? "" : "поле не найдено", detail: result });
421
+ } else if (step.type === "press") {
422
+ await page.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(step.selector ?? "body")}); if (el && el.focus) el.focus(); return true; })()`);
423
+ await pressKey(page, String(step.key ?? "Enter"));
424
+ steps.push({ index: step.index, type: step.type, ok: true, reason: "", detail: { key: step.key ?? "Enter" } });
425
+ } else if (step.type === "wait") {
426
+ await sleep(Math.max(0, Math.min(10_000, Number(step.ms ?? 300))));
427
+ steps.push({ index: step.index, type: step.type, ok: true, reason: "" });
428
+ } else if (step.type === "reload") {
429
+ await page.navigate(target.url, { timeoutMs, signal: options.signal });
430
+ steps.push({ index: step.index, type: step.type, ok: true, reason: "" });
431
+ } else if (step.type === "eval") {
432
+ const value = await page.evaluate(String(step.code ?? "true"));
433
+ steps.push({ index: step.index, type: step.type, ok: true, reason: "", detail: { value } });
434
+ } else if (step.type === "shot") {
435
+ if (!outDir) {
436
+ steps.push({ index: step.index, type: step.type, ok: true, reason: "outDir не задан — PNG не сохранён" });
437
+ } else {
438
+ const shot = await page.screenshot({ fullPage: step.fullPage === true, timeoutMs: 20_000 });
439
+ const file = path.join(outDir, screenshotFileName({ target: target.url, width: viewport.width, height: viewport.height, fullPage: step.fullPage === true }));
440
+ const named = step.name ? file.replace(/\.png$/u, `-${String(step.name).replace(/[^\w-]+/gu, "-")}.png`) : file;
441
+ fs.writeFileSync(named, Buffer.from(shot.base64, "base64"));
442
+ steps.push({ index: step.index, type: step.type, ok: true, reason: "", detail: { file: named } });
443
+ }
444
+ } else if (step.type === "expect") {
445
+ const spec = { selector: step.selector, visible: step.visible, text: step.text, count: step.count, enabled: step.enabled };
446
+ const state = await page.evaluate(`(${expectProbe.toString()})(${JSON.stringify(spec)})`);
447
+ const failures = [];
448
+ if (step.visible === true && state.visible !== true) failures.push("не виден");
449
+ if (step.visible === false && state.visible === true) failures.push("должен быть скрыт");
450
+ if (step.enabled === true && state.enabled !== true) failures.push("выключен");
451
+ if (typeof step.text === "string" && !state.text.includes(step.text)) failures.push(`текст не содержит «${step.text}»`);
452
+ if (typeof step.count === "number" && state.count !== step.count) failures.push(`найдено ${state.count}, ожидалось ${step.count}`);
453
+ steps.push({ index: step.index, type: step.type, selector: step.selector, ok: failures.length === 0, reason: failures.join(", "), detail: state });
454
+ }
455
+ } catch (error) {
456
+ steps.push({ index: step.index, type: step.type, ok: false, reason: error instanceof Error ? error.message : String(error) });
457
+ }
458
+ steps[steps.length - 1].ms = Date.now() - stepStart;
459
+ }
460
+ const failed = steps.filter((step) => step.ok !== true);
461
+ const shots = steps.filter((step) => step.detail?.file).map((step) => step.detail.file);
462
+ return {
463
+ ok: failed.length === 0,
464
+ action: "interact",
465
+ target: { url: target.url, finalUrl: navigation.finalUrl, kind: target.kind },
466
+ viewport: { width: viewport.width, height: viewport.height },
467
+ chrome: session.chromeInfo(),
468
+ steps,
469
+ summary: { steps: steps.length, passed: steps.length - failed.length, failed: failed.length },
470
+ screenshots: shots,
471
+ ms: Date.now() - startedAt,
472
+ text: formatFlowText({ steps, failed, viewport, target: navigation.finalUrl, shots }),
473
+ };
474
+ });
475
+ }
476
+
477
+ function formatFlowText({ steps, failed, viewport, target, shots }) {
478
+ const lines = [
479
+ `browser_qa interact: ${target} @ ${viewport.width}x${viewport.height}`,
480
+ `Сценарий: ${steps.length} шагов · провалено ${failed.length}`,
481
+ ];
482
+ for (const step of steps.slice(0, 30)) {
483
+ lines.push(` ${step.ok ? "ok " : "FAIL"} ${step.index + 1}. ${step.type}${step.selector ? ` ${step.selector}` : ""}${step.reason ? ` — ${step.reason}` : ""}${step.ms !== undefined ? ` (${step.ms} ms)` : ""}`);
484
+ }
485
+ if (shots.length > 0) lines.push(`PNG: ${shots.join(", ")}`);
486
+ lines.push(failed.length === 0 ? "Итог: PASS — все шаги прошли" : `Итог: FAIL — ${failed.length} шагов`);
487
+ return lines.join("\n");
488
+ }
489
+
490
+ /* ------------------------------------------------------------------ */
491
+ /* performance */
492
+ /* ------------------------------------------------------------------ */
493
+
494
+ function perfProbe() {
495
+ return new Promise((resolve) => {
496
+ const nav = performance.getEntriesByType("navigation")[0] || {};
497
+ const paint = performance.getEntriesByType("paint") || [];
498
+ const fcp = paint.find((entry) => entry.name === "first-contentful-paint");
499
+ const resources = performance.getEntriesByType("resource") || [];
500
+ const bytes = resources.reduce((sum, entry) => sum + (entry.transferSize || 0), 0);
501
+ const result = {
502
+ url: location.href,
503
+ ttfb: nav.responseStart ? Math.round(nav.responseStart) : null,
504
+ domContentLoaded: nav.domContentLoadedEventEnd ? Math.round(nav.domContentLoadedEventEnd) : null,
505
+ load: nav.loadEventEnd ? Math.round(nav.loadEventEnd) : null,
506
+ fcp: fcp ? Math.round(fcp.startTime) : null,
507
+ lcp: null,
508
+ cls: null,
509
+ inp: null,
510
+ longTasks: 0,
511
+ requests: resources.length,
512
+ bytes,
513
+ };
514
+ let pending = 3;
515
+ const done = () => {
516
+ pending -= 1;
517
+ if (pending <= 0) resolve(result);
518
+ };
519
+ /* Safety net: an observer may stay silent (unsupported type, hidden tab). */
520
+ const safety = setTimeout(() => resolve(result), 3000);
521
+ if (typeof safety.unref === "function") safety.unref();
522
+ try {
523
+ const lcpObserver = new PerformanceObserver((list) => {
524
+ const entries = list.getEntries();
525
+ const last = entries[entries.length - 1];
526
+ if (last) result.lcp = Math.round(last.startTime);
527
+ done();
528
+ });
529
+ lcpObserver.observe({ type: "largest-contentful-paint", buffered: true });
530
+ } catch {
531
+ done();
532
+ }
533
+ try {
534
+ const clsObserver = new PerformanceObserver((list) => {
535
+ for (const entry of list.getEntries()) {
536
+ if (!entry.hadRecentInput) result.cls = Math.round(((result.cls || 0) + entry.value) * 1000) / 1000;
537
+ }
538
+ done();
539
+ });
540
+ clsObserver.observe({ type: "layout-shift", buffered: true });
541
+ } catch {
542
+ done();
543
+ }
544
+ try {
545
+ const eventObserver = new PerformanceObserver((list) => {
546
+ for (const entry of list.getEntries()) {
547
+ if (entry.duration > (result.inp || 0)) result.inp = Math.round(entry.duration);
548
+ }
549
+ done();
550
+ });
551
+ eventObserver.observe({ type: "event", buffered: true, durationThreshold: 16 });
552
+ } catch {
553
+ done();
554
+ }
555
+ try {
556
+ const longObserver = new PerformanceObserver((list) => {
557
+ result.longTasks += list.getEntries().length;
558
+ });
559
+ longObserver.observe({ type: "longtask", buffered: true });
560
+ } catch {
561
+ /* unsupported */
562
+ }
563
+ });
564
+ }
565
+
566
+ export const PERF_EXPRESSION = `(${perfProbe.toString()})()`;
567
+
568
+ export async function runPerf(options = {}) {
569
+ const viewport = normalizeViewport(options);
570
+ const timeoutMs = options.timeoutMs ?? 30_000;
571
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
572
+ return withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
573
+ await page.setViewport(viewport.width, viewport.height);
574
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
575
+ const metrics = await page.evaluate(PERF_EXPRESSION, { timeoutMs: 12_000 });
576
+ const lcp = metrics?.lcp ?? null;
577
+ const cls = metrics?.cls ?? null;
578
+ const inp = metrics?.inp ?? null;
579
+ const budget = { lcp: 2500, cls: 0.1, inp: 200 };
580
+ const verdict = {
581
+ lcp: lcp === null ? "unknown" : lcp <= budget.lcp ? "pass" : "fail",
582
+ cls: cls === null ? "unknown" : cls <= budget.cls ? "pass" : "fail",
583
+ inp: inp === null ? "unknown" : inp <= budget.inp ? "pass" : "fail",
584
+ };
585
+ const failed = Object.values(verdict).filter((value) => value === "fail").length;
586
+ const result = {
587
+ ok: failed === 0,
588
+ action: "perf",
589
+ target: { url: target.url, finalUrl: navigation.finalUrl, kind: target.kind },
590
+ viewport: { width: viewport.width, height: viewport.height },
591
+ chrome: session.chromeInfo(),
592
+ metrics: { ...metrics, bytesLabel: formatBytes(metrics?.bytes ?? 0) },
593
+ budget,
594
+ verdict,
595
+ text: [
596
+ `browser_qa perf: ${navigation.finalUrl} @ ${viewport.width}x${viewport.height}`,
597
+ `LCP ${lcp === null ? "n/a" : `${lcp} мс`} (${verdict.lcp}) · INP ${inp === null ? "n/a" : `${inp} мс`} (${verdict.inp}) · CLS ${cls === null ? "n/a" : cls} (${verdict.cls})`,
598
+ `FCP ${metrics?.fcp ?? "n/a"} мс · TTFB ${metrics?.ttfb ?? "n/a"} мс · запросов ${metrics?.requests ?? 0} · ${formatBytes(metrics?.bytes ?? 0)} · long tasks ${metrics?.longTasks ?? 0}`,
599
+ `Порог: LCP ≤ ${budget.lcp} мс, INP ≤ ${budget.inp} мс, CLS ≤ ${budget.cls}`,
600
+ failed === 0 ? "Итог: PASS" : `Итог: FAIL — ${failed} метрик вне бюджета`,
601
+ ].join("\n"),
602
+ };
603
+ return result;
604
+ });
605
+ }
606
+
607
+ /* ------------------------------------------------------------------ */
608
+ /* link and section probe */
609
+ /* ------------------------------------------------------------------ */
610
+
611
+ function linksProbe() {
612
+ const links = [];
613
+ for (const anchor of document.querySelectorAll("a[href]")) {
614
+ const href = anchor.getAttribute("href") || "";
615
+ const text = (anchor.textContent || anchor.getAttribute("aria-label") || "").replace(/\s+/gu, " ").trim().slice(0, 80);
616
+ let absolute = "";
617
+ try {
618
+ absolute = new URL(href, location.href).href;
619
+ } catch {
620
+ absolute = "";
621
+ }
622
+ links.push({ href, absolute, text, sameOrigin: absolute.startsWith(location.origin) });
623
+ }
624
+ const emptySections = [];
625
+ for (const section of document.querySelectorAll("section, [data-section]")) {
626
+ const heading = section.querySelector("h1, h2, h3");
627
+ const anchors = section.querySelectorAll("a[href]");
628
+ const textLength = (section.textContent || "").trim().length;
629
+ if (anchors.length === 0 && textLength > 0 && textLength < 400) {
630
+ emptySections.push({ heading: heading ? (heading.textContent || "").trim().slice(0, 60) : "", nodes: section.children.length });
631
+ }
632
+ }
633
+ return { origin: location.origin, links, emptySections: emptySections.slice(0, 20) };
634
+ }
635
+
636
+ export const LINKS_EXPRESSION = `(${linksProbe.toString()})()`;
637
+
638
+ async function headStatus(url, signal) {
639
+ const controller = new AbortController();
640
+ const timer = setTimeout(() => controller.abort(), 8_000);
641
+ const onAbort = () => controller.abort();
642
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
643
+ try {
644
+ let response = await fetch(url, { method: "HEAD", redirect: "follow", signal: controller.signal, headers: { "user-agent": "dsh-browser-qa/probe" } });
645
+ if (response.status === 405 || response.status === 501) {
646
+ response = await fetch(url, { method: "GET", redirect: "follow", signal: controller.signal, headers: { "user-agent": "dsh-browser-qa/probe" } });
647
+ }
648
+ return { status: response.status, finalUrl: response.url };
649
+ } catch (error) {
650
+ return { status: 0, error: error instanceof Error ? error.message : String(error) };
651
+ } finally {
652
+ clearTimeout(timer);
653
+ if (signal) signal.removeEventListener("abort", onAbort);
654
+ }
655
+ }
656
+
657
+ export async function runProbe(options = {}) {
658
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
659
+ const timeoutMs = options.timeoutMs ?? 30_000;
660
+ const maxLinks = Math.max(1, Math.min(80, Number(options.maxLinks) || 40));
661
+ const stage = await withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
662
+ await page.setViewport(1440, 900);
663
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
664
+ const data = await page.evaluate(LINKS_EXPRESSION, { timeoutMs: 10_000 });
665
+ return { data, finalUrl: navigation.finalUrl, chrome: session.chromeInfo() };
666
+ });
667
+ const data = stage.data ?? { links: [], emptySections: [], origin: "" };
668
+ const seen = new Set();
669
+ const candidates = [];
670
+ for (const link of data.links ?? []) {
671
+ if (!link.absolute || seen.has(link.absolute)) continue;
672
+ seen.add(link.absolute);
673
+ if (options.internalOnly !== false && !link.sameOrigin) continue;
674
+ candidates.push(link);
675
+ if (candidates.length >= maxLinks) break;
676
+ }
677
+ const results = [];
678
+ const queue = [...candidates];
679
+ const workers = Array.from({ length: Math.min(6, queue.length) }, async () => {
680
+ while (queue.length > 0) {
681
+ const link = queue.shift();
682
+ if (!link) break;
683
+ const status = await headStatus(link.absolute, options.signal);
684
+ results.push({ ...link, ...status });
685
+ }
686
+ });
687
+ await Promise.all(workers);
688
+ const broken = results.filter((item) => item.status === 0 || item.status >= 400);
689
+ const empty = (data.links ?? []).filter((link) => link.href === "#" || /^javascript:/iu.test(link.href));
690
+ return {
691
+ ok: broken.length === 0 && empty.length === 0 && (data.emptySections ?? []).length === 0,
692
+ action: "probe",
693
+ target: { url: target.url, finalUrl: stage.finalUrl, kind: target.kind },
694
+ chrome: stage.chrome,
695
+ checked: results.length,
696
+ broken,
697
+ emptyLinks: empty.slice(0, 20),
698
+ emptySections: data.emptySections ?? [],
699
+ text: [
700
+ `browser_qa probe: ${stage.finalUrl}`,
701
+ `Проверено ссылок: ${results.length} · битых: ${broken.length} · пустых href: ${empty.length} · пустых разделов: ${(data.emptySections ?? []).length}`,
702
+ ...broken.slice(0, 15).map((item) => ` FAIL ${item.status || "error"} ${item.absolute}${item.error ? ` — ${item.error}` : ""}`),
703
+ ...(data.emptySections ?? []).slice(0, 10).map((item) => ` раздел без ссылок: «${item.heading}»`),
704
+ broken.length === 0 && empty.length === 0 ? "Итог: PASS" : "Итог: FAIL",
705
+ ].join("\n"),
706
+ };
707
+ }
708
+
709
+ /* ------------------------------------------------------------------ */
710
+ /* accessibility runner (static checks + optional focus walk) */
711
+ /* ------------------------------------------------------------------ */
712
+
713
+ function shapeA11y(raw) {
714
+ const issues = Array.isArray(raw?.issues) ? raw.issues : [];
715
+ const counts = { serious: 0, moderate: 0, minor: 0 };
716
+ for (const issue of issues) counts[issue.severity] = (counts[issue.severity] || 0) + 1;
717
+ const byRule = {};
718
+ for (const issue of issues) byRule[issue.rule] = (byRule[issue.rule] || 0) + 1;
719
+ return { issues, counts, byRule };
720
+ }
721
+
722
+ export async function runA11y(options = {}) {
723
+ const viewport = normalizeViewport(options);
724
+ const timeoutMs = options.timeoutMs ?? 30_000;
725
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
726
+ const focusLimit = Math.max(0, Math.min(20, Number(options.focusLimit ?? 12)));
727
+ return withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
728
+ await page.setViewport(viewport.width, viewport.height);
729
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
730
+ const raw = await page.evaluate(A11Y_EXPRESSION, { timeoutMs: 20_000 });
731
+ const shaped = shapeA11y(raw);
732
+ const focus = [];
733
+ if (focusLimit > 0) {
734
+ const list = await page.evaluate(`window.__qaFocusLimit = ${focusLimit}; ${FOCUS_PROBE}`, { timeoutMs: 10_000 });
735
+ for (const item of Array.isArray(list) ? list : []) {
736
+ const before = await page.evaluate(`(() => { const el = document.querySelector('[data-qa-focus="${item.index}"]'); if (!el) return null; el.blur(); const s = getComputedStyle(el); return { outlineStyle: s.outlineStyle, outlineWidth: s.outlineWidth, boxShadow: s.boxShadow }; })()`, { timeoutMs: 3_000 });
737
+ await page.evaluate(`(() => { const el = document.querySelector('[data-qa-focus="${item.index}"]'); if (el && el.focus) { el.scrollIntoView({ block: "center", inline: "center" }); el.focus({ preventScroll: true }); } return true; })()`, { timeoutMs: 3_000 });
738
+ const state = await page.evaluate(FOCUS_STATE, { timeoutMs: 3_000 });
739
+ const outlineVisible = state?.outlineStyle !== "none" && Number(state?.outlineWidth) > 0;
740
+ const shadowVisible = Boolean(state?.boxShadow && state.boxShadow !== "none");
741
+ const changed = Boolean(before) && (before.outlineStyle !== state?.outlineStyle || before.boxShadow !== state?.boxShadow);
742
+ focus.push({
743
+ index: item.index,
744
+ tag: item.tag,
745
+ label: item.label,
746
+ focusVisible: state?.focusVisible === true,
747
+ visible: outlineVisible || shadowVisible || changed,
748
+ obscured: state?.obscured === true,
749
+ top: state?.topTag ?? "",
750
+ });
751
+ }
752
+ }
753
+ /* A missing focus ring is only a defect when the element really can be
754
+ * reached by keyboard (`:focus-visible`): programmatic focus alone does
755
+ * not render the UA ring in Chrome. */
756
+ const invisibleFocus = focus.filter((item) => item.focusVisible === true && item.visible === false);
757
+ const obscuredFocus = focus.filter((item) => item.obscured === true);
758
+ const pass = shaped.counts.serious === 0 && invisibleFocus.length === 0;
759
+ const result = {
760
+ ok: pass,
761
+ action: "a11y",
762
+ target: { url: target.url, finalUrl: navigation.finalUrl, kind: target.kind },
763
+ viewport: { width: viewport.width, height: viewport.height },
764
+ chrome: session.chromeInfo(),
765
+ counts: shaped.counts,
766
+ byRule: shaped.byRule,
767
+ issues: shaped.issues.slice(0, 120),
768
+ stats: raw?.stats ?? {},
769
+ focus,
770
+ focusInvisible: invisibleFocus.length,
771
+ focusObscured: obscuredFocus.length,
772
+ };
773
+ result.text = formatA11yText(result);
774
+ return result;
775
+ });
776
+ }
777
+
778
+ function formatA11yText(result) {
779
+ const counts = result.counts ?? {};
780
+ const lines = [
781
+ `browser_qa a11y: ${result.target?.finalUrl ?? ""} @ ${result.viewport?.width}x${result.viewport?.height}`,
782
+ `serious ${counts.serious ?? 0} · moderate ${counts.moderate ?? 0} · minor ${counts.minor ?? 0} · фокус: невидим ${result.focusInvisible}, перекрыт ${result.focusObscured}`,
783
+ ];
784
+ const rules = Object.entries(result.byRule ?? {}).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([rule, count]) => `${rule}×${count}`);
785
+ if (rules.length > 0) lines.push(`Правила: ${rules.join(" · ")}`);
786
+ for (const issue of (result.issues ?? []).slice(0, 18)) {
787
+ lines.push(` ${issue.severity === "serious" ? "FAIL" : issue.severity === "moderate" ? "warn" : "info"} ${issue.rule}: ${issue.detail} [${issue.node}]`);
788
+ }
789
+ for (const item of (result.focus ?? []).filter((entry) => entry.visible === false || entry.obscured).slice(0, 8)) {
790
+ const why = item.visible === false ? "нет видимого индикатора" : `перекрыт (${item.top}); проверьте после закрытия оверлеев`;
791
+ lines.push(` ${item.visible === false ? "FAIL" : "warn"} focus ${item.tag} «${item.label}»: ${why}`);
792
+ }
793
+ lines.push(result.ok ? "Итог: PASS — serious 0, фокус виден" : "Итог: FAIL — устраните serious и невидимый фокус");
794
+ return lines.join("\n");
795
+ }
796
+
797
+ /* ------------------------------------------------------------------ */
798
+ /* design audit: rhythm, duplicates, layers, type scale */
799
+ /* ------------------------------------------------------------------ */
800
+
801
+ function designProbe() {
802
+ const issues = [];
803
+ const push = (rule, severity, node, detail) => {
804
+ if (issues.length < 200) issues.push({ rule, severity, node, detail });
805
+ };
806
+ const round = (value) => Math.round(value * 10) / 10;
807
+ const pathOf = (el) => {
808
+ if (!el || el.nodeType !== 1) return "(none)";
809
+ const parts = [];
810
+ let node = el;
811
+ while (node && node.nodeType === 1 && parts.length < 4) {
812
+ let part = node.tagName.toLowerCase();
813
+ if (node.id) {
814
+ part += `#${node.id}`;
815
+ parts.unshift(part);
816
+ break;
817
+ }
818
+ const cls = (node.getAttribute("class") || "").trim().split(/\s+/u).filter(Boolean).slice(0, 2);
819
+ if (cls.length > 0) part += `.${cls.join(".")}`;
820
+ parts.unshift(part);
821
+ node = node.parentElement;
822
+ }
823
+ return parts.join(" > ");
824
+ };
825
+ const visible = (el) => {
826
+ const style = getComputedStyle(el);
827
+ const rect = el.getBoundingClientRect();
828
+ return style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) > 0 && rect.width >= 1 && rect.height >= 1;
829
+ };
830
+
831
+ /* 1. Rhythm of sections: the same rhythm everywhere, no 100px outliers. */
832
+ const sections = [...document.querySelectorAll("section, main > div, [data-section]")].filter((el) => {
833
+ const style = getComputedStyle(el);
834
+ const rect = el.getBoundingClientRect();
835
+ return style.display !== "none" && rect.height > 40;
836
+ });
837
+ const rhythm = sections.map((el) => {
838
+ const style = getComputedStyle(el);
839
+ return {
840
+ node: pathOf(el),
841
+ top: round(parseFloat(style.paddingTop) || 0),
842
+ bottom: round(parseFloat(style.paddingBottom) || 0),
843
+ };
844
+ });
845
+ const totals = rhythm.map((item) => item.top + item.bottom).filter((value) => value > 0).sort((a, b) => a - b);
846
+ const median = totals.length > 0 ? totals[Math.floor(totals.length / 2)] : 0;
847
+ let rhythmOutliers = 0;
848
+ for (const item of rhythm) {
849
+ const total = item.top + item.bottom;
850
+ if (total === 0) {
851
+ push("rhythm-zero", "minor", item.node, "у секции нет вертикальных отступов (соседние блоки слипаются)");
852
+ continue;
853
+ }
854
+ if (median > 0 && (total > median * 1.5 || total < median * 0.5)) {
855
+ rhythmOutliers += 1;
856
+ push("rhythm-outlier", "moderate", item.node, `вертикальные отступы ${total}px против медианы ${median}px`);
857
+ }
858
+ if (Math.abs(item.top - item.bottom) > 8) {
859
+ push("rhythm-asymmetric", "minor", item.node, `сверху ${item.top}px, снизу ${item.bottom}px — секция «висит»`);
860
+ }
861
+ }
862
+
863
+ /* 2. The 4/8 grid: a padding not divisible by 4 is usually accidental. */
864
+ let magic = 0;
865
+ for (const item of rhythm) {
866
+ for (const [side, value] of [["сверху", item.top], ["снизу", item.bottom]]) {
867
+ if (value > 0 && value % 4 !== 0) {
868
+ magic += 1;
869
+ push("magic-spacing", "minor", item.node, `${side} ${value}px не кратно 4`);
870
+ }
871
+ }
872
+ }
873
+
874
+ /* 3. Copy-paste rules: the same selector **with the same declarations** twice
875
+ * in one media context. A selector redefined with other properties is normal
876
+ * cascade, so only an identical block counts — that is what "дописали .cookie
877
+ * ещё раз" looks like in a real stylesheet. */
878
+ const signatureCount = new Map();
879
+ let scanned = 0;
880
+ for (const sheet of [...document.styleSheets]) {
881
+ let rules;
882
+ try {
883
+ rules = sheet.cssRules;
884
+ } catch {
885
+ continue;
886
+ }
887
+ if (!rules) continue;
888
+ const walk = (list, media = "") => {
889
+ for (const rule of list) {
890
+ if (rule.type === 1 && rule.selectorText && rule.style) {
891
+ scanned += 1;
892
+ const signature = [...rule.style].map((prop) => `${prop}:${rule.style.getPropertyValue(prop)}`).sort().join(";");
893
+ if (signature.length > 0) {
894
+ const key = `${media}||${rule.selectorText.trim()}||${signature}`;
895
+ signatureCount.set(key, (signatureCount.get(key) || 0) + 1);
896
+ }
897
+ } else if (rule.cssRules && rule.type !== 7) {
898
+ walk(rule.cssRules, rule.type === 4 ? `@media ${rule.conditionText ?? ""}` : media);
899
+ }
900
+ }
901
+ };
902
+ walk(rules);
903
+ }
904
+ const duplicates = [...signatureCount.entries()].filter(([, count]) => count > 1).map(([key, count]) => {
905
+ const [media, selector] = key.split("||");
906
+ return { selector, media, count };
907
+ }).sort((a, b) => b.count - a.count);
908
+ for (const item of duplicates.slice(0, 20)) {
909
+ push("duplicate-rule", "moderate", item.selector, `правило продублировано ${item.count} раз(а) с теми же свойствами${item.media ? ` (${item.media})` : ""} — сведите к одному слою`);
910
+ }
911
+
912
+ /* 4. Layers: z-index values far above the token scale. */
913
+ const zValues = new Map();
914
+ for (const el of document.querySelectorAll("body *")) {
915
+ const value = Number(getComputedStyle(el).zIndex);
916
+ if (!Number.isFinite(value) || value === 0) continue;
917
+ if (!zValues.has(value)) zValues.set(value, pathOf(el));
918
+ }
919
+ const maxZ = Math.max(0, ...zValues.keys());
920
+ for (const value of [...zValues.keys()].sort((a, b) => b - a).slice(0, 5)) {
921
+ if (value > 1000) push("z-index-extreme", "moderate", zValues.get(value), `z-index ${value} вне шкалы слоёв`);
922
+ }
923
+
924
+ /* 5. Type scale: too many distinct sizes means no scale at all. */
925
+ const sizes = new Map();
926
+ for (const el of document.querySelectorAll("h1, h2, h3, h4, p, li, a, button")) {
927
+ const style = getComputedStyle(el);
928
+ if (style.display === "none") continue;
929
+ const key = round(parseFloat(style.fontSize) || 0);
930
+ if (!sizes.has(key)) sizes.set(key, pathOf(el));
931
+ }
932
+ if (sizes.size > 12) {
933
+ push("type-scale", "minor", "body", `различных размеров шрифта ${sizes.size} — шкала разрастается (норма ≤ 12)`);
934
+ }
935
+
936
+ /* 6. Section heads: two different classes with different margins. */
937
+ const heads = [...document.querySelectorAll("[class*='sec__head'], [class*='sec-head']")];
938
+ const headGaps = new Map();
939
+ for (const head of heads) {
940
+ const style = getComputedStyle(head);
941
+ const gap = round((parseFloat(style.marginBottom) || 0) + (parseFloat(style.paddingBottom) || 0));
942
+ if (!headGaps.has(gap)) headGaps.set(gap, pathOf(head));
943
+ }
944
+ if (headGaps.size > 1) {
945
+ push("head-inconsistent", "moderate", [...headGaps.values()][0], `отступы шапок секций различаются: ${[...headGaps.keys()].join(" / ")}px`);
946
+ }
947
+
948
+ /* 7. Typography depth: measure, line-height, families, weights. */
949
+ const families = new Set();
950
+ const weights = new Set();
951
+ const measures = [];
952
+ const ratios = [];
953
+ const canvas = document.createElement("canvas");
954
+ const context = canvas.getContext("2d");
955
+ for (const el of document.querySelectorAll("p, li")) {
956
+ if (!visible(el)) continue;
957
+ const style = getComputedStyle(el);
958
+ families.add((style.fontFamily || "").split(",")[0].trim());
959
+ weights.add(style.fontWeight);
960
+ const size = parseFloat(style.fontSize) || 16;
961
+ const height = parseFloat(style.lineHeight) || 0;
962
+ if (height > 0) ratios.push(Math.round((height / size) * 100) / 100);
963
+ if (context) {
964
+ context.font = `${style.fontWeight} ${size}px ${style.fontFamily}`;
965
+ const ch = context.measureText("0").width || size * 0.5;
966
+ const width = el.getBoundingClientRect().width;
967
+ if (ch > 0) measures.push(Math.round((width / ch) * 10) / 10);
968
+ }
969
+ }
970
+ measures.sort((a, b) => a - b);
971
+ ratios.sort((a, b) => a - b);
972
+ const measureMedian = measures.length > 0 ? measures[Math.floor(measures.length / 2)] : 0;
973
+ const ratioMedian = ratios.length > 0 ? ratios[Math.floor(ratios.length / 2)] : 0;
974
+ if (measureMedian > 85) push("measure-long", "moderate", "p", `строка ${measureMedian}ch — читать тяжело (норма 45–75ch)`);
975
+ if (measureMedian > 0 && measureMedian < 30) push("measure-short", "minor", "p", `строка ${measureMedian}ch — слишком коротко`);
976
+ if (ratioMedian > 0 && (ratioMedian < 1.3 || ratioMedian > 1.8)) push("line-height", "minor", "p", `межстрочный ${ratioMedian} — норма 1.4–1.7 для текста`);
977
+ if (families.size > 2) push("font-families", "moderate", "body", `семейств шрифта ${families.size} — норма ≤ 2`);
978
+
979
+ const counts = { serious: 0, moderate: 0, minor: 0 };
980
+ for (const issue of issues) counts[issue.severity] = (counts[issue.severity] || 0) + 1;
981
+
982
+ return {
983
+ url: location.href,
984
+ counts,
985
+ issues,
986
+ stats: {
987
+ sections: sections.length,
988
+ medianRhythm: median,
989
+ rhythmOutliers,
990
+ magicValues: magic,
991
+ duplicates: duplicates.length,
992
+ rulesScanned: scanned,
993
+ maxZ,
994
+ typeSizes: sizes.size,
995
+ headGaps: [...headGaps.keys()],
996
+ fontFamilies: families.size,
997
+ fontWeights: weights.size,
998
+ measureMedian,
999
+ lineHeightMedian: ratioMedian,
1000
+ },
1001
+ };
1002
+ }
1003
+
1004
+ export const DESIGN_EXPRESSION = `(${designProbe.toString()})()`;
1005
+
1006
+ function formatDesignText(result) {
1007
+ const stats = result.stats ?? {};
1008
+ const counts = result.counts ?? {};
1009
+ const lines = [
1010
+ `browser_qa design: ${result.target?.finalUrl ?? ""}`,
1011
+ `секций ${stats.sections ?? 0} · медиана ритма ${stats.medianRhythm ?? 0}px · выбросов ${stats.rhythmOutliers ?? 0} · магических px ${stats.magicValues ?? 0}`,
1012
+ `дублей селекторов ${stats.duplicates ?? 0} (правил просмотрено ${stats.rulesScanned ?? 0}) · max z-index ${stats.maxZ ?? 0} · размеров шрифта ${stats.typeSizes ?? 0}`,
1013
+ `serious ${counts.serious ?? 0} · moderate ${counts.moderate ?? 0} · minor ${counts.minor ?? 0}`,
1014
+ ];
1015
+ for (const issue of (result.issues ?? []).slice(0, 18)) {
1016
+ const mark = issue.severity === "serious" ? "FAIL" : issue.severity === "moderate" ? "warn" : "info";
1017
+ lines.push(` ${mark} ${issue.rule}: ${issue.detail} [${issue.node}]`);
1018
+ }
1019
+ lines.push(result.ok ? "Итог: PASS — ритм ровный, дублей ≤5, магических px ≤2" : "Итог: FAIL — порог: ритм-выбросов ≤1, дублей ≤5, магических px ≤2, serious 0");
1020
+ return lines.join("\n");
1021
+ }
1022
+
1023
+ export async function runDesign(options = {}) {
1024
+ const viewport = normalizeViewport(options);
1025
+ const timeoutMs = options.timeoutMs ?? 30_000;
1026
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
1027
+ return withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
1028
+ await page.setViewport(viewport.width, viewport.height);
1029
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
1030
+ const raw = await page.evaluate(DESIGN_EXPRESSION, { timeoutMs: 15_000 });
1031
+ const counts = raw?.counts ?? { serious: 0, moderate: 0, minor: 0 };
1032
+ const stats = raw?.stats ?? {};
1033
+ const ok =
1034
+ counts.serious === 0 &&
1035
+ (stats.duplicates ?? 0) <= 5 &&
1036
+ (stats.rhythmOutliers ?? 0) <= 1 &&
1037
+ (stats.magicValues ?? 0) <= 2;
1038
+ const result = {
1039
+ ok,
1040
+ action: "design",
1041
+ target: { url: target.url, finalUrl: navigation.finalUrl, kind: target.kind },
1042
+ viewport: { width: viewport.width, height: viewport.height },
1043
+ chrome: session.chromeInfo(),
1044
+ counts,
1045
+ stats,
1046
+ issues: (raw?.issues ?? []).slice(0, 80),
1047
+ };
1048
+ result.text = formatDesignText(result);
1049
+ return result;
1050
+ });
1051
+ }
1052
+
1053
+ /* ------------------------------------------------------------------ */
1054
+ /* locate: "вот этот блок" -> selector, metrics, crop */
1055
+ /* ------------------------------------------------------------------ */
1056
+
1057
+ function locateProbe(spec) {
1058
+ const normalize = (value) => String(value ?? "").replace(/\s+/gu, " ").trim().toLowerCase();
1059
+ const needle = normalize(spec.text);
1060
+ const scope = spec.scope ? document.querySelector(spec.scope) : document.body;
1061
+ if (!scope) return { found: false, reason: `scope не найден: ${spec.scope}` };
1062
+ if (!needle) return { found: false, reason: "пустой text" };
1063
+
1064
+ const visible = (el) => {
1065
+ const style = getComputedStyle(el);
1066
+ const rect = el.getBoundingClientRect();
1067
+ return style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) > 0 && rect.width >= 1 && rect.height >= 1;
1068
+ };
1069
+ const ownText = (el) => {
1070
+ const text = [...el.childNodes]
1071
+ .filter((node) => node.nodeType === 3)
1072
+ .map((node) => node.textContent)
1073
+ .join(" ");
1074
+ return normalize(text);
1075
+ };
1076
+ const depth = (el) => {
1077
+ let level = 0;
1078
+ let node = el;
1079
+ while (node && node !== document.body) {
1080
+ level += 1;
1081
+ node = node.parentElement;
1082
+ }
1083
+ return level;
1084
+ };
1085
+ const selectorOf = (el) => {
1086
+ const parts = [];
1087
+ let node = el;
1088
+ while (node && node.nodeType === 1 && node !== document.documentElement) {
1089
+ let part = node.tagName.toLowerCase();
1090
+ if (node.id) {
1091
+ part = `${part}#${node.id}`;
1092
+ parts.unshift(part);
1093
+ break;
1094
+ }
1095
+ const parent = node.parentElement;
1096
+ if (parent) {
1097
+ const same = [...parent.children].filter((child) => child.tagName === node.tagName);
1098
+ if (same.length > 1) part += `:nth-of-type(${same.indexOf(node) + 1})`;
1099
+ }
1100
+ parts.unshift(part);
1101
+ node = node.parentElement;
1102
+ }
1103
+ return parts.join(" > ");
1104
+ };
1105
+
1106
+ const matches = [];
1107
+ for (const el of scope.querySelectorAll("*")) {
1108
+ if (!visible(el)) continue;
1109
+ const full = normalize(el.textContent);
1110
+ if (!full.includes(needle)) continue;
1111
+ matches.push({ el, own: ownText(el).includes(needle), depth: depth(el), length: full.length });
1112
+ }
1113
+ if (matches.length === 0) return { found: false, reason: `текст не найден: ${spec.text}` };
1114
+ const exact = matches.filter((item) => item.own);
1115
+ const pool = (exact.length > 0 ? exact : matches).sort((a, b) => (b.depth - a.depth) || (a.length - b.length));
1116
+ const index = Math.max(0, Number(spec.index ?? 0));
1117
+ const chosen = pool[index] ?? pool[0];
1118
+ const el = chosen.el;
1119
+ const rect = el.getBoundingClientRect();
1120
+ const style = getComputedStyle(el);
1121
+ const scrollX = window.scrollX;
1122
+ const scrollY = window.scrollY;
1123
+ const gap = (sibling) => {
1124
+ if (!sibling || sibling.nodeType !== 1) return null;
1125
+ const other = sibling.getBoundingClientRect();
1126
+ if (other.width < 1 && other.height < 1) return null;
1127
+ const verticalGap = Math.round(rect.top >= other.bottom ? rect.top - other.bottom : other.top - rect.bottom);
1128
+ return { tag: sibling.tagName.toLowerCase(), gap: verticalGap };
1129
+ };
1130
+
1131
+ return {
1132
+ found: true,
1133
+ total: matches.length,
1134
+ exact: exact.length,
1135
+ index,
1136
+ selector: selectorOf(el),
1137
+ tag: el.tagName.toLowerCase(),
1138
+ text: String(el.textContent ?? "").replace(/\s+/gu, " ").trim().slice(0, 120),
1139
+ rect: {
1140
+ x: Math.round(rect.left + scrollX),
1141
+ y: Math.round(rect.top + scrollY),
1142
+ width: Math.round(rect.width),
1143
+ height: Math.round(rect.height),
1144
+ },
1145
+ viewportRect: { x: Math.round(rect.left), y: Math.round(rect.top) },
1146
+ computed: {
1147
+ padding: style.padding,
1148
+ margin: style.margin,
1149
+ fontSize: style.fontSize,
1150
+ lineHeight: style.lineHeight,
1151
+ color: style.color,
1152
+ background: style.backgroundColor,
1153
+ },
1154
+ neighbours: { previous: gap(el.previousElementSibling), next: gap(el.nextElementSibling) },
1155
+ scroll: { x: Math.round(scrollX), y: Math.round(scrollY) },
1156
+ page: { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight },
1157
+ };
1158
+ }
1159
+
1160
+ export const LOCATE_EXPRESSION = `(${locateProbe.toString()})`;
1161
+
1162
+ export async function runLocate(options = {}) {
1163
+ const viewport = normalizeViewport(options);
1164
+ const timeoutMs = options.timeoutMs ?? 30_000;
1165
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
1166
+ const outDir = resolveOutDir(options.outDir ?? ".dsh/browser-qa", options.cwd ?? process.cwd());
1167
+ fs.mkdirSync(outDir, { recursive: true });
1168
+ return withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
1169
+ await page.setViewport(viewport.width, viewport.height);
1170
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
1171
+ const spec = { text: options.text, index: options.index, scope: options.scope };
1172
+ const found = await page.evaluate(`${LOCATE_EXPRESSION}(${JSON.stringify(spec)})`, { timeoutMs: 10_000 });
1173
+ if (!found?.found) {
1174
+ return {
1175
+ ok: false,
1176
+ action: "locate",
1177
+ target: { url: target.url, finalUrl: navigation.finalUrl, kind: target.kind },
1178
+ reason: found?.reason ?? "элемент не найден",
1179
+ text: `browser_qa locate: не найдено «${options.text ?? ""}» на ${navigation.finalUrl}\n${found?.reason ?? ""}`,
1180
+ };
1181
+ }
1182
+ const pad = 24;
1183
+ const x = Math.max(0, found.rect.x - pad);
1184
+ const y = Math.max(0, found.rect.y - pad);
1185
+ const width = Math.min(found.page.width - x, found.rect.width + pad * 2);
1186
+ const height = Math.min(found.page.height - y, found.rect.height + pad * 2);
1187
+ let file = "";
1188
+ try {
1189
+ const shot = await page.cdp.send(
1190
+ "Page.captureScreenshot",
1191
+ { format: "png", clip: { x, y, width: Math.max(1, width), height: Math.max(1, height), scale: 1 }, captureBeyondViewport: true },
1192
+ 20_000,
1193
+ );
1194
+ file = path.join(outDir, `locate-${Date.now().toString(36)}.png`);
1195
+ fs.writeFileSync(file, Buffer.from(shot.data, "base64"));
1196
+ } catch {
1197
+ /* a crop is a bonus; the metrics are the payload */
1198
+ }
1199
+ const gapPrev = found.neighbours?.previous?.gap;
1200
+ const gapNext = found.neighbours?.next?.gap;
1201
+ return {
1202
+ ok: true,
1203
+ action: "locate",
1204
+ target: { url: target.url, finalUrl: navigation.finalUrl, kind: target.kind },
1205
+ viewport: { width: viewport.width, height: viewport.height },
1206
+ selector: found.selector,
1207
+ matches: { total: found.total, exact: found.exact },
1208
+ rect: found.rect,
1209
+ computed: found.computed,
1210
+ neighbours: found.neighbours,
1211
+ screenshot: file ? { file, crop: { x, y, width, height } } : null,
1212
+ text: [
1213
+ `browser_qa locate: ${navigation.finalUrl} @ ${viewport.width}x${viewport.height}`,
1214
+ `Элемент: ${found.selector} (${found.tag}) — «${found.text}»`,
1215
+ `rect: ${found.rect.x},${found.rect.y} ${found.rect.width}×${found.rect.height} · совпадений ${found.total} (точных ${found.exact})`,
1216
+ `padding ${found.computed.padding} · margin ${found.computed.margin} · font ${found.computed.fontSize}/${found.computed.lineHeight}`,
1217
+ `соседи: сверху ${gapPrev === undefined || gapPrev === null ? "—" : `${gapPrev}px`} · снизу ${gapNext === undefined || gapNext === null ? "—" : `${gapNext}px`}`,
1218
+ file ? `PNG: ${file}` : "",
1219
+ "Итог: PASS — объект найден; правьте его, а не «страницу».",
1220
+ ].filter(Boolean).join("\n"),
1221
+ };
1222
+ });
1223
+ }
1224
+
1225
+ /* ------------------------------------------------------------------ */
1226
+ /* compare: baseline screenshot + pixel diff */
1227
+ /* ------------------------------------------------------------------ */
1228
+
1229
+ export async function runCompare(options = {}) {
1230
+ const viewport = normalizeViewport(options);
1231
+ const timeoutMs = options.timeoutMs ?? 30_000;
1232
+ const target = normalizeTarget(options.target ?? options.url, { cwd: options.cwd ?? process.cwd() });
1233
+ const cwd = options.cwd ?? process.cwd();
1234
+ const outDir = resolveOutDir(options.outDir ?? ".dsh/browser-qa", cwd);
1235
+ const baselineDir = resolveOutDir(options.baselineDir ?? path.join(".dsh", "browser-qa", "baseline"), cwd);
1236
+ fs.mkdirSync(outDir, { recursive: true });
1237
+ fs.mkdirSync(baselineDir, { recursive: true });
1238
+ const slug = slugForTarget(target.url);
1239
+ const baselineFile = path.join(baselineDir, `${slug}-${viewport.width}x${viewport.height}.png`);
1240
+ const shot = await withSession({ ...options, target: options.target ?? options.url }, async ({ session, page }) => {
1241
+ await page.setViewport(viewport.width, viewport.height);
1242
+ const navigation = await page.navigate(target.url, { timeoutMs, signal: options.signal });
1243
+ const image = await page.screenshot({ fullPage: options.fullPage === true, timeoutMs: 30_000 });
1244
+ return { base64: image.base64, navigation, chrome: session.chromeInfo() };
1245
+ });
1246
+ const current = Buffer.from(shot.base64, "base64");
1247
+ const threshold = Number.isFinite(Number(options.threshold)) ? Math.max(0, Math.min(1, Number(options.threshold))) : 0.002;
1248
+ const rotate = options.update === true || !fs.existsSync(baselineFile);
1249
+ if (rotate) {
1250
+ fs.writeFileSync(baselineFile, current);
1251
+ return {
1252
+ ok: true,
1253
+ action: "compare",
1254
+ baseline: "created",
1255
+ target: { url: target.url, finalUrl: shot.navigation.finalUrl },
1256
+ viewport: { width: viewport.width, height: viewport.height },
1257
+ baselineFile,
1258
+ text: `browser_qa compare: baseline создан для ${shot.navigation.finalUrl} @ ${viewport.width}x${viewport.height}\nPNG: ${baselineFile}\nИтог: PASS — следующий прогон сравнит с этим кадром.`,
1259
+ };
1260
+ }
1261
+ const baselineBuffer = fs.readFileSync(baselineFile);
1262
+ let result;
1263
+ try {
1264
+ const before = decodePng(baselineBuffer);
1265
+ const after = decodePng(current);
1266
+ if (before.width !== after.width || before.height !== after.height) {
1267
+ return {
1268
+ ok: false,
1269
+ action: "compare",
1270
+ baseline: "size-mismatch",
1271
+ baselineFile,
1272
+ before: { width: before.width, height: before.height },
1273
+ after: { width: after.width, height: after.height },
1274
+ text: `browser_qa compare: размер кадра изменился ${before.width}x${before.height} → ${after.width}x${after.height}\nЭто уже регрессия раскладки. Обновить baseline: update=true.`,
1275
+ };
1276
+ }
1277
+ result = compareImages(before, after);
1278
+ } catch (error) {
1279
+ return {
1280
+ ok: false,
1281
+ action: "compare",
1282
+ baseline: "decode-error",
1283
+ baselineFile,
1284
+ text: `browser_qa compare: не удалось сравнить PNG (${error instanceof Error ? error.message : String(error)}). Обновить baseline: update=true.`,
1285
+ };
1286
+ }
1287
+ const stamp = new Date().toISOString().replace(/[:.]/gu, "-");
1288
+ const diffFile = path.join(outDir, `diff-${slug}-${viewport.width}x${viewport.height}-${stamp}.png`);
1289
+ fs.writeFileSync(diffFile, encodePng({ width: result.width, height: result.height, rgba: result.diff }));
1290
+ const ok = result.ratio <= threshold;
1291
+ return {
1292
+ ok,
1293
+ action: "compare",
1294
+ baseline: "compared",
1295
+ baselineFile,
1296
+ diffFile,
1297
+ changed: result.changed,
1298
+ ratio: Math.round(result.ratio * 10000) / 10000,
1299
+ box: result.box,
1300
+ threshold,
1301
+ target: { url: target.url, finalUrl: shot.navigation.finalUrl },
1302
+ viewport: { width: viewport.width, height: viewport.height },
1303
+ text: [
1304
+ `browser_qa compare: ${shot.navigation.finalUrl} @ ${viewport.width}x${viewport.height}`,
1305
+ `Изменено ${result.changed} px (${(result.ratio * 100).toFixed(2)} %), порог ${(threshold * 100).toFixed(2)} %`,
1306
+ result.box ? `Область изменений: ${result.box.x},${result.box.y} ${result.box.width}×${result.box.height}` : "Изменений нет",
1307
+ `Дифф: ${diffFile}`,
1308
+ ok ? "Итог: PASS — в пределах порога" : "Итог: FAIL — визуальная регрессия; проверьте область и обновите baseline после осознанного изменения",
1309
+ ].join("\n"),
1310
+ };
1311
+ }
1312
+
1313
+ export { PageSession };