@ashishjain15491/tapcheck 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +75 -0
- package/LICENSE +21 -0
- package/README.md +243 -2
- package/dist/auth.d.ts +5 -0
- package/dist/auth.js +100 -0
- package/dist/browser.d.ts +143 -0
- package/dist/browser.js +237 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +321 -0
- package/dist/config.d.ts +169 -0
- package/dist/config.js +369 -0
- package/dist/coverage.d.ts +17 -0
- package/dist/coverage.js +56 -0
- package/dist/flow.d.ts +193 -0
- package/dist/flow.js +512 -0
- package/dist/jev.d.ts +48 -0
- package/dist/jev.js +89 -0
- package/dist/parts.d.ts +65 -0
- package/dist/parts.js +157 -0
- package/dist/questions.d.ts +66 -0
- package/dist/questions.js +203 -0
- package/dist/report.d.ts +29 -0
- package/dist/report.js +59 -0
- package/dist/routes.d.ts +18 -0
- package/dist/routes.js +54 -0
- package/dist/stub.d.ts +51 -0
- package/dist/stub.js +244 -0
- package/dist/suites/a11y.d.ts +3 -0
- package/dist/suites/a11y.js +73 -0
- package/dist/suites/audit.d.ts +2 -0
- package/dist/suites/audit.js +440 -0
- package/dist/suites/code.d.ts +10 -0
- package/dist/suites/code.js +48 -0
- package/dist/suites/contract.d.ts +5 -0
- package/dist/suites/contract.js +79 -0
- package/dist/suites/crawl.d.ts +2 -0
- package/dist/suites/crawl.js +135 -0
- package/dist/suites/interact.d.ts +2 -0
- package/dist/suites/interact.js +319 -0
- package/dist/suites/security.d.ts +12 -0
- package/dist/suites/security.js +134 -0
- package/dist/suites/usability.d.ts +3 -0
- package/dist/suites/usability.js +205 -0
- package/dist/suites/ux.d.ts +6 -0
- package/dist/suites/ux.js +183 -0
- package/package.json +61 -5
- package/schema/tapcheck.schema.json +368 -0
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Full UI audit, per screen (the configured screens, plus up to audit.max crawled pages; paths matching audit.skip are
|
|
3
|
+
* left out). Measured by code; Jev only adds its look.
|
|
4
|
+
* - desktop, light: text cut off or shortened with no way to read it, controls that overlap, targets under 24 px, leaked
|
|
5
|
+
* placeholders, heading levels, images without alt text, the focus ring on each Tab stop; every menu and dialog the
|
|
6
|
+
* screen's markup says it opens (aria-haspopup, aria-expanded, popovertarget) is opened and measured the same way,
|
|
7
|
+
* plus whether it fits on the screen;
|
|
8
|
+
* - desktop, dark (prefers-color-scheme: dark): axe's colour-contrast rule, which also catches text that became
|
|
9
|
+
* invisible, and backgrounds that stayed white. A page that doesn't react to the colour scheme is one info finding;
|
|
10
|
+
* - tablet (768 px) and phone (375 px): sideways scroll, cut-off text, overlap, small targets;
|
|
11
|
+
* - across the screens: buttons and fields of one kind that come in several sizes, radii or colours, labels in Title
|
|
12
|
+
* Case next to labels in sentence case, and, with `design:` in tapcheck.yml, computed colours, fonts, radii and
|
|
13
|
+
* spacing that are not among the tokens (warnings, the most used offenders first);
|
|
14
|
+
* - Jev's look, when Jev is on: the VISUAL questions (src/questions.ts) about the desktop screen and about each opened
|
|
15
|
+
* menu and dialog, within the run's budget. With JEV=off or no key that is one info finding and the rest still runs.
|
|
16
|
+
* It only opens menus and dialogs and closes them with Escape: never a control whose label is one of the usability
|
|
17
|
+
* suite's UNSAFE words, never a submit button. audit.json holds everything found.
|
|
18
|
+
*/
|
|
19
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { context, open, resolve, SessionExpired, slices, slug } from '../browser.js';
|
|
21
|
+
import { ask, BudgetReached, img, whyOff } from '../jev.js';
|
|
22
|
+
import { VISUAL } from '../questions.js';
|
|
23
|
+
import { AXE } from './a11y.js';
|
|
24
|
+
import { UNSAFE } from './usability.js';
|
|
25
|
+
import { visual } from './ux.js';
|
|
26
|
+
const S = 'audit';
|
|
27
|
+
const NARROW = [{ name: 'tablet', width: 768, height: 1024, mobile: false }, { name: 'phone', width: 375, height: 812, mobile: true }];
|
|
28
|
+
const WARN = new Set(['shortened text can be read in full', 'heading levels in order']); // the other measured checks fail
|
|
29
|
+
const TABS = 20, MAX_POPUPS = 4;
|
|
30
|
+
const POPUP = '[role=menu], [role=listbox], dialog[open], [role=dialog], [role=alertdialog], [popover]:popover-open';
|
|
31
|
+
// ponytail: primary, secondary and danger is the most a button kind gets before its colours count as inconsistent; fields get one.
|
|
32
|
+
const PAINTS = { button: 3, 'icon button': 3, 'text button': 2 };
|
|
33
|
+
/**
|
|
34
|
+
* Runs in the page. Measures everything under `root` (a selector; the whole page without one). `extras` adds the
|
|
35
|
+
* desktop-only checks and collects the controls, labels and (with `design`) the styles outside the tokens.
|
|
36
|
+
*/
|
|
37
|
+
function measure({ root: rootSel, extras, design }) {
|
|
38
|
+
const root = (rootSel && document.querySelector(rootSel)) || document.body;
|
|
39
|
+
const vw = innerWidth, vh = innerHeight;
|
|
40
|
+
const visible = (el) => { const r = el.getBoundingClientRect(), s = getComputedStyle(el); return r.width > 1 && r.height > 1 && s.visibility !== 'hidden' && Number(s.opacity) > 0 && !el.closest('[aria-hidden=true], [hidden]'); };
|
|
41
|
+
const txt = (el) => (el.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 60);
|
|
42
|
+
const name = (el) => (el.getAttribute('aria-label') || txt(el) || el.getAttribute('title') || el.placeholder || el.tagName.toLowerCase()).slice(0, 40);
|
|
43
|
+
const desc = (el) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : typeof el.className === 'string' && el.className.trim() ? `.${el.className.trim().split(/\s+/)[0]}` : ''}`;
|
|
44
|
+
const ownText = (el) => [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent.trim());
|
|
45
|
+
const px = (v) => Math.round(parseFloat(v) || 0);
|
|
46
|
+
const all = [...root.querySelectorAll('*')].filter(visible);
|
|
47
|
+
const cut = new Set(), short = new Set(), overlap = new Set(), small = new Set();
|
|
48
|
+
const problems = {};
|
|
49
|
+
if (!rootSel) {
|
|
50
|
+
const wide = document.documentElement.scrollWidth > vw + 1 && all.filter((e) => e.getBoundingClientRect().right > vw + 1).sort((a, b) => b.getBoundingClientRect().right - a.getBoundingClientRect().right)[0];
|
|
51
|
+
problems['no sideways scroll'] = document.documentElement.scrollWidth > vw + 1 ? [`the page is ${document.documentElement.scrollWidth} px wide in a ${vw} px window${wide ? `; widest: ${desc(wide)}` : ''}`] : [];
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
const b = root.getBoundingClientRect();
|
|
55
|
+
const out = b.left < -1 || b.top < -1 || b.right > vw + 1 || (getComputedStyle(root).position === 'fixed' && b.bottom > vh + 1);
|
|
56
|
+
problems['fits on the screen'] = out ? [`it spans ${Math.round(b.left)},${Math.round(b.top)} to ${Math.round(b.right)},${Math.round(b.bottom)} in a ${vw} × ${vh} window`] : [];
|
|
57
|
+
}
|
|
58
|
+
// Text wider than its box, in an element that holds text itself (not a carousel or another clipping container).
|
|
59
|
+
for (const el of all) {
|
|
60
|
+
if (el.children.length > 2 || el.matches('input, select, textarea') || !txt(el))
|
|
61
|
+
continue;
|
|
62
|
+
const s = getComputedStyle(el);
|
|
63
|
+
if (el.scrollWidth <= el.clientWidth + 1 || !/hidden|clip/.test(s.overflowX))
|
|
64
|
+
continue;
|
|
65
|
+
if (!ownText(el) && ![...el.children].every((c) => getComputedStyle(c).display.startsWith('inline')))
|
|
66
|
+
continue;
|
|
67
|
+
if (s.textOverflow !== 'ellipsis')
|
|
68
|
+
cut.add(`"${txt(el)}" (${desc(el)})`);
|
|
69
|
+
else if (!el.getAttribute('title') && !el.getAttribute('aria-label') && !el.closest('[title], [aria-describedby]'))
|
|
70
|
+
short.add(`"${txt(el)}" (${desc(el)})`);
|
|
71
|
+
}
|
|
72
|
+
// Controls, each clipped to what its scrolling ancestors leave visible.
|
|
73
|
+
const seen = (el) => {
|
|
74
|
+
const r = el.getBoundingClientRect();
|
|
75
|
+
let [l, t, rt, b] = [r.left, r.top, r.right, r.bottom];
|
|
76
|
+
for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
|
|
77
|
+
const cs = getComputedStyle(p);
|
|
78
|
+
if (cs.overflowX === 'visible' && cs.overflowY === 'visible')
|
|
79
|
+
continue;
|
|
80
|
+
const c = p.getBoundingClientRect();
|
|
81
|
+
l = Math.max(l, c.left);
|
|
82
|
+
t = Math.max(t, c.top);
|
|
83
|
+
rt = Math.min(rt, c.right);
|
|
84
|
+
b = Math.min(b, c.bottom);
|
|
85
|
+
}
|
|
86
|
+
return { left: l, top: t, right: rt, bottom: b, width: Math.max(0, rt - l), height: Math.max(0, b - t) };
|
|
87
|
+
};
|
|
88
|
+
const controls = all.filter((e) => e.matches('a[href], button, input:not([type=hidden]), select, textarea, [role=button], [role=tab], [role=switch]')).slice(0, 300)
|
|
89
|
+
.map((el) => ({ el, box: seen(el) })).filter((c) => c.box.width > 1 && c.box.height > 1);
|
|
90
|
+
for (const [i, a] of controls.entries())
|
|
91
|
+
for (const b of controls.slice(i + 1)) {
|
|
92
|
+
if (a.el.contains(b.el) || b.el.contains(a.el) || (a.el.closest('label') && a.el.closest('label') === b.el.closest('label')))
|
|
93
|
+
continue;
|
|
94
|
+
const w = Math.min(a.box.right, b.box.right) - Math.max(a.box.left, b.box.left), h = Math.min(a.box.bottom, b.box.bottom) - Math.max(a.box.top, b.box.top);
|
|
95
|
+
if (w > 4 && h > 4 && w * h > 0.25 * Math.min(a.box.width * a.box.height, b.box.width * b.box.height))
|
|
96
|
+
overlap.add(`${name(a.el)} ↔ ${name(b.el)}`);
|
|
97
|
+
}
|
|
98
|
+
// WCAG 2.2 target size (2.5.8): under 24 px fails unless a 24 px area centred on it touches no other target. Links in a sentence are exempt.
|
|
99
|
+
for (const { el } of controls) {
|
|
100
|
+
const r = el.getBoundingClientRect();
|
|
101
|
+
if (Math.min(r.width, r.height) >= 24 || (el.matches('input[type=checkbox], input[type=radio]') && el.closest('label')))
|
|
102
|
+
continue;
|
|
103
|
+
if (el.matches('a') && el.closest('p, li, td, dd') && getComputedStyle(el).display === 'inline')
|
|
104
|
+
continue;
|
|
105
|
+
const cx = r.left + r.width / 2, cy = r.top + r.height / 2, hw = Math.max(12, r.width / 2), hh = Math.max(12, r.height / 2);
|
|
106
|
+
const crowded = controls.some((o) => { const t = o.el.getBoundingClientRect(); return o.el !== el && !o.el.contains(el) && !el.contains(o.el) && t.left < cx + hw && t.right > cx - hw && t.top < cy + hh && t.bottom > cy - hh; });
|
|
107
|
+
if (crowded)
|
|
108
|
+
small.add(`${name(el)} ${Math.round(r.width)}×${Math.round(r.height)}`);
|
|
109
|
+
}
|
|
110
|
+
Object.assign(problems, { 'text is not cut off': [...cut], 'shortened text can be read in full': [...short], 'controls do not overlap': [...overlap], 'targets at least 24 px': [...small] });
|
|
111
|
+
const items = [], labels = [], off = [];
|
|
112
|
+
if (!extras)
|
|
113
|
+
return { problems, items, labels, off };
|
|
114
|
+
// Placeholders that reached the screen: a value that printed as undefined, NaN or [object Object], or an unfilled template.
|
|
115
|
+
const leaked = new Set();
|
|
116
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
117
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
118
|
+
const t = n.textContent.trim(), el = n.parentElement;
|
|
119
|
+
if (!t || !el || el.closest('script, style, code, pre, textarea, [aria-hidden=true]') || !el.getClientRects().length)
|
|
120
|
+
continue;
|
|
121
|
+
if (/^(undefined|null)$|\bNaN\b|\[object Object\]|\{\{[^}]*\}\}|\$\{[^}]*\}/.test(t))
|
|
122
|
+
leaked.add(t.slice(0, 60));
|
|
123
|
+
}
|
|
124
|
+
const heads = [...root.querySelectorAll('h1, h2, h3, h4, h5, h6')].filter(visible);
|
|
125
|
+
problems['no leaked placeholders'] = [...leaked];
|
|
126
|
+
problems['heading levels in order'] = heads.slice(1).flatMap((h, i) => (+h.tagName[1] > +heads[i].tagName[1] + 1 ? [`${heads[i].tagName.toLowerCase()} → ${h.tagName.toLowerCase()} "${txt(h)}"`] : []));
|
|
127
|
+
problems['images have alt text'] = [...root.querySelectorAll('img')].filter((i) => visible(i) && !i.hasAttribute('alt') && !i.getAttribute('aria-label')).map((i) => i.src.slice(-60));
|
|
128
|
+
// Controls by kind, with the look that should be the same wherever the kind is used.
|
|
129
|
+
for (const el of all) {
|
|
130
|
+
const tag = el.tagName.toLowerCase(), f = el;
|
|
131
|
+
const button = el.matches('button, input[type=submit], input[type=button], input[type=reset], [role=button]') && !el.matches('[role=tab], [role=menuitem], [role=switch], :disabled, [aria-disabled=true]');
|
|
132
|
+
const field = tag === 'select' || tag === 'textarea' || (tag === 'input' && ['text', 'email', 'url', 'tel', 'number', 'password', 'search', 'date'].includes(f.type));
|
|
133
|
+
if (!button && !field)
|
|
134
|
+
continue;
|
|
135
|
+
const s = getComputedStyle(el), r = el.getBoundingClientRect();
|
|
136
|
+
const label = field ? (f.labels?.[0] ? txt(f.labels[0]) : name(el)) : txt(el) || (tag === 'input' ? f.value : '');
|
|
137
|
+
const bare = s.backgroundColor === 'rgba(0, 0, 0, 0)' && !parseFloat(s.borderTopWidth);
|
|
138
|
+
const kind = field ? (tag === 'input' ? 'text input' : tag) : !label ? 'icon button' : bare ? 'text button' : 'button';
|
|
139
|
+
items.push({ kind, label, shape: `${kind === 'textarea' ? '' : `${Math.round(r.height)} px high, `}radius ${px(s.borderTopLeftRadius)} px, ${px(s.fontSize)} px text`,
|
|
140
|
+
paint: `${s.color} on ${s.backgroundColor}, ${parseFloat(s.borderTopWidth) ? `border ${s.borderTopColor}` : 'no border'}` });
|
|
141
|
+
if (button && label)
|
|
142
|
+
labels.push(label);
|
|
143
|
+
}
|
|
144
|
+
for (const h of [...heads, ...root.querySelectorAll('[role=tab]')])
|
|
145
|
+
if (visible(h) && txt(h))
|
|
146
|
+
labels.push(txt(h));
|
|
147
|
+
if (design) {
|
|
148
|
+
// Any CSS colour as sRGB bytes, by painting it; null when it is fully transparent.
|
|
149
|
+
const cv = document.createElement('canvas').getContext('2d', { willReadFrequently: true });
|
|
150
|
+
const memo = new Map();
|
|
151
|
+
const rgb = (c) => {
|
|
152
|
+
if (!memo.has(c)) {
|
|
153
|
+
cv.clearRect(0, 0, 1, 1);
|
|
154
|
+
cv.fillStyle = c;
|
|
155
|
+
cv.fillRect(0, 0, 1, 1);
|
|
156
|
+
const d = cv.getImageData(0, 0, 1, 1).data;
|
|
157
|
+
memo.set(c, d[3] ? [d[0], d[1], d[2]] : null);
|
|
158
|
+
}
|
|
159
|
+
return memo.get(c);
|
|
160
|
+
};
|
|
161
|
+
const tokens = (design.colors ?? []).map((c) => rgb(c));
|
|
162
|
+
const colour = (c, use, el) => {
|
|
163
|
+
const v = rgb(c);
|
|
164
|
+
if (v && !tokens.some((t) => Math.abs(t[0] - v[0]) + Math.abs(t[1] - v[1]) + Math.abs(t[2] - v[2]) <= 6))
|
|
165
|
+
off.push(['colors', `#${v.map((x) => x.toString(16).padStart(2, '0')).join('')} ${use}`, desc(el)]);
|
|
166
|
+
};
|
|
167
|
+
const fonts = design.fonts?.map((x) => x.toLowerCase());
|
|
168
|
+
const among = (list, v) => list.some((t) => Math.abs(t - v) < 0.5);
|
|
169
|
+
for (const el of all) {
|
|
170
|
+
if (el.closest('svg, img, canvas, video, iframe'))
|
|
171
|
+
continue;
|
|
172
|
+
const s = getComputedStyle(el), own = ownText(el);
|
|
173
|
+
if (design.colors) {
|
|
174
|
+
if (own)
|
|
175
|
+
colour(s.color, 'text', el);
|
|
176
|
+
colour(s.backgroundColor, 'background', el);
|
|
177
|
+
if (parseFloat(s.borderTopWidth))
|
|
178
|
+
colour(s.borderTopColor, 'border', el);
|
|
179
|
+
}
|
|
180
|
+
const family = s.fontFamily.split(',')[0].replace(/["']/g, '').trim();
|
|
181
|
+
if (fonts && own && !fonts.includes(family.toLowerCase()))
|
|
182
|
+
off.push(['fonts', family, desc(el)]);
|
|
183
|
+
const radius = parseFloat(s.borderTopLeftRadius) || 0;
|
|
184
|
+
if (design.radii && radius > 0 && !s.borderTopLeftRadius.includes('%') && !among(design.radii, radius))
|
|
185
|
+
off.push(['radii', `${px(s.borderTopLeftRadius)} px`, desc(el)]);
|
|
186
|
+
if (design.spacing)
|
|
187
|
+
for (const p of ['paddingTop', 'paddingLeft', 'marginTop', 'marginBottom', 'rowGap', 'columnGap']) {
|
|
188
|
+
const v = parseFloat(s[p]) || 0;
|
|
189
|
+
if (v > 0 && !among(design.spacing, v))
|
|
190
|
+
off.push(['spacing', `${px(s[p])} px`, desc(el)]);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return { problems, items, labels, off };
|
|
195
|
+
}
|
|
196
|
+
/** Tab through the page; returns the stops whose look doesn't change between focused and not. */
|
|
197
|
+
async function noFocusRing(page) {
|
|
198
|
+
await page.evaluate(() => document.activeElement?.blur());
|
|
199
|
+
const stops = new Map(); // by place: two links may share a label
|
|
200
|
+
for (let i = 0; i < TABS; i++) {
|
|
201
|
+
await page.keyboard.press('Tab');
|
|
202
|
+
const f = await page.evaluate(() => {
|
|
203
|
+
const el = document.activeElement;
|
|
204
|
+
if (!el || el === document.body)
|
|
205
|
+
return null;
|
|
206
|
+
const chain = [el, el.parentElement, el.parentElement?.parentElement].filter((e) => !!e);
|
|
207
|
+
const look = (e) => { const s = getComputedStyle(e); return [s.outlineStyle, s.outlineWidth, s.outlineColor, s.boxShadow, s.borderTopColor, s.borderBottomColor, s.backgroundColor, s.textDecorationLine].join('|'); };
|
|
208
|
+
// A ring that eases in or out still shows right after blur: compare with transitions off.
|
|
209
|
+
const saved = chain.map((e) => e.style.transition);
|
|
210
|
+
chain.forEach((e) => { e.style.transition = 'none'; });
|
|
211
|
+
const on = chain.map(look);
|
|
212
|
+
el.blur();
|
|
213
|
+
const off = chain.map(look);
|
|
214
|
+
el.focus({ preventScroll: true });
|
|
215
|
+
chain.forEach((e, k) => { e.style.transition = saved[k]; });
|
|
216
|
+
const b = el.getBoundingClientRect();
|
|
217
|
+
return { ring: on.some((k, j) => k !== off[j]), at: `${Math.round(b.left + scrollX)},${Math.round(b.top + scrollY)}`,
|
|
218
|
+
name: `${el.tagName.toLowerCase()} "${(el.getAttribute('aria-label') || el.innerText || el.placeholder || '').replace(/\s+/g, ' ').trim().slice(0, 30)}"` };
|
|
219
|
+
});
|
|
220
|
+
if (!f || stops.has(f.at))
|
|
221
|
+
break; // left the page, or came round again
|
|
222
|
+
stops.set(f.at, f);
|
|
223
|
+
}
|
|
224
|
+
await page.evaluate(() => { document.activeElement?.blur(); scrollTo(0, 0); });
|
|
225
|
+
return [...new Set([...stops.values()].filter((f) => !f.ring).map((f) => f.name))];
|
|
226
|
+
}
|
|
227
|
+
/** Marks the controls whose markup says they open a menu or dialog, and returns their labels (in order; '' is one to leave alone). */
|
|
228
|
+
const openers = (page) => page.evaluate((unsafe) => {
|
|
229
|
+
const no = new RegExp(unsafe, 'i');
|
|
230
|
+
return [...document.querySelectorAll('[aria-haspopup]:not([aria-haspopup=false]), [aria-expanded=false], [popovertarget]')].slice(0, 8).map((el, i) => {
|
|
231
|
+
const b = el;
|
|
232
|
+
const label = (b.innerText || el.getAttribute('aria-label') || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim().slice(0, 40);
|
|
233
|
+
const submit = el.matches('button[type=submit], input[type=submit]') || (el.matches('button:not([type])') && !!b.form);
|
|
234
|
+
const leaves = el instanceof HTMLAnchorElement && !!el.getAttribute('href') && !el.getAttribute('href').startsWith('#'); // a link that goes somewhere
|
|
235
|
+
if (!label || no.test(label) || submit || leaves || b.disabled || el.getClientRects().length === 0)
|
|
236
|
+
return '';
|
|
237
|
+
el.setAttribute('data-tapcheck-opener', String(i));
|
|
238
|
+
return label;
|
|
239
|
+
});
|
|
240
|
+
}, UNSAFE.source);
|
|
241
|
+
export async function run(r) {
|
|
242
|
+
mkdirSync(`${r.dir}/shots`, { recursive: true });
|
|
243
|
+
const desktop = r.cfg.viewports.find((v) => !v.mobile) ?? { name: 'desktop', width: 1440, height: 900, mobile: false };
|
|
244
|
+
const skip = r.cfg.audit.skip;
|
|
245
|
+
const out = { screens: [], components: {}, labelCase: {}, tokens: {} };
|
|
246
|
+
const looks = new Map(); // kind → shape → where it is used
|
|
247
|
+
const labels = new Set();
|
|
248
|
+
const outside = new Map(); // token list → value → uses
|
|
249
|
+
let jevOff = whyOff();
|
|
250
|
+
if (jevOff)
|
|
251
|
+
r.record({ suite: S, where: 'Jev', check: "Jev's look at each screen, menu and dialog", status: 'info', detail: `skipped (${jevOff}); the measured checks ran` });
|
|
252
|
+
/** Jev's look at `shots`. Reaching the budget ends the looks, not the audit. */
|
|
253
|
+
const look = async (where, key, state, questions, shots) => {
|
|
254
|
+
if (jevOff)
|
|
255
|
+
return;
|
|
256
|
+
try {
|
|
257
|
+
visual(r, S, where, await ask(key, { ...state, screenshots: shots.map(img) }, questions, shots), shots);
|
|
258
|
+
}
|
|
259
|
+
catch (e) {
|
|
260
|
+
if (!(e instanceof BudgetReached))
|
|
261
|
+
throw e;
|
|
262
|
+
jevOff = 'Jev budget reached';
|
|
263
|
+
r.record({ suite: S, where: 'Jev', check: "Jev's look at each screen, menu and dialog", status: 'info', detail: `stopped at ${where}: ${e.message}` });
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
/** One finding per measured check; the problems also go to audit.json. */
|
|
267
|
+
const emit = async (page, screen, view, where, problems, shots) => {
|
|
268
|
+
const bad = Object.values(problems).some((l) => l.length);
|
|
269
|
+
const shot = `${r.dir}/shots/audit-${slug(where)}.png`;
|
|
270
|
+
if (bad && !shots)
|
|
271
|
+
await page.screenshot({ path: shot });
|
|
272
|
+
for (const [check, list] of Object.entries(problems)) {
|
|
273
|
+
r.record({ suite: S, where, check, status: !list.length ? 'pass' : WARN.has(check) ? 'warn' : 'fail', detail: list.length ? `${list.length}: ${list.slice(0, 5).join('; ')}` : undefined,
|
|
274
|
+
evidence: list.length ? shots ?? [shot] : undefined });
|
|
275
|
+
}
|
|
276
|
+
screen.views[view] = Object.fromEntries(Object.entries(problems).filter(([, l]) => l.length));
|
|
277
|
+
};
|
|
278
|
+
async function onDesktop(page, t) {
|
|
279
|
+
const where = `${t.name} · desktop`, key = `audit-${slug(t.name)}`;
|
|
280
|
+
await open(r, page, t.path);
|
|
281
|
+
const colours = () => page.evaluate(() => [document.documentElement, ...document.querySelectorAll('body, body *')].slice(0, 400).map((el) => { const s = getComputedStyle(el); return s.backgroundColor + s.color; }).join());
|
|
282
|
+
const light = await colours();
|
|
283
|
+
const m = await page.evaluate(measure, { extras: true, design: r.cfg.design });
|
|
284
|
+
for (const it of m.items) {
|
|
285
|
+
const shapes = looks.get(it.kind) ?? looks.set(it.kind, new Map()).get(it.kind);
|
|
286
|
+
const use = shapes.get(it.shape) ?? shapes.set(it.shape, { n: 0, labels: new Set(), paints: new Set() }).get(it.shape);
|
|
287
|
+
use.n++;
|
|
288
|
+
use.paints.add(it.paint);
|
|
289
|
+
if (it.label && use.labels.size < 4)
|
|
290
|
+
use.labels.add(it.label);
|
|
291
|
+
}
|
|
292
|
+
m.labels.forEach((l) => labels.add(l));
|
|
293
|
+
for (const [list, value, at] of m.off) {
|
|
294
|
+
const values = outside.get(list) ?? outside.set(list, new Map()).get(list);
|
|
295
|
+
const use = values.get(value) ?? values.set(value, { n: 0, at: `${at} on ${t.name}` }).get(value);
|
|
296
|
+
use.n++;
|
|
297
|
+
}
|
|
298
|
+
const shots = jevOff ? undefined : await slices(r, page, key, await page.evaluate(() => document.documentElement.scrollHeight), desktop.height);
|
|
299
|
+
await emit(page, t, 'desktop', where, { ...m.problems, 'focus ring on every Tab stop': await noFocusRing(page) }, shots);
|
|
300
|
+
if (shots) {
|
|
301
|
+
await look(where, key, { screen: t.name, viewport: `desktop, ${desktop.width} × ${desktop.height} px`, note: shots.length > 1 ? 'The screenshots are consecutive slices of one screen, top to bottom.' : undefined }, VISUAL, shots);
|
|
302
|
+
}
|
|
303
|
+
// Menus and dialogs: opened one at a time, measured, closed with Escape.
|
|
304
|
+
let opened = 0;
|
|
305
|
+
for (const [i, label] of (await openers(page)).entries()) {
|
|
306
|
+
if (!label || opened >= MAX_POPUPS)
|
|
307
|
+
continue;
|
|
308
|
+
const home = page.url().split('#')[0];
|
|
309
|
+
await page.locator(`[data-tapcheck-opener="${i}"]`).click({ timeout: 2000 }).catch(() => { });
|
|
310
|
+
await page.waitForTimeout(300);
|
|
311
|
+
const found = page.url().split('#')[0] === home && await page.evaluate((POPUP) => {
|
|
312
|
+
const p = [...document.querySelectorAll(POPUP)].filter((el) => el.getClientRects().length > 0).at(-1);
|
|
313
|
+
p?.setAttribute('data-tapcheck-popup', '');
|
|
314
|
+
return p ? p.getAttribute('role') ?? p.tagName.toLowerCase() : '';
|
|
315
|
+
}, POPUP);
|
|
316
|
+
if (found) {
|
|
317
|
+
opened++;
|
|
318
|
+
const at = `${t.name} › ${label}`, shot = `${r.dir}/shots/${key}-popup-${opened}.png`;
|
|
319
|
+
await page.screenshot({ path: shot });
|
|
320
|
+
const p = await page.evaluate(measure, { root: '[data-tapcheck-popup]', extras: false });
|
|
321
|
+
await emit(page, t, `${found} "${label}"`, at, p.problems, [shot]);
|
|
322
|
+
const { loaded: _, ...questions } = VISUAL; // a menu isn't a screen that loads
|
|
323
|
+
await look(at, `${key}-popup-${opened}`, { screen: `${t.name}, after "${label}" was clicked`, viewport: `desktop, ${desktop.width} × ${desktop.height} px` }, questions, [shot]);
|
|
324
|
+
}
|
|
325
|
+
await page.keyboard.press('Escape').catch(() => { });
|
|
326
|
+
await page.waitForTimeout(150);
|
|
327
|
+
// Still open, or the click went somewhere else: start again from the screen.
|
|
328
|
+
if (page.url().split('#')[0] !== home || await page.evaluate((POPUP) => [...document.querySelectorAll(POPUP)].some((el) => el.getClientRects().length > 0), POPUP)) {
|
|
329
|
+
await open(r, page, t.path);
|
|
330
|
+
await openers(page);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
// Dark: the page is loaded again so a theme chosen by script at load time is seen too.
|
|
334
|
+
await page.emulateMedia({ colorScheme: 'dark' });
|
|
335
|
+
try {
|
|
336
|
+
await open(r, page, t.path);
|
|
337
|
+
if ((await colours()) === light) {
|
|
338
|
+
r.record({ suite: S, where: `${t.name} · dark`, check: 'dark mode', status: 'info', detail: "skipped: the page looks the same with prefers-color-scheme: dark, so it has no dark mode to check" });
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
await page.addScriptTag({ content: AXE });
|
|
342
|
+
const axe = await page.evaluate(() => window.axe.run(document, { runOnly: { type: 'rule', values: ['color-contrast'] }, resultTypes: ['violations'] }));
|
|
343
|
+
const contrast = axe.violations.flatMap((v) => v.nodes.map((n) => n.target.join(' ')));
|
|
344
|
+
// ponytail: reads rgb() colours only; a background written in another colour space (oklch, color()) is not seen.
|
|
345
|
+
const white = await page.evaluate(() => {
|
|
346
|
+
const hits = [];
|
|
347
|
+
for (const el of document.querySelectorAll('body, body *')) {
|
|
348
|
+
const b = el.getBoundingClientRect(), s = getComputedStyle(el), c = s.backgroundColor.match(/[\d.]+/g);
|
|
349
|
+
if (b.width < 40 || b.height < 16 || s.visibility === 'hidden' || !s.backgroundColor.startsWith('rgb') || !c || (c[3] !== undefined && +c[3] <= 0.5) || +c[0] <= 235 || +c[1] <= 235 || +c[2] <= 235)
|
|
350
|
+
continue;
|
|
351
|
+
if (!el.closest('img, svg, canvas, video, iframe') && !hits.some((h) => h.contains(el)))
|
|
352
|
+
hits.push(el);
|
|
353
|
+
}
|
|
354
|
+
return hits.slice(0, 5).map((el) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : typeof el.className === 'string' && el.className.trim() ? `.${el.className.trim().split(/\s+/)[0]}` : ''} (${getComputedStyle(el).backgroundColor})`);
|
|
355
|
+
});
|
|
356
|
+
await emit(page, t, 'dark', `${t.name} · dark`, { 'dark mode: text contrast (axe)': contrast, 'dark mode: no background left white': white });
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
await page.emulateMedia({ colorScheme: 'light' });
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
for (const vp of [desktop, ...NARROW]) {
|
|
363
|
+
const first = vp === desktop;
|
|
364
|
+
const ctx = await context(r, vp, true, first); // axe is injected on desktop, so the page's own CSP is set aside there
|
|
365
|
+
const page = await ctx.newPage();
|
|
366
|
+
try {
|
|
367
|
+
if (first) {
|
|
368
|
+
// The screens to audit, then crawled pages up to audit.max; found once, used at every size.
|
|
369
|
+
const left = [];
|
|
370
|
+
const add = (name, path) => { if (skip?.test(path))
|
|
371
|
+
left.push(path);
|
|
372
|
+
else if (!out.screens.some((x) => x.path === path))
|
|
373
|
+
out.screens.push({ name, path, views: {} }); };
|
|
374
|
+
for (const s of r.side.screens.length ? r.side.screens : [{ name: 'Home', path: '/' }]) {
|
|
375
|
+
const path = await resolve(r, page, s).catch((e) => { if (e instanceof SessionExpired)
|
|
376
|
+
throw e; return null; });
|
|
377
|
+
if (path)
|
|
378
|
+
add(s.name, path);
|
|
379
|
+
else
|
|
380
|
+
r.record({ suite: S, where: s.name, check: 'screen reachable', status: 'warn', detail: 'no link to it found' });
|
|
381
|
+
}
|
|
382
|
+
const configured = out.screens.length;
|
|
383
|
+
for (const p of r.cfg.audit.max ? r.crawl.pages : [])
|
|
384
|
+
if (p.status >= 200 && p.status < 400 && out.screens.length < configured + r.cfg.audit.max)
|
|
385
|
+
add(p.path, p.path);
|
|
386
|
+
if (r.cfg.audit.max && !r.crawl.done)
|
|
387
|
+
r.record({ suite: S, where: 'audit.max', check: 'crawled pages audited', status: 'info', detail: "none: the crawl didn't run in this run, so only the screens were audited (choose crawl too: ONLY=crawl,audit)" });
|
|
388
|
+
if (left.length)
|
|
389
|
+
r.record({ suite: S, where: 'audit.skip', check: 'pages left out', status: 'info', detail: [...new Set(left)].slice(0, 8).join(', ') });
|
|
390
|
+
}
|
|
391
|
+
for (const t of out.screens) {
|
|
392
|
+
const where = `${t.name} · ${vp.name}`;
|
|
393
|
+
try {
|
|
394
|
+
if (first) {
|
|
395
|
+
await onDesktop(page, t);
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
await open(r, page, t.path);
|
|
399
|
+
await emit(page, t, vp.name, where, (await page.evaluate(measure, { extras: false })).problems);
|
|
400
|
+
}
|
|
401
|
+
catch (e) {
|
|
402
|
+
if (e instanceof SessionExpired)
|
|
403
|
+
throw e;
|
|
404
|
+
r.record({ suite: S, where, check: 'audit ran', status: 'fail', detail: e.message.slice(0, 200) });
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
finally {
|
|
409
|
+
await ctx.close();
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
// Across the screens: one look per kind of control.
|
|
413
|
+
const across = 'all audited screens';
|
|
414
|
+
for (const [kind, shapes] of looks) {
|
|
415
|
+
const by = [...shapes].sort((a, b) => b[1].n - a[1].n);
|
|
416
|
+
const paints = new Set(by.flatMap(([, u]) => [...u.paints]));
|
|
417
|
+
r.record({ suite: S, where: across, check: `consistency: one size and radius per ${kind}`, status: by.length > 1 ? 'warn' : 'pass',
|
|
418
|
+
detail: `${by.length} look(s): ${by.slice(0, 4).map(([shape, u]) => `${shape} ×${u.n}${u.labels.size ? ` (${[...u.labels].join(', ')})` : ''}`).join('; ')}` });
|
|
419
|
+
r.record({ suite: S, where: across, check: `consistency: ${kind} colours`, status: paints.size > (PAINTS[kind] ?? 1) ? 'warn' : 'pass', detail: `${paints.size} colour scheme(s): ${[...paints].slice(0, 4).join('; ')}` });
|
|
420
|
+
out.components[kind] = by.map(([shape, u]) => ({ shape, uses: u.n, labels: [...u.labels], colours: [...u.paints] }));
|
|
421
|
+
}
|
|
422
|
+
// Label case: Title Case needs two capitalised words after the first, sentence case none; names and one-word labels count as neither.
|
|
423
|
+
const SMALL = new Set(['a', 'an', 'and', 'as', 'at', 'by', 'for', 'in', 'of', 'on', 'or', 'the', 'to', 'with']);
|
|
424
|
+
const rest = (l) => l.split(/\s+/).slice(1).filter((w) => /^[A-Za-z]/.test(w) && !SMALL.has(w.toLowerCase()));
|
|
425
|
+
const caps = (l) => rest(l).filter((w) => /^[A-Z][a-z]/.test(w)).length;
|
|
426
|
+
const title = [...labels].filter((l) => rest(l).length >= 2 && caps(l) >= 2 && caps(l) / rest(l).length > 0.6), sentence = [...labels].filter((l) => rest(l).length >= 1 && caps(l) === 0);
|
|
427
|
+
const odd = title.length && sentence.length ? (title.length <= sentence.length ? title : sentence) : [];
|
|
428
|
+
r.record({ suite: S, where: across, check: 'labels use one case', status: odd.length ? 'warn' : 'pass',
|
|
429
|
+
detail: odd.length ? `${title.length} in Title Case, ${sentence.length} in sentence case; the fewer: ${odd.slice(0, 6).map((l) => `"${l}"`).join(', ')}` : undefined });
|
|
430
|
+
out.labelCase = { title, sentence };
|
|
431
|
+
for (const [list, word] of [['colors', 'colours'], ['fonts', 'fonts'], ['radii', 'radii'], ['spacing', 'spacing']]) {
|
|
432
|
+
if (!r.cfg.design?.[list])
|
|
433
|
+
continue;
|
|
434
|
+
const worst = [...(outside.get(list) ?? [])].sort((a, b) => b[1].n - a[1].n);
|
|
435
|
+
r.record({ suite: S, where: across, check: `design tokens: ${word}`, status: worst.length ? 'warn' : 'pass',
|
|
436
|
+
detail: worst.length ? `${worst.length} value(s) outside design.${list}; most used: ${worst.slice(0, 6).map(([v, u]) => `${v} ×${u.n} (${u.at})`).join('; ')}` : undefined });
|
|
437
|
+
out.tokens[list] = worst.map(([value, u]) => ({ value, uses: u.n, first: u.at }));
|
|
438
|
+
}
|
|
439
|
+
writeFileSync(`${r.dir}/audit.json`, JSON.stringify(out, null, 2));
|
|
440
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Config, Gate } from '../config.ts';
|
|
2
|
+
import type { Finding } from '../report.ts';
|
|
3
|
+
/** Runs one gate in its own process group, so a timeout stops everything it started. */
|
|
4
|
+
export declare function gate(g: Gate, cwd: string): Promise<{
|
|
5
|
+
code: number;
|
|
6
|
+
out: string;
|
|
7
|
+
timedOut: boolean;
|
|
8
|
+
}>;
|
|
9
|
+
export declare const tail: (s: string, n?: number) => string;
|
|
10
|
+
export declare function run(cfg: Config, dir: string, record: (f: Omit<Finding, 'side'>) => void): Promise<void>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Code gates (measured, no Jev, no browser, no running app). A code review needs certainty, so this runs the project's
|
|
3
|
+
* own toolchain and keeps the evidence:
|
|
4
|
+
* - each `gates` command (a linter, a type check, a dependency audit…) runs from the config file's folder: exit 0
|
|
5
|
+
* passes, anything else fails (or warns, with `warn: true`) with the exit code and the last lines of output; a gate
|
|
6
|
+
* still running after its `timeout` is stopped and fails. The end of every gate's output is kept in code.json;
|
|
7
|
+
* - when the `routes` command says which routes need sign-in (`auth`): state-changing routes (POST, PUT, PATCH, DELETE)
|
|
8
|
+
* with `auth: false` that don't match security.publicWrites are listed as a warning for a person to look at.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { writeFileSync } from 'node:fs';
|
|
12
|
+
import { routes } from '../routes.js';
|
|
13
|
+
const KEEP = 20_000; // characters of each gate's output kept
|
|
14
|
+
/** Runs one gate in its own process group, so a timeout stops everything it started. */
|
|
15
|
+
export function gate(g, cwd) {
|
|
16
|
+
return new Promise((done) => {
|
|
17
|
+
const child = spawn('/bin/sh', ['-c', g.run], { cwd, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
18
|
+
let out = '', timedOut = false;
|
|
19
|
+
const keep = (d) => { out = (out + d).slice(-KEEP); };
|
|
20
|
+
child.stdout.on('data', keep);
|
|
21
|
+
child.stderr.on('data', keep);
|
|
22
|
+
const timer = setTimeout(() => { timedOut = true; try {
|
|
23
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
24
|
+
}
|
|
25
|
+
catch { /* already gone */ } }, g.timeout * 1000);
|
|
26
|
+
child.on('close', (code) => { clearTimeout(timer); done({ code: code ?? -1, out: out.replace(/\x1b\[[0-9;]*m/g, ''), timedOut }); });
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
export const tail = (s, n = 6) => s.trim().split('\n').filter((l) => l.trim()).slice(-n).join(' ⏎ ').slice(-600);
|
|
30
|
+
export async function run(cfg, dir, record) {
|
|
31
|
+
const S = 'code';
|
|
32
|
+
const log = {};
|
|
33
|
+
for (const g of cfg.gates) {
|
|
34
|
+
const res = await gate(g, cfg.root);
|
|
35
|
+
log[g.name] = { code: res.code, out: res.out };
|
|
36
|
+
record({ suite: S, where: 'repository', check: g.name, status: res.code === 0 ? 'pass' : g.warn ? 'warn' : 'fail',
|
|
37
|
+
detail: res.code === 0 ? undefined : `${res.timedOut ? `stopped after ${g.timeout} s` : `exit ${res.code}`}: ${tail(res.out) || 'no output'}`,
|
|
38
|
+
evidence: res.code === 0 ? undefined : [`${dir}/code.json`] });
|
|
39
|
+
}
|
|
40
|
+
if (cfg.gates.length)
|
|
41
|
+
writeFileSync(`${dir}/code.json`, JSON.stringify(log, null, 2));
|
|
42
|
+
const list = routes(cfg);
|
|
43
|
+
if (!list.some((x) => x.auth !== undefined))
|
|
44
|
+
return;
|
|
45
|
+
const open = list.filter((x) => ['POST', 'PUT', 'PATCH', 'DELETE'].includes(x.method) && x.auth === false && !cfg.security.publicWrites?.test(x.path));
|
|
46
|
+
record({ suite: S, where: 'routes', check: 'state-changing routes need sign-in', status: open.length ? 'warn' : 'pass',
|
|
47
|
+
detail: open.length ? `${open.slice(0, 8).map((x) => `${x.method} ${x.path}`).join('; ')}${open.length > 8 ? ` (+${open.length - 8})` : ''}` : `${list.length} routes checked` });
|
|
48
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Run } from '../browser.ts';
|
|
2
|
+
/** /reports/01m7azs8…/stats → /reports/{id}/stats, so one endpoint is one contract. */
|
|
3
|
+
export declare const endpoint: (method: string, url: string) => string;
|
|
4
|
+
export declare function shape(body: string): string[] | null;
|
|
5
|
+
export declare function run(r: Run): Promise<void>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Frontend contract QA, from every request the crawl recorded (measured, no Jev):
|
|
3
|
+
* - nothing answers 5xx; the app's own XHR/fetch calls don't answer 4xx;
|
|
4
|
+
* - a JSON content type always carries JSON that parses, and every response says its content type;
|
|
5
|
+
* - an XHR/fetch call never gets a whole HTML document back (a login or error page served to a script);
|
|
6
|
+
* - XHR/fetch latency: p95 under P95_MS;
|
|
7
|
+
* - response shape: the top-level keys of each JSON endpoint (ids in the path normalised) against the saved baseline
|
|
8
|
+
* `contract-<side>.json` in the out folder; a key that disappeared is a breaking change. CONTRACT_UPDATE=1 rewrites
|
|
9
|
+
* the baseline; the first run creates it.
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { host } from '../browser.js';
|
|
13
|
+
import { run as runCrawl } from './crawl.js';
|
|
14
|
+
const P95_MS = 800;
|
|
15
|
+
/** /reports/01m7azs8…/stats → /reports/{id}/stats, so one endpoint is one contract. */
|
|
16
|
+
export const endpoint = (method, url) => {
|
|
17
|
+
const u = new URL(url);
|
|
18
|
+
return `${method} ${u.pathname.split('/').map((p) => (/^[0-9]+$|^[0-9a-z]{20,}$|^[0-9a-f-]{32,36}$/i.test(p) ? '{id}' : p)).join('/')}`;
|
|
19
|
+
};
|
|
20
|
+
export function shape(body) {
|
|
21
|
+
try {
|
|
22
|
+
const j = JSON.parse(body);
|
|
23
|
+
return Array.isArray(j) ? ['[array]'] : j && typeof j === 'object' ? Object.keys(j).sort() : null;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export async function run(r) {
|
|
30
|
+
const S = 'contract';
|
|
31
|
+
if (!r.crawl.done)
|
|
32
|
+
await runCrawl(r);
|
|
33
|
+
const own = r.crawl.hits.filter((h) => host(h.url) === host(r.side.baseUrl));
|
|
34
|
+
const calls = own.filter((h) => ['xhr', 'fetch'].includes(h.type));
|
|
35
|
+
const where = (h) => `${h.status ? `${h.status} ` : ''}${endpoint(h.method, h.url)} (on ${h.page})`;
|
|
36
|
+
const server = own.filter((h) => h.status >= 500);
|
|
37
|
+
r.record({ suite: S, where: 'all requests', check: 'no 5xx responses', status: server.length ? 'fail' : 'pass',
|
|
38
|
+
detail: server.length ? server.slice(0, 8).map(where).join('; ') : `${own.length} requests` });
|
|
39
|
+
const client = calls.filter((h) => h.status >= 400 && h.status < 500);
|
|
40
|
+
r.record({ suite: S, where: 'XHR/fetch', check: "no 4xx from the app's own calls", status: client.length ? 'fail' : 'pass',
|
|
41
|
+
detail: client.slice(0, 8).map(where).join('; ') || `${calls.length} calls` });
|
|
42
|
+
const badJson = calls.filter((h) => h.json === 'invalid');
|
|
43
|
+
r.record({ suite: S, where: 'XHR/fetch', check: 'JSON responses parse', status: badJson.length ? 'fail' : 'pass', detail: badJson.slice(0, 5).map((h) => endpoint(h.method, h.url)).join('; ') || undefined });
|
|
44
|
+
const noType = own.filter((h) => !h.contentType && h.status >= 200 && h.status < 300 && h.status !== 204);
|
|
45
|
+
r.record({ suite: S, where: 'all requests', check: 'content type declared', status: noType.length ? 'warn' : 'pass', detail: noType.slice(0, 5).map((h) => endpoint(h.method, h.url)).join('; ') || undefined });
|
|
46
|
+
const htmlDocs = calls.filter((h) => /text\/html/.test(h.contentType) && /<!doctype html|<html[\s>]/i.test(h.body ?? ''));
|
|
47
|
+
r.record({ suite: S, where: 'XHR/fetch', check: 'no whole HTML documents to scripts', status: htmlDocs.length ? 'fail' : 'pass',
|
|
48
|
+
detail: htmlDocs.slice(0, 5).map((h) => `${endpoint(h.method, h.url)} (on ${h.page})`).join('; ') || undefined });
|
|
49
|
+
const times = calls.map((h) => h.ms).sort((a, b) => a - b);
|
|
50
|
+
const p95 = times.length ? times[Math.min(times.length - 1, Math.floor(times.length * 0.95))] : 0;
|
|
51
|
+
r.record({ suite: S, where: 'XHR/fetch', check: `p95 latency under ${P95_MS} ms`, status: p95 < P95_MS ? 'pass' : 'warn', detail: `p95 ${p95} ms over ${times.length} calls` });
|
|
52
|
+
// Response shape against the baseline. Bodies are kept to 400 characters, so longer ones would give partial keys.
|
|
53
|
+
const now = {};
|
|
54
|
+
for (const h of calls) {
|
|
55
|
+
if (h.json !== 'ok' || h.status >= 300 || (h.body?.length ?? 0) >= 400)
|
|
56
|
+
continue;
|
|
57
|
+
const keys = shape(h.body ?? '');
|
|
58
|
+
if (keys)
|
|
59
|
+
now[endpoint(h.method, h.url)] = keys;
|
|
60
|
+
}
|
|
61
|
+
const file = `${r.cfg.out}/contract-${r.side.name}.json`;
|
|
62
|
+
const had = existsSync(file);
|
|
63
|
+
const base = had ? JSON.parse(readFileSync(file, 'utf8')) : {};
|
|
64
|
+
if (!had || process.env.CONTRACT_UPDATE === '1') {
|
|
65
|
+
writeFileSync(file, JSON.stringify({ ...base, ...now }, null, 2));
|
|
66
|
+
r.record({ suite: S, where: 'response shapes', check: 'baseline', status: 'info', detail: `${Object.keys(now).length} endpoint shape(s) saved to ${file}` });
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
for (const [ep, keys] of Object.entries(now)) {
|
|
70
|
+
const was = base[ep];
|
|
71
|
+
if (!was) {
|
|
72
|
+
r.record({ suite: S, where: ep, check: 'response shape', status: 'info', detail: `new endpoint: ${keys.join(', ')}` });
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const gone = was.filter((k) => !keys.includes(k)), added = keys.filter((k) => !was.includes(k));
|
|
76
|
+
r.record({ suite: S, where: ep, check: 'response shape', status: gone.length ? 'fail' : 'pass',
|
|
77
|
+
detail: [gone.length ? `removed: ${gone.join(', ')}` : '', added.length ? `added: ${added.join(', ')}` : ''].filter(Boolean).join(' · ') || undefined });
|
|
78
|
+
}
|
|
79
|
+
}
|