proofed-cli 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 +286 -2
- package/bin/node-version.cjs +11 -0
- package/bin/proofed.cjs +14 -0
- package/dist/args.js +156 -0
- package/dist/cache.js +48 -0
- package/dist/cdp.js +46 -0
- package/dist/changes.js +59 -0
- package/dist/check.js +334 -0
- package/dist/children.js +33 -0
- package/dist/chrome.js +77 -0
- package/dist/clip.js +270 -0
- package/dist/doctor.js +133 -0
- package/dist/github.js +143 -0
- package/dist/help.js +124 -0
- package/dist/kane.js +75 -0
- package/dist/list.js +82 -0
- package/dist/live.js +139 -0
- package/dist/livefile.js +83 -0
- package/dist/log.js +7 -0
- package/dist/models.js +44 -0
- package/dist/pipeline.js +194 -0
- package/dist/precheck.js +111 -0
- package/dist/proofed.js +70 -0
- package/dist/recorder.js +209 -0
- package/dist/render.js +426 -0
- package/dist/report.js +328 -0
- package/dist/requests.js +58 -0
- package/dist/result.js +135 -0
- package/dist/run.js +164 -0
- package/dist/runfile.js +11 -0
- package/dist/scenarios.js +89 -0
- package/dist/serve.js +82 -0
- package/dist/server.js +24 -0
- package/dist/setuperror.js +11 -0
- package/dist/target.js +132 -0
- package/dist/which.js +28 -0
- package/package.json +44 -4
package/dist/pipeline.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// Shared by the PR check (cli.ts) and the fix loop (fix.ts).
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { editComment, listReports, minimize, postComment, publishClips, repoFromEnv, setStatus } from "./github.js";
|
|
6
|
+
import { live } from "./live.js";
|
|
7
|
+
import { log } from "./log.js";
|
|
8
|
+
import { crashResult, findCrashes } from "./precheck.js";
|
|
9
|
+
import { buildReport, outdated, postsNew } from "./report.js";
|
|
10
|
+
import { nothingAsked } from "./requests.js";
|
|
11
|
+
import { creditsOf, scenarioDoubted, runScenario } from "./run.js";
|
|
12
|
+
import { FAILED_CHECK_ACTION, FAILED_CHECK_REASON, RUN_FILE } from "./runfile.js";
|
|
13
|
+
import { affectedBy, loadScenariosOr } from "./scenarios.js";
|
|
14
|
+
export const env = (name, fallback) => {
|
|
15
|
+
const value = process.env[name]?.trim() || fallback;
|
|
16
|
+
if (value === undefined)
|
|
17
|
+
throw new Error(`Missing ${name}`);
|
|
18
|
+
return value;
|
|
19
|
+
};
|
|
20
|
+
export function readEvent() {
|
|
21
|
+
return process.env.GITHUB_EVENT_PATH ? JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")) : {};
|
|
22
|
+
}
|
|
23
|
+
export const ctx = () => {
|
|
24
|
+
const token = process.env.GITHUB_TOKEN;
|
|
25
|
+
return {
|
|
26
|
+
repo: token && process.env.GITHUB_REPOSITORY ? repoFromEnv(token) : undefined,
|
|
27
|
+
runUrl: process.env.GITHUB_RUN_ID
|
|
28
|
+
? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`
|
|
29
|
+
: undefined,
|
|
30
|
+
outDir: env("PROOFED_OUT", ".proofed-out"),
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
export const changedFiles = (base, head = "HEAD") => execFileSync("git", ["diff", "--name-only", `${base}...${head}`], { encoding: "utf8" }).split("\n").filter(Boolean);
|
|
34
|
+
// The base branch as the runner sees it (origin/main), so the diff and any scenarios read from it
|
|
35
|
+
// are current even for a PR whose recorded base commit is weeks old. Falls back to that commit.
|
|
36
|
+
export function baseRev(base) {
|
|
37
|
+
try {
|
|
38
|
+
execFileSync("git", ["rev-parse", "--verify", "--quiet", `origin/${base.ref}`], { stdio: "ignore" });
|
|
39
|
+
return `origin/${base.ref}`;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return base.sha;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function pickScenarios({ changed, only, rev }) {
|
|
46
|
+
const all = loadScenariosOr(env("PROOFED_SCENARIOS", ".proofed/scenarios"), rev);
|
|
47
|
+
const selected = only?.length ? all.filter((s) => only.includes(s.id)) : changed ? affectedBy(all, changed) : all;
|
|
48
|
+
return { selected, skipped: all.filter((s) => !selected.includes(s)).map((s) => s.name) };
|
|
49
|
+
}
|
|
50
|
+
// Every scenario gets its own Chrome, so they can run side by side; Kane is mostly waiting on its backend.
|
|
51
|
+
// A start page that crashes while loading fails its scenarios without Kane (see precheck.ts).
|
|
52
|
+
export async function runAll(scenarios, outDir, concurrency = Number(process.env.PROOFED_CONCURRENCY) || 3, o = {}) {
|
|
53
|
+
const baseUrl = o.baseUrl ?? env("PROOFED_URL");
|
|
54
|
+
const emit = o.onEvent ?? (() => { });
|
|
55
|
+
for (const s of scenarios)
|
|
56
|
+
emit({ type: "waiting", id: s.id });
|
|
57
|
+
const urlOf = (s) => new URL(s.url, baseUrl).href;
|
|
58
|
+
live.track(scenarios);
|
|
59
|
+
const checking = Date.now();
|
|
60
|
+
const crashes = await findCrashes([...new Set(scenarios.map(urlOf))], outDir);
|
|
61
|
+
const checkSeconds = Math.round((Date.now() - checking) / 1000);
|
|
62
|
+
const results = new Array(scenarios.length);
|
|
63
|
+
let next = 0;
|
|
64
|
+
const worker = async () => {
|
|
65
|
+
for (let i = next++; i < scenarios.length; i = next++) {
|
|
66
|
+
const scenario = scenarios[i];
|
|
67
|
+
const crash = crashes.get(urlOf(scenario));
|
|
68
|
+
if (crash) {
|
|
69
|
+
log(`✗ ${scenario.name}: ${urlOf(scenario)} crashed while loading (${crash.error}); Kane not run`);
|
|
70
|
+
const result = { ...crashResult(scenario, crash), seconds: checkSeconds };
|
|
71
|
+
results[i] = result;
|
|
72
|
+
live.scenario(scenario.id, { status: result.outcome });
|
|
73
|
+
emit({ type: "finished", id: scenario.id, result });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
log(`▶ ${scenario.name}`);
|
|
77
|
+
emit({ type: "started", id: scenario.id });
|
|
78
|
+
const started = Date.now();
|
|
79
|
+
const result = await runScenario(scenario, {
|
|
80
|
+
baseUrl,
|
|
81
|
+
outDir,
|
|
82
|
+
username: process.env.LT_USERNAME,
|
|
83
|
+
accessKey: process.env.LT_ACCESS_KEY,
|
|
84
|
+
headless: o.headless,
|
|
85
|
+
onEvent: o.onEvent,
|
|
86
|
+
});
|
|
87
|
+
const timed = { ...result, seconds: Math.round((Date.now() - started) / 1000) };
|
|
88
|
+
results[i] = timed;
|
|
89
|
+
live.scenario(scenario.id, { status: result.outcome });
|
|
90
|
+
emit({ type: "finished", id: scenario.id, result: timed });
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, scenarios.length) }, worker));
|
|
94
|
+
return results;
|
|
95
|
+
}
|
|
96
|
+
export const isBroken = (r) => r.outcome === "failed" || r.outcome === "error";
|
|
97
|
+
// Posts the report as a new comment or edits the current one (postsNew). A new one retires the reports
|
|
98
|
+
// before it: folded as outdated and left without anything that reads as the report. Neither step can
|
|
99
|
+
// fail the run; the newest report is the one everything reads.
|
|
100
|
+
export async function putReport(repo, pr, body, notify) {
|
|
101
|
+
const { current, older } = await listReports(repo, pr);
|
|
102
|
+
if (current && !postsNew(current.body, body, notify))
|
|
103
|
+
return editComment(repo, current.id, body);
|
|
104
|
+
const posted = await postComment(repo, pr, body);
|
|
105
|
+
for (const old of current ? [...older, current] : older) {
|
|
106
|
+
await editComment(repo, old.id, outdated(old.body ?? "")).catch((e) => console.log(`Couldn't retire the old report: ${e instanceof Error ? e.message : e}`));
|
|
107
|
+
await minimize(repo, old.node_id).catch((e) => console.log(`Couldn't fold the old report: ${e instanceof Error ? e.message : e}`));
|
|
108
|
+
}
|
|
109
|
+
return posted;
|
|
110
|
+
}
|
|
111
|
+
// The dashboard's copy of the run. Steps are capped like the comment's, so the file stays small.
|
|
112
|
+
// A description that asked for nothing isn't in it, as it isn't in the comment's count.
|
|
113
|
+
export function runFile({ sha, results, skipped, runUrl, fix }, clips) {
|
|
114
|
+
return {
|
|
115
|
+
sha,
|
|
116
|
+
runUrl,
|
|
117
|
+
skipped,
|
|
118
|
+
scenarios: results.filter((r) => !nothingAsked(r)).map((r) => ({
|
|
119
|
+
id: r.scenario.id,
|
|
120
|
+
name: r.scenario.name,
|
|
121
|
+
outcome: r.outcome,
|
|
122
|
+
reason: scenarioDoubted(r) ? `${r.end?.reason ?? ""} ${FAILED_CHECK_REASON} ${FAILED_CHECK_ACTION}` : (r.outcome === "passed" ? r.end?.summary || r.end?.reason : r.end?.reason || r.error) || undefined,
|
|
123
|
+
...(scenarioDoubted(r) && { failedCheck: "scenario_doubted" }),
|
|
124
|
+
diagnosis: scenarioDoubted(r) ? `Kane's opinion: ${r.end?.verdict?.root_cause ?? ""}` : r.outcome === "passed" ? undefined : r.end?.verdict?.root_cause,
|
|
125
|
+
suggestion: scenarioDoubted(r) ? FAILED_CHECK_ACTION : r.end?.verdict?.suggestion,
|
|
126
|
+
steps: r.steps
|
|
127
|
+
.filter((s) => s.status !== "running" && s.remark)
|
|
128
|
+
.slice(-30)
|
|
129
|
+
.map((s) => ({ remark: s.remark.slice(0, 200), ...(s.status === "failed" && { failed: true }), ...(s.at !== undefined && { at: s.at }) })),
|
|
130
|
+
clip: clips.get(r.scenario.id),
|
|
131
|
+
credits: r.end?.credits_consumed === undefined ? undefined : creditsOf(r),
|
|
132
|
+
seconds: r.seconds,
|
|
133
|
+
})),
|
|
134
|
+
fix: fix && {
|
|
135
|
+
status: fix.status,
|
|
136
|
+
model: fix.model,
|
|
137
|
+
effort: fix.effort,
|
|
138
|
+
summary: fix.summary,
|
|
139
|
+
commit: fix.commit,
|
|
140
|
+
attempts: fix.tries,
|
|
141
|
+
files: fix.changes?.map(({ file, added, removed }) => ({ path: file, added, removed })),
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
export async function publish(input) {
|
|
146
|
+
const { repo, pr, sha, results, skipped, runUrl, outDir, fix, asked, previous, written, requested = false } = input;
|
|
147
|
+
const clips = new Map();
|
|
148
|
+
let runKey;
|
|
149
|
+
if (repo && pr) {
|
|
150
|
+
const prefix = `pr-${pr}/${sha.slice(0, 7)}-${process.env.GITHUB_RUN_ID ?? "local"}`;
|
|
151
|
+
const files = results.flatMap(({ scenario: { id }, clip }) => {
|
|
152
|
+
if (!clip)
|
|
153
|
+
return [];
|
|
154
|
+
const file = (kind, local) => ({ id, kind, path: `${prefix}/${id}.${kind}`, local });
|
|
155
|
+
// A crash's screenshot comes without a video.
|
|
156
|
+
return [...(clip.mp4 ? [file("gif", clip.gif), file("mp4", clip.mp4)] : []), file("jpg", clip.jpg)];
|
|
157
|
+
});
|
|
158
|
+
const urls = await publishClips(repo, files);
|
|
159
|
+
for (const f of files)
|
|
160
|
+
clips.set(f.id, { ...clips.get(f.id), [f.kind]: urls.get(f.path) });
|
|
161
|
+
// In a commit of its own, after the clips: the file holds their links.
|
|
162
|
+
const local = join(outDir, RUN_FILE);
|
|
163
|
+
writeFileSync(local, JSON.stringify(runFile(input, clips)));
|
|
164
|
+
await publishClips(repo, [{ path: `${prefix}/${RUN_FILE}`, local }]);
|
|
165
|
+
runKey = prefix;
|
|
166
|
+
}
|
|
167
|
+
const repoUrl = repo && `https://github.com/${repo.owner}/${repo.name}`;
|
|
168
|
+
const body = buildReport({
|
|
169
|
+
sha, results, skipped, clips, runUrl, fixEnabled: process.env.PROOFED_FIX !== "false", fix, asked, previous, repoUrl, runKey, written,
|
|
170
|
+
});
|
|
171
|
+
writeFileSync(join(outDir, "report.md"), body);
|
|
172
|
+
writeFileSync(join(outDir, "results.json"), JSON.stringify(results, null, 2));
|
|
173
|
+
if (process.env.GITHUB_STEP_SUMMARY)
|
|
174
|
+
appendFileSync(process.env.GITHUB_STEP_SUMMARY, body);
|
|
175
|
+
const broken = results.filter(isBroken);
|
|
176
|
+
const failed = results.filter((r) => r.outcome === "failed");
|
|
177
|
+
const passed = results.filter((r) => r.outcome === "passed");
|
|
178
|
+
const counted = results.filter((r) => !nothingAsked(r));
|
|
179
|
+
if (repo && pr) {
|
|
180
|
+
// The end of a fix is news too, either way it went.
|
|
181
|
+
const comment = await putReport(repo, pr, body, requested || !!fix);
|
|
182
|
+
const names = (rs) => rs.map((r) => r.scenario.name).join(", ");
|
|
183
|
+
// Unsure runs don't block a merge, but they aren't passes either.
|
|
184
|
+
const [state, description] = failed.length > 0
|
|
185
|
+
? ["failure", `${failed.length} of ${counted.length} broke: ${names(failed)}`]
|
|
186
|
+
: broken.length > 0
|
|
187
|
+
? ["error", `Kane couldn't finish: ${names(broken)}`]
|
|
188
|
+
: passed.length < counted.length
|
|
189
|
+
? ["success", `${passed.length} passed, ${counted.length - passed.length} not checked`]
|
|
190
|
+
: ["success", `${counted.length} scenario(s) pass in Chrome`];
|
|
191
|
+
await setStatus(repo, sha, state, description, comment.html_url);
|
|
192
|
+
}
|
|
193
|
+
return broken;
|
|
194
|
+
}
|
package/dist/precheck.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Kane can't tell a page that crashed while loading from a slow one: on a blank page it waits,
|
|
2
|
+
// reloads and waits again, for minutes and dozens of credits, before it fails. So each start URL
|
|
3
|
+
// is opened once in headless Chrome first. A page that threw an uncaught exception and is still
|
|
4
|
+
// blank well after loading fails at once, without Kane. Anything less certain (blank but
|
|
5
|
+
// no exception, an exception but something on screen, a page that doesn't load) goes to Kane as
|
|
6
|
+
// before: this must never fail a healthy or a slow page.
|
|
7
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
10
|
+
import { connectCdp } from "./cdp.js";
|
|
11
|
+
import { launchChrome } from "./chrome.js";
|
|
12
|
+
import { log } from "./log.js";
|
|
13
|
+
import { BLANK_PAGE } from "./runfile.js";
|
|
14
|
+
const LOAD_TIMEOUT = 15_000;
|
|
15
|
+
// How long a loaded page gets to put something on screen.
|
|
16
|
+
const SETTLE = 3_000;
|
|
17
|
+
// A blank page that threw gets this much longer before it's called a crash: a slow app may still
|
|
18
|
+
// be about to render, and the exception may be someone else's (an analytics script).
|
|
19
|
+
const RECHECK = 10_000;
|
|
20
|
+
const POLL = 250;
|
|
21
|
+
// Any text, or an element that shows something without text.
|
|
22
|
+
const PAINTED = `(() => {
|
|
23
|
+
const body = document.body;
|
|
24
|
+
return !!body && (body.innerText.trim() !== "" || !!body.querySelector("img, svg, canvas, video, iframe, input, button"));
|
|
25
|
+
})()`;
|
|
26
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
27
|
+
// A time limit that doesn't keep the process alive once the check is over.
|
|
28
|
+
const limit = (ms) => delay(ms, undefined, { ref: false });
|
|
29
|
+
// "TypeError: Cannot read properties of null (reading '1')", without the stack.
|
|
30
|
+
const message = (d) => (d.exception?.description ?? (d.exception?.value !== undefined ? String(d.exception.value) : d.text)).split("\n")[0].trim();
|
|
31
|
+
// The URLs that crashed while loading. Screenshots go into `dir`.
|
|
32
|
+
export async function findCrashes(urls, dir) {
|
|
33
|
+
const crashes = new Map();
|
|
34
|
+
if (urls.length === 0)
|
|
35
|
+
return crashes;
|
|
36
|
+
mkdirSync(dir, { recursive: true });
|
|
37
|
+
let chrome;
|
|
38
|
+
const seconds = (from, to = Date.now()) => ((to - from) / 1000).toFixed(1);
|
|
39
|
+
const started = Date.now();
|
|
40
|
+
try {
|
|
41
|
+
chrome = await launchChrome();
|
|
42
|
+
const opened = Date.now();
|
|
43
|
+
const cdp = await connectCdp(chrome.endpoint);
|
|
44
|
+
await Promise.all(urls.map(async (url, i) => {
|
|
45
|
+
const crash = await Promise.race([crashOf(cdp, url, join(dir, `crash-${i}.jpg`)), limit(LOAD_TIMEOUT + SETTLE + RECHECK + 5_000)]).catch(() => undefined);
|
|
46
|
+
if (crash)
|
|
47
|
+
crashes.set(url, crash);
|
|
48
|
+
}));
|
|
49
|
+
cdp.close();
|
|
50
|
+
log(`Checked ${urls.length} start page(s) for a crash on load in ${seconds(started)} s (Chrome took ${seconds(started, opened)} s to start)`);
|
|
51
|
+
}
|
|
52
|
+
catch (e) {
|
|
53
|
+
// The check is only a shortcut: without it, Kane runs every scenario as it always did.
|
|
54
|
+
log(`Couldn't check the pages before Kane: ${e instanceof Error ? e.message : e}`);
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
chrome?.close();
|
|
58
|
+
}
|
|
59
|
+
return crashes;
|
|
60
|
+
}
|
|
61
|
+
async function crashOf(cdp, url, file) {
|
|
62
|
+
const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
|
|
63
|
+
const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
|
|
64
|
+
const page = (method, params = {}) => cdp.send(method, params, sessionId);
|
|
65
|
+
const errors = [];
|
|
66
|
+
let loaded = () => { };
|
|
67
|
+
const load = new Promise((resolve) => (loaded = resolve));
|
|
68
|
+
cdp.on("Runtime.exceptionThrown", ({ exceptionDetails }, from) => from === sessionId && errors.push(message(exceptionDetails)));
|
|
69
|
+
cdp.on("Page.loadEventFired", (_, from) => from === sessionId && loaded());
|
|
70
|
+
await page("Page.enable");
|
|
71
|
+
await page("Runtime.enable");
|
|
72
|
+
const { errorText } = await page("Page.navigate", { url });
|
|
73
|
+
if (errorText)
|
|
74
|
+
return undefined; // Not reachable at all: Kane reports that as it always has.
|
|
75
|
+
await Promise.race([load, limit(LOAD_TIMEOUT)]);
|
|
76
|
+
// `blank` only turns true on a definite answer; an evaluation lost to a navigation counts as unknown.
|
|
77
|
+
let blank = false;
|
|
78
|
+
let rechecking = false;
|
|
79
|
+
for (let until = Date.now() + SETTLE;; await sleep(POLL)) {
|
|
80
|
+
const painted = await page("Runtime.evaluate", { expression: PAINTED, returnByValue: true }).then(({ result }) => result.value, () => undefined);
|
|
81
|
+
if (painted === true)
|
|
82
|
+
return undefined;
|
|
83
|
+
blank = painted === false;
|
|
84
|
+
if (Date.now() < until)
|
|
85
|
+
continue;
|
|
86
|
+
if (rechecking || !blank || errors.length === 0)
|
|
87
|
+
break;
|
|
88
|
+
rechecking = true;
|
|
89
|
+
until += RECHECK;
|
|
90
|
+
}
|
|
91
|
+
const error = blank ? errors[0] : undefined;
|
|
92
|
+
if (!error)
|
|
93
|
+
return undefined;
|
|
94
|
+
// Without Kane there is no recording; this is the picture the report shows instead. A failed
|
|
95
|
+
// screenshot only costs the picture, never the verdict.
|
|
96
|
+
const screenshot = await page("Page.captureScreenshot", { format: "jpeg", quality: 80 }).then(({ data }) => (writeFileSync(file, Buffer.from(data, "base64")), file), () => undefined);
|
|
97
|
+
return { error, screenshot };
|
|
98
|
+
}
|
|
99
|
+
// A normal failed result, so the report, the run file, the dashboard and the fixer need nothing new.
|
|
100
|
+
// The verdict is ours, in the shape Kane gives one. Kane never ran, so there are no steps or credits,
|
|
101
|
+
// and the clip is only the screenshot.
|
|
102
|
+
export function crashResult(scenario, { error, screenshot }) {
|
|
103
|
+
return {
|
|
104
|
+
scenario,
|
|
105
|
+
outcome: "failed",
|
|
106
|
+
steps: [],
|
|
107
|
+
end: { type: "run_end", status: "failed", reason: BLANK_PAGE, verdict: { family: "application_issue", root_cause: error } },
|
|
108
|
+
clip: screenshot ? { jpg: screenshot } : undefined,
|
|
109
|
+
pageError: error,
|
|
110
|
+
};
|
|
111
|
+
}
|
package/dist/proofed.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `proofed` in a terminal: the PR check (src/cli.ts) for the change on this machine, for a person
|
|
3
|
+
// or a coding agent that wants to see a UI change work before calling it done.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { parse, UsageError } from "./args.js";
|
|
6
|
+
import { check } from "./check.js";
|
|
7
|
+
import { killChildren, stopChildren } from "./children.js";
|
|
8
|
+
import { doctor } from "./doctor.js";
|
|
9
|
+
import { helpText } from "./help.js";
|
|
10
|
+
import { list } from "./list.js";
|
|
11
|
+
const argv = process.argv.slice(2);
|
|
12
|
+
const io = { stdout: process.stdout, stderr: process.stderr, env: process.env, cwd: process.cwd() };
|
|
13
|
+
// Whatever ends the process, nothing it started keeps running, and the cursor comes back.
|
|
14
|
+
process.on("exit", () => {
|
|
15
|
+
killChildren();
|
|
16
|
+
if (process.stdout.isTTY)
|
|
17
|
+
process.stdout.write("\x1b[?25h");
|
|
18
|
+
});
|
|
19
|
+
async function main() {
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = parse(argv);
|
|
23
|
+
}
|
|
24
|
+
catch (e) {
|
|
25
|
+
if (!(e instanceof UsageError))
|
|
26
|
+
throw e;
|
|
27
|
+
if (argv.includes("--json")) {
|
|
28
|
+
io.stdout.write(`${JSON.stringify({ ok: false, exitCode: 3, error: { code: "usage", message: e.message, fix: "See proofed --help." } }, null, 2)}\n`);
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
io.stderr.write(`proofed: ${e.message}\n`);
|
|
32
|
+
}
|
|
33
|
+
return 3;
|
|
34
|
+
}
|
|
35
|
+
if (parsed.kind === "version") {
|
|
36
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
37
|
+
io.stdout.write(`${pkg.version}\n`);
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
if (parsed.kind === "help") {
|
|
41
|
+
io.stdout.write(`${helpText(parsed.command)}\n`);
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
const { command, flags, text } = parsed;
|
|
45
|
+
if (flags.help) {
|
|
46
|
+
io.stdout.write(`${helpText(command)}\n`);
|
|
47
|
+
return 0;
|
|
48
|
+
}
|
|
49
|
+
if (command === "check")
|
|
50
|
+
return check(flags, text, io);
|
|
51
|
+
if (command === "list")
|
|
52
|
+
return list(flags, io);
|
|
53
|
+
return doctor(flags, io);
|
|
54
|
+
}
|
|
55
|
+
// Exit 1 is "a scenario failed", so a crash must not end that way: 3, with the error where the
|
|
56
|
+
// caller reads it.
|
|
57
|
+
const code = await main().catch((e) => {
|
|
58
|
+
const message = `Proofed hit an unexpected error: ${e instanceof Error ? e.message : String(e)}`;
|
|
59
|
+
if (argv.includes("--json")) {
|
|
60
|
+
io.stdout.write(`${JSON.stringify({ ok: false, exitCode: 3, error: { code: "internal", message, fix: "Run it again with --verbose; nothing was checked." } }, null, 2)}\n`);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
io.stderr.write(`proofed: ${message}\n`);
|
|
64
|
+
}
|
|
65
|
+
return 3;
|
|
66
|
+
});
|
|
67
|
+
// A closed Chrome may still be shutting down; its profile folder is removed once it has exited.
|
|
68
|
+
await stopChildren();
|
|
69
|
+
// Exit once stdout has drained: a pipe may still hold the end of the JSON.
|
|
70
|
+
process.stdout.write("", () => process.exit(code));
|
package/dist/recorder.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { connectCdp } from "./cdp.js";
|
|
4
|
+
const PAGE = `({ doc: performance.timeOrigin, href: location.href, sx: scrollX, sy: scrollY, w: innerWidth, h: innerHeight })`;
|
|
5
|
+
const MAX_WIDTH = 1920;
|
|
6
|
+
const MAX_HEIGHT = 1080;
|
|
7
|
+
// The largest frame Proofed's server takes (MAX_FRAME in site/src/worker/live.ts).
|
|
8
|
+
const MAX_LIVE_FRAME = 400_000;
|
|
9
|
+
const BINDING = "__proofedAction";
|
|
10
|
+
// Runs in every page Kane opens. It only listens: Kane's clicks and typing are reported back
|
|
11
|
+
// through a CDP binding so the clip can draw a cursor and zoom to where things happen.
|
|
12
|
+
// It also says which page the action was on, so the live view only draws a cursor over the same
|
|
13
|
+
// page as it was then.
|
|
14
|
+
const LISTENER = `(() => {
|
|
15
|
+
const report = (kind, x, y, el) => {
|
|
16
|
+
const r = el.getBoundingClientRect();
|
|
17
|
+
const page = ${PAGE};
|
|
18
|
+
globalThis.${BINDING}?.(JSON.stringify({ kind, time: Date.now() / 1000, x, y, rect: { x: r.x, y: r.y, width: r.width, height: r.height }, page }));
|
|
19
|
+
};
|
|
20
|
+
let pointerAt = 0;
|
|
21
|
+
let typingIn = null;
|
|
22
|
+
let clicked = null;
|
|
23
|
+
addEventListener("pointerdown", (e) => {
|
|
24
|
+
if (!e.isTrusted || !(e.target instanceof Element)) return;
|
|
25
|
+
pointerAt = Date.now();
|
|
26
|
+
typingIn = null;
|
|
27
|
+
clicked = { el: e.target, x: e.clientX, y: e.clientY };
|
|
28
|
+
report("click", e.clientX, e.clientY, e.target);
|
|
29
|
+
}, true);
|
|
30
|
+
// A click dispatched from script has no pointer events before it: place it on the element.
|
|
31
|
+
addEventListener("click", (e) => {
|
|
32
|
+
if (Date.now() - pointerAt < 500 || !(e.target instanceof Element)) return;
|
|
33
|
+
const r = e.target.getBoundingClientRect();
|
|
34
|
+
clicked = { el: e.target, x: r.x + r.width / 2, y: r.y + r.height / 2 };
|
|
35
|
+
report("click", clicked.x, clicked.y, e.target);
|
|
36
|
+
}, true);
|
|
37
|
+
// Typing in the field Kane just clicked stays at the click point, still inside the field unless it
|
|
38
|
+
// scrolled away; its centre would make the cursor jump a few pixels within the same field.
|
|
39
|
+
addEventListener("input", (e) => {
|
|
40
|
+
if (!(e.target instanceof Element) || e.target === typingIn) return;
|
|
41
|
+
typingIn = e.target;
|
|
42
|
+
const r = e.target.getBoundingClientRect();
|
|
43
|
+
const at = clicked?.el === e.target && clicked.x >= r.left && clicked.x <= r.right && clicked.y >= r.top && clicked.y <= r.bottom
|
|
44
|
+
? clicked
|
|
45
|
+
: { x: r.x + r.width / 2, y: r.y + r.height / 2 };
|
|
46
|
+
report("type", at.x, at.y, e.target);
|
|
47
|
+
}, true);
|
|
48
|
+
})();`;
|
|
49
|
+
// Finds the smallest visible element that mentions most of the given words, so the end of the
|
|
50
|
+
// clip can settle on what the final check was about (a total, a confirmation message).
|
|
51
|
+
const LOCATE = (words) => `(() => {
|
|
52
|
+
const words = ${JSON.stringify(words)};
|
|
53
|
+
const vw = innerWidth, vh = innerHeight;
|
|
54
|
+
let best = null;
|
|
55
|
+
for (const el of document.body?.querySelectorAll("*") ?? []) {
|
|
56
|
+
const r = el.getBoundingClientRect();
|
|
57
|
+
if (r.width < 4 || r.height < 4 || r.bottom <= 0 || r.top >= vh || r.right <= 0 || r.left >= vw) continue;
|
|
58
|
+
const area = r.width * r.height;
|
|
59
|
+
if (area > vw * vh * 0.4) continue;
|
|
60
|
+
const text = (el.innerText ?? "").toLowerCase().replace(/[‘’]/g, "'");
|
|
61
|
+
const hits = words.filter((w) => text.includes(w)).length;
|
|
62
|
+
if (hits && (!best || hits > best.hits || (hits === best.hits && area < best.area))) {
|
|
63
|
+
best = { hits, area, el, rect: { x: r.x, y: r.y, width: r.width, height: r.height } };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (!best || best.hits < Math.min(2, words.length)) return null;
|
|
67
|
+
// Tighten to the text itself: a block is often page-wide while its words sit on the left.
|
|
68
|
+
let box = null;
|
|
69
|
+
const walker = document.createTreeWalker(best.el, NodeFilter.SHOW_TEXT);
|
|
70
|
+
const range = document.createRange();
|
|
71
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
72
|
+
if (!node.textContent.trim()) continue;
|
|
73
|
+
range.selectNodeContents(node);
|
|
74
|
+
const r = range.getBoundingClientRect();
|
|
75
|
+
if (!r.width || !r.height) continue;
|
|
76
|
+
box = box
|
|
77
|
+
? { left: Math.min(box.left, r.left), top: Math.min(box.top, r.top), right: Math.max(box.right, r.right), bottom: Math.max(box.bottom, r.bottom) }
|
|
78
|
+
: { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
|
|
79
|
+
}
|
|
80
|
+
return JSON.stringify(box ? { x: box.left, y: box.top, width: box.right - box.left, height: box.bottom - box.top } : best.rect);
|
|
81
|
+
})()`;
|
|
82
|
+
// A cursor drawn where an action was is only right on the same page, scrolled and sized the same:
|
|
83
|
+
// another document or address (a single-page app's route), a scroll or another layout and it would
|
|
84
|
+
// point at something else.
|
|
85
|
+
export const samePage = (a, b) => a.doc === b.doc && a.href === b.href && Math.abs(a.sx - b.sx) < 2 && Math.abs(a.sy - b.sy) < 2 && a.w === b.w && a.h === b.h;
|
|
86
|
+
// Kane doesn't record video, so we attach to the same Chrome over CDP and keep every
|
|
87
|
+
// screencast frame with its timestamp. Frames are only sent when the page repaints,
|
|
88
|
+
// which is why the clip later replays them with their real durations.
|
|
89
|
+
export async function startRecorder(endpoint, outDir) {
|
|
90
|
+
mkdirSync(outDir, { recursive: true });
|
|
91
|
+
const cdp = await connectCdp(endpoint);
|
|
92
|
+
const frames = [];
|
|
93
|
+
const actions = [];
|
|
94
|
+
let lastSession;
|
|
95
|
+
let lastAction;
|
|
96
|
+
// The latest screencast frame of each page. Chrome sends one on each repaint, so it shows the page
|
|
97
|
+
// as it still is until the next comes in.
|
|
98
|
+
const latest = new Map();
|
|
99
|
+
const attached = new Set();
|
|
100
|
+
cdp.on("Target.targetCreated", ({ targetInfo }) => {
|
|
101
|
+
if (targetInfo.type !== "page" || attached.has(targetInfo.targetId))
|
|
102
|
+
return;
|
|
103
|
+
attached.add(targetInfo.targetId);
|
|
104
|
+
void cdp.send("Target.attachToTarget", { targetId: targetInfo.targetId, flatten: true }).catch(() => { });
|
|
105
|
+
});
|
|
106
|
+
const prepare = async (sessionId) => {
|
|
107
|
+
await cdp.send("Page.enable", {}, sessionId);
|
|
108
|
+
await cdp.send("Runtime.enable", {}, sessionId);
|
|
109
|
+
await cdp.send("Runtime.addBinding", { name: BINDING }, sessionId);
|
|
110
|
+
await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: LISTENER }, sessionId);
|
|
111
|
+
await cdp.send("Page.startScreencast", { format: "jpeg", quality: 80, maxWidth: MAX_WIDTH, maxHeight: MAX_HEIGHT }, sessionId);
|
|
112
|
+
};
|
|
113
|
+
let firstPage = () => { };
|
|
114
|
+
const ready = new Promise((resolve) => (firstPage = resolve));
|
|
115
|
+
cdp.on("Target.attachedToTarget", ({ sessionId, targetInfo }) => {
|
|
116
|
+
if (targetInfo.type !== "page")
|
|
117
|
+
return;
|
|
118
|
+
prepare(sessionId).then(() => firstPage(targetInfo), () => { });
|
|
119
|
+
});
|
|
120
|
+
cdp.on("Page.screencastFrame", ({ data, metadata, sessionId: ack }, sessionId) => {
|
|
121
|
+
const file = join(outDir, `${String(frames.length).padStart(5, "0")}.jpg`);
|
|
122
|
+
const jpeg = Buffer.from(data, "base64");
|
|
123
|
+
writeFileSync(file, jpeg);
|
|
124
|
+
const scale = Math.min(1, MAX_WIDTH / metadata.deviceWidth, MAX_HEIGHT / metadata.deviceHeight);
|
|
125
|
+
frames.push({
|
|
126
|
+
file,
|
|
127
|
+
time: metadata.timestamp,
|
|
128
|
+
scale,
|
|
129
|
+
width: Math.round(metadata.deviceWidth * scale),
|
|
130
|
+
height: Math.round(metadata.deviceHeight * scale),
|
|
131
|
+
bytes: jpeg.length,
|
|
132
|
+
});
|
|
133
|
+
lastSession = sessionId;
|
|
134
|
+
if (sessionId)
|
|
135
|
+
latest.set(sessionId, { jpeg, meta: metadata });
|
|
136
|
+
void cdp.send("Page.screencastFrameAck", { sessionId: ack }, sessionId).catch(() => { });
|
|
137
|
+
});
|
|
138
|
+
cdp.on("Runtime.bindingCalled", ({ name, payload }, sessionId) => {
|
|
139
|
+
if (name !== BINDING)
|
|
140
|
+
return;
|
|
141
|
+
const { page, ...action } = JSON.parse(payload);
|
|
142
|
+
actions.push(action);
|
|
143
|
+
lastAction = { ...action, page, session: sessionId };
|
|
144
|
+
recorder.onAction?.(before(lastAction));
|
|
145
|
+
});
|
|
146
|
+
// The page's last screencast frame, picked as the action is reported: it shows the very page Kane
|
|
147
|
+
// clicked, even when the click then navigates, and frames of the next page only come in after it.
|
|
148
|
+
// Only one of the same page, at the same viewport size and scroll, gets the cursor.
|
|
149
|
+
const before = (action) => {
|
|
150
|
+
const frame = action.session ? latest.get(action.session) : undefined;
|
|
151
|
+
if (!frame || frame.jpeg.length > MAX_LIVE_FRAME)
|
|
152
|
+
return undefined;
|
|
153
|
+
const { meta } = frame;
|
|
154
|
+
const { page } = action;
|
|
155
|
+
if (Math.round(meta.deviceWidth) !== page.w || Math.round(meta.deviceHeight) !== page.h)
|
|
156
|
+
return undefined;
|
|
157
|
+
if (Math.abs(meta.scrollOffsetX - page.sx) >= 2 || Math.abs(meta.scrollOffsetY - page.sy) >= 2)
|
|
158
|
+
return undefined;
|
|
159
|
+
return { jpeg: frame.jpeg, at: Date.now(), cursor: { x: action.x / page.w, y: action.y / page.h } };
|
|
160
|
+
};
|
|
161
|
+
await cdp.send("Target.setDiscoverTargets", { discover: true });
|
|
162
|
+
// Don't let Kane navigate before the listener is installed on the starting tab.
|
|
163
|
+
await Promise.race([ready, new Promise((r) => setTimeout(r, 5000))]);
|
|
164
|
+
const recorder = {
|
|
165
|
+
frames,
|
|
166
|
+
actions,
|
|
167
|
+
// Called on each of Kane's clicks and the first keystroke in a field, with the frame from just
|
|
168
|
+
// before it and the cursor on it, when there is a usable one.
|
|
169
|
+
onAction: undefined,
|
|
170
|
+
async locate(words) {
|
|
171
|
+
if (!lastSession || words.length === 0)
|
|
172
|
+
return undefined;
|
|
173
|
+
const { result } = await cdp
|
|
174
|
+
.send("Runtime.evaluate", { expression: LOCATE(words), returnByValue: true }, lastSession)
|
|
175
|
+
.catch(() => ({ result: {} }));
|
|
176
|
+
return result.value ? JSON.parse(result.value) : undefined;
|
|
177
|
+
},
|
|
178
|
+
// A still of what the page shows now, for the dashboard while the run is going (live.ts), with
|
|
179
|
+
// the last action's cursor while the page is still the one it was on: a screenshot of its own, so
|
|
180
|
+
// the page check after it holds for the picture. No clip or scale: Chrome shrinks a screenshot by
|
|
181
|
+
// emulating a smaller viewport for it, and when Kane takes a screenshot at the same moment the
|
|
182
|
+
// page is left at that size, in its narrow layout.
|
|
183
|
+
async snapshot() {
|
|
184
|
+
const session = lastSession;
|
|
185
|
+
if (!session)
|
|
186
|
+
return undefined;
|
|
187
|
+
const action = lastAction;
|
|
188
|
+
const at = Date.now();
|
|
189
|
+
try {
|
|
190
|
+
const { data } = await cdp.send("Page.captureScreenshot", { format: "jpeg", quality: 60 }, session);
|
|
191
|
+
const jpeg = Buffer.from(data, "base64");
|
|
192
|
+
if (!action || action.session !== session)
|
|
193
|
+
return { jpeg, at };
|
|
194
|
+
// Asked after the screenshot: a page that is still the one of the action was showing during it.
|
|
195
|
+
const { result } = await cdp.send("Runtime.evaluate", { expression: PAGE, returnByValue: true }, session);
|
|
196
|
+
const now = result.value;
|
|
197
|
+
return { jpeg, at, ...(now && samePage(action.page, now) && { cursor: { x: action.x / now.w, y: action.y / now.h } }) };
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
return undefined; // The page is navigating or closed; the next one will do.
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
stop() {
|
|
204
|
+
cdp.close();
|
|
205
|
+
return { frames, actions };
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
return recorder;
|
|
209
|
+
}
|