kitskill 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +397 -2
- package/THIRD-PARTY-NOTICES.md +24 -0
- package/banner.jpeg +0 -0
- package/bin/cli.mjs +464 -0
- package/lib/fs-safe.mjs +136 -0
- package/lib/hook.mjs +79 -0
- package/lib/installer.mjs +449 -0
- package/lib/manifest.mjs +47 -0
- package/lib/permissions.mjs +175 -0
- package/lib/profile.mjs +124 -0
- package/lib/project-scan.mjs +186 -0
- package/lib/validator.mjs +72 -0
- package/logo.png +0 -0
- package/logohead.png +0 -0
- package/package.json +54 -4
- package/templates/core/memory/PROJECT.md +33 -0
- package/templates/core/memory/decisions/ADR.md +22 -0
- package/templates/core/profile.json +17 -0
- package/templates/core/router.md +89 -0
- package/templates/core/state/STATE.md +32 -0
- package/templates/opencode/policy-plugin.js +66 -0
- package/templates/scripts/graph-client.mjs +231 -0
- package/templates/scripts/review-packet.mjs +250 -0
- package/templates/scripts/shrink-output.mjs +159 -0
- package/templates/scripts/ui-audit.mjs +639 -0
- package/templates/scripts/verify.mjs +293 -0
- package/templates/skills/ks-api/SKILL.md +87 -0
- package/templates/skills/ks-api/references/api-contract.md +131 -0
- package/templates/skills/ks-build/SKILL.md +92 -0
- package/templates/skills/ks-data/SKILL.md +81 -0
- package/templates/skills/ks-data/references/data-migrations.md +120 -0
- package/templates/skills/ks-deliver/SKILL.md +99 -0
- package/templates/skills/ks-deliver/references/doc-patterns.md +180 -0
- package/templates/skills/ks-design/SKILL.md +147 -0
- package/templates/skills/ks-design/references/app-models.md +216 -0
- package/templates/skills/ks-design/references/design-contract.md +98 -0
- package/templates/skills/ks-design/references/visual-directions.md +159 -0
- package/templates/skills/ks-plan/SKILL.md +84 -0
- package/templates/skills/ks-review/SKILL.md +71 -0
- package/templates/skills/ks-secure/SKILL.md +55 -0
|
@@ -0,0 +1,639 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const BROWSERS = [
|
|
10
|
+
process.env.CHROME_PATH,
|
|
11
|
+
'google-chrome',
|
|
12
|
+
'google-chrome-stable',
|
|
13
|
+
'chromium',
|
|
14
|
+
'chromium-browser',
|
|
15
|
+
].filter(Boolean);
|
|
16
|
+
|
|
17
|
+
export function findBrowser() {
|
|
18
|
+
for (const candidate of BROWSERS) {
|
|
19
|
+
const run = spawnSync(candidate, ['--version'], { encoding: 'utf8', timeout: 5000 });
|
|
20
|
+
if (run.status === 0) return candidate;
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function auditInPage(contrast) {
|
|
26
|
+
const issues = [];
|
|
27
|
+
const hasLabel = (el) => {
|
|
28
|
+
if (el.getAttribute('aria-label') || el.getAttribute('aria-labelledby')) return true;
|
|
29
|
+
if (el.id && document.querySelector(`label[for="${CSS.escape(el.id)}"]`)) return true;
|
|
30
|
+
return Boolean(el.closest('label'));
|
|
31
|
+
};
|
|
32
|
+
const nameOf = (el) =>
|
|
33
|
+
(el.getAttribute('aria-label') || el.textContent || el.getAttribute('title') || '').trim();
|
|
34
|
+
|
|
35
|
+
document.querySelectorAll('a[href],button,input,select,textarea,[tabindex]').forEach((el) => {
|
|
36
|
+
if (el.matches('input[type=hidden]')) return;
|
|
37
|
+
const formControl = ['INPUT', 'SELECT', 'TEXTAREA'].includes(el.tagName);
|
|
38
|
+
if (formControl) {
|
|
39
|
+
if (!hasLabel(el) && !el.getAttribute('placeholder') && !el.getAttribute('title')) {
|
|
40
|
+
issues.push({ rule: 'form-label', tag: el.tagName.toLowerCase(), html: el.outerHTML.slice(0, 160) });
|
|
41
|
+
}
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (!nameOf(el) && !el.getAttribute('title')) {
|
|
45
|
+
issues.push({ rule: 'accessible-name', tag: el.tagName.toLowerCase(), html: el.outerHTML.slice(0, 160) });
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
document.querySelectorAll('img').forEach((img) => {
|
|
50
|
+
if (!img.hasAttribute('alt')) {
|
|
51
|
+
issues.push({ rule: 'image-alt', html: img.outerHTML.slice(0, 160) });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
if (!document.documentElement.lang) issues.push({ rule: 'html-lang' });
|
|
56
|
+
if (!document.title.trim()) issues.push({ rule: 'document-title' });
|
|
57
|
+
|
|
58
|
+
if (contrast) {
|
|
59
|
+
const parseColor = (value) => {
|
|
60
|
+
const match = String(value).match(/rgba?\(([^)]+)\)/);
|
|
61
|
+
if (!match) return null;
|
|
62
|
+
const parts = match[1].split(',').map((part) => Number.parseFloat(part));
|
|
63
|
+
return { r: parts[0], g: parts[1], b: parts[2], a: parts.length > 3 ? parts[3] : 1 };
|
|
64
|
+
};
|
|
65
|
+
const luminance = ({ r, g, b }) => {
|
|
66
|
+
const channel = (value) => {
|
|
67
|
+
const v = value / 255;
|
|
68
|
+
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
|
69
|
+
};
|
|
70
|
+
return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
|
|
71
|
+
};
|
|
72
|
+
const ratio = (a, b) => {
|
|
73
|
+
const l1 = luminance(a);
|
|
74
|
+
const l2 = luminance(b);
|
|
75
|
+
return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
|
76
|
+
};
|
|
77
|
+
const backgroundOf = (el) => {
|
|
78
|
+
let node = el;
|
|
79
|
+
while (node) {
|
|
80
|
+
const style = getComputedStyle(node);
|
|
81
|
+
if (style.backgroundImage && style.backgroundImage !== 'none') return null;
|
|
82
|
+
const color = parseColor(style.backgroundColor);
|
|
83
|
+
if (color) {
|
|
84
|
+
if (color.a >= 0.99) return color;
|
|
85
|
+
if (color.a > 0) return null;
|
|
86
|
+
}
|
|
87
|
+
node = node.parentElement;
|
|
88
|
+
}
|
|
89
|
+
return { r: 255, g: 255, b: 255, a: 1 };
|
|
90
|
+
};
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
93
|
+
let node;
|
|
94
|
+
let reported = 0;
|
|
95
|
+
while ((node = walker.nextNode()) && reported < 10) {
|
|
96
|
+
if (!node.textContent.trim()) continue;
|
|
97
|
+
const el = node.parentElement;
|
|
98
|
+
if (!el || seen.has(el)) continue;
|
|
99
|
+
seen.add(el);
|
|
100
|
+
const style = getComputedStyle(el);
|
|
101
|
+
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) continue;
|
|
102
|
+
const fg = parseColor(style.color);
|
|
103
|
+
const bg = backgroundOf(el);
|
|
104
|
+
if (!fg || fg.a < 0.99 || !bg) continue;
|
|
105
|
+
const size = Number.parseFloat(style.fontSize);
|
|
106
|
+
const bold = style.fontWeight === 'bold' || Number(style.fontWeight) >= 700;
|
|
107
|
+
const large = size >= 24 || (size >= 18.66 && bold);
|
|
108
|
+
const required = large ? 3 : 4.5;
|
|
109
|
+
const value = ratio(fg, bg);
|
|
110
|
+
if (value + 0.01 < required) {
|
|
111
|
+
issues.push({
|
|
112
|
+
rule: 'contrast',
|
|
113
|
+
ratio: Number(value.toFixed(2)),
|
|
114
|
+
required,
|
|
115
|
+
color: style.color,
|
|
116
|
+
background: `rgb(${bg.r}, ${bg.g}, ${bg.b})`,
|
|
117
|
+
html: el.outerHTML.slice(0, 160),
|
|
118
|
+
});
|
|
119
|
+
reported += 1;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
width: window.innerWidth,
|
|
126
|
+
overflow: document.documentElement.scrollWidth > window.innerWidth + 1,
|
|
127
|
+
interactive: document.querySelectorAll('a[href],button,input,select,textarea,[tabindex]').length,
|
|
128
|
+
issues,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function parseArgs(argv) {
|
|
133
|
+
const options = { target: null, widths: [320, 375, 1280], json: false, consoleErrors: false, contrast: false, keyboard: false, focusStyle: false, screenshots: null, baseline: null, maxDiff: 0.01, flow: null, flowTimeout: 5000, wait: 600 };
|
|
134
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
135
|
+
const arg = argv[i];
|
|
136
|
+
if (arg === '--file' || arg === '--url') options.target = argv[++i];
|
|
137
|
+
else if (arg === '--widths') {
|
|
138
|
+
options.widths = String(argv[++i] ?? '')
|
|
139
|
+
.split(',')
|
|
140
|
+
.map((value) => Number.parseInt(value, 10))
|
|
141
|
+
.filter((value) => Number.isInteger(value) && value > 0);
|
|
142
|
+
} else if (arg === '--json') options.json = true;
|
|
143
|
+
else if (arg === '--console') options.consoleErrors = true;
|
|
144
|
+
else if (arg === '--contrast') options.contrast = true;
|
|
145
|
+
else if (arg === '--keyboard') options.keyboard = true;
|
|
146
|
+
else if (arg === '--focus-style') options.focusStyle = true;
|
|
147
|
+
else if (arg === '--baseline') options.baseline = path.resolve(argv[++i]);
|
|
148
|
+
else if (arg === '--max-diff') options.maxDiff = Number.parseFloat(argv[++i]);
|
|
149
|
+
else if (arg === '--flow') options.flow = path.resolve(argv[++i]);
|
|
150
|
+
else if (arg === '--flow-timeout') options.flowTimeout = Number.parseInt(argv[++i], 10);
|
|
151
|
+
else if (arg === '--screenshots') options.screenshots = path.resolve(argv[++i]);
|
|
152
|
+
else if (arg === '--wait') options.wait = Number.parseInt(argv[++i], 10);
|
|
153
|
+
else if (!arg.startsWith('-')) options.target = arg;
|
|
154
|
+
else throw new Error(`unknown option: ${arg}`);
|
|
155
|
+
}
|
|
156
|
+
if (!options.target) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
'usage: ui-audit <file.html|url> [--widths 320,375,1280] [--console] [--contrast] [--keyboard] [--focus-style] [--flow file] [--screenshots dir] [--baseline dir] [--json]',
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (options.widths.length === 0) throw new Error('--widths must include at least one positive integer');
|
|
162
|
+
return options;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function waitForPort(profile, timeoutMs = 8000) {
|
|
166
|
+
const started = Date.now();
|
|
167
|
+
while (Date.now() - started < timeoutMs) {
|
|
168
|
+
const file = path.join(profile, 'DevToolsActivePort');
|
|
169
|
+
if (existsSync(file)) {
|
|
170
|
+
const [port] = readFileSync(file, 'utf8').split('\n');
|
|
171
|
+
return Number.parseInt(port, 10);
|
|
172
|
+
}
|
|
173
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
174
|
+
}
|
|
175
|
+
throw new Error('Chrome DevTools port did not open');
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function connectCdp(url) {
|
|
179
|
+
const socket = new WebSocket(url);
|
|
180
|
+
let nextId = 0;
|
|
181
|
+
const pending = new Map();
|
|
182
|
+
const listeners = new Map();
|
|
183
|
+
const ready = new Promise((resolve, reject) => {
|
|
184
|
+
socket.addEventListener('open', resolve, { once: true });
|
|
185
|
+
socket.addEventListener('error', reject, { once: true });
|
|
186
|
+
});
|
|
187
|
+
socket.addEventListener('message', (event) => {
|
|
188
|
+
let message;
|
|
189
|
+
try {
|
|
190
|
+
message = JSON.parse(event.data);
|
|
191
|
+
} catch {
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (message.method) {
|
|
195
|
+
for (const listener of listeners.get(message.method) ?? []) listener(message.params);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!message.id || !pending.has(message.id)) return;
|
|
199
|
+
const { resolve, reject } = pending.get(message.id);
|
|
200
|
+
pending.delete(message.id);
|
|
201
|
+
if (message.error) reject(new Error(message.error.message));
|
|
202
|
+
else resolve(message.result);
|
|
203
|
+
});
|
|
204
|
+
const send = (method, params = {}) =>
|
|
205
|
+
new Promise((resolve, reject) => {
|
|
206
|
+
const id = ++nextId;
|
|
207
|
+
pending.set(id, { resolve, reject });
|
|
208
|
+
socket.send(JSON.stringify({ id, method, params }));
|
|
209
|
+
});
|
|
210
|
+
const on = (method, listener) => {
|
|
211
|
+
const list = listeners.get(method) ?? [];
|
|
212
|
+
list.push(listener);
|
|
213
|
+
listeners.set(method, list);
|
|
214
|
+
};
|
|
215
|
+
return { socket, ready, send, on };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async function evaluate(cdp, expression) {
|
|
219
|
+
const result = await cdp.send('Runtime.evaluate', {
|
|
220
|
+
expression,
|
|
221
|
+
returnByValue: true,
|
|
222
|
+
awaitPromise: true,
|
|
223
|
+
});
|
|
224
|
+
if (result.exceptionDetails) {
|
|
225
|
+
throw new Error(result.exceptionDetails.text ?? 'page evaluation failed');
|
|
226
|
+
}
|
|
227
|
+
return result.result.value;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function waitFor(cdp, expression, timeoutMs) {
|
|
231
|
+
const started = Date.now();
|
|
232
|
+
while (Date.now() - started < timeoutMs) {
|
|
233
|
+
if (await evaluate(cdp, expression)) return true;
|
|
234
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
235
|
+
}
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function hoverElement(cdp, selector) {
|
|
240
|
+
const point = await evaluate(
|
|
241
|
+
cdp,
|
|
242
|
+
`(() => {
|
|
243
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
244
|
+
if (!el) return null;
|
|
245
|
+
el.scrollIntoView({ block: 'center', behavior: 'instant' });
|
|
246
|
+
const rect = el.getBoundingClientRect();
|
|
247
|
+
if (rect.width === 0 || rect.height === 0) return null;
|
|
248
|
+
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
|
|
249
|
+
})()`,
|
|
250
|
+
);
|
|
251
|
+
if (!point) throw new Error(`hover: selector not found or not visible: ${selector}`);
|
|
252
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
253
|
+
await cdp.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: point.x, y: point.y });
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function uploadFiles(cdp, selector, files) {
|
|
257
|
+
const resolved = files.map((file) => path.resolve(process.cwd(), file));
|
|
258
|
+
for (const file of resolved) {
|
|
259
|
+
if (!existsSync(file)) throw new Error(`upload: file not found: ${file}`);
|
|
260
|
+
}
|
|
261
|
+
await cdp.send('DOM.enable');
|
|
262
|
+
const { root } = await cdp.send('DOM.getDocument', { depth: -1 });
|
|
263
|
+
const { nodeId } = await cdp.send('DOM.querySelector', { nodeId: root.nodeId, selector });
|
|
264
|
+
if (!nodeId) throw new Error(`upload: selector not found: ${selector}`);
|
|
265
|
+
await cdp.send('DOM.setFileInputFiles', { nodeId, files: resolved });
|
|
266
|
+
await evaluate(
|
|
267
|
+
cdp,
|
|
268
|
+
`(() => {
|
|
269
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
270
|
+
if (!el) return false;
|
|
271
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
272
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
273
|
+
return true;
|
|
274
|
+
})()`,
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
async function runFlow(cdp, flow, timeoutMs) {
|
|
279
|
+
try {
|
|
280
|
+
for (const step of flow) {
|
|
281
|
+
if (step.fill !== undefined) {
|
|
282
|
+
const ok = await evaluate(
|
|
283
|
+
cdp,
|
|
284
|
+
`(() => { const el = document.querySelector(${JSON.stringify(step.fill)}); if (!el) return false; el.focus(); el.value = ${JSON.stringify(step.value ?? '')}; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); return true; })()`,
|
|
285
|
+
);
|
|
286
|
+
if (!ok) throw new Error(`fill: selector not found: ${step.fill}`);
|
|
287
|
+
} else if (step.click !== undefined) {
|
|
288
|
+
const ok = await evaluate(
|
|
289
|
+
cdp,
|
|
290
|
+
`(() => { const el = document.querySelector(${JSON.stringify(step.click)}); if (!el) return false; el.click(); return true; })()`,
|
|
291
|
+
);
|
|
292
|
+
if (!ok) throw new Error(`click: selector not found: ${step.click}`);
|
|
293
|
+
} else if (step.hover !== undefined) {
|
|
294
|
+
await hoverElement(cdp, step.hover);
|
|
295
|
+
} else if (step.upload !== undefined) {
|
|
296
|
+
const files = Array.isArray(step.files) ? step.files : step.file ? [step.file] : [];
|
|
297
|
+
if (files.length === 0) throw new Error('upload: file or files is required');
|
|
298
|
+
await uploadFiles(cdp, step.upload, files);
|
|
299
|
+
} else if (step.expectText !== undefined) {
|
|
300
|
+
const ok = await waitFor(
|
|
301
|
+
cdp,
|
|
302
|
+
`document.body.innerText.includes(${JSON.stringify(step.expectText)})`,
|
|
303
|
+
timeoutMs,
|
|
304
|
+
);
|
|
305
|
+
if (!ok) throw new Error(`expectText not found: ${step.expectText}`);
|
|
306
|
+
} else if (step.expectUrl !== undefined) {
|
|
307
|
+
const ok = await waitFor(
|
|
308
|
+
cdp,
|
|
309
|
+
`location.href.includes(${JSON.stringify(step.expectUrl)})`,
|
|
310
|
+
timeoutMs,
|
|
311
|
+
);
|
|
312
|
+
if (!ok) throw new Error(`expectUrl not found: ${step.expectUrl}`);
|
|
313
|
+
} else if (step.wait !== undefined) {
|
|
314
|
+
await new Promise((resolve) => setTimeout(resolve, Number(step.wait) || 0));
|
|
315
|
+
} else {
|
|
316
|
+
throw new Error(`unknown flow step: ${JSON.stringify(step)}`);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return { ok: true, steps: flow.length };
|
|
320
|
+
} catch (error) {
|
|
321
|
+
return { ok: false, error: error.message };
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function slugFor(target) {
|
|
326
|
+
return String(target)
|
|
327
|
+
.replace(/^https?:\/\//, '')
|
|
328
|
+
.replace(/[^a-z0-9.-]+/gi, '-')
|
|
329
|
+
.replace(/^-+|-+$/g, '')
|
|
330
|
+
.slice(0, 60) || 'page';
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function runKeyboard(cdp, checkStyle = false) {
|
|
334
|
+
const focusables = await evaluate(
|
|
335
|
+
cdp,
|
|
336
|
+
`(() => {
|
|
337
|
+
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
|
|
338
|
+
const selector = 'a[href],button,input:not([type=hidden]),select,textarea,[tabindex]:not([tabindex="-1"])';
|
|
339
|
+
return [...document.querySelectorAll(selector)]
|
|
340
|
+
.filter((el) => {
|
|
341
|
+
const rect = el.getBoundingClientRect();
|
|
342
|
+
const style = getComputedStyle(el);
|
|
343
|
+
return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden';
|
|
344
|
+
})
|
|
345
|
+
.map((el, index) => {
|
|
346
|
+
el.setAttribute('data-ks-focus', String(index));
|
|
347
|
+
const name = (el.getAttribute('aria-label') || el.textContent || el.name || '').trim().slice(0, 60);
|
|
348
|
+
const style = getComputedStyle(el);
|
|
349
|
+
return {
|
|
350
|
+
index,
|
|
351
|
+
tag: el.tagName.toLowerCase(),
|
|
352
|
+
name,
|
|
353
|
+
style: [
|
|
354
|
+
style.outlineStyle,
|
|
355
|
+
style.outlineWidth,
|
|
356
|
+
style.outlineColor,
|
|
357
|
+
style.outlineOffset,
|
|
358
|
+
style.boxShadow,
|
|
359
|
+
style.borderColor,
|
|
360
|
+
style.backgroundColor,
|
|
361
|
+
].join('|'),
|
|
362
|
+
};
|
|
363
|
+
});
|
|
364
|
+
})()`,
|
|
365
|
+
);
|
|
366
|
+
if (!Array.isArray(focusables) || focusables.length === 0) {
|
|
367
|
+
return { ok: true, focusables: 0, order: [], unreached: [], missing: [] };
|
|
368
|
+
}
|
|
369
|
+
const order = [];
|
|
370
|
+
const missing = [];
|
|
371
|
+
for (let step = 0; step < focusables.length + 2; step += 1) {
|
|
372
|
+
await cdp.send('Input.dispatchKeyEvent', {
|
|
373
|
+
type: 'keyDown',
|
|
374
|
+
key: 'Tab',
|
|
375
|
+
code: 'Tab',
|
|
376
|
+
windowsVirtualKeyCode: 9,
|
|
377
|
+
nativeVirtualKeyCode: 9,
|
|
378
|
+
});
|
|
379
|
+
await cdp.send('Input.dispatchKeyEvent', {
|
|
380
|
+
type: 'keyUp',
|
|
381
|
+
key: 'Tab',
|
|
382
|
+
code: 'Tab',
|
|
383
|
+
windowsVirtualKeyCode: 9,
|
|
384
|
+
nativeVirtualKeyCode: 9,
|
|
385
|
+
});
|
|
386
|
+
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
387
|
+
const active = await evaluate(
|
|
388
|
+
cdp,
|
|
389
|
+
`(() => {
|
|
390
|
+
const el = document.activeElement;
|
|
391
|
+
if (!el) return null;
|
|
392
|
+
const s = getComputedStyle(el);
|
|
393
|
+
return {
|
|
394
|
+
index: el.getAttribute('data-ks-focus'),
|
|
395
|
+
style: [
|
|
396
|
+
s.outlineStyle,
|
|
397
|
+
s.outlineWidth,
|
|
398
|
+
s.outlineColor,
|
|
399
|
+
s.outlineOffset,
|
|
400
|
+
s.boxShadow,
|
|
401
|
+
s.borderColor,
|
|
402
|
+
s.backgroundColor,
|
|
403
|
+
].join('|'),
|
|
404
|
+
};
|
|
405
|
+
})()`,
|
|
406
|
+
);
|
|
407
|
+
if (active && active.index !== null) {
|
|
408
|
+
const index = Number(active.index);
|
|
409
|
+
order.push(index);
|
|
410
|
+
if (checkStyle && focusables[index] && active.style === focusables[index].style) {
|
|
411
|
+
missing.push({ index, tag: focusables[index].tag, name: focusables[index].name });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
await evaluate(
|
|
416
|
+
cdp,
|
|
417
|
+
`document.querySelectorAll('[data-ks-focus]').forEach((el) => el.removeAttribute('data-ks-focus'))`,
|
|
418
|
+
);
|
|
419
|
+
const reached = new Set(order);
|
|
420
|
+
const unreached = focusables.filter((item) => !reached.has(item.index));
|
|
421
|
+
return {
|
|
422
|
+
ok: unreached.length === 0 && missing.length === 0,
|
|
423
|
+
focusables: focusables.length,
|
|
424
|
+
order,
|
|
425
|
+
unreached,
|
|
426
|
+
missing,
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function imageDiff(cdp, currentPath, baselinePath) {
|
|
431
|
+
const current = readFileSync(currentPath).toString('base64');
|
|
432
|
+
const baseline = readFileSync(baselinePath).toString('base64');
|
|
433
|
+
const result = await cdp.send('Runtime.evaluate', {
|
|
434
|
+
expression: `(async () => {
|
|
435
|
+
const load = (src) => new Promise((resolve, reject) => {
|
|
436
|
+
const image = new Image();
|
|
437
|
+
image.onload = () => resolve(image);
|
|
438
|
+
image.onerror = reject;
|
|
439
|
+
image.src = src;
|
|
440
|
+
});
|
|
441
|
+
const [a, b] = await Promise.all([
|
|
442
|
+
load('data:image/png;base64,${current}'),
|
|
443
|
+
load('data:image/png;base64,${baseline}')
|
|
444
|
+
]);
|
|
445
|
+
const width = Math.min(a.width, b.width);
|
|
446
|
+
const height = Math.min(a.height, b.height);
|
|
447
|
+
const canvas = document.createElement('canvas');
|
|
448
|
+
canvas.width = width;
|
|
449
|
+
canvas.height = height;
|
|
450
|
+
const context = canvas.getContext('2d');
|
|
451
|
+
context.drawImage(a, 0, 0);
|
|
452
|
+
const left = context.getImageData(0, 0, width, height).data;
|
|
453
|
+
context.clearRect(0, 0, width, height);
|
|
454
|
+
context.drawImage(b, 0, 0);
|
|
455
|
+
const right = context.getImageData(0, 0, width, height).data;
|
|
456
|
+
let diff = 0;
|
|
457
|
+
for (let i = 0; i < left.length; i += 4) {
|
|
458
|
+
if (
|
|
459
|
+
Math.abs(left[i] - right[i]) > 10 ||
|
|
460
|
+
Math.abs(left[i + 1] - right[i + 1]) > 10 ||
|
|
461
|
+
Math.abs(left[i + 2] - right[i + 2]) > 10
|
|
462
|
+
) diff += 1;
|
|
463
|
+
}
|
|
464
|
+
return { ratio: diff / (width * height), width, height };
|
|
465
|
+
})()`,
|
|
466
|
+
awaitPromise: true,
|
|
467
|
+
returnByValue: true,
|
|
468
|
+
});
|
|
469
|
+
if (result.exceptionDetails) throw new Error(result.exceptionDetails.text ?? 'image diff failed');
|
|
470
|
+
return result.result.value;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
async function auditTarget(browser, target, widths, options = {}) {
|
|
474
|
+
const profile = await mkdtemp(path.join(tmpdir(), 'kitskill-ui-profile-'));
|
|
475
|
+
const chrome = spawn(
|
|
476
|
+
browser,
|
|
477
|
+
[
|
|
478
|
+
'--headless=new',
|
|
479
|
+
'--disable-gpu',
|
|
480
|
+
'--no-sandbox',
|
|
481
|
+
'--hide-scrollbars',
|
|
482
|
+
'--remote-debugging-port=0',
|
|
483
|
+
`--user-data-dir=${profile}`,
|
|
484
|
+
'about:blank',
|
|
485
|
+
],
|
|
486
|
+
{ stdio: 'ignore', detached: true },
|
|
487
|
+
);
|
|
488
|
+
try {
|
|
489
|
+
const port = await waitForPort(profile);
|
|
490
|
+
const pages = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
|
491
|
+
const page = pages.find((entry) => entry.type === 'page');
|
|
492
|
+
if (!page) throw new Error('no Chrome page target');
|
|
493
|
+
const cdp = connectCdp(page.webSocketDebuggerUrl);
|
|
494
|
+
await cdp.ready;
|
|
495
|
+
try {
|
|
496
|
+
await cdp.send('Page.enable');
|
|
497
|
+
await cdp.send('Runtime.enable');
|
|
498
|
+
const consoleErrors = new Set();
|
|
499
|
+
cdp.on('Runtime.consoleAPICalled', (params) => {
|
|
500
|
+
if (params.type !== 'error') return;
|
|
501
|
+
const text = (params.args ?? [])
|
|
502
|
+
.map((arg) => arg.value ?? arg.description ?? '')
|
|
503
|
+
.filter(Boolean)
|
|
504
|
+
.join(' ');
|
|
505
|
+
consoleErrors.add(text || 'console.error');
|
|
506
|
+
});
|
|
507
|
+
cdp.on('Runtime.exceptionThrown', (params) => {
|
|
508
|
+
consoleErrors.add(params.exceptionDetails?.text ?? 'uncaught exception');
|
|
509
|
+
});
|
|
510
|
+
const url = /^https?:\/\//.test(target) ? target : pathToFileURL(path.resolve(target)).href;
|
|
511
|
+
await cdp.send('Page.navigate', { url });
|
|
512
|
+
await new Promise((resolve) => setTimeout(resolve, options.wait ?? 600));
|
|
513
|
+
const flow = options.flow ? JSON.parse(readFileSync(options.flow, 'utf8')) : null;
|
|
514
|
+
if (flow && !Array.isArray(flow)) throw new Error('flow must be a JSON array');
|
|
515
|
+
const results = [];
|
|
516
|
+
for (const width of widths) {
|
|
517
|
+
await cdp.send('Emulation.setDeviceMetricsOverride', {
|
|
518
|
+
width,
|
|
519
|
+
height: 900,
|
|
520
|
+
screenWidth: width,
|
|
521
|
+
screenHeight: 900,
|
|
522
|
+
deviceScaleFactor: 1,
|
|
523
|
+
mobile: false,
|
|
524
|
+
});
|
|
525
|
+
await cdp.send('Page.reload');
|
|
526
|
+
await new Promise((resolve) => setTimeout(resolve, options.wait ?? 300));
|
|
527
|
+
const evaluation = await cdp.send('Runtime.evaluate', {
|
|
528
|
+
expression: `(${auditInPage.toString()})(${Boolean(options.contrast)})`,
|
|
529
|
+
returnByValue: true,
|
|
530
|
+
});
|
|
531
|
+
if (evaluation.exceptionDetails) {
|
|
532
|
+
results.push({ width, error: evaluation.exceptionDetails.text ?? 'page evaluation failed' });
|
|
533
|
+
} else {
|
|
534
|
+
const result = evaluation.result.value;
|
|
535
|
+
if (options.screenshots) {
|
|
536
|
+
const shot = await cdp.send('Page.captureScreenshot', { format: 'png' });
|
|
537
|
+
await mkdir(options.screenshots, { recursive: true });
|
|
538
|
+
const file = path.join(options.screenshots, `${slugFor(target)}-${width}.png`);
|
|
539
|
+
await writeFile(file, Buffer.from(shot.data, 'base64'));
|
|
540
|
+
result.screenshot = file;
|
|
541
|
+
}
|
|
542
|
+
if (options.consoleErrors) result.consoleErrors = [...consoleErrors];
|
|
543
|
+
results.push(result);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (flow) {
|
|
547
|
+
const flowResult = await runFlow(cdp, flow, options.flowTimeout ?? 5000);
|
|
548
|
+
if (results[0]) results[0].flow = flowResult;
|
|
549
|
+
}
|
|
550
|
+
if (options.keyboard || options.focusStyle) {
|
|
551
|
+
const keyboard = await runKeyboard(cdp, options.focusStyle);
|
|
552
|
+
if (results[0]) results[0].keyboard = keyboard;
|
|
553
|
+
}
|
|
554
|
+
if (options.baseline && options.screenshots) {
|
|
555
|
+
for (const result of results) {
|
|
556
|
+
if (!result.screenshot) continue;
|
|
557
|
+
const baselineFile = path.join(options.baseline, path.basename(result.screenshot));
|
|
558
|
+
if (!existsSync(baselineFile)) {
|
|
559
|
+
result.diff = { ok: false, error: `baseline missing: ${baselineFile}` };
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
try {
|
|
563
|
+
const diff = await imageDiff(cdp, result.screenshot, baselineFile);
|
|
564
|
+
result.diff = { ...diff, ok: diff.ratio <= options.maxDiff };
|
|
565
|
+
} catch (error) {
|
|
566
|
+
result.diff = { ok: false, error: error.message };
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return results;
|
|
571
|
+
} finally {
|
|
572
|
+
cdp.socket.close();
|
|
573
|
+
}
|
|
574
|
+
} finally {
|
|
575
|
+
try {
|
|
576
|
+
process.kill(-chrome.pid, 'SIGKILL');
|
|
577
|
+
} catch {
|
|
578
|
+
chrome.kill('SIGKILL');
|
|
579
|
+
}
|
|
580
|
+
await rm(profile, { recursive: true, force: true });
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
async function main() {
|
|
585
|
+
const options = parseArgs(process.argv.slice(2));
|
|
586
|
+
if (options.baseline && !options.screenshots) {
|
|
587
|
+
throw new Error('--baseline requires --screenshots');
|
|
588
|
+
}
|
|
589
|
+
const browser = findBrowser();
|
|
590
|
+
if (!browser) throw new Error('no Chrome/Chromium found; set CHROME_PATH or install one');
|
|
591
|
+
const results = await auditTarget(browser, options.target, options.widths, options);
|
|
592
|
+
if (options.json) {
|
|
593
|
+
process.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
|
|
594
|
+
} else {
|
|
595
|
+
for (const result of results) {
|
|
596
|
+
if (result.error) {
|
|
597
|
+
process.stdout.write(`FAIL ${result.width}px: ${result.error}\n`);
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
const label = result.overflow || result.issues.length > 0 ? 'FAIL' : 'PASS';
|
|
601
|
+
process.stdout.write(
|
|
602
|
+
`${label} ${result.width}px: overflow=${result.overflow} ` +
|
|
603
|
+
`interactive=${result.interactive} issues=${result.issues.length}` +
|
|
604
|
+
(result.consoleErrors ? ` console=${result.consoleErrors.length}` : '') +
|
|
605
|
+
(result.flow ? ` flow=${result.flow.ok ? 'PASS' : 'FAIL'}` : '') +
|
|
606
|
+
(result.keyboard ? ` keyboard=${result.keyboard.ok ? 'PASS' : 'FAIL'}` : '') +
|
|
607
|
+
(result.keyboard?.missing?.length ? ` focus-missing=${result.keyboard.missing.length}` : '') +
|
|
608
|
+
(result.diff
|
|
609
|
+
? ` diff=${result.diff.ok ? (result.diff.ratio * 100).toFixed(1) + '%' : 'FAIL'}`
|
|
610
|
+
: '') +
|
|
611
|
+
'\n',
|
|
612
|
+
);
|
|
613
|
+
for (const issue of result.issues) {
|
|
614
|
+
process.stdout.write(` - ${issue.rule}${issue.tag ? ` (${issue.tag})` : ''}\n`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
const failed = results.some(
|
|
619
|
+
(result) =>
|
|
620
|
+
result.error ||
|
|
621
|
+
result.overflow ||
|
|
622
|
+
result.issues.length > 0 ||
|
|
623
|
+
(options.consoleErrors && result.consoleErrors.length > 0) ||
|
|
624
|
+
(result.flow && !result.flow.ok) ||
|
|
625
|
+
(result.keyboard && !result.keyboard.ok) ||
|
|
626
|
+
(result.diff && !result.diff.ok),
|
|
627
|
+
);
|
|
628
|
+
return failed ? 1 : 0;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))) {
|
|
632
|
+
main().then(
|
|
633
|
+
(code) => process.exit(code),
|
|
634
|
+
(error) => {
|
|
635
|
+
process.stderr.write(`${error.message}\n`);
|
|
636
|
+
process.exit(2);
|
|
637
|
+
},
|
|
638
|
+
);
|
|
639
|
+
}
|