@ashishjain15491/tapcheck 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/CHANGELOG.md +87 -0
- package/LICENSE +21 -0
- package/README.md +190 -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
package/dist/browser.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The browser side every suite shares: one Chromium, a context per viewport (signed in with the side's saved session, or
|
|
3
|
+
* not), page settling, the facts code can measure on a page, screenshot slices, and the Run each suite is handed.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdirSync } from 'node:fs';
|
|
6
|
+
import { chromium } from 'playwright';
|
|
7
|
+
/** Every recording of the run (RECORD=1), for the report. */
|
|
8
|
+
export const recordings = [];
|
|
9
|
+
const seconds = (name, env) => {
|
|
10
|
+
const n = Number(env[name] ?? 0);
|
|
11
|
+
if (!(n >= 0))
|
|
12
|
+
throw new Error(`${name} must be a number, 0 or more (got "${env[name]}").`);
|
|
13
|
+
return n;
|
|
14
|
+
};
|
|
15
|
+
/** How the run's browser starts: HEADED=1 shows it, SLOWMO=<ms> waits that long between its actions; `args` are the config's browser.args. */
|
|
16
|
+
export const launchOptions = (env = process.env, args = []) => ({ headless: env.HEADED !== '1', slowMo: seconds('SLOWMO', env), ...(args.length ? { args } : {}) });
|
|
17
|
+
/** START_DELAY=<s>: seconds to count down before the first action (time to start a screen recording). */
|
|
18
|
+
export const startDelay = (env = process.env) => seconds('START_DELAY', env);
|
|
19
|
+
let browser = null;
|
|
20
|
+
const live = new Set(); // recorded contexts not closed yet
|
|
21
|
+
/** The run's one Chromium; `args` (browser.args) count on the call that starts it. */
|
|
22
|
+
export async function launch(args = []) {
|
|
23
|
+
browser ??= await chromium.launch(launchOptions(process.env, args));
|
|
24
|
+
return browser;
|
|
25
|
+
}
|
|
26
|
+
/** Closes the browser. A recorded context a suite left open is closed first, so its video and trace are still written. */
|
|
27
|
+
export const closeBrowser = async () => {
|
|
28
|
+
for (const ctx of [...live])
|
|
29
|
+
await ctx.close().catch(() => { });
|
|
30
|
+
await browser?.close();
|
|
31
|
+
browser = null;
|
|
32
|
+
};
|
|
33
|
+
/** Counts down START_DELAY seconds, in the terminal and (headed) in the browser window. */
|
|
34
|
+
export async function countdown(s = startDelay()) {
|
|
35
|
+
if (!s)
|
|
36
|
+
return;
|
|
37
|
+
const ctx = launchOptions().headless ? null : await (await launch()).newContext();
|
|
38
|
+
const page = await ctx?.newPage();
|
|
39
|
+
for (let left = Math.ceil(s); left > 0; left--) {
|
|
40
|
+
process.stdout.write(`\rStarting in ${left} s… `);
|
|
41
|
+
await page?.setContent(`<body style="font:48px system-ui;display:grid;place-items:center;height:90vh">tapcheck starts in ${left}…</body>`).catch(() => { });
|
|
42
|
+
await new Promise((done) => setTimeout(done, 1000));
|
|
43
|
+
}
|
|
44
|
+
process.stdout.write('\n');
|
|
45
|
+
await ctx?.close();
|
|
46
|
+
}
|
|
47
|
+
/** Files `what` under the part (and flow step) running now, once. */
|
|
48
|
+
export function reach(r, what, step = r.step) {
|
|
49
|
+
const list = (r.reached ??= []), part = r.part ?? '';
|
|
50
|
+
if (!list.some((x) => x.part === part && x.step === step && x.what === what))
|
|
51
|
+
list.push({ part, ...(step ? { step } : {}), what });
|
|
52
|
+
}
|
|
53
|
+
const ASSET = ['image', 'font', 'stylesheet', 'script', 'media', 'manifest'];
|
|
54
|
+
/** Answers that mean the app refused the request or has no such route: not reached. */
|
|
55
|
+
export const REFUSED = [401, 403, 404, 405];
|
|
56
|
+
/** The method the app routes a request by: a form POST that says `_method` (Laravel, Rails, Symfony) or an override header is that method. */
|
|
57
|
+
export function routedMethod(q) {
|
|
58
|
+
if (q.method() !== 'POST')
|
|
59
|
+
return q.method();
|
|
60
|
+
let body = '';
|
|
61
|
+
try {
|
|
62
|
+
body = q.postData() ?? '';
|
|
63
|
+
}
|
|
64
|
+
catch { /* a body that isn't text */ }
|
|
65
|
+
const said = q.headers()['x-http-method-override'] ?? new URL(q.url()).searchParams.get('_method')
|
|
66
|
+
?? body.match(/(?:^|&)_method=([A-Za-z]+)(?:&|$)|name="_method"\r?\n\r?\n([A-Za-z]+)|"_method"\s*:\s*"([A-Za-z]+)"/)?.slice(1).find(Boolean);
|
|
67
|
+
return said && /^(PUT|PATCH|DELETE)$/i.test(said) ? said.toUpperCase() : 'POST';
|
|
68
|
+
}
|
|
69
|
+
/** A screen's address: a path on the side's base URL, or a full URL as given. */
|
|
70
|
+
export const abs = (r, path) => (/^https?:\/\//.test(path) ? path : r.side.baseUrl + path);
|
|
71
|
+
export const host = (u) => { try {
|
|
72
|
+
return new URL(u).host;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return '';
|
|
76
|
+
} };
|
|
77
|
+
export const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '').slice(0, 48) || 'unlabelled';
|
|
78
|
+
/**
|
|
79
|
+
* A context at this viewport: signed in with the side's session unless auth is false. Every suite and flow gets its
|
|
80
|
+
* contexts here, so two things hold for all of them: each answered request to the side's own host is filed for the
|
|
81
|
+
* coverage map, and with RECORD=1 the context records a video per page (<side dir>/videos/) and a Playwright trace
|
|
82
|
+
* (<side dir>/traces/), written when the context closes.
|
|
83
|
+
*/
|
|
84
|
+
export async function context(r, vp, auth = true, bypassCSP = false, more = {}) {
|
|
85
|
+
const record = process.env.RECORD === '1';
|
|
86
|
+
const ctx = await (await launch()).newContext({ ...(auth && r.auth ? { storageState: r.auth } : {}), viewport: { width: vp.width, height: vp.height },
|
|
87
|
+
deviceScaleFactor: 1, isMobile: vp.mobile, hasTouch: vp.mobile, bypassCSP, ...(record ? { recordVideo: { dir: `${r.dir}/videos` } } : {}), ...more });
|
|
88
|
+
const own = host(r.side.baseUrl);
|
|
89
|
+
// Reached: a request to the app itself that it didn't refuse (401, 403, 405) or not find (404). Page assets aside.
|
|
90
|
+
ctx.on('response', (res) => {
|
|
91
|
+
const q = res.request();
|
|
92
|
+
if (host(q.url()) === own && !ASSET.includes(q.resourceType()) && !REFUSED.includes(res.status()))
|
|
93
|
+
reach(r, `${routedMethod(q)} ${new URL(q.url()).pathname}`);
|
|
94
|
+
});
|
|
95
|
+
if (!record)
|
|
96
|
+
return ctx;
|
|
97
|
+
const label = `${r.part ?? 'run'}-${vp.name}${auth ? '' : '-signed-out'}`;
|
|
98
|
+
const name = `${String(recordings.length + 1).padStart(3, '0')}-${slug(label).replace(/_/g, '-')}`;
|
|
99
|
+
const rec = { side: r.side.name, part: r.part ?? '', label, videos: [], trace: `${r.dir}/traces/${name}.zip` };
|
|
100
|
+
recordings.push(rec); // now, so the number in the name is taken
|
|
101
|
+
const pages = [];
|
|
102
|
+
ctx.on('page', (p) => pages.push(p));
|
|
103
|
+
await ctx.tracing.start({ screenshots: true, snapshots: true, title: label });
|
|
104
|
+
live.add(ctx);
|
|
105
|
+
const close = ctx.close.bind(ctx);
|
|
106
|
+
ctx.close = async (...a) => {
|
|
107
|
+
if (!live.delete(ctx))
|
|
108
|
+
return close(...a);
|
|
109
|
+
await ctx.tracing.stop({ path: rec.trace }).catch(() => { rec.trace = undefined; });
|
|
110
|
+
await close(...a); // the videos are complete once the context is closed
|
|
111
|
+
for (const [i, p] of pages.entries()) {
|
|
112
|
+
const file = `${r.dir}/videos/${name}${i ? `-${i + 1}` : ''}.webm`;
|
|
113
|
+
if (await p.video()?.saveAs(file).then(() => true, () => false))
|
|
114
|
+
rec.videos.push(file);
|
|
115
|
+
await p.video()?.delete().catch(() => { }); // the copy under Playwright's own random name
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
return ctx;
|
|
119
|
+
}
|
|
120
|
+
/** Console errors and uncaught page errors, collected from now on. */
|
|
121
|
+
export function watch(page) {
|
|
122
|
+
const errors = [];
|
|
123
|
+
page.on('pageerror', (e) => errors.push(e.message));
|
|
124
|
+
// Not the page's own: a trace (RECORD=1) puts a script in every frame, and a sandboxed frame refuses it out loud.
|
|
125
|
+
page.on('console', (m) => m.type() === 'error' && !/Blocked script execution in .* sandboxed/.test(m.text()) && errors.push(m.text()));
|
|
126
|
+
return errors;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Network idle, then the DOM quiet for 500 ms (at most 5 s more), so late-rendering widgets are judged as people see them.
|
|
130
|
+
* page.evaluate has no timeout, and a page's own timers never fire when its CSP sandboxes it without allow-scripts (an
|
|
131
|
+
* email preview, say) or its main thread never yields, so the 6 s cap is kept here, outside the page.
|
|
132
|
+
*/
|
|
133
|
+
export async function settle(page) {
|
|
134
|
+
await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => { });
|
|
135
|
+
let cap;
|
|
136
|
+
const outside = new Promise((done) => { cap = setTimeout(done, 6000); });
|
|
137
|
+
const quiet = page.evaluate(() => new Promise((done) => {
|
|
138
|
+
let timer = setTimeout(finish, 500);
|
|
139
|
+
const cap = setTimeout(finish, 5000);
|
|
140
|
+
const obs = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(finish, 500); });
|
|
141
|
+
obs.observe(document.documentElement, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
142
|
+
function finish() { obs.disconnect(); clearTimeout(timer); clearTimeout(cap); done(); }
|
|
143
|
+
})).catch(() => { });
|
|
144
|
+
await Promise.race([quiet, outside]);
|
|
145
|
+
clearTimeout(cap);
|
|
146
|
+
}
|
|
147
|
+
export class SessionExpired extends Error {
|
|
148
|
+
}
|
|
149
|
+
/** Being sent to a sign-in page on a side that signs in means the session is gone: stop rather than audit the login page. */
|
|
150
|
+
export function guard(r, requested, landed) {
|
|
151
|
+
if ('none' in r.side.login)
|
|
152
|
+
return;
|
|
153
|
+
if (r.cfg.loginPaths.test(new URL(landed).pathname) && !r.cfg.loginPaths.test(requested.split('?')[0])) {
|
|
154
|
+
// LOGIN=1 only does something on a manual side; form and command sides sign in afresh on every run.
|
|
155
|
+
const hint = 'manual' in r.side.login ? 'run again with LOGIN=1' : 'it ended during the run, or this user may not open that page';
|
|
156
|
+
throw new SessionExpired(`Sent to sign in at ${landed}: the ${r.side.name} session has expired (${hint}).`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** Opens a page of the app and waits for it to settle. A load that fails (a timeout on a busy app, a navigation
|
|
160
|
+
* aborted or cut short by another) is tried once more before the error counts; a download is not a page and isn't. */
|
|
161
|
+
export async function open(r, page, path) {
|
|
162
|
+
const go = () => page.goto(abs(r, path), { waitUntil: 'domcontentloaded' });
|
|
163
|
+
const res = await go().catch(async (e) => {
|
|
164
|
+
if (/Download is starting/.test(e.message))
|
|
165
|
+
throw e;
|
|
166
|
+
await page.waitForTimeout(1000);
|
|
167
|
+
return go();
|
|
168
|
+
});
|
|
169
|
+
await settle(page);
|
|
170
|
+
guard(r, path, page.url());
|
|
171
|
+
return res;
|
|
172
|
+
}
|
|
173
|
+
/** A screen's path: given directly, or the first link on `from` whose path matches `link`. Null when no link matches. */
|
|
174
|
+
export async function resolve(r, page, s) {
|
|
175
|
+
if (s.path)
|
|
176
|
+
return s.path;
|
|
177
|
+
await open(r, page, s.from);
|
|
178
|
+
const re = new RegExp(s.link, 'i');
|
|
179
|
+
const hrefs = await page.$$eval('a[href]', (as) => as.map((a) => a.pathname));
|
|
180
|
+
const hit = hrefs.find((h) => re.test(h));
|
|
181
|
+
return hit ? hit + (s.suffix ?? '') : null;
|
|
182
|
+
}
|
|
183
|
+
/** The screen as up to `max` viewport-sized slices, top to bottom, saved as <run dir>/shots/<key>-<n>.png (Jev takes images 280–1568 px a side). */
|
|
184
|
+
export async function slices(r, page, key, height, vh, max = 3) {
|
|
185
|
+
mkdirSync(`${r.dir}/shots`, { recursive: true });
|
|
186
|
+
const n = Math.min(max, Math.max(1, Math.ceil(height / vh)));
|
|
187
|
+
const out = [];
|
|
188
|
+
for (let i = 0; i < n; i++) {
|
|
189
|
+
await page.evaluate((y) => scrollTo(0, y), i * vh);
|
|
190
|
+
await page.waitForTimeout(250);
|
|
191
|
+
const file = `${r.dir}/shots/${key}-${i + 1}.png`;
|
|
192
|
+
await page.screenshot({ path: file });
|
|
193
|
+
out.push(file);
|
|
194
|
+
}
|
|
195
|
+
await page.evaluate(() => scrollTo(0, 0));
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
/** What code measures exactly: sideways scroll, broken images, off-screen and small controls, text coverage, headings. */
|
|
199
|
+
export async function facts(page) {
|
|
200
|
+
return page.evaluate(() => {
|
|
201
|
+
const vw = innerWidth, vh = innerHeight;
|
|
202
|
+
const visible = (el) => {
|
|
203
|
+
const r = el.getBoundingClientRect();
|
|
204
|
+
const s = getComputedStyle(el);
|
|
205
|
+
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && Number(s.opacity) > 0 && !el.closest('[aria-hidden=true]');
|
|
206
|
+
};
|
|
207
|
+
const broken = [...document.images].filter((i) => visible(i) && i.complete && i.naturalWidth === 0).map((i) => i.currentSrc || i.src);
|
|
208
|
+
const controls = [...document.querySelectorAll('a[href], button, [role=button], input:not([type=hidden]), select, textarea, summary')]
|
|
209
|
+
.filter(visible).slice(0, 250).map((el) => {
|
|
210
|
+
const r = el.getBoundingClientRect();
|
|
211
|
+
const label = (el.innerText || el.getAttribute('aria-label') || el.getAttribute('title') || el.placeholder || '')
|
|
212
|
+
.replace(/\s+/g, ' ').trim().slice(0, 60);
|
|
213
|
+
return { tag: el.tagName.toLowerCase(), role: el.getAttribute('role') || '', label, x: Math.round(r.left), y: Math.round(r.top + scrollY),
|
|
214
|
+
w: Math.round(r.width), h: Math.round(r.height), href: el.href || undefined };
|
|
215
|
+
});
|
|
216
|
+
// Text coverage of the first screen: the share of the viewport covered by text runs (negative space is what's left).
|
|
217
|
+
let ink = 0;
|
|
218
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
219
|
+
const range = document.createRange();
|
|
220
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
221
|
+
if (!n.textContent?.trim() || !n.parentElement || !visible(n.parentElement))
|
|
222
|
+
continue;
|
|
223
|
+
range.selectNodeContents(n);
|
|
224
|
+
for (const r of range.getClientRects()) {
|
|
225
|
+
ink += Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0)) * Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// WCAG 2.2 target size (2.5.8): controls in the first screen smaller than 24 × 24 px, inline text links aside.
|
|
229
|
+
const small = controls.filter((c) => c.y < vh && (c.w < 24 || c.h < 24) && c.tag !== 'a').map((c) => `${c.tag} "${c.label}" ${c.w}×${c.h}`);
|
|
230
|
+
return {
|
|
231
|
+
title: document.title, lang: document.documentElement.lang, overflowX: document.documentElement.scrollWidth > vw + 1,
|
|
232
|
+
brokenImages: broken, offscreen: controls.filter((c) => c.x < -1 || c.x + c.w > vw + 1).length, controls,
|
|
233
|
+
height: document.documentElement.scrollHeight, textCoverage: Math.round((ink / (vw * vh)) * 1000) / 1000, smallTargets: small,
|
|
234
|
+
h1: document.querySelectorAll('h1').length,
|
|
235
|
+
};
|
|
236
|
+
});
|
|
237
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/*
|
|
3
|
+
* tapcheck: start (or find) the app, sign in each side, run the suites, write one report.
|
|
4
|
+
*
|
|
5
|
+
* Every suite on every side is a part, named <suite>-<side> (crawl-public, ux-customer), tagged with its suite, its
|
|
6
|
+
* side, and jev (ux, usability) or measured (crawl, contract, security, a11y, interact, audit). Two more kinds of part:
|
|
7
|
+
* code the project's own gates (`gates:`) and the route sign-in check (`routes:`); tags code, measured. It has
|
|
8
|
+
* no side: a run of only `code` starts no app and no browser.
|
|
9
|
+
* flow-<name> each custom flow (`flows:`, see src/flow.ts) on its side; tags flow, its side, measured.
|
|
10
|
+
* With `stub:` in tapcheck.yml, a stub server (src/stub.ts) stands in for the outside services the app calls; it starts
|
|
11
|
+
* before the app, and its address is TAPCHECK_STUB_URL for app.start, the gates and tapcheck.yml itself (with `stub.dns`
|
|
12
|
+
* it answers DNS too, at TAPCHECK_DNS).
|
|
13
|
+
*
|
|
14
|
+
* tapcheck every part, with ./tapcheck.yml
|
|
15
|
+
* ONLY=crawl,a11y tapcheck only these parts: part names or tags, comma-separated; a trailing * matches name prefixes
|
|
16
|
+
* ONLY=customer SKIP=jev tapcheck SKIP takes parts out again (contract, security and interact still bring their side's crawl)
|
|
17
|
+
* CHANGED=1 tapcheck of the chosen parts, only those whose files changed since each last passed (needs git;
|
|
18
|
+
* `changes:` in tapcheck.yml says which files count for which part or suite)
|
|
19
|
+
* CHANGED=origin/main tapcheck the same, but files changed since the branch point with that git ref: QA for a pull
|
|
20
|
+
* request's own changes, with no state from earlier runs
|
|
21
|
+
* PARALLEL=4 tapcheck run up to 4 flows of a side at once (default `parallel` in tapcheck.yml, or 1); a flow
|
|
22
|
+
* with `serial: true` runs alone; the suites still run one by one
|
|
23
|
+
* LIST=1 tapcheck print the parts and their tags, mark what would run, and exit
|
|
24
|
+
* JEV=off tapcheck skip the suites Jev judges (ux, usability) and audit's Jev looks; also skipped when there is no key
|
|
25
|
+
* JEV_BUDGET=0.5 tapcheck the most to spend on Jev this run, in USD (default jev.budget, or 1)
|
|
26
|
+
* RESET=1 tapcheck run app.reset first (refused unless the app is local or allowRemoteReset is set); with
|
|
27
|
+
* app.resetWhen it also runs by itself when a matching file changed since the last reset
|
|
28
|
+
* HEADED=1 tapcheck a visible browser instead of a headless one; SLOWMO=150 waits that many ms between its
|
|
29
|
+
* actions; START_DELAY=10 counts down that many seconds before the first one
|
|
30
|
+
* RECORD=1 tapcheck a video and a Playwright trace of every browser context, per side under videos/ and
|
|
31
|
+
* traces/, linked from the report (open a trace with npx playwright show-trace <file>)
|
|
32
|
+
* COVERAGE=1 tapcheck no run: merge the hits.json of every run so far into COVERAGE.md (coverage.file): each
|
|
33
|
+
* route of `routes:` with the part that reached it or GAP, and the dialogs and tables seen
|
|
34
|
+
* LOGIN=1 tapcheck sign in again by hand on manual sides
|
|
35
|
+
* TAPCHECK_CONFIG=path tapcheck another config file
|
|
36
|
+
*
|
|
37
|
+
* ux, usability and audit ask Jev (TypeSafe): put TYPESAFE_API_KEY in the environment, or in a .env file next to tapcheck.yml.
|
|
38
|
+
*
|
|
39
|
+
* Output: <out>/run-<time>/report.html (open it), REPORT.md, findings.json, payloads.json (every Jev request) and per
|
|
40
|
+
* side the raw evidence, with hits.json (what each part reached). <out>/state.json remembers the code each part last
|
|
41
|
+
* passed at, and the code at the last reset. Exit code 1 when any check fails.
|
|
42
|
+
* The suites only read: they never submit a form or follow a delete, send or sign-out. Two exceptions. interact clicks
|
|
43
|
+
* every control whose label isn't one of those, so a button that saves on click is clicked: run it on test data
|
|
44
|
+
* (interact.submit: true goes further and submits valid input in dialog forms: a throwaway database only). Flows are
|
|
45
|
+
* your own code, may click and submit anything, and so may change data (leave them out with SKIP=flow).
|
|
46
|
+
*/
|
|
47
|
+
import { execSync, spawn } from 'node:child_process';
|
|
48
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
49
|
+
import { dirname, resolve } from 'node:path';
|
|
50
|
+
import { CHANGE_KEYS, isLocal, load, SUITES } from './config.js';
|
|
51
|
+
import { build, changedParts, findingSuite, list, mark, pool, resetDue, select, snapshot, withNeeds } from './parts.js';
|
|
52
|
+
import { signIn } from './auth.js';
|
|
53
|
+
import { closeBrowser, countdown, launch, recordings, SessionExpired, startDelay } from './browser.js';
|
|
54
|
+
import { coverage, hits } from './coverage.js';
|
|
55
|
+
import { routes } from './routes.js';
|
|
56
|
+
import * as jev from './jev.js';
|
|
57
|
+
import { loadFlows, runFlow } from './flow.js';
|
|
58
|
+
import { findings, record, write } from './report.js';
|
|
59
|
+
import { start as startStub } from './stub.js';
|
|
60
|
+
import * as code from './suites/code.js';
|
|
61
|
+
import * as crawl from './suites/crawl.js';
|
|
62
|
+
import * as contract from './suites/contract.js';
|
|
63
|
+
import * as security from './suites/security.js';
|
|
64
|
+
import * as a11y from './suites/a11y.js';
|
|
65
|
+
import * as interact from './suites/interact.js';
|
|
66
|
+
import * as audit from './suites/audit.js';
|
|
67
|
+
import * as ux from './suites/ux.js';
|
|
68
|
+
import * as usability from './suites/usability.js';
|
|
69
|
+
// A config or usage error reads better as one line than a stack trace (agents parse this output too).
|
|
70
|
+
// TAPCHECK_DEBUG=1 keeps the stack for real bugs.
|
|
71
|
+
if (process.env.TAPCHECK_DEBUG !== '1') {
|
|
72
|
+
process.setUncaughtExceptionCaptureCallback((e) => {
|
|
73
|
+
console.error(`tapcheck: ${e?.message ?? e}`);
|
|
74
|
+
process.exit(2);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const RUN = { crawl: crawl.run, contract: contract.run, security: security.run, a11y: a11y.run, interact: interact.run, audit: audit.run, ux: ux.run, usability: usability.run };
|
|
78
|
+
async function answers(url) {
|
|
79
|
+
return fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(5000) }).then((r) => r.status > 0 && r.status < 500).catch(() => false);
|
|
80
|
+
}
|
|
81
|
+
/** Starts the app unless it already answers; resolves with the process tapcheck started (to stop it after), if any. */
|
|
82
|
+
async function startApp(cfg) {
|
|
83
|
+
const ready = new URL(cfg.app.ready, cfg.baseUrl + '/').href;
|
|
84
|
+
if (await answers(ready))
|
|
85
|
+
return null;
|
|
86
|
+
if (!cfg.app.start)
|
|
87
|
+
throw new Error(`The app isn't answering at ${ready}, and tapcheck.yml has no app.start to start it.`);
|
|
88
|
+
console.log(`Starting the app: ${cfg.app.start}`);
|
|
89
|
+
// `wait` keeps the shell alive while anything it started in the background runs, so stopApp can stop that whole
|
|
90
|
+
// process group, and its id can't be reused by an unrelated one meanwhile.
|
|
91
|
+
const child = spawn('/bin/sh', ['-c', `${cfg.app.start}\nwait`], { stdio: 'inherit', detached: true });
|
|
92
|
+
const until = Date.now() + cfg.app.timeout * 1000;
|
|
93
|
+
while (Date.now() < until) {
|
|
94
|
+
if (await answers(ready))
|
|
95
|
+
return child;
|
|
96
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
97
|
+
}
|
|
98
|
+
stopApp(cfg, child);
|
|
99
|
+
throw new Error(`The app didn't answer at ${ready} within ${cfg.app.timeout} s of app.start.`);
|
|
100
|
+
}
|
|
101
|
+
/** Stops what app.start started, nothing when the app was already up: app.stop, then the whole process group,
|
|
102
|
+
* background workers included. */
|
|
103
|
+
function stopApp(cfg, child) {
|
|
104
|
+
if (!child?.pid)
|
|
105
|
+
return;
|
|
106
|
+
if (cfg.app.stop) {
|
|
107
|
+
try {
|
|
108
|
+
execSync(cfg.app.stop, { stdio: 'inherit', shell: '/bin/sh' });
|
|
109
|
+
}
|
|
110
|
+
catch { /* reported by the command itself */ }
|
|
111
|
+
}
|
|
112
|
+
if (child.exitCode === null) {
|
|
113
|
+
try {
|
|
114
|
+
process.kill(-child.pid, 'SIGTERM');
|
|
115
|
+
}
|
|
116
|
+
catch { /* already gone */ }
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const configFile = process.env.TAPCHECK_CONFIG ?? 'tapcheck.yml';
|
|
120
|
+
const cfg = load(configFile);
|
|
121
|
+
if (process.env.COVERAGE === '1') {
|
|
122
|
+
const { all, runs } = hits(cfg.out);
|
|
123
|
+
const c = coverage(all, runs, routes(cfg), cfg.coverage.reasons);
|
|
124
|
+
const file = resolve(cfg.root, cfg.coverage.file);
|
|
125
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
126
|
+
writeFileSync(file, c.md);
|
|
127
|
+
console.log(`${c.summary}; ${runs} run(s) merged → ${file}`);
|
|
128
|
+
for (const g of c.gaps)
|
|
129
|
+
console.log(` GAP ${g}`);
|
|
130
|
+
process.exit(0);
|
|
131
|
+
}
|
|
132
|
+
const flows = await loadFlows(cfg);
|
|
133
|
+
const PARTS = build(cfg.sides.map((s) => s.name), { code: cfg.gates.length > 0 || !!cfg.routes, flows });
|
|
134
|
+
const statePath = `${cfg.out}/state.json`;
|
|
135
|
+
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { parts: {} };
|
|
136
|
+
let chosen = select(PARTS, list(process.env.ONLY), list(process.env.SKIP));
|
|
137
|
+
const changedBase = process.env.CHANGED && !['0', '1'].includes(process.env.CHANGED) ? process.env.CHANGED : undefined;
|
|
138
|
+
const unknownKeys = Object.keys(cfg.changes).filter((k) => k !== '*' && !CHANGE_KEYS.includes(k) && !PARTS.some((p) => p.name === k));
|
|
139
|
+
if (unknownKeys.length)
|
|
140
|
+
throw new Error(`changes: ${unknownKeys.join(', ')} ${unknownKeys.length > 1 ? 'are' : 'is'} not a part. Run with LIST=1 to see them.`);
|
|
141
|
+
if (process.env.CHANGED === '1' || changedBase)
|
|
142
|
+
chosen = changedParts(chosen, state, cfg.changes, { config: configFile, out: cfg.out, base: changedBase });
|
|
143
|
+
chosen = withNeeds(PARTS, chosen);
|
|
144
|
+
if (process.env.LIST === '1') {
|
|
145
|
+
const w = Math.max(...PARTS.map((p) => p.name.length));
|
|
146
|
+
for (const p of PARTS)
|
|
147
|
+
console.log(`${chosen.includes(p) ? '▶' : ' '} ${p.name.padEnd(w)} ${p.tags.join(', ')}`);
|
|
148
|
+
process.exit(0);
|
|
149
|
+
}
|
|
150
|
+
if (!chosen.length) {
|
|
151
|
+
console.log(`Nothing to run: ${changedBase ? `no chosen part has changed files since ${changedBase}.` : process.env.CHANGED === '1' ? 'no chosen part has changed files since it last passed.' : 'SKIP took out every chosen part.'}`);
|
|
152
|
+
process.exit(0);
|
|
153
|
+
}
|
|
154
|
+
console.log(`Running: ${chosen.map((p) => p.name).join(', ')}`);
|
|
155
|
+
jev.setup(cfg.jev);
|
|
156
|
+
// Why the Jev parts are skipped, or '' when they run. Once the budget is reached it says so, and the rest are skipped too.
|
|
157
|
+
let jevOff = jev.whyOff();
|
|
158
|
+
const jevParts = chosen.filter((p) => p.tags.includes('jev'));
|
|
159
|
+
const jevAsked = !jevOff && jevParts.length > 0;
|
|
160
|
+
const ran = []; // parts that ran, to the end or not
|
|
161
|
+
const skipped = {}; // Jev parts left out, and why: neither passed nor failed
|
|
162
|
+
const notRun = {}; // parts that couldn't run, and why: they count as failed
|
|
163
|
+
const label = (p) => (p.suite === 'flow' ? p.name : p.suite);
|
|
164
|
+
/** Runs one part; what it throws becomes a failing finding of its own and is returned. */
|
|
165
|
+
async function runPart(p, rec, fn, together = false) {
|
|
166
|
+
const t0 = Date.now();
|
|
167
|
+
const flow = p.suite === 'flow'; // a flow prints a line per step under its name
|
|
168
|
+
const end = `${flow ? ' ' : ''}${together ? `${label(p)} ` : ''}`; // flows running together: say whose end it is
|
|
169
|
+
process.stdout.write(` ${label(p)}…${flow ? '\n' : ' '}`);
|
|
170
|
+
ran.push(p);
|
|
171
|
+
try {
|
|
172
|
+
await fn();
|
|
173
|
+
console.log(`${end}done in ${((Date.now() - t0) / 1000).toFixed(0)} s`);
|
|
174
|
+
}
|
|
175
|
+
catch (e) {
|
|
176
|
+
const msg = e.message;
|
|
177
|
+
console.log(`${end}stopped: ${msg}`);
|
|
178
|
+
rec({ suite: findingSuite(p), where: 'suite', check: 'suite ran to the end', status: 'fail', detail: msg.slice(0, 300) });
|
|
179
|
+
return e;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
startDelay(); // a wrong START_DELAY or SLOWMO stops the run here, before anything starts
|
|
183
|
+
const started = Date.now();
|
|
184
|
+
const dir = `${cfg.out}/run-${new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)}`;
|
|
185
|
+
mkdirSync(dir, { recursive: true });
|
|
186
|
+
const needsApp = chosen.some((p) => p.side); // the code part alone needs neither the app nor a browser
|
|
187
|
+
// The browser first, before anything else starts: a missing Chromium is one line here, not Playwright's long error in every part.
|
|
188
|
+
if (needsApp) {
|
|
189
|
+
await launch(cfg.browser.args).catch((e) => {
|
|
190
|
+
throw new Error(/Executable doesn't exist|playwright install/.test(e.message) ? "Chromium isn't installed. Run: npx playwright install chromium" : e.message);
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
const stub = cfg.stub ? await startStub(cfg.stub, cfg.out, cfg.root) : null; // before the app, which is started with its address
|
|
194
|
+
const app = needsApp ? await startApp(cfg).catch(async (e) => { await stub?.stop(); throw e; }) : null;
|
|
195
|
+
const onSignal = () => { if (needsApp)
|
|
196
|
+
stopApp(cfg, app); process.exit(130); };
|
|
197
|
+
process.once('SIGINT', onSignal);
|
|
198
|
+
process.once('SIGTERM', onSignal);
|
|
199
|
+
try {
|
|
200
|
+
// Reset: asked for (RESET=1), or due by app.resetWhen (first use, or a matching file changed since the last one).
|
|
201
|
+
const now = needsApp && cfg.app.resetWhen.length ? snapshot() : null;
|
|
202
|
+
if (needsApp && cfg.app.resetWhen.length && !now)
|
|
203
|
+
console.log('app.resetWhen is ignored: this is not a git repository with a commit.');
|
|
204
|
+
const why = process.env.RESET === '1' ? 'RESET=1' : now && resetDue(state, cfg.app.resetWhen);
|
|
205
|
+
if (why) {
|
|
206
|
+
if (!cfg.app.reset)
|
|
207
|
+
throw new Error('RESET=1 but tapcheck.yml has no app.reset.');
|
|
208
|
+
if (!isLocal(cfg.baseUrl) && !cfg.app.allowRemoteReset) {
|
|
209
|
+
throw new Error(`Refusing to reset ${cfg.baseUrl} (${why}): it isn't local. Set app.allowRemoteReset: true if that's really a throwaway copy.`);
|
|
210
|
+
}
|
|
211
|
+
console.log(`Resetting (${why}): ${cfg.app.reset}`);
|
|
212
|
+
execSync(cfg.app.reset, { stdio: 'inherit', shell: '/bin/sh' });
|
|
213
|
+
const snap = now ?? snapshot();
|
|
214
|
+
if (snap)
|
|
215
|
+
state.reset = snap;
|
|
216
|
+
}
|
|
217
|
+
if (needsApp)
|
|
218
|
+
await countdown();
|
|
219
|
+
const codePart = chosen.find((p) => p.suite === 'code');
|
|
220
|
+
if (codePart) {
|
|
221
|
+
const rec = (f) => record({ ...f, side: '' });
|
|
222
|
+
console.log(`\ncode: ${cfg.gates.length} gate(s)${cfg.routes ? ', routes' : ''}`);
|
|
223
|
+
await runPart(codePart, rec, () => code.run(cfg, dir, rec));
|
|
224
|
+
}
|
|
225
|
+
for (const side of cfg.sides) {
|
|
226
|
+
const parts = chosen.filter((p) => p.side === side.name);
|
|
227
|
+
if (!parts.length)
|
|
228
|
+
continue;
|
|
229
|
+
const sideDir = `${dir}/${side.name}`;
|
|
230
|
+
mkdirSync(sideDir, { recursive: true });
|
|
231
|
+
console.log(`\n${side.name} at ${side.baseUrl}: ${parts.map(label).join(', ')}`);
|
|
232
|
+
// reached: one list, so the copies the flows running together get (each its own part and step) share it
|
|
233
|
+
const r = { cfg, side, dir: sideDir, record: (f) => record({ ...f, side: side.name }), crawl: { pages: [], hits: [], done: false }, reached: [] };
|
|
234
|
+
try {
|
|
235
|
+
r.auth = await signIn(cfg, side);
|
|
236
|
+
}
|
|
237
|
+
catch (e) {
|
|
238
|
+
console.log(` sign-in failed, so ${parts.map(label).join(', ')} didn't run: ${e.message}`);
|
|
239
|
+
r.record({ suite: 'sign-in', where: side.baseUrl, check: 'signed in', status: 'fail', detail: e.message.slice(0, 300) });
|
|
240
|
+
for (const p of parts)
|
|
241
|
+
notRun[p.name] = 'sign-in failed';
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
let expired = false;
|
|
245
|
+
const one = async (p, rp, together = false) => {
|
|
246
|
+
if (jevOff && p.tags.includes('jev')) {
|
|
247
|
+
console.log(` ${p.suite}… skipped (${jevOff})`);
|
|
248
|
+
skipped[p.name] = jevOff;
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const flow = flows.find((f) => f.part === p.name);
|
|
252
|
+
const e = await runPart(p, rp.record, () => (flow ? runFlow(flow, rp, stub?.url) : RUN[p.suite](rp)), together);
|
|
253
|
+
if (e instanceof jev.BudgetReached)
|
|
254
|
+
jevOff = 'Jev budget reached';
|
|
255
|
+
if (e instanceof SessionExpired)
|
|
256
|
+
expired = true;
|
|
257
|
+
};
|
|
258
|
+
// The suites one by one, then the flows: `parallel` at a time (a serial flow alone), each with its own copy of the run.
|
|
259
|
+
const together = cfg.parallel > 1 ? parts.filter((p) => p.suite === 'flow') : [];
|
|
260
|
+
for (const p of parts.filter((q) => !together.includes(q))) {
|
|
261
|
+
if (expired)
|
|
262
|
+
break;
|
|
263
|
+
r.part = p.name;
|
|
264
|
+
await one(p, r);
|
|
265
|
+
}
|
|
266
|
+
if (together.length) {
|
|
267
|
+
console.log(` flows, ${cfg.parallel} at a time: their step lines start with the flow's name`);
|
|
268
|
+
const alone = (p) => flows.find((f) => f.part === p.name)?.serial === true;
|
|
269
|
+
await pool(together, cfg.parallel, alone, (p) => one(p, { ...r, part: p.name, step: undefined, prefix: `[${p.name}] ` }, true), () => expired);
|
|
270
|
+
}
|
|
271
|
+
if (expired)
|
|
272
|
+
for (const q of parts)
|
|
273
|
+
if (!ran.includes(q) && !(q.name in skipped))
|
|
274
|
+
notRun[q.name] = 'the session expired';
|
|
275
|
+
writeFileSync(`${sideDir}/hits.json`, JSON.stringify(r.reached ?? [], null, 1));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
finally {
|
|
279
|
+
await closeBrowser();
|
|
280
|
+
if (needsApp)
|
|
281
|
+
stopApp(cfg, app);
|
|
282
|
+
await stub?.stop();
|
|
283
|
+
const u = jev.usage();
|
|
284
|
+
const asked = jevAsked || u.calls + u.cached > 0; // audit asks Jev too, and isn't a Jev part
|
|
285
|
+
const note = asked ? `Jev: ${u.calls} calls (avg ${u.avgMs} ms, ${u.cached} from cache), ${u.tokens} input tokens, $${u.usd} of the $${u.budget} budget` : undefined;
|
|
286
|
+
if (asked)
|
|
287
|
+
jev.savePayloads(dir);
|
|
288
|
+
// Every part that didn't run gets a finding of its own, so the report (not just this terminal) says which and why.
|
|
289
|
+
// Skipped Jev parts are neither passed nor failed (info); a part that couldn't run counts as failed.
|
|
290
|
+
for (const p of chosen) {
|
|
291
|
+
if (ran.includes(p))
|
|
292
|
+
continue;
|
|
293
|
+
const skip = skipped[p.name];
|
|
294
|
+
const hint = skip && !/budget/.test(skip) ? ' To run it, set TYPESAFE_API_KEY in the environment or in .env here, without JEV=off.'
|
|
295
|
+
: skip ? ' Raise JEV_BUDGET (or jev.budget) to let it finish.' : '';
|
|
296
|
+
record({ suite: findingSuite(p), side: p.side, where: p.name, check: 'part ran', status: skip ? 'info' : 'fail',
|
|
297
|
+
detail: `${skip ? `skipped (${skip})` : `not run (${notRun[p.name] ?? 'the run stopped before it'})`}.${hint}` });
|
|
298
|
+
}
|
|
299
|
+
const { bySuite, fails } = write(dir, { base: cfg.baseUrl, started, note, recordings });
|
|
300
|
+
console.log('');
|
|
301
|
+
console.table(bySuite.map((b) => ({ suite: b.s, failing: b.fail, warnings: b.warn, passing: b.pass })));
|
|
302
|
+
if (note)
|
|
303
|
+
console.log(note);
|
|
304
|
+
const passed = mark(state, ran, findings, snapshot());
|
|
305
|
+
for (const p of chosen) {
|
|
306
|
+
if (p.name in skipped) {
|
|
307
|
+
console.log(` – ${p.name} (skipped: ${skipped[p.name]})`);
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
if (!passed[p.name])
|
|
311
|
+
delete state.parts[p.name];
|
|
312
|
+
console.log(` ${passed[p.name] ? '✓' : '✗'} ${p.name}${p.name in notRun ? ` (not run: ${notRun[p.name]})` : ran.includes(p) ? '' : ' (not run)'}`);
|
|
313
|
+
}
|
|
314
|
+
writeFileSync(statePath, JSON.stringify(state, null, 1));
|
|
315
|
+
if (recordings.length)
|
|
316
|
+
console.log(`Recordings: ${recordings.length} (videos and traces, listed in the report). Open a trace: npx playwright show-trace <file>`);
|
|
317
|
+
console.log(`Report: ${dir}/report.html`);
|
|
318
|
+
process.exitCode = fails ? 1 : 0;
|
|
319
|
+
// A flow that timed out may leave its own browser or timers behind, which would keep the process alive.
|
|
320
|
+
setTimeout(() => process.exit(), 10_000).unref();
|
|
321
|
+
}
|