trykeyline-browser 0.0.0-stage → 0.2.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.
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Every page a product has, found three ways and merged:
3
+ *
4
+ * 1. From the code: the router's own files (Next app and pages routers,
5
+ * SvelteKit, Astro, Nuxt, Remix/React Router file routes, route objects
6
+ * and <Route path> in a React Router app, plain .html files).
7
+ * 2. From /sitemap.xml on the running site.
8
+ * 3. From a crawl of the running site: same-origin links, breadth first.
9
+ *
10
+ * A route with a parameter (`/projects/[id]`) can't be visited until someone
11
+ * names an example; it's returned with `dynamic: true` and, when the crawl met a
12
+ * matching URL, that URL as its `sample`.
13
+ */
14
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
15
+ import { join, relative, sep } from "node:path";
16
+ import { walk } from "trykeyline/check/files";
17
+
18
+ /** Route files: what a router reads, and plain HTML. */
19
+ const ROUTE_FILES = new Set([".tsx", ".ts", ".jsx", ".js", ".mdx", ".md", ".svelte", ".astro", ".vue", ".html"]);
20
+
21
+ /** Every route-shaped file under `dir`, as absolute paths, skipping what the detector skips (dependencies, build output, reports, dot-folders). */
22
+ const files = (dir) => walk(dir, { accept: ROUTE_FILES, skip: null, maxSize: Infinity }).map((f) => f.abs);
23
+
24
+ const segs = (rel) => rel.split(sep).filter(Boolean);
25
+ const toPath = (parts) => "/" + parts.filter(Boolean).join("/");
26
+ const isDynamic = (path) => /\[|:|\$|\*/.test(path);
27
+
28
+ function readDeps(root) {
29
+ try {
30
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
31
+ return { ...pkg.dependencies, ...pkg.devDependencies };
32
+ } catch {
33
+ return {};
34
+ }
35
+ }
36
+
37
+ /** Next.js app router: every page.* under app/, route groups and slots dropped. */
38
+ function nextApp(root) {
39
+ const out = [];
40
+ for (const base of ["app", "src/app"]) {
41
+ const dir = join(root, base);
42
+ for (const file of files(dir)) {
43
+ if (!/[\\/]page\.(tsx|ts|jsx|js|mdx|md)$/.test(file)) continue;
44
+ const all = segs(relative(dir, file)).slice(0, -1);
45
+ // A _private folder opts its whole subtree out of routing.
46
+ if (all.some((s) => s.startsWith("_"))) continue;
47
+ const parts = all.filter((s) => !/^\(.*\)$/.test(s) && !s.startsWith("@"));
48
+ out.push({ path: toPath(parts), file: relative(root, file), source: "next-app" });
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /** Next.js pages router: files under pages/, minus _app, _document, _error and api/. */
55
+ function nextPages(root) {
56
+ const out = [];
57
+ for (const base of ["pages", "src/pages"]) {
58
+ const dir = join(root, base);
59
+ for (const file of files(dir)) {
60
+ if (!/\.(tsx|ts|jsx|js|mdx|md)$/.test(file)) continue;
61
+ const parts = segs(relative(dir, file));
62
+ if (parts[0] === "api" || /^_(app|document|error)\./.test(parts.at(-1))) continue;
63
+ parts[parts.length - 1] = parts.at(-1).replace(/\.\w+$/, "");
64
+ if (parts.at(-1) === "index") parts.pop();
65
+ out.push({ path: toPath(parts), file: relative(root, file), source: "next-pages" });
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function sveltekit(root) {
72
+ const dir = join(root, "src/routes");
73
+ return files(dir)
74
+ .filter((f) => /[\\/]\+page\.svelte$/.test(f))
75
+ .map((file) => {
76
+ const parts = segs(relative(dir, file)).slice(0, -1).filter((s) => !/^\(.*\)$/.test(s));
77
+ return { path: toPath(parts), file: relative(root, file), source: "sveltekit" };
78
+ });
79
+ }
80
+
81
+ function astro(root) {
82
+ const dir = join(root, "src/pages");
83
+ return files(dir)
84
+ .filter((f) => /\.(astro|md|mdx|html)$/.test(f))
85
+ .map((file) => {
86
+ const parts = segs(relative(dir, file));
87
+ parts[parts.length - 1] = parts.at(-1).replace(/\.\w+$/, "");
88
+ if (parts.at(-1) === "index") parts.pop();
89
+ return { path: toPath(parts), file: relative(root, file), source: "astro" };
90
+ });
91
+ }
92
+
93
+ function nuxt(root) {
94
+ const dir = join(root, "pages");
95
+ return files(dir)
96
+ .filter((f) => f.endsWith(".vue"))
97
+ .map((file) => {
98
+ const parts = segs(relative(dir, file));
99
+ parts[parts.length - 1] = parts.at(-1).replace(/\.vue$/, "");
100
+ if (parts.at(-1) === "index") parts.pop();
101
+ return { path: toPath(parts), file: relative(root, file), source: "nuxt" };
102
+ });
103
+ }
104
+
105
+ /** Remix and React Router v7 flat routes: app/routes/a.b._index.tsx → /a/b. */
106
+ function flatRoutes(root) {
107
+ const dir = join(root, "app/routes");
108
+ if (!existsSync(dir)) return [];
109
+ return readdirSync(dir)
110
+ .filter((f) => /\.(tsx|ts|jsx|js|mdx)$/.test(f) || existsSync(join(dir, f, "route.tsx")))
111
+ .map((name) => {
112
+ const parts = name.replace(/\.(tsx|ts|jsx|js|mdx)$/, "").split(".").filter((s) => s !== "_index" && !s.startsWith("_"));
113
+ return { path: toPath(parts.map((p) => p.replace(/^\$/, ":"))), file: join("app/routes", name), source: "flat-routes" };
114
+ })
115
+ .filter((r) => !r.file.includes("resources") && !r.path.includes("api"));
116
+ }
117
+
118
+ /** React Router route objects and <Route path="…">, read from source text. */
119
+ function routerConfig(root) {
120
+ const out = [];
121
+ const re = /(?:<Route[^>]*\spath=|\bpath:\s*)["'`](\/?[^"'`]*)["'`]/g;
122
+ for (const file of files(join(root, "src"))) {
123
+ if (!/\.(tsx|ts|jsx|js)$/.test(file)) continue;
124
+ const text = readFileSync(file, "utf8");
125
+ if (!/react-router|createBrowserRouter|<Route\b/.test(text)) continue;
126
+ for (const m of text.matchAll(re)) {
127
+ if (m[1] === "*" || m[1].startsWith("http")) continue;
128
+ out.push({ path: m[1].startsWith("/") ? m[1] : "/" + m[1], file: relative(root, file), source: "react-router" });
129
+ }
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /** Plain HTML: every .html file outside build output. */
135
+ function staticHtml(root) {
136
+ return files(root)
137
+ .filter((f) => f.endsWith(".html"))
138
+ .map((file) => {
139
+ const rel = relative(root, file).split(sep).join("/");
140
+ const path = "/" + rel.replace(/(^|\/)index\.html$/, "$1").replace(/\/$/, "");
141
+ return { path: path || "/", file: rel, source: "html" };
142
+ });
143
+ }
144
+
145
+ /** Routes the code declares. */
146
+ export function routesFromCode(root) {
147
+ const deps = readDeps(root);
148
+ const found = [];
149
+ if (deps.next) found.push(...nextApp(root), ...nextPages(root));
150
+ if (deps["@sveltejs/kit"]) found.push(...sveltekit(root));
151
+ if (deps.astro) found.push(...astro(root));
152
+ if (deps.nuxt) found.push(...nuxt(root));
153
+ if (deps["@remix-run/react"] || deps["@react-router/dev"]) found.push(...flatRoutes(root));
154
+ if (deps["react-router"] || deps["react-router-dom"]) found.push(...routerConfig(root));
155
+ if (!found.length) found.push(...staticHtml(root));
156
+ return found.map((r) => ({ ...r, path: r.path.replace(/\/+$/, "") || "/", dynamic: isDynamic(r.path) }));
157
+ }
158
+
159
+ /** Paths listed in the running site's sitemap, same origin only. */
160
+ export async function routesFromSitemap(base) {
161
+ try {
162
+ const res = await fetch(new URL("/sitemap.xml", base));
163
+ if (!res.ok) return [];
164
+ const xml = await res.text();
165
+ const origin = new URL(base).origin;
166
+ return [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)]
167
+ .map((m) => m[1])
168
+ .filter((u) => u.startsWith(origin))
169
+ .map((u) => ({ path: new URL(u).pathname.replace(/\/+$/, "") || "/", source: "sitemap", dynamic: false }));
170
+ } catch {
171
+ return [];
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Same-origin links, breadth first, read from server HTML. A client-rendered
177
+ * app shows few links this way; capture.mjs adds the links each page renders.
178
+ */
179
+ export async function crawl(base, { limit = 40, depth = 2 } = {}) {
180
+ const origin = new URL(base).origin;
181
+ const seen = new Set(["/"]);
182
+ const failed = new Set();
183
+ let frontier = ["/"];
184
+ for (let d = 0; d < depth && frontier.length && seen.size < limit; d++) {
185
+ const next = [];
186
+ for (const path of frontier) {
187
+ let html = "";
188
+ try {
189
+ const res = await fetch(new URL(path, base), { redirect: "follow" });
190
+ if (!res.ok || !(res.headers.get("content-type") ?? "").includes("html")) {
191
+ if (!res.ok) failed.add(path);
192
+ continue;
193
+ }
194
+ html = await res.text();
195
+ } catch {
196
+ failed.add(path);
197
+ continue;
198
+ }
199
+ for (const m of html.matchAll(/<a\b[^>]*\shref=["']([^"'#]+)/gi)) {
200
+ const p = linkPath(m[1], new URL(path, base).href, origin);
201
+ if (p && !seen.has(p) && seen.size < limit) {
202
+ seen.add(p);
203
+ next.push(p);
204
+ }
205
+ }
206
+ }
207
+ frontier = next;
208
+ }
209
+ // The seed is a guess; keep it only if it answered. Linked paths stay: a broken link is a finding, not noise.
210
+ if (failed.has("/")) seen.delete("/");
211
+ return [...seen].map((path) => ({ path, source: "crawl", dynamic: false }));
212
+ }
213
+
214
+ /** A same-origin page path for an href, or null (assets, mail, other sites). */
215
+ export function linkPath(href, from, origin) {
216
+ try {
217
+ const u = new URL(href, from);
218
+ if (u.origin !== origin) return null;
219
+ if (/\.(png|jpe?g|gif|svg|webp|avif|ico|pdf|zip|css|js|mjs|json|xml|txt|mp4|webm|woff2?)$/i.test(u.pathname)) return null;
220
+ return u.pathname.replace(/\/index\.html$/, "/").replace(/\/+$/, "") || "/";
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ /** Fill a dynamic route from a concrete path that matches its shape. */
227
+ function sampleFor(route, paths) {
228
+ // A catch-all ([...slug], *) matches any path, so no known page is an example of it.
229
+ if (/\[\.\.\.|\*/.test(route.path)) return null;
230
+ const re = new RegExp("^" + route.path.split("/").map((s) => (/^\[|^:|^\$/.test(s) ? "[^/]+" : s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))).join("/") + "$");
231
+ return paths.find((p) => re.test(p) && !isDynamic(p)) ?? null;
232
+ }
233
+
234
+ /**
235
+ * Everything, merged: code first (it knows files), then the sitemap and the
236
+ * crawl. Returns `{ routes, dynamic }` — routes to visit, and parameterised
237
+ * routes still waiting for an example.
238
+ */
239
+ export async function discover({ root, base = null, limit = 40 } = {}) {
240
+ const code = root ? routesFromCode(root) : [];
241
+ const live = base ? [...(await routesFromSitemap(base)), ...(await crawl(base, { limit }))] : [];
242
+ const byPath = new Map();
243
+ for (const r of [...code, ...live]) {
244
+ const prev = byPath.get(r.path);
245
+ byPath.set(r.path, prev ? { ...prev, sources: [...new Set([...prev.sources, r.source])] } : { ...r, sources: [r.source] });
246
+ }
247
+ const all = [...byPath.values()];
248
+ const concrete = all.filter((r) => !r.dynamic).map((r) => r.path);
249
+ const dynamic = all.filter((r) => r.dynamic).map((r) => ({ ...r, sample: sampleFor(r, concrete) }));
250
+ const routes = all.filter((r) => !r.dynamic).sort((a, b) => a.path.localeCompare(b.path)).slice(0, limit);
251
+ return { routes, dynamic };
252
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A static file server for a folder, so a site with no dev server (plain HTML,
3
+ * a build output) can be walked like a running one. Localhost only, a free
4
+ * port, closed when the run ends.
5
+ */
6
+ import { createReadStream, existsSync, statSync } from "node:fs";
7
+ import { createServer } from "node:http";
8
+ import { extname, join, normalize, resolve } from "node:path";
9
+
10
+ const TYPES = {
11
+ ".html": "text/html; charset=utf-8",
12
+ ".css": "text/css; charset=utf-8",
13
+ ".js": "text/javascript; charset=utf-8",
14
+ ".mjs": "text/javascript; charset=utf-8",
15
+ ".json": "application/json",
16
+ ".svg": "image/svg+xml",
17
+ ".png": "image/png",
18
+ ".jpg": "image/jpeg",
19
+ ".jpeg": "image/jpeg",
20
+ ".gif": "image/gif",
21
+ ".webp": "image/webp",
22
+ ".avif": "image/avif",
23
+ ".ico": "image/x-icon",
24
+ ".woff": "font/woff",
25
+ ".woff2": "font/woff2",
26
+ ".txt": "text/plain; charset=utf-8",
27
+ ".xml": "application/xml",
28
+ };
29
+
30
+ export function serve(dir) {
31
+ const root = resolve(dir);
32
+ const server = createServer((req, res) => {
33
+ const url = new URL(req.url, "http://localhost");
34
+ let path = normalize(join(root, decodeURIComponent(url.pathname)));
35
+ if (!path.startsWith(root)) {
36
+ res.writeHead(403).end();
37
+ return;
38
+ }
39
+ if (existsSync(path) && statSync(path).isDirectory()) {
40
+ // As every static host does: a folder without its slash redirects, so relative links resolve inside it.
41
+ if (!url.pathname.endsWith("/")) {
42
+ res.writeHead(301, { location: url.pathname + "/" + url.search }).end();
43
+ return;
44
+ }
45
+ path = join(path, "index.html");
46
+ }
47
+ else if (!existsSync(path) && existsSync(path + ".html")) path += ".html";
48
+ if (!existsSync(path)) {
49
+ res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
50
+ return;
51
+ }
52
+ res.writeHead(200, { "content-type": TYPES[extname(path).toLowerCase()] ?? "application/octet-stream" });
53
+ createReadStream(path).pipe(res);
54
+ });
55
+ return new Promise((ok) => {
56
+ server.listen(0, "127.0.0.1", () => {
57
+ const { port } = server.address();
58
+ ok({ url: `http://127.0.0.1:${port}`, close: () => new Promise((done) => server.close(done)) });
59
+ });
60
+ });
61
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Walk a running product: every route × viewport × theme, one fresh browser
3
+ * context per pass. The first pass also follows the links each page renders,
4
+ * so a client-side app's pages are found even when its server HTML shows none.
5
+ *
6
+ * `walk()` returns a run (see findings.mjs) with the pages, their shots and the
7
+ * runtime findings every walk can make: pages that fail to load, error
8
+ * statuses, console errors, uncaught exceptions and failed requests. Callers
9
+ * pass `probes` to measure more inside each page and `judge` to turn what they
10
+ * measured into findings: the audit and the smoke test are both a walk plus
11
+ * their own probes and judges. `probeFor(viewport, theme, route)` adds probes
12
+ * that depend on the pass.
13
+ */
14
+ import { add, newRun } from "./findings.mjs";
15
+ import { THEMES, openContext, shotKey, visit, withHelpers } from "./capture.mjs";
16
+ import { discover } from "./routes.mjs";
17
+ import { launch } from "./playwright.mjs";
18
+
19
+ export async function walk({
20
+ kind = "capture",
21
+ title = null,
22
+ base,
23
+ root = null,
24
+ out,
25
+ routes = null,
26
+ limit = 40,
27
+ viewports = ["desktop", "phone"],
28
+ themes = THEMES,
29
+ probes = [],
30
+ probeFor = null,
31
+ judge = null,
32
+ headless = true,
33
+ reducedMotion = false,
34
+ // Optional, for callers that drive more than a walk (the smoke test):
35
+ browser: shared = null, // a browser already launched; left open
36
+ storageState = undefined, // a signed-in session for every context
37
+ prepare = null, // async (context, { viewport, theme }) before any page opens: route guards, init scripts
38
+ follow = () => true, // (path) => whether to follow a link the page rendered
39
+ log = (m) => process.stderr.write(m + "\n"),
40
+ }) {
41
+ const run = newRun({ kind, title, base, root });
42
+ const found = routes ? { routes: routes.map((path) => ({ path, sources: ["given"] })), dynamic: [] } : await discover({ root, base, limit });
43
+ const queue = found.routes.map((r) => r.path);
44
+ const known = new Set(queue);
45
+ for (const d of found.dynamic) {
46
+ if (d.sample && !known.has(d.sample)) {
47
+ queue.push(d.sample);
48
+ known.add(d.sample);
49
+ }
50
+ }
51
+ run.dynamic = found.dynamic.map((d) => ({ path: d.path, sample: d.sample, file: d.file ?? null }));
52
+
53
+ const browser = shared ?? (await launch({ root: root ?? process.cwd(), headless, log }));
54
+ const pages = new Map();
55
+ try {
56
+ let first = true;
57
+ for (const viewport of viewports) {
58
+ for (const theme of themes) {
59
+ const context = await withHelpers(await openContext(browser, { viewport, theme, reducedMotion, storageState }));
60
+ if (prepare) await prepare(context, { viewport, theme });
61
+ for (let i = 0; i < queue.length; i++) {
62
+ const route = queue[i];
63
+ log(` ${viewport} ${theme} ${route}`);
64
+ const v = await visit(context, { base, route, out, viewport, theme, probes: probeFor ? [...probes, ...probeFor(viewport, theme, route)] : probes });
65
+ if (first) {
66
+ for (const link of v.links) {
67
+ if (!known.has(link) && known.size < limit && follow(link)) {
68
+ known.add(link);
69
+ queue.push(link);
70
+ }
71
+ }
72
+ }
73
+ const page = pages.get(route) ?? { route, url: v.url, title: v.title, status: v.status, finalUrl: v.finalUrl, shots: {} };
74
+ if (v.shot) page.shots[shotKey(viewport, theme)] = v.shot;
75
+ pages.set(route, page);
76
+ runtimeFindings(run, v, first);
77
+ if (judge) await judge(run, v);
78
+ }
79
+ await context.close();
80
+ first = false;
81
+ }
82
+ }
83
+ } finally {
84
+ if (!shared) await browser.close();
85
+ }
86
+ run.pages = [...pages.values()];
87
+ return run;
88
+ }
89
+
90
+ /** What any walk can say about a page from its load alone. Console and network only on the first pass, so one bug isn't reported four times. */
91
+ export function runtimeFindings(run, v, firstPass) {
92
+ const at = { page: v.route, viewport: v.viewport, theme: v.theme, shot: v.shot ? shotKey(v.viewport, v.theme) : undefined };
93
+ if (v.navError) {
94
+ add(run, { ...at, rule: "runtime/load-failed", severity: "error", title: "The page didn't load", evidence: v.navError, detail: "Opening this URL failed or timed out, so nothing on it could be checked." });
95
+ return;
96
+ }
97
+ if (v.status >= 400) {
98
+ add(run, { ...at, rule: "runtime/http-status", severity: "error", title: `The page answers ${v.status}`, evidence: `HTTP ${v.status}`, detail: "A route the product links to or declares returns an error status." });
99
+ }
100
+ if (!firstPass) return;
101
+ for (const e of v.log.pageErrors) {
102
+ add(run, { ...at, rule: "runtime/exception", severity: "error", title: "An uncaught exception on load", evidence: e.text, detail: "Script threw while the page loaded. Whatever ran after it may be missing." });
103
+ }
104
+ // The browser logs every failed request as a console error too; those are reported once, as requests.
105
+ for (const e of v.log.console.filter((c) => c.type === "error" && !/^Failed to load resource/.test(c.text))) {
106
+ add(run, { ...at, rule: "runtime/console-error", severity: "warning", title: "A console error on load", evidence: e.text });
107
+ }
108
+ for (const r of v.log.failedRequests) {
109
+ add(run, {
110
+ ...at,
111
+ rule: "runtime/request-failed",
112
+ severity: r.sameOrigin ? "error" : "warning",
113
+ title: r.sameOrigin ? "A request to the product failed" : "A third-party request failed",
114
+ evidence: `${r.method} ${r.url.slice(0, 160)} → ${r.status ?? r.error}`,
115
+ });
116
+ }
117
+ }
package/browse.mjs ADDED
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Keyline's browser tools: the pages a product has, a walk through them, and
3
+ * the report. The audit and the smoke test are built on these.
4
+ *
5
+ * keyline pages [--root .] [--base URL] [--json]
6
+ * keyline capture (--base URL | --serve DIR) [--root .] [--out keyline-report]
7
+ * keyline report [DIR] [--compare PREVIOUS-DIR]
8
+ *
9
+ * Exit codes: 0 done, 1 the walk found errors, 2 a usage error.
10
+ */
11
+ import { existsSync, rmSync } from "node:fs";
12
+ import { resolve } from "node:path";
13
+ import { parseOrExplain } from "./browse/args.mjs";
14
+ import { counts, writeRun } from "./browse/findings.mjs";
15
+ import { renderDir } from "./browse/report.mjs";
16
+ import { compareDirs } from "./browse/compare.mjs";
17
+ import { discover } from "./browse/routes.mjs";
18
+ import { serve } from "./browse/serve.mjs";
19
+ import { walk } from "./browse/walk.mjs";
20
+
21
+ const USAGE = `keyline browse — find a product's pages, walk them, and report.
22
+
23
+ keyline pages [--root .] [--base URL] [--json]
24
+ Every route: from the router's files, the sitemap and a crawl.
25
+
26
+ keyline capture (--base URL | --serve DIR) [options]
27
+ Visit every page at desktop and phone, light and dark; screenshot each,
28
+ record load failures, error statuses, console errors, exceptions and
29
+ failed requests; write findings.json and index.html.
30
+
31
+ keyline report [DIR] [--compare PREVIOUS-DIR]
32
+ Re-render DIR/index.html from DIR/findings.json (default keyline-report).
33
+ With --compare, first mark each finding new, still or back since the
34
+ run in PREVIOUS-DIR, list what was fixed, and diff the screenshots.
35
+
36
+ Options:
37
+ --base <url> the running product, e.g. http://localhost:3000
38
+ --serve <dir> serve a static folder on a free port instead
39
+ --root <dir> the project's code, for routes (default: .)
40
+ --out <dir> where the report goes (default: keyline-report)
41
+ --routes <a,b> only these paths
42
+ --limit <n> at most this many pages (default 40)
43
+ --viewports <list> desktop,phone (default both)
44
+ --themes <list> light,dark (default both)
45
+ --headed show the browser
46
+ --json pages as JSON
47
+ --compare <dir> an earlier report to compare with (report, capture)
48
+ --threshold <pct> a page whose screenshot changed more than this gets a
49
+ visual/changed note (default 0.01; one changed heading
50
+ on a 1440×900 page is about 0.08)
51
+ --no-diff compare findings only, not screenshots
52
+ -h, --help this`;
53
+
54
+ /** What pages, capture and report take. */
55
+ export const BROWSE_OPTIONS = {
56
+ values: ["base", "serve", "root", "out", "routes", "limit", "viewports", "themes", "compare", "threshold"],
57
+ switches: ["headed", "json", "no-diff"],
58
+ };
59
+
60
+ const list = (v, fallback) => (v ? String(v).split(",").map((s) => s.trim()).filter(Boolean) : fallback);
61
+
62
+ /** The base URL to walk: the one given, or a static server over --serve. */
63
+ export async function target(opts) {
64
+ if (opts.base) return { base: opts.base, root: resolve(opts.root ?? "."), stop: async () => {} };
65
+ if (opts.serve) {
66
+ const dir = resolve(opts.serve);
67
+ if (!existsSync(dir)) throw new Error(`no folder ${opts.serve}`);
68
+ const s = await serve(dir);
69
+ return { base: s.url, root: resolve(opts.root ?? dir), stop: s.close };
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /** Why `--compare` can't run, or null. A capture writes over its own folder, so the earlier run must live elsewhere. */
75
+ function compareProblem(dir, prev, { before = false } = {}) {
76
+ const p = resolve(prev);
77
+ if (p === dir) return `--compare needs an earlier report in another folder: ${before ? "a capture writes over its own, so copy it first (cp -R keyline-report keyline-report-before) or pass --out" : "this is the same one"}`;
78
+ if (!existsSync(`${p}/findings.json`)) return `no findings.json in ${prev} to compare with`;
79
+ return null;
80
+ }
81
+
82
+ const compareOptions = (opts) => ({ diff: !opts["no-diff"], threshold: Number(opts.threshold ?? 0.01) });
83
+
84
+ function sinceLine(run) {
85
+ const c = run.compare;
86
+ const v = c.visual;
87
+ return `Since ${c.against}: ${c.new} new · ${c.returned} back · ${c.still} still · ${c.fixed} fixed${v ? ` · ${v.changed} of ${v.compared} screenshots changed` : ""}`;
88
+ }
89
+
90
+ export async function run(argv) {
91
+ const opts = parseOrExplain(["pages", "capture", "report"].includes(argv[0]) ? argv[0] : "browse", argv, BROWSE_OPTIONS);
92
+ if (!opts) return 2;
93
+ const [cmd, arg] = opts._;
94
+ if (opts.help || !cmd) {
95
+ console.log(USAGE);
96
+ return cmd ? 0 : 2;
97
+ }
98
+
99
+ if (cmd === "report") {
100
+ const dir = resolve(arg ?? opts.out ?? "keyline-report");
101
+ if (opts.compare) {
102
+ const err = compareProblem(dir, opts.compare);
103
+ if (err) {
104
+ console.error(err);
105
+ return 2;
106
+ }
107
+ const run = await compareDirs(dir, resolve(opts.compare), compareOptions(opts));
108
+ console.log(sinceLine(run));
109
+ }
110
+ console.log(renderDir(dir));
111
+ return 0;
112
+ }
113
+
114
+ if (cmd === "pages") {
115
+ const t = await target(opts);
116
+ const found = await discover({ root: t?.root ?? resolve(opts.root ?? "."), base: t?.base ?? null, limit: Number(opts.limit ?? 200) });
117
+ await t?.stop();
118
+ if (opts.json) {
119
+ console.log(JSON.stringify(found, null, 2));
120
+ return 0;
121
+ }
122
+ for (const r of found.routes) console.log(`${r.path.padEnd(40)} ${r.sources.join(", ")}`);
123
+ if (found.dynamic.length) {
124
+ console.log(`\nNeed an example to visit:`);
125
+ for (const d of found.dynamic) console.log(`${d.path.padEnd(40)} ${d.sample ? `→ ${d.sample}` : "no example found"}`);
126
+ }
127
+ return 0;
128
+ }
129
+
130
+ if (cmd === "capture") {
131
+ const t = await target(opts);
132
+ if (!t) {
133
+ console.error("capture needs --base <url> or --serve <dir>\n");
134
+ console.error(USAGE);
135
+ return 2;
136
+ }
137
+ const out = resolve(opts.out ?? "keyline-report");
138
+ if (opts.compare) {
139
+ const err = compareProblem(out, opts.compare, { before: true });
140
+ if (err) {
141
+ await t.stop();
142
+ console.error(err);
143
+ return 2;
144
+ }
145
+ }
146
+ if (existsSync(`${out}/shots`)) rmSync(`${out}/shots`, { recursive: true });
147
+ if (existsSync(`${out}/diffs`)) rmSync(`${out}/diffs`, { recursive: true });
148
+ try {
149
+ const result = await walk({
150
+ kind: "capture",
151
+ base: t.base,
152
+ root: t.root,
153
+ out,
154
+ routes: opts.routes ? list(opts.routes) : null,
155
+ limit: Number(opts.limit ?? 40),
156
+ viewports: list(opts.viewports, ["desktop", "phone"]),
157
+ themes: list(opts.themes, ["light", "dark"]),
158
+ headless: !opts.headed,
159
+ });
160
+ writeRun(out, result);
161
+ const final = opts.compare ? await compareDirs(out, resolve(opts.compare), compareOptions(opts)) : result;
162
+ const file = renderDir(out);
163
+ const c = counts(final.findings);
164
+ // Against an earlier run, only errors this run added fail it, as with the detector's baseline.
165
+ const failing = final.compare ? counts(final.findings.filter((f) => f.change === "new" || f.change === "returned")) : c;
166
+ console.log(`\n${final.pages.length} pages · ${c.error} errors · ${c.warning} warnings · ${c.info} notes${final.compare ? `\n${sinceLine(final)}` : ""}\n${file}`);
167
+ return failing.error ? 1 : 0;
168
+ } finally {
169
+ await t.stop();
170
+ }
171
+ }
172
+
173
+ console.error(`no command '${cmd}'\n\n${USAGE}`);
174
+ return 2;
175
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "trykeyline-browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Keyline's browser tools: find a product's pages, walk them at desktop and phone in light and dark, and report what the audit and the smoke test find. Run through `npx trykeyline audit|smoke|pages|capture|report|probe`.",
5
+ "keywords": [
6
+ "design",
7
+ "ui",
8
+ "accessibility",
9
+ "audit",
10
+ "smoke-test",
11
+ "playwright",
12
+ "agent-skills",
13
+ "claude-code"
14
+ ],
15
+ "homepage": "https://github.com/Mihirmodi27/keyline#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Mihirmodi27/keyline.git",
19
+ "directory": "packages/browser"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Mihir Modi (https://modimihir.com)",
23
+ "type": "module",
24
+ "bin": {
25
+ "trykeyline-browser": "bin/trykeyline-browser.mjs"
26
+ },
27
+ "files": [
28
+ "bin",
29
+ "browse",
30
+ "smoke",
31
+ "audit",
32
+ "browse.mjs",
33
+ "smoke.mjs",
34
+ "audit.mjs",
35
+ "probe.mjs"
36
+ ],
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "dependencies": {
41
+ "trykeyline": "0.2.0"
42
+ },
43
+ "peerDependencies": {
44
+ "playwright": "^1.40.0"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "playwright": {
48
+ "optional": true
49
+ }
50
+ },
51
+ "scripts": {
52
+ "pretest": "node link.mjs",
53
+ "test": "node --test \"test/**/*.test.mjs\""
54
+ }
55
+ }