proofed-cli 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/LICENSE +21 -0
- package/README.md +280 -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 +338 -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 +122 -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 +425 -0
- package/dist/report.js +328 -0
- package/dist/requests.js +58 -0
- package/dist/result.js +135 -0
- package/dist/run.js +147 -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/run.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { stopping } from "./children.js";
|
|
4
|
+
import { launchChrome } from "./chrome.js";
|
|
5
|
+
import { makeClip } from "./clip.js";
|
|
6
|
+
import { live } from "./live.js";
|
|
7
|
+
import { log as logLine } from "./log.js";
|
|
8
|
+
import { runKane } from "./kane.js";
|
|
9
|
+
import { NOTHING_CHECKED } from "./runfile.js";
|
|
10
|
+
import { startRecorder } from "./recorder.js";
|
|
11
|
+
// Failures of the browser plumbing rather than of the app: the run is retried, never reported as a bug.
|
|
12
|
+
const INFRA = /Screenshot failed|TimeoutError|TargetClosedError|has been closed|ECONNREFUSED|ECONNRESET|socket hang up|Project and folder must be configured/i;
|
|
13
|
+
// Words of what the run checked last: the quoted expectation of a failed check, or the values
|
|
14
|
+
// Kane read off the page when it passed. The clip ends zoomed on the element that holds them.
|
|
15
|
+
const STOP = new Set(["that", "this", "with", "from", "have", "after", "then", "should", "shows", "page", "into", "when", "each", "there", "them", "than", "what", "which", "only", "also", "visible", "displayed"]);
|
|
16
|
+
export function focusWords(end) {
|
|
17
|
+
const text = end.status === "passed"
|
|
18
|
+
? Object.values(end.final_state ?? {})
|
|
19
|
+
.filter((v) => typeof v === "string" && !v.startsWith("http"))
|
|
20
|
+
.join(" ")
|
|
21
|
+
: (/["“«]([^"”»]+)["”»]/.exec(end.reason ?? "")?.[1] ?? "");
|
|
22
|
+
const words = (text.toLowerCase().replace(/[‘’]/g, "'").match(/[\p{L}\p{Sc}\d][\p{L}\p{N}\p{Sc}.,%'-]*/gu) ?? [])
|
|
23
|
+
.map((w) => w.replace(/[.,]+$/, ""))
|
|
24
|
+
.filter((w) => (/\d/.test(w) ? w.length >= 2 : w.length >= 4) && !STOP.has(w));
|
|
25
|
+
return [...new Set(words)];
|
|
26
|
+
}
|
|
27
|
+
export { NOTHING_CHECKED };
|
|
28
|
+
// Each step's remark starts with its kind ("navigate: …", "wait: …", "analyze: …", "assert: …").
|
|
29
|
+
// Only an assert compares the page with what the scenario expects.
|
|
30
|
+
const checked = (steps) => steps.some((s) => s.status === "done" && /^assert:/i.test(s.remark));
|
|
31
|
+
// Kane read the page and the scenario's own check came out false. When the app is wrong all over
|
|
32
|
+
// (a changed threshold shown in its banner too), Kane sides with the app and blames the test; the
|
|
33
|
+
// scenario is what the app was meant to do, so that is a failure.
|
|
34
|
+
const refuted = (steps) => steps.some((s) => s.status === "failed" && /^assert:/i.test(s.remark));
|
|
35
|
+
export function outcomeOf(end, steps) {
|
|
36
|
+
if (!end || INFRA.test(end.reason ?? ""))
|
|
37
|
+
return "error";
|
|
38
|
+
// A vague objective lets Kane open the page, wait, and call that a pass.
|
|
39
|
+
if (end.status === "passed")
|
|
40
|
+
return checked(steps) ? "passed" : "unsure";
|
|
41
|
+
return end.verdict?.family === "automation_bug" && !refuted(steps) ? "unsure" : "failed";
|
|
42
|
+
}
|
|
43
|
+
// An unsure run where Kane said "passed": nothing was checked, as opposed to Kane doubting the test.
|
|
44
|
+
export const unchecked = (r) => r.outcome === "unsure" && r.end?.status === "passed";
|
|
45
|
+
export const scenarioDoubted = (r) => r.outcome === "failed" && r.end?.verdict?.family === "automation_bug";
|
|
46
|
+
// Kane is good at reaching a goal, so on its own it routes around a broken button (a key press, another
|
|
47
|
+
// link) and passes. A user who clicks the button and gets the wrong screen has found a bug.
|
|
48
|
+
const NO_WORKAROUNDS = "Do each step once, the way it is described. If a click or a key press does something other than what " +
|
|
49
|
+
"the step expects, the check fails: don't retry it, and don't reach the goal another way (other " +
|
|
50
|
+
"buttons, links, keyboard shortcuts, typing the URL). Waiting for a slow page to load is fine.";
|
|
51
|
+
export function kaneObjective(objective) {
|
|
52
|
+
return `${objective}\n\n${NO_WORKAROUNDS}`;
|
|
53
|
+
}
|
|
54
|
+
export async function runScenario(scenario, o) {
|
|
55
|
+
let result = await runOnce(scenario, o);
|
|
56
|
+
for (let i = 2; i <= (o.attempts ?? 2) && result.outcome === "error" && !stopping(); i++) {
|
|
57
|
+
logLine(`[${scenario.id}] ${result.error ?? "infra error"}; retrying`);
|
|
58
|
+
o.onEvent?.({ type: "retry", id: scenario.id, error: result.error ?? "infra error", credits: result.end?.credits_consumed });
|
|
59
|
+
result = await runOnce(scenario, o);
|
|
60
|
+
}
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
async function runOnce(scenario, o) {
|
|
64
|
+
const log = (line) => logLine(`[${scenario.id}] ${line}`);
|
|
65
|
+
const dir = join(o.outDir, scenario.id);
|
|
66
|
+
rmSync(dir, { recursive: true, force: true });
|
|
67
|
+
mkdirSync(dir, { recursive: true });
|
|
68
|
+
let chrome;
|
|
69
|
+
try {
|
|
70
|
+
chrome = await launchChrome({ headless: o.headless ?? true });
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
// Counts as a browser hiccup: retried, and reported as "couldn't finish", never as a bug.
|
|
74
|
+
return { scenario, outcome: "error", steps: [], end: undefined, clip: undefined, error: String(e) };
|
|
75
|
+
}
|
|
76
|
+
let stills;
|
|
77
|
+
try {
|
|
78
|
+
const recorder = await startRecorder(chrome.endpoint, join(dir, "frames"));
|
|
79
|
+
live.scenario(scenario.id, { status: "running", steps: [], startedAt: Date.now() });
|
|
80
|
+
// A still for each click or typing with the cursor on it: the frame from just before it, or a
|
|
81
|
+
// new screenshot when there is none to use. Between actions, one every couple of seconds.
|
|
82
|
+
const still = (action) => {
|
|
83
|
+
if (live.on())
|
|
84
|
+
void recorder.snapshot().then((s) => s && live.frame(scenario.id, s, action));
|
|
85
|
+
};
|
|
86
|
+
recorder.onAction = (before) => {
|
|
87
|
+
if (before)
|
|
88
|
+
live.frame(scenario.id, before, true);
|
|
89
|
+
else
|
|
90
|
+
still(true);
|
|
91
|
+
};
|
|
92
|
+
stills = setInterval(() => still(false), 2000);
|
|
93
|
+
let focus = Promise.resolve(undefined);
|
|
94
|
+
const kane = await runKane({
|
|
95
|
+
objective: kaneObjective(scenario.objective),
|
|
96
|
+
url: new URL(scenario.url, o.baseUrl).href,
|
|
97
|
+
cdpEndpoint: chrome.endpoint,
|
|
98
|
+
username: o.username,
|
|
99
|
+
accessKey: o.accessKey,
|
|
100
|
+
onStep: (s) => {
|
|
101
|
+
live.step(scenario.id, s);
|
|
102
|
+
o.onEvent?.({ type: "step", id: scenario.id, step: s });
|
|
103
|
+
if (s.status !== "running" && s.remark)
|
|
104
|
+
log(`${s.status === "failed" ? "✗" : "·"} ${s.remark}`);
|
|
105
|
+
},
|
|
106
|
+
onEnd: (end) => (focus = recorder.locate(focusWords(end))),
|
|
107
|
+
});
|
|
108
|
+
clearInterval(stills);
|
|
109
|
+
const focusRect = await focus;
|
|
110
|
+
// Drop the blank about:blank frames from before Kane's first navigation.
|
|
111
|
+
const start = Date.parse(kane.steps[0]?.ts ?? "") / 1000 || 0;
|
|
112
|
+
const recorded = recorder.stop();
|
|
113
|
+
const frames = recorded.frames.filter((f) => f.time >= start);
|
|
114
|
+
const outcome = outcomeOf(kane.end, kane.steps);
|
|
115
|
+
// Kane left without a verdict: all it said goes to the log, where the cause can be read later.
|
|
116
|
+
if (!kane.end)
|
|
117
|
+
log(`Kane exited with code ${kane.exitCode} and no verdict${kane.timedOut ? " (cut off by Proofed's time limit)" : ""}. Its stderr:\n${kane.stderr.trim() || "(empty)"}`);
|
|
118
|
+
// Kane's reason for such a pass is "Objective completed"; the report, the run file and the fixer show ours.
|
|
119
|
+
const end = kane.end && outcome === "unsure" && kane.end.status === "passed" ? { ...kane.end, reason: NOTHING_CHECKED } : kane.end;
|
|
120
|
+
log(`→ ${outcome}${end?.reason ? `: ${end.reason}` : ""} (${frames.length} frames)`);
|
|
121
|
+
const error = kane.timedOut
|
|
122
|
+
? "Kane stopped responding and the run was cut off"
|
|
123
|
+
: (kane.end?.reason ?? kane.stderr.trim().split("\n").slice(-5).join("\n"));
|
|
124
|
+
const film = { frames, actions: recorded.actions, focus: focusRect };
|
|
125
|
+
writeFileSync(join(dir, "film.json"), JSON.stringify(film));
|
|
126
|
+
// A step starts when Kane announces it (the "running" event), not when it reports it done.
|
|
127
|
+
const announced = new Map(kane.steps.filter((s) => s.status === "running").map((s) => [s.step, s.ts]));
|
|
128
|
+
const marks = kane.steps.map((s) => Date.parse(announced.get(s.step) ?? s.ts) / 1000);
|
|
129
|
+
const made = await makeClip({ ...film, marks, endpoint: chrome.endpoint }, join(dir, "clip")).catch((e) => {
|
|
130
|
+
log(`clip failed: ${String(e)}`);
|
|
131
|
+
return undefined;
|
|
132
|
+
});
|
|
133
|
+
const clip = made && { mp4: made.mp4, gif: made.gif, jpg: made.jpg };
|
|
134
|
+
return {
|
|
135
|
+
scenario,
|
|
136
|
+
outcome,
|
|
137
|
+
steps: kane.steps.map((s, i) => ({ ...s, at: made?.marks[i] })),
|
|
138
|
+
end,
|
|
139
|
+
clip,
|
|
140
|
+
...(outcome === "error" && { error }),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
clearInterval(stills);
|
|
145
|
+
chrome.close();
|
|
146
|
+
}
|
|
147
|
+
}
|
package/dist/runfile.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The reason of a scenario Kane called passed without asserting anything; the dashboard words such a
|
|
2
|
+
// scenario as "not checked" by it.
|
|
3
|
+
export const NOTHING_CHECKED = "Kane finished without checking anything on the page.";
|
|
4
|
+
// The reason of a scenario whose start page crashed on load, so Kane never ran (src/precheck.ts).
|
|
5
|
+
export const BLANK_PAGE = "The page is blank: it crashed while loading, before anything could be checked.";
|
|
6
|
+
export const RUN_FILE = "run.json";
|
|
7
|
+
export const runMarker = (key) => `<!-- proofed:run ${key} -->`;
|
|
8
|
+
export const readRunKey = (body) => /<!-- proofed:run (pr-\d+\/[\w.-]+) -->/.exec(body)?.[1];
|
|
9
|
+
// A refuted check stays a failure even when Kane blames the scenario. Consumers share the next step.
|
|
10
|
+
export const FAILED_CHECK_REASON = "The scenario's check did not hold on the page. Kane believes the scenario is out of date.";
|
|
11
|
+
export const FAILED_CHECK_ACTION = "If the change in the app was intended, update the scenario; otherwise fix the app.";
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, join, matchesGlob } from "node:path";
|
|
4
|
+
// A scenario is a Markdown file: a small frontmatter block, then the plain-English objective Kane runs.
|
|
5
|
+
// ---
|
|
6
|
+
// name: Promo code total
|
|
7
|
+
// paths: [src/pricing.ts, src/pages/**]
|
|
8
|
+
// url: /
|
|
9
|
+
// ---
|
|
10
|
+
// Add two bags of Guji, apply welcome10, check the total is €26.10.
|
|
11
|
+
export function parseScenario(file, text) {
|
|
12
|
+
const match = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text.replace(/\r\n/g, "\n"));
|
|
13
|
+
if (!match)
|
|
14
|
+
throw new Error(`${file}: missing frontmatter`);
|
|
15
|
+
const [, head = "", body = ""] = match;
|
|
16
|
+
const meta = new Map();
|
|
17
|
+
for (const line of head.split("\n")) {
|
|
18
|
+
const kv = /^(\w+):\s*(.*)$/.exec(line.trim());
|
|
19
|
+
if (kv)
|
|
20
|
+
meta.set(kv[1], kv[2].trim());
|
|
21
|
+
}
|
|
22
|
+
const list = (raw = "") => raw
|
|
23
|
+
.replace(/^\[|\]$/g, "")
|
|
24
|
+
.split(",")
|
|
25
|
+
.map((s) => s.trim().replace(/^["']|["']$/g, ""))
|
|
26
|
+
.filter(Boolean);
|
|
27
|
+
const id = basename(file, ".md");
|
|
28
|
+
const objective = body.trim();
|
|
29
|
+
if (!objective)
|
|
30
|
+
throw new Error(`${file}: empty objective`);
|
|
31
|
+
return {
|
|
32
|
+
id,
|
|
33
|
+
file,
|
|
34
|
+
name: meta.get("name") ?? id,
|
|
35
|
+
paths: list(meta.get("paths")),
|
|
36
|
+
url: meta.get("url") ?? "/",
|
|
37
|
+
objective,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export function loadScenarios(dir) {
|
|
41
|
+
return readdirSync(dir)
|
|
42
|
+
.filter((f) => f.endsWith(".md"))
|
|
43
|
+
.sort()
|
|
44
|
+
.map((f) => parseScenario(join(dir, f), readFileSync(join(dir, f), "utf8")));
|
|
45
|
+
}
|
|
46
|
+
// Every file that parses, and what's wrong with each one that doesn't: `proofed list` and
|
|
47
|
+
// `proofed doctor` show a broken file next to the good ones instead of stopping at it.
|
|
48
|
+
export function readScenarios(dir) {
|
|
49
|
+
const scenarios = [];
|
|
50
|
+
const errors = [];
|
|
51
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory())
|
|
52
|
+
return { missing: true, scenarios, errors };
|
|
53
|
+
for (const f of readdirSync(dir).filter((f) => f.endsWith(".md")).sort()) {
|
|
54
|
+
const file = join(dir, f);
|
|
55
|
+
try {
|
|
56
|
+
scenarios.push(parseScenario(file, readFileSync(file, "utf8")));
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
errors.push({ file, message: (e instanceof Error ? e.message : String(e)).replace(`${file}: `, "") });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { missing: false, scenarios, errors };
|
|
63
|
+
}
|
|
64
|
+
// A PR opened before Proofed was added has no scenarios on its branch; they're read from the base
|
|
65
|
+
// branch instead (`rev`, e.g. origin/main).
|
|
66
|
+
export function loadScenariosOr(dir, rev) {
|
|
67
|
+
if (existsSync(dir))
|
|
68
|
+
return loadScenarios(dir);
|
|
69
|
+
if (!rev)
|
|
70
|
+
return [];
|
|
71
|
+
const git = (...args) => execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
72
|
+
try {
|
|
73
|
+
return git("ls-tree", "--name-only", rev, `${dir.replace(/\/$/, "")}/`)
|
|
74
|
+
.split("\n")
|
|
75
|
+
.filter((f) => f.endsWith(".md"))
|
|
76
|
+
.sort()
|
|
77
|
+
.map((f) => parseScenario(f, git("show", `${rev}:${f}`)));
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// A scenario runs when the diff touches one of its paths, or the scenario file itself.
|
|
84
|
+
// No `paths` means "always run".
|
|
85
|
+
export function affectedBy(scenarios, changed) {
|
|
86
|
+
return scenarios.filter((s) => s.paths.length === 0 ||
|
|
87
|
+
changed.includes(s.file) ||
|
|
88
|
+
changed.some((file) => s.paths.some((glob) => matchesGlob(file, glob))));
|
|
89
|
+
}
|
package/dist/serve.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The app under test on this machine: used as it is when its URL already answers, otherwise built
|
|
2
|
+
// and served for the check, then stopped. The commands run in a process group of their own, so
|
|
3
|
+
// stopping the server also stops what it started (pnpm → vite), on Ctrl-C too.
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { closeSync, openSync, readFileSync, writeSync } from "node:fs";
|
|
6
|
+
import { adopt } from "./children.js";
|
|
7
|
+
import { SetupError } from "./setuperror.js";
|
|
8
|
+
// Any HTTP answer below 500 means a server is there; a proxy in front of nothing gives 502.
|
|
9
|
+
export async function answers(url, timeout = 2000) {
|
|
10
|
+
try {
|
|
11
|
+
const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(timeout) });
|
|
12
|
+
await res.body?.cancel();
|
|
13
|
+
return res.status < 500;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function tail(file, lines = 20) {
|
|
20
|
+
try {
|
|
21
|
+
return readFileSync(file, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return "";
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function start(command, cwd, logFile) {
|
|
28
|
+
const fd = openSync(logFile, "a");
|
|
29
|
+
writeSync(fd, `$ ${command}\n`);
|
|
30
|
+
const proc = spawn(command, { cwd, shell: true, detached: true, stdio: ["ignore", fd, fd] });
|
|
31
|
+
closeSync(fd);
|
|
32
|
+
const exited = new Promise((resolve) => {
|
|
33
|
+
proc.once("exit", (code, signal) => resolve(code ?? (signal ? 128 : null)));
|
|
34
|
+
proc.once("error", () => resolve(127));
|
|
35
|
+
});
|
|
36
|
+
const kill = (signal) => {
|
|
37
|
+
try {
|
|
38
|
+
if (proc.pid)
|
|
39
|
+
process.kill(-proc.pid, signal);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// Already gone.
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const release = adopt({ kill, exited });
|
|
46
|
+
void exited.then(release);
|
|
47
|
+
return { proc, exited, kill, release };
|
|
48
|
+
}
|
|
49
|
+
export async function startApp(o) {
|
|
50
|
+
if (o.build) {
|
|
51
|
+
o.onPhase?.(`Building the app: ${o.build}`);
|
|
52
|
+
const build = start(o.build, o.cwd, o.logFile);
|
|
53
|
+
const code = await build.exited;
|
|
54
|
+
if (code !== 0) {
|
|
55
|
+
throw new SetupError("build_failed", `The build command exited with code ${code}: ${o.build}\n${tail(o.logFile)}`, `Fix the build, or pass --build "<command>". Full output: ${o.logFile}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
o.onPhase?.(`Starting the app: ${o.serve}`);
|
|
59
|
+
const server = start(o.serve, o.cwd, o.logFile);
|
|
60
|
+
let exitCode;
|
|
61
|
+
void server.exited.then((code) => (exitCode = code));
|
|
62
|
+
const stop = async () => {
|
|
63
|
+
server.kill("SIGTERM");
|
|
64
|
+
await Promise.race([server.exited, new Promise((r) => setTimeout(r, 3000))]);
|
|
65
|
+
// A child can stay behind its exited leader; the group goes as a whole.
|
|
66
|
+
server.kill("SIGKILL");
|
|
67
|
+
server.release();
|
|
68
|
+
};
|
|
69
|
+
const deadline = Date.now() + o.timeoutSeconds * 1000;
|
|
70
|
+
while (!(await answers(o.url, 1000))) {
|
|
71
|
+
if (exitCode !== undefined) {
|
|
72
|
+
await stop();
|
|
73
|
+
throw new SetupError("serve_failed", `The serve command exited with code ${exitCode} before ${o.url} answered: ${o.serve}\n${tail(o.logFile)}`, `Fix the serve command, or pass --serve "<command>". Full output: ${o.logFile}`);
|
|
74
|
+
}
|
|
75
|
+
if (Date.now() > deadline) {
|
|
76
|
+
await stop();
|
|
77
|
+
throw new SetupError("app_not_reachable", `${o.url} didn't answer within ${o.timeoutSeconds} s of: ${o.serve}\n${tail(o.logFile)}`, `Check that the serve command listens on ${o.url}, or allow longer with --serve-timeout 120. Full output: ${o.logFile}`);
|
|
78
|
+
}
|
|
79
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
80
|
+
}
|
|
81
|
+
return { pid: server.proc.pid, stop };
|
|
82
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Proofed's server, as the action talks to it: the job proves which repository it runs in with the
|
|
2
|
+
// OIDC token GitHub gives a job that has `id-token: write` (site/src/worker/actions.ts checks it).
|
|
3
|
+
// Set when the workflow names a Proofed server and may ask GitHub for an OIDC token.
|
|
4
|
+
export const serverUrl = () => {
|
|
5
|
+
const { ACTIONS_ID_TOKEN_REQUEST_URL: url, ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer, PROOFED_SERVER: server } = process.env;
|
|
6
|
+
return url && bearer && server ? server : undefined;
|
|
7
|
+
};
|
|
8
|
+
// GitHub's tokens last five minutes; one is reused for four.
|
|
9
|
+
const TOKEN_LASTS = 4 * 60_000;
|
|
10
|
+
let token;
|
|
11
|
+
export async function oidcToken() {
|
|
12
|
+
if (token && Date.now() - token.at < TOKEN_LASTS)
|
|
13
|
+
return token.value;
|
|
14
|
+
const { ACTIONS_ID_TOKEN_REQUEST_URL: url = "", ACTIONS_ID_TOKEN_REQUEST_TOKEN: bearer } = process.env;
|
|
15
|
+
const request = new URL(url);
|
|
16
|
+
request.searchParams.set("audience", "proofed");
|
|
17
|
+
const oidc = await fetch(request, { headers: { authorization: `bearer ${bearer}` } });
|
|
18
|
+
const { value } = oidc.ok ? (await oidc.json()) : {};
|
|
19
|
+
if (!value)
|
|
20
|
+
throw new Error(`GitHub gave no OIDC token (${oidc.status})`);
|
|
21
|
+
console.log(`::add-mask::${value}`);
|
|
22
|
+
token = { value, at: Date.now() };
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// Proofed could not run: a missing tool, an app that doesn't answer, a scenario that doesn't parse.
|
|
2
|
+
// `code` is stable, for scripts and agents; `fix` is the exact command or step that fixes it.
|
|
3
|
+
export class SetupError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
fix;
|
|
6
|
+
constructor(code, message, fix) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.fix = fix;
|
|
10
|
+
}
|
|
11
|
+
}
|
package/dist/target.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Where the app under test is, for `proofed check` and `proofed doctor`: its URL, and the commands
|
|
2
|
+
// that build and serve it when it isn't running. Each comes from the first place that has it:
|
|
3
|
+
// a flag, the environment, .proofed/config.json, then the Proofed step of the repo's workflow.
|
|
4
|
+
// So in a repo that already runs Proofed on its pull requests, `proofed check` needs no flags.
|
|
5
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { SetupError } from "./setuperror.js";
|
|
8
|
+
const KEYS = ["url", "serve", "build"];
|
|
9
|
+
export const CONFIG_FILE = ".proofed/config.json";
|
|
10
|
+
// "localhost:5173" parses as a URL with the scheme "localhost:", so parsing alone isn't the test.
|
|
11
|
+
export function isHttpUrl(value) {
|
|
12
|
+
try {
|
|
13
|
+
return /^https?:$/.test(new URL(value).protocol);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function readConfig(cwd) {
|
|
20
|
+
const file = join(cwd, CONFIG_FILE);
|
|
21
|
+
if (!existsSync(file))
|
|
22
|
+
return {};
|
|
23
|
+
let data;
|
|
24
|
+
try {
|
|
25
|
+
data = JSON.parse(readFileSync(file, "utf8"));
|
|
26
|
+
}
|
|
27
|
+
catch (e) {
|
|
28
|
+
throw new SetupError("config_invalid", `${CONFIG_FILE} is not valid JSON: ${e instanceof Error ? e.message : e}`, `Fix ${CONFIG_FILE}; it holds { "url", "serve", "build" }.`);
|
|
29
|
+
}
|
|
30
|
+
if (typeof data !== "object" || data === null)
|
|
31
|
+
return {};
|
|
32
|
+
const out = {};
|
|
33
|
+
for (const key of KEYS) {
|
|
34
|
+
const v = data[key];
|
|
35
|
+
if (typeof v === "string" && v.trim())
|
|
36
|
+
out[key] = v.trim();
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
const unquote = (v) => {
|
|
41
|
+
const q = /^(["'])(.*)\1$/.exec(v);
|
|
42
|
+
return q ? q[2].replace(/''/g, "'") : v;
|
|
43
|
+
};
|
|
44
|
+
// "url: http://localhost:4173 # the preview" without its comment; a # inside quotes stays.
|
|
45
|
+
const scalar = (raw) => {
|
|
46
|
+
const v = raw.trim();
|
|
47
|
+
if (/^["']/.test(v))
|
|
48
|
+
return unquote(v.replace(/^((["']).*?\2)\s*(#.*)?$/, "$1"));
|
|
49
|
+
return v.replace(/\s+#.*$/, "");
|
|
50
|
+
};
|
|
51
|
+
const indent = (line) => line.length - line.trimStart().length;
|
|
52
|
+
const blank = (line) => line.trim() === "" || line.trim().startsWith("#");
|
|
53
|
+
// The `with:` inputs of the first step that uses the Proofed action (t1dem/proofed@…, not /fix).
|
|
54
|
+
// A line reader, not YAML: it knows the shape of a step and nothing more. Block scalars (|, >)
|
|
55
|
+
// and expressions (${{ … }}) are skipped, since they can't be run outside Actions.
|
|
56
|
+
export function workflowInputs(text) {
|
|
57
|
+
const lines = text.split(/\r?\n/);
|
|
58
|
+
const uses = lines.findIndex((l) => /^\s*(-\s+)?uses:\s*["']?t1dem\/proofed@/.test(l));
|
|
59
|
+
if (uses === -1)
|
|
60
|
+
return undefined;
|
|
61
|
+
const usesLine = lines[uses];
|
|
62
|
+
const keyIndent = usesLine.indexOf("uses:");
|
|
63
|
+
// The step starts at its dash: on the uses line, or on a line above it.
|
|
64
|
+
let start = uses;
|
|
65
|
+
while (start > 0 && !/^\s*-\s/.test(lines[start]))
|
|
66
|
+
start--;
|
|
67
|
+
const dash = indent(lines[start]);
|
|
68
|
+
let end = uses + 1;
|
|
69
|
+
while (end < lines.length && (blank(lines[end]) || indent(lines[end]) > dash))
|
|
70
|
+
end++;
|
|
71
|
+
const step = lines.slice(start, end);
|
|
72
|
+
const withAt = step.findIndex((l) => indent(l) === keyIndent && /^\s*with:\s*(#.*)?$/.test(l));
|
|
73
|
+
if (withAt === -1)
|
|
74
|
+
return {};
|
|
75
|
+
const inputs = {};
|
|
76
|
+
for (const line of step.slice(withAt + 1)) {
|
|
77
|
+
if (blank(line))
|
|
78
|
+
continue;
|
|
79
|
+
if (indent(line) <= keyIndent)
|
|
80
|
+
break;
|
|
81
|
+
const kv = /^\s*([\w-]+):\s*(.*)$/.exec(line);
|
|
82
|
+
if (!kv)
|
|
83
|
+
continue;
|
|
84
|
+
const value = scalar(kv[2]);
|
|
85
|
+
if (!value || /^[|>]/.test(value) || value.includes("${{"))
|
|
86
|
+
continue;
|
|
87
|
+
inputs[kv[1]] = value;
|
|
88
|
+
}
|
|
89
|
+
return inputs;
|
|
90
|
+
}
|
|
91
|
+
export function readWorkflow(cwd) {
|
|
92
|
+
const dir = join(cwd, ".github/workflows");
|
|
93
|
+
if (!existsSync(dir))
|
|
94
|
+
return undefined;
|
|
95
|
+
for (const name of readdirSync(dir).filter((f) => /\.ya?ml$/.test(f)).sort()) {
|
|
96
|
+
const file = join(".github/workflows", name);
|
|
97
|
+
const inputs = workflowInputs(readFileSync(join(cwd, file), "utf8"));
|
|
98
|
+
if (inputs)
|
|
99
|
+
return { file, inputs };
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
export function resolveTarget({ flags, env, cwd }) {
|
|
104
|
+
const workflow = readWorkflow(cwd);
|
|
105
|
+
const layers = [
|
|
106
|
+
{ from: (k) => `--${k}`, values: flags },
|
|
107
|
+
{ from: (k) => `PROOFED_${k.toUpperCase()}`, values: { url: env.PROOFED_URL?.trim(), serve: env.PROOFED_SERVE?.trim(), build: env.PROOFED_BUILD?.trim() } },
|
|
108
|
+
{ from: () => CONFIG_FILE, values: readConfig(cwd) },
|
|
109
|
+
...(workflow
|
|
110
|
+
? [{ from: () => workflow.file, values: { url: workflow.inputs.url, serve: workflow.inputs.serve, build: workflow.inputs.build }, dir: workflow.inputs["working-directory"] }]
|
|
111
|
+
: []),
|
|
112
|
+
];
|
|
113
|
+
const pick = (key, from = layers) => {
|
|
114
|
+
for (const layer of from) {
|
|
115
|
+
const value = layer.values[key];
|
|
116
|
+
if (value)
|
|
117
|
+
return { setting: { value, from: layer.from(key) }, layer };
|
|
118
|
+
}
|
|
119
|
+
return undefined;
|
|
120
|
+
};
|
|
121
|
+
const url = pick("url");
|
|
122
|
+
const serve = pick("serve");
|
|
123
|
+
// A build belongs with its serve command: the workflow's build is for the workflow's serve. One
|
|
124
|
+
// given as a flag or in the environment applies to whichever serve is used.
|
|
125
|
+
const build = pick("build", layers.slice(0, 2)) ?? (serve && pick("build", [serve.layer]));
|
|
126
|
+
return {
|
|
127
|
+
url: url?.setting,
|
|
128
|
+
serve: serve?.setting,
|
|
129
|
+
build: build?.setting,
|
|
130
|
+
dir: resolve(cwd, serve?.layer.dir ?? "."),
|
|
131
|
+
};
|
|
132
|
+
}
|
package/dist/which.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { accessSync, constants, statSync } from "node:fs";
|
|
2
|
+
import { delimiter, join, resolve } from "node:path";
|
|
3
|
+
const executable = (file) => {
|
|
4
|
+
try {
|
|
5
|
+
accessSync(file, constants.X_OK);
|
|
6
|
+
return statSync(file).isFile();
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return false;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
export function findOnPath(name, env = process.env) {
|
|
13
|
+
for (const dir of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
|
|
14
|
+
const file = join(dir, name);
|
|
15
|
+
if (executable(file))
|
|
16
|
+
return file;
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
// The Kane binary src/kane.ts will spawn: KANE_CLI when set, else kane-cli on PATH.
|
|
21
|
+
export function findKane(env = process.env) {
|
|
22
|
+
const own = env.KANE_CLI?.trim();
|
|
23
|
+
if (own) {
|
|
24
|
+
const file = own.includes("/") ? resolve(own) : findOnPath(own, env);
|
|
25
|
+
return { path: file && executable(file) ? file : undefined, from: `KANE_CLI=${own}` };
|
|
26
|
+
}
|
|
27
|
+
return { path: findOnPath("kane-cli", env), from: "PATH" };
|
|
28
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "proofed-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Check web app scenarios in Chrome with Kane CLI before you call a change done.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/t1dem/proofed.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/t1dem/proofed#readme",
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/t1dem/proofed/issues"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cli",
|
|
15
|
+
"browser",
|
|
16
|
+
"testing",
|
|
17
|
+
"chrome",
|
|
18
|
+
"kane"
|
|
19
|
+
],
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"bin": {
|
|
23
|
+
"proofed": "bin/proofed.cjs"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=24"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "node --input-type=module -e 'import { rmSync } from \"node:fs\"; rmSync(\"dist\", { recursive: true, force: true });' && tsc -p tsconfig.build.json",
|
|
30
|
+
"typecheck": "tsc --noEmit",
|
|
31
|
+
"test": "node --test src/*.test.ts",
|
|
32
|
+
"check:package": "node scripts/check-package.ts",
|
|
33
|
+
"prepack": "npm run build",
|
|
34
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run check:package"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "^26.6.6",
|
|
38
|
+
"typescript": "^7.0.2"
|
|
39
|
+
},
|
|
40
|
+
"packageManager": "pnpm@10.20.0",
|
|
41
|
+
"files": [
|
|
42
|
+
"bin/*.cjs",
|
|
43
|
+
"dist/*.js",
|
|
44
|
+
"README.md"
|
|
45
|
+
]
|
|
46
|
+
}
|