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/dist/clip.js ADDED
@@ -0,0 +1,270 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { connectCdp } from "./cdp.js";
5
+ const FPS = 25;
6
+ // Kane thinks for several seconds between actions. The clip keeps a moment around each action
7
+ // (and around any visible change it caused) and cuts the waiting in between.
8
+ const BEFORE = 0.35;
9
+ const AFTER = 1.2;
10
+ const OPENING = 1;
11
+ const HOLD_LAST = 3.5;
12
+ // A screencast frame this much bigger or smaller than the previous one is a visible change
13
+ // (new page, content loaded); a blinking caret stays far below it.
14
+ const CHANGED = 0.015;
15
+ const LEAD = 0.75; // the camera starts moving this long before an action
16
+ const LINGER = 1.8; // and pulls back out this long after the last one in a row
17
+ const MAX_ZOOM = 1.8;
18
+ const FOCUS_ZOOM = 2.2;
19
+ const OVERVIEW_ZOOM = 1.4;
20
+ const OUT_WIDTH = 1280;
21
+ const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
22
+ const easeInOut = (u) => (u < 0.5 ? 4 * u * u * u : 1 - (-2 * u + 2) ** 3 / 2);
23
+ // Real time (screencast timestamps) → clip time, keeping only the stretches where something happens.
24
+ function timeline(frames, actions) {
25
+ const first = frames[0].time;
26
+ const last = frames.at(-1).time;
27
+ const changes = frames.filter((f, i) => i > 0 && Math.abs(f.bytes - frames[i - 1].bytes) > f.bytes * CHANGED);
28
+ const moments = [...actions.map((a) => a.time), ...changes.map((f) => f.time)].sort((a, b) => a - b);
29
+ const kept = [{ from: first, to: Math.min(first + OPENING, last) }];
30
+ for (const m of moments) {
31
+ const from = clamp(m - BEFORE, first, last);
32
+ const to = clamp(m + AFTER, first, last);
33
+ const prev = kept.at(-1);
34
+ if (from <= prev.to)
35
+ prev.to = Math.max(prev.to, to);
36
+ else
37
+ kept.push({ from, to });
38
+ }
39
+ const pieces = [];
40
+ let at = 0;
41
+ for (const k of kept) {
42
+ pieces.push({ ...k, at });
43
+ at += k.to - k.from;
44
+ }
45
+ // The last frame stays up while the camera settles on the result.
46
+ pieces.push({ from: last, to: last + HOLD_LAST, at });
47
+ return {
48
+ duration: at + HOLD_LAST,
49
+ holdStart: at,
50
+ toClip(time) {
51
+ const p = pieces.findLast((p) => p.from <= time) ?? pieces[0];
52
+ return p.at + clamp(time - p.from, 0, p.to - p.from);
53
+ },
54
+ scaleAt: (time) => (frames.findLast((f) => f.time <= time) ?? frames[0]).scale,
55
+ frameAt(t) {
56
+ const p = pieces.findLast((p) => p.at <= t) ?? pieces[0];
57
+ const time = p.from + Math.min(t - p.at, p.to - p.from);
58
+ return frames.findLast((f) => f.time <= time) ?? frames[0];
59
+ },
60
+ };
61
+ }
62
+ function fit(shot, { width, height }) {
63
+ const z = clamp(shot.z, 1, FOCUS_ZOOM);
64
+ const hw = width / (2 * z);
65
+ const hh = height / (2 * z);
66
+ return { x: clamp(shot.x, hw, width - hw), y: clamp(shot.y, hh, height - hh), z };
67
+ }
68
+ // Frames the element with room around it; small targets get the most zoom.
69
+ export function shotOf(rect, maxZoom, size, room = 1) {
70
+ const u = (room * size.width) / OUT_WIDTH;
71
+ const z = Math.min(size.width / (rect.width * (1 + 0.6 * room) + 300 * u), size.height / (rect.height * (1 + 0.6 * room) + 220 * u));
72
+ return fit({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2, z: Math.min(z, maxZoom) }, size);
73
+ }
74
+ export function plan(beats, focus, holdStart, size) {
75
+ const rects = beats.map((b) => b.rect);
76
+ const left = Math.min(...rects.map((r) => r.x));
77
+ const top = Math.min(...rects.map((r) => r.y));
78
+ const right = Math.max(...rects.map((r) => r.x + r.width));
79
+ const bottom = Math.max(...rects.map((r) => r.y + r.height));
80
+ const full = rects.length
81
+ ? shotOf({ x: left, y: top, width: right - left, height: bottom - top }, OVERVIEW_ZOOM, size, 0.5)
82
+ : { x: size.width / 2, y: size.height / 2, z: 1 };
83
+ const moves = [{ start: 0, dur: 0, shot: full }];
84
+ const push = (m) => {
85
+ while (moves.length > 1 && moves.at(-1).start >= m.start)
86
+ moves.pop();
87
+ moves.push(m);
88
+ };
89
+ // Two zoomed shots that don't overlap would whip-pan: pull back between them.
90
+ const apart = (a, b) => a.z > 1 && b.z > 1 && (Math.abs(a.x - b.x) > size.width / (2 * a.z) || Math.abs(a.y - b.y) > size.height / (2 * a.z));
91
+ beats.forEach((b, i) => {
92
+ const shot = shotOf(b.rect, MAX_ZOOM, size);
93
+ const prev = moves.at(-1).shot;
94
+ const after = i > 0 ? beats[i - 1].t + 0.15 : 0;
95
+ const arrive = b.t - 0.1;
96
+ if (apart(prev, shot) && arrive - after >= 0.8) {
97
+ const dx = Math.abs(shot.x - prev.x);
98
+ const dy = Math.abs(shot.y - prev.y);
99
+ const z = Math.min(size.width / (dx + size.width * 0.45), size.height / (dy + size.height * 0.45), prev.z, shot.z);
100
+ const start = Math.max(arrive - LEAD - 0.35, after);
101
+ const mid = start + (arrive - start) * 0.45;
102
+ push({ start, dur: mid - start, shot: fit({ x: (prev.x + shot.x) / 2, y: (prev.y + shot.y) / 2, z }, size) });
103
+ push({ start: mid, dur: arrive - mid, shot });
104
+ }
105
+ else {
106
+ const start = Math.max(arrive - LEAD, after);
107
+ push({ start, dur: Math.max(arrive - start, 0.2), shot });
108
+ }
109
+ const next = beats[i + 1];
110
+ if (!next || next.t - b.t > LINGER + LEAD + 0.5)
111
+ push({ start: b.t + LINGER, dur: 0.8, shot: full });
112
+ });
113
+ // Head for the result as soon as the last action has had its effect, not once the hold begins.
114
+ const last = beats.at(-1);
115
+ push({ start: last ? Math.max(last.t + 0.3, holdStart - 0.6) : holdStart, dur: 1, shot: focus ?? full });
116
+ return moves;
117
+ }
118
+ // Plays the moves: each one eases from wherever the camera is when it starts (centre linearly,
119
+ // zoom in log space so it feels even) to its shot.
120
+ export function film(moves, frames, size) {
121
+ const from = [];
122
+ const at = (i, t) => {
123
+ const m = moves[i];
124
+ const a = from[i];
125
+ const u = m.dur > 0 ? easeInOut(clamp((t - m.start) / m.dur, 0, 1)) : 1;
126
+ return {
127
+ x: a.x + (m.shot.x - a.x) * u,
128
+ y: a.y + (m.shot.y - a.y) * u,
129
+ z: Math.exp(Math.log(a.z) + (Math.log(m.shot.z) - Math.log(a.z)) * u),
130
+ };
131
+ };
132
+ moves.forEach((m, i) => from.push(i === 0 ? m.shot : at(i - 1, m.start)));
133
+ return Array.from({ length: frames }, (_, n) => {
134
+ const t = n / FPS;
135
+ return fit(at(Math.max(moves.findLastIndex((m) => m.start <= t), 0), t), size);
136
+ });
137
+ }
138
+ // The cursor glides along a slight arc into each action and dips when it clicks.
139
+ function cursor(beats, hideFrom, size) {
140
+ const first = beats[0];
141
+ if (!first)
142
+ return () => undefined;
143
+ const start = { x: clamp(first.x + 160, 0, size.width), y: clamp(first.y + 120, 0, size.height) };
144
+ return (t) => {
145
+ const appear = clamp((t - (first.t - 1)) / 0.3, 0, 1);
146
+ const fade = hideFrom === undefined ? 1 : 1 - clamp((t - hideFrom) / 0.4, 0, 1);
147
+ const opacity = appear * fade;
148
+ if (opacity === 0)
149
+ return undefined;
150
+ const i = beats.findIndex((b) => b.t > t);
151
+ let at;
152
+ if (i === -1) {
153
+ at = beats.at(-1);
154
+ }
155
+ else {
156
+ const to = beats[i];
157
+ const from = i === 0 ? start : beats[i - 1];
158
+ const move = i === 0 ? 0.7 : Math.min(0.6, (to.t - beats[i - 1].t) * 0.7);
159
+ const u = clamp((t - (to.t - move)) / move, 0, 1);
160
+ const e = easeInOut(u);
161
+ const bend = Math.sin(Math.PI * u) * 0.12;
162
+ at = {
163
+ x: from.x + (to.x - from.x) * e - (to.y - from.y) * bend,
164
+ y: from.y + (to.y - from.y) * e + (to.x - from.x) * bend,
165
+ };
166
+ }
167
+ const click = beats.findLast((b) => b.kind === "click" && t >= b.t - 0.05 && t < b.t + 0.6);
168
+ const since = click ? t - click.t : Infinity;
169
+ return {
170
+ ...at,
171
+ opacity,
172
+ press: since < 0.25 ? 1 - 0.18 * Math.sin((Math.PI * (since + 0.05)) / 0.3) : 1,
173
+ ripple: click && since >= 0 ? { x: click.x, y: click.y, p: since / 0.6 } : undefined,
174
+ };
175
+ };
176
+ }
177
+ const CURSOR_SVG = `<svg id="cursor" viewBox="0 0 24 34" width="24" height="34"><path d="M2 2v25.5l6.4-6.2 4.1 9.9 4.4-1.8-4-9.7h8.9z" fill="#0b0d12" stroke="#fff" stroke-width="2" stroke-linejoin="round"/></svg>`;
178
+ const STAGE = ({ width, height }) => `<!doctype html><html><head><style>
179
+ html,body{margin:0;width:${width}px;height:${height}px;overflow:hidden;background:#fff}
180
+ #shot{position:absolute;left:0;top:0;width:${width}px;height:${height}px;transform-origin:0 0}
181
+ #ring{position:absolute;left:0;top:0;width:60px;height:60px;border-radius:50%;border:3px solid #2f6feb;background:rgba(47,111,235,.16);opacity:0}
182
+ #cursor{position:absolute;left:0;top:0;transform-origin:0 0;filter:drop-shadow(0 2px 3px rgba(0,0,0,.35));opacity:0}
183
+ </style></head><body><img id="shot" alt=""><div id="ring"></div>${CURSOR_SVG}
184
+ <script>
185
+ window.paint = async (s) => {
186
+ const shot = document.getElementById("shot");
187
+ if (s.src) { shot.src = s.src; await shot.decode(); }
188
+ shot.style.transform = "translate(" + s.tx + "px," + s.ty + "px) scale(" + s.z + ")";
189
+ const cursor = document.getElementById("cursor");
190
+ const ring = document.getElementById("ring");
191
+ cursor.style.opacity = s.cursor ? s.cursor.opacity : 0;
192
+ if (s.cursor) cursor.style.transform = "translate(" + (s.cursor.x - 2 * s.cursor.k) + "px," + (s.cursor.y - 2 * s.cursor.k) + "px) scale(" + s.cursor.k + ")";
193
+ ring.style.opacity = s.ripple ? 0.9 * (1 - s.ripple.p) : 0;
194
+ if (s.ripple) ring.style.transform = "translate(" + (s.ripple.x - 30) + "px," + (s.ripple.y - 30) + "px) scale(" + (0.25 + 0.75 * s.ripple.p) * s.ripple.k + ")";
195
+ await new Promise((r) => requestAnimationFrame(() => r()));
196
+ };
197
+ </script></body></html>`;
198
+ export async function makeClip({ frames, actions, focus, endpoint, marks = [] }, base) {
199
+ const last = frames.at(-1);
200
+ if (!last)
201
+ return undefined;
202
+ const size = { width: last.width, height: last.height };
203
+ const time = timeline(frames, actions);
204
+ const scaleRect = (r, s) => ({ x: r.x * s, y: r.y * s, width: r.width * s, height: r.height * s });
205
+ const beats = actions
206
+ .filter((a) => a.time >= frames[0].time)
207
+ .sort((a, b) => a.time - b.time)
208
+ .map((a) => {
209
+ const s = time.scaleAt(a.time);
210
+ return { t: time.toClip(a.time), kind: a.kind, x: a.x * s, y: a.y * s, rect: scaleRect(a.rect, s) };
211
+ });
212
+ const focusShot = focus && shotOf(scaleRect(focus, last.scale), FOCUS_ZOOM, size, 0.5);
213
+ const count = Math.ceil(time.duration * FPS);
214
+ const shots = film(plan(beats, focusShot, time.holdStart, size), count, size);
215
+ const pointer = cursor(beats, focusShot && time.holdStart + 0.4, size);
216
+ const dir = `${base}.render`;
217
+ mkdirSync(dir, { recursive: true });
218
+ const cdp = await connectCdp(endpoint);
219
+ try {
220
+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
221
+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
222
+ const page = (method, params = {}) => cdp.send(method, params, sessionId);
223
+ await page("Page.enable");
224
+ await page("Page.bringToFront");
225
+ // Frames come in at the page's own resolution; the clip is drawn from them at OUT_WIDTH,
226
+ // so zoomed-in shots stay sharp.
227
+ const ui = size.width / OUT_WIDTH;
228
+ await page("Emulation.setDeviceMetricsOverride", { ...size, deviceScaleFactor: 1 / ui, mobile: false });
229
+ const { frameTree } = await page("Page.getFrameTree");
230
+ await page("Page.setDocumentContent", { frameId: frameTree.frame.id, html: STAGE(size) });
231
+ let shown;
232
+ for (let n = 0; n < count; n++) {
233
+ const t = n / FPS;
234
+ const cam = shots[n];
235
+ const toScreen = (p) => ({ x: (p.x - cam.x) * cam.z + size.width / 2, y: (p.y - cam.y) * cam.z + size.height / 2 });
236
+ const source = time.frameAt(t).file;
237
+ const c = pointer(t);
238
+ const k = ui * Math.sqrt(cam.z);
239
+ await page("Runtime.evaluate", {
240
+ awaitPromise: true,
241
+ expression: `paint(${JSON.stringify({
242
+ src: source === shown ? undefined : `data:image/jpeg;base64,${readFileSync(source).toString("base64")}`,
243
+ tx: size.width / 2 - cam.x * cam.z,
244
+ ty: size.height / 2 - cam.y * cam.z,
245
+ z: cam.z,
246
+ cursor: c && { ...toScreen(c), opacity: c.opacity, k: k * c.press },
247
+ ripple: c?.ripple && { ...toScreen(c.ripple), p: c.ripple.p, k },
248
+ })})`,
249
+ });
250
+ shown = source;
251
+ const { data } = await page("Page.captureScreenshot", { format: "jpeg", quality: 90 });
252
+ writeFileSync(join(dir, `${String(n).padStart(5, "0")}.jpg`), Buffer.from(data, "base64"));
253
+ }
254
+ await cdp.send("Target.closeTarget", { targetId });
255
+ }
256
+ finally {
257
+ cdp.close();
258
+ }
259
+ const mp4 = `${base}.mp4`;
260
+ const gif = `${base}.gif`;
261
+ const ffmpeg = (...args) => execFileSync("ffmpeg", ["-y", "-loglevel", "error", ...args]);
262
+ ffmpeg("-framerate", String(FPS), "-i", join(dir, "%05d.jpg"), "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-crf", "20", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4);
263
+ ffmpeg("-i", mp4, "-vf", "fps=10,scale=720:-1:flags=lanczos,split[a][b];[a]palettegen=max_colors=96:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle", gif);
264
+ // The still: the last frame, settled on what the check was about. The before/after table after a
265
+ // fix shows it, and so does the dashboard at full column width, so it keeps the clip's resolution.
266
+ const jpg = `${base}.jpg`;
267
+ ffmpeg("-i", join(dir, `${String(count - 1).padStart(5, "0")}.jpg`), "-frames:v", "1", "-q:v", "3", jpg);
268
+ const at = marks.map((t) => (Number.isFinite(t) ? Math.round(time.toClip(t) * 10) / 10 : undefined));
269
+ return { mp4, gif, jpg, marks: at };
270
+ }
package/dist/doctor.js ADDED
@@ -0,0 +1,133 @@
1
+ // `proofed doctor`: whether `proofed check` can run here, and the exact fix for what can't. It only
2
+ // calls Kane's free commands (--version, whoami, balance); no run, no credits.
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { DEFAULT_CREDITS } from "./cache.js";
6
+ import { scenariosDirOf } from "./check.js";
7
+ import { findBase } from "./changes.js";
8
+ import { findChrome } from "./chrome.js";
9
+ import { colorOn, palette, stripAnsi } from "./render.js";
10
+ import { readScenarios } from "./scenarios.js";
11
+ import { answers } from "./serve.js";
12
+ import { SetupError } from "./setuperror.js";
13
+ import { isHttpUrl, resolveTarget } from "./target.js";
14
+ import { findKane, findOnPath } from "./which.js";
15
+ const run = promisify(execFile);
16
+ // Kane prints update notices around its answer; only the answer counts.
17
+ async function kane(bin, args, env) {
18
+ try {
19
+ const { stdout, stderr } = await run(bin, args, { env, timeout: 20_000 });
20
+ return { ok: true, text: stripAnsi(`${stdout}\n${stderr}`) };
21
+ }
22
+ catch (e) {
23
+ const err = e;
24
+ return { ok: false, text: stripAnsi(`${err.stdout ?? ""}\n${err.stderr ?? ""}`) };
25
+ }
26
+ }
27
+ export async function doctorChecks(flags, io) {
28
+ const checks = [];
29
+ const add = (name, status, detail, fix) => checks.push({ name, status, detail, ...(fix && { fix }) });
30
+ const major = Number(process.versions.node.split(".")[0]);
31
+ add("Node", major >= 24 ? "ok" : "fail", `v${process.versions.node}`, major >= 24 ? undefined : "Install Node 24 or newer from https://nodejs.org/.");
32
+ try {
33
+ const base = findBase(io.cwd, flags.base);
34
+ if (base.rev)
35
+ add("Git", "ok", `changes are taken against ${base.rev}`);
36
+ else
37
+ add("Git", "warn", `${base.why}: proofed check runs every scenario`, "Run proofed in the app's git repository, or pass --base <rev>.");
38
+ }
39
+ catch (e) {
40
+ add("Git", "fail", e instanceof Error ? e.message : String(e), e instanceof SetupError ? e.fix : undefined);
41
+ }
42
+ const dir = scenariosDirOf(flags, io);
43
+ const loaded = readScenarios(dir);
44
+ if (loaded.missing)
45
+ add("Scenarios", "fail", `${dir} doesn't exist`, `Write one Markdown file per flow in ${dir}/ (see the Scenarios section of Proofed's README), or pass --scenarios <dir>.`);
46
+ else if (loaded.scenarios.length === 0 && loaded.errors.length === 0)
47
+ add("Scenarios", "fail", `${dir} has no .md files`, `Write one Markdown file per flow in ${dir}/.`);
48
+ else
49
+ add("Scenarios", "ok", `${loaded.scenarios.length} in ${dir}`);
50
+ for (const e of loaded.errors)
51
+ add("Scenario", "fail", `${e.file}: ${e.message}`, `Fix the frontmatter of ${e.file}: --- name, paths, url --- then the objective.`);
52
+ const found = findKane(io.env);
53
+ const creds = io.env.LT_USERNAME && io.env.LT_ACCESS_KEY ? ["--username", io.env.LT_USERNAME, "--access-key", io.env.LT_ACCESS_KEY] : [];
54
+ if (!found.path) {
55
+ add("Kane CLI", "fail", `not found (${found.from})`, io.env.KANE_CLI ? "Point KANE_CLI at the kane-cli binary, or unset it." : "npm install -g @testmuai/kane-cli");
56
+ }
57
+ else {
58
+ const [version, who, balance] = await Promise.all([
59
+ kane(found.path, ["--version"], io.env),
60
+ kane(found.path, ["whoami"], io.env),
61
+ kane(found.path, ["balance", ...creds], io.env),
62
+ ]);
63
+ add("Kane CLI", "ok", `${found.path}, ${/\d+\.\d+\.\d+\S*/.exec(version.text)?.[0] ?? "version unknown"}`);
64
+ if (creds.length)
65
+ add("Kane login", "ok", "LT_USERNAME and LT_ACCESS_KEY are set; Kane uses them");
66
+ else if (who.ok)
67
+ add("Kane login", "ok", "signed in");
68
+ else
69
+ add("Kane login", "fail", "not signed in", "kane-cli login (or export LT_USERNAME and LT_ACCESS_KEY from TestMu: Settings → Keys)");
70
+ const left = /credits:\s*([\d.,]+)/i.exec(balance.text)?.[1];
71
+ if (balance.ok && left) {
72
+ const n = Number(left.replace(/,/g, ""));
73
+ add("Credits", n >= DEFAULT_CREDITS ? "ok" : "warn", `${Math.floor(n)} available; a first run is estimated at ${DEFAULT_CREDITS} credits`, n >= DEFAULT_CREDITS ? undefined : "Top up your TestMu account before running scenarios.");
74
+ }
75
+ else {
76
+ add("Credits", "warn", "couldn't read the balance", "kane-cli balance");
77
+ }
78
+ }
79
+ const chrome = findChrome();
80
+ add("Chrome", chrome ? "ok" : "fail", chrome ?? "not found", chrome ? undefined : "Install Google Chrome, or set CHROME_PATH to its binary.");
81
+ const ffmpeg = findOnPath("ffmpeg", io.env);
82
+ add("ffmpeg", ffmpeg ? "ok" : "warn", ffmpeg ?? "not found: no clips, the verdicts still work", ffmpeg ? undefined : process.platform === "darwin" ? "brew install ffmpeg" : "sudo apt-get install ffmpeg");
83
+ try {
84
+ const target = resolveTarget({ flags: { url: flags.url, serve: flags.serve, build: flags.build }, env: io.env, cwd: io.cwd });
85
+ const url = target.url;
86
+ if (!url) {
87
+ add("App", "fail", "no URL", 'Pass --url http://localhost:5173 to proofed check, set PROOFED_URL, or write .proofed/config.json: { "url": "http://localhost:5173", "serve": "npm run dev" }');
88
+ }
89
+ else if (!isHttpUrl(url.value)) {
90
+ add("App", "fail", `"${url.value}" from ${url.from} is not an http(s) URL`, "Use a full URL, e.g. http://localhost:5173");
91
+ }
92
+ else {
93
+ add("App URL", "ok", `${url.value} (from ${url.from})`);
94
+ if (target.build)
95
+ add("Build", "ok", `${target.build.value} (from ${target.build.from})`);
96
+ if (target.serve)
97
+ add("Serve", "ok", `${target.serve.value} (from ${target.serve.from}${target.dir !== io.cwd ? `, in ${target.dir}` : ""})`);
98
+ const up = await answers(url.value);
99
+ if (up && target.build)
100
+ add("App", "warn", `${url.value} answers now, maybe from an old build: proofed check stops rather than test it`, "Stop that server so Proofed builds and serves the current code, or pass --reuse to proofed check.");
101
+ else if (up)
102
+ add("App", "ok", `${url.value} answers now`);
103
+ else if (target.serve)
104
+ add("App", "warn", `${url.value} doesn't answer now; proofed check starts it with the serve command`);
105
+ else
106
+ add("App", "fail", `${url.value} doesn't answer and there is no serve command`, 'Start the app, or tell Proofed how: --serve "npm run dev", PROOFED_SERVE, or "serve" in .proofed/config.json');
107
+ }
108
+ }
109
+ catch (e) {
110
+ if (!(e instanceof SetupError))
111
+ throw e;
112
+ add("App", "fail", e.message, e.fix);
113
+ }
114
+ return checks;
115
+ }
116
+ export async function doctor(flags, io) {
117
+ const checks = await doctorChecks(flags, io);
118
+ const exitCode = checks.some((c) => c.status === "fail") ? 3 : 0;
119
+ if (flags.json) {
120
+ io.stdout.write(`${JSON.stringify({ ok: exitCode === 0, exitCode, checks }, null, 2)}\n`);
121
+ return exitCode;
122
+ }
123
+ const c = palette(colorOn(io.env, !!io.stdout.isTTY));
124
+ const mark = { ok: c.green("✓"), warn: c.yellow("!"), fail: c.red("✗") };
125
+ const width = Math.max(...checks.map((k) => k.name.length));
126
+ for (const k of checks) {
127
+ io.stdout.write(`${mark[k.status]} ${k.name.padEnd(width)} ${k.detail}\n`);
128
+ if (k.fix && k.status !== "ok")
129
+ io.stdout.write(` ${" ".repeat(width)} ${c.dim("Fix:")} ${k.fix}\n`);
130
+ }
131
+ io.stdout.write(exitCode === 0 ? `\n${c.green("Ready:")} proofed check can run here.\n` : `\n${c.red("Not ready:")} fix the ✗ lines above.\n`);
132
+ return exitCode;
133
+ }
package/dist/github.js ADDED
@@ -0,0 +1,143 @@
1
+ import { readFileSync } from "node:fs";
2
+ export const repoFromEnv = (token) => {
3
+ const [owner = "", name = ""] = (process.env.GITHUB_REPOSITORY ?? "").split("/");
4
+ return { owner, name, token };
5
+ };
6
+ async function api(repo, method, path, body) {
7
+ const res = await fetch(`https://api.github.com/repos/${repo.owner}/${repo.name}${path}`, {
8
+ method,
9
+ headers: {
10
+ authorization: `Bearer ${repo.token}`,
11
+ accept: "application/vnd.github+json",
12
+ "x-github-api-version": "2022-11-28",
13
+ ...(body !== undefined && { "content-type": "application/json" }),
14
+ },
15
+ body: body === undefined ? undefined : JSON.stringify(body),
16
+ });
17
+ if (!res.ok)
18
+ throw new GitHubError(res.status, `${method} ${path}: ${res.status} ${await res.text()}`);
19
+ return (res.status === 204 ? undefined : await res.json());
20
+ }
21
+ export const getPullRequest = (repo, number) => api(repo, "GET", `/pulls/${number}`);
22
+ // A folder's entries at `ref`, or undefined when there is no folder there.
23
+ export async function listFolder(repo, path, ref) {
24
+ try {
25
+ const found = await api(repo, "GET", `/contents/${path}?ref=${ref}`);
26
+ return Array.isArray(found) ? found : undefined;
27
+ }
28
+ catch (e) {
29
+ if (e instanceof GitHubError && e.status === 404)
30
+ return undefined;
31
+ throw e;
32
+ }
33
+ }
34
+ export async function readFile(repo, path, ref) {
35
+ const file = await api(repo, "GET", `/contents/${path}?ref=${ref}`);
36
+ return Buffer.from(file.content ?? "", "base64").toString("utf8");
37
+ }
38
+ // 👀 on a /proofed comment, so whoever asked sees it was picked up.
39
+ export const acknowledge = (repo, commentId) => api(repo, "POST", `/issues/comments/${commentId}/reactions`, { content: "eyes" });
40
+ export class GitHubError extends Error {
41
+ status;
42
+ constructor(status, message) {
43
+ super(message);
44
+ this.status = status;
45
+ }
46
+ }
47
+ export const MARKER = "<!-- proofed -->";
48
+ // A report a newer one replaced carries this instead. Neither the fix trigger in the installed workflows
49
+ // nor the dashboard's webhook matches it, so an edit of an old report is never read as the PR's report.
50
+ export const OLD_MARKER = "<!-- proofed:old -->";
51
+ // Proofed's reports on the PR, oldest first: the newest is the report. Only a bot's comment counts,
52
+ // since anyone can paste the marker. `older` are reports that weren't retired, as when an edit failed.
53
+ export function reportsIn(comments) {
54
+ const reports = comments.filter((c) => c.user?.type === "Bot" && c.body?.includes(MARKER));
55
+ return { current: reports.at(-1), older: reports.slice(0, -1) };
56
+ }
57
+ // Every page: a report is posted afresh further down a long thread, past the first hundred comments.
58
+ export async function listReports(repo, pr) {
59
+ const comments = [];
60
+ for (let page = 1;; page++) {
61
+ const batch = await api(repo, "GET", `/issues/${pr}/comments?per_page=100&page=${page}`);
62
+ comments.push(...batch);
63
+ if (batch.length < 100)
64
+ return reportsIn(comments);
65
+ }
66
+ }
67
+ export const findReport = async (repo, pr) => (await listReports(repo, pr)).current;
68
+ export const reply = (repo, pr, body) => api(repo, "POST", `/issues/${pr}/comments`, { body });
69
+ export const postComment = (repo, pr, body) => api(repo, "POST", `/issues/${pr}/comments`, { body });
70
+ export const editComment = (repo, id, body) => api(repo, "PATCH", `/issues/comments/${id}`, { body });
71
+ // Folded on GitHub as outdated. A token that may comment but not minimize only leaves it unfolded.
72
+ export async function minimize(repo, nodeId) {
73
+ const res = await fetch("https://api.github.com/graphql", {
74
+ method: "POST",
75
+ headers: { authorization: `Bearer ${repo.token}`, "content-type": "application/json" },
76
+ body: JSON.stringify({
77
+ query: "mutation($id: ID!) { minimizeComment(input: { subjectId: $id, classifier: OUTDATED }) { minimizedComment { isMinimized } } }",
78
+ variables: { id: nodeId },
79
+ }),
80
+ });
81
+ // GraphQL reports most errors with a 200.
82
+ const answer = (await res.json().catch(() => ({})));
83
+ if (!res.ok || answer.errors?.length)
84
+ throw new GitHubError(res.status, `minimizeComment: ${res.status} ${answer.errors?.map((e) => e.message).join("; ") ?? ""}`);
85
+ }
86
+ const STATUS = "Proofed";
87
+ export const hasStatus = async (repo, sha) => (await api(repo, "GET", `/commits/${sha}/status`)).statuses.some((s) => s.context === STATUS);
88
+ export function setStatus(repo, sha, state, description, targetUrl) {
89
+ return api(repo, "POST", `/statuses/${sha}`, {
90
+ state,
91
+ context: STATUS,
92
+ description: description.slice(0, 140),
93
+ ...(targetUrl && { target_url: targetUrl }),
94
+ });
95
+ }
96
+ const CLIPS_BRANCH = "proofed-clips";
97
+ // Clips go to an orphan branch of the same repo, so the repo needs no storage of its own.
98
+ // Links go through github.com/…/raw/…, not raw.githubusercontent.com: for a private repo GitHub
99
+ // redirects a signed-in viewer to a tokened raw URL, so the GIF still renders in the PR comment.
100
+ export async function publishClips(repo, files) {
101
+ if (files.length === 0)
102
+ return new Map();
103
+ for (let attempt = 0;; attempt++) {
104
+ const parent = await api(repo, "GET", `/git/ref/heads/${CLIPS_BRANCH}`).catch((e) => {
105
+ if (e instanceof GitHubError && e.status === 404)
106
+ return undefined;
107
+ throw e;
108
+ });
109
+ const parentCommit = parent
110
+ ? await api(repo, "GET", `/git/commits/${parent.object.sha}`)
111
+ : undefined;
112
+ const tree = await Promise.all(files.map(async (f) => {
113
+ const blob = await api(repo, "POST", "/git/blobs", {
114
+ content: readFileSync(f.local).toString("base64"),
115
+ encoding: "base64",
116
+ });
117
+ return { path: f.path, mode: "100644", type: "blob", sha: blob.sha };
118
+ }));
119
+ const newTree = await api(repo, "POST", "/git/trees", {
120
+ tree,
121
+ ...(parentCommit && { base_tree: parentCommit.tree.sha }),
122
+ });
123
+ const commit = await api(repo, "POST", "/git/commits", {
124
+ message: `Clips for ${files[0]?.path.split("/").slice(0, -1).join("/")}`,
125
+ tree: newTree.sha,
126
+ parents: parent ? [parent.object.sha] : [],
127
+ });
128
+ try {
129
+ if (parent)
130
+ await api(repo, "PATCH", `/git/refs/heads/${CLIPS_BRANCH}`, { sha: commit.sha });
131
+ else
132
+ await api(repo, "POST", "/git/refs", { ref: `refs/heads/${CLIPS_BRANCH}`, sha: commit.sha });
133
+ break;
134
+ }
135
+ catch (e) {
136
+ // Another run moved the branch first: rebuild on top of it.
137
+ if (attempt < 3 && e instanceof GitHubError && e.status === 422)
138
+ continue;
139
+ throw e;
140
+ }
141
+ }
142
+ return new Map(files.map((f) => [f.path, `https://github.com/${repo.owner}/${repo.name}/raw/${CLIPS_BRANCH}/${f.path}`]));
143
+ }