architecture-harness 0.22.0 → 0.23.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/package.json +23 -3
- package/src/cli/bash-command-guard.mjs +44 -5
- package/src/cli/bash-command-guard.test.mjs +35 -1
- package/src/cli/check-commands.mjs +82 -0
- package/src/cli/check-commands.test.mjs +190 -0
- package/src/cli/check.mjs +34 -13
- package/src/cli/ci-template.test.mjs +12 -0
- package/src/cli/cli.test.mjs +17 -1
- package/src/cli/codex-implement.mjs +7 -2
- package/src/cli/codex-implement.test.mjs +29 -0
- package/src/cli/commit-msg.mjs +5 -2
- package/src/cli/commit-msg.test.mjs +12 -0
- package/src/cli/dispatch-reminder.mjs +4 -1
- package/src/cli/dispatch-reminder.test.mjs +5 -1
- package/src/cli/generated-file-guard.mjs +10 -1
- package/src/cli/generated-file-guard.test.mjs +10 -0
- package/src/cli/git-hooks.test.mjs +5 -0
- package/src/cli/post-edit-gate.test.mjs +9 -2
- package/src/cli/pr-check.mjs +15 -2
- package/src/cli/pr-check.test.mjs +19 -9
- package/src/cli/qc.mjs +27 -3
- package/src/cli/screens-discovery.mjs +60 -0
- package/src/cli/screens.mjs +84 -0
- package/src/cli/shell-command.mjs +3 -1
- package/src/cli/stack.mjs +14 -0
- package/src/cli/stop-gate.test.mjs +17 -0
- package/src/cli/work-order-guard.mjs +2 -2
- package/src/config.mjs +15 -0
- package/src/config.test.mjs +33 -1
- package/src/eslint/rules/no-raw-fetch.mjs +42 -2
- package/src/eslint/rules.test.mjs +15 -0
- package/src/gates/audit-append-only.mjs +18 -4
- package/src/gates/audit-append-only.test.mjs +19 -0
- package/src/gates/tenant-predicate.mjs +147 -7
- package/src/gates/tenant-predicate.test.mjs +55 -0
- package/src/gates/tenant-tables.mjs +5 -2
- package/src/gates/tenant-tables.test.mjs +8 -0
- package/src/gates/threshold-ratchet.mjs +12 -9
- package/src/gates/threshold-ratchet.test.mjs +16 -0
- package/src/plugin.test.mjs +28 -0
- package/src/screens/auth-context.test.mjs +41 -0
- package/src/screens/auth-run.test.mjs +147 -0
- package/src/screens/auth.mjs +223 -0
- package/src/screens/auth.test.mjs +76 -0
- package/src/screens/capture-idle.test.mjs +27 -0
- package/src/screens/capture.browser-test.mjs +73 -0
- package/src/screens/capture.mjs +175 -0
- package/src/screens/capture.test.mjs +28 -0
- package/src/screens/catalog.browser-test.mjs +32 -0
- package/src/screens/catalog.mjs +72 -0
- package/src/screens/catalog.test.mjs +36 -0
- package/src/screens/chrome.mjs +21 -0
- package/src/screens/compare.mjs +40 -0
- package/src/screens/compare.test.mjs +30 -0
- package/src/screens/discovery.browser-test.mjs +29 -0
- package/src/screens/discovery.mjs +158 -0
- package/src/screens/discovery.test.mjs +27 -0
- package/src/screens/inventory.mjs +69 -0
- package/src/screens/inventory.test.mjs +10 -0
- package/src/screens/map.mjs +63 -0
- package/src/screens/map.test.mjs +35 -0
- package/src/screens/open.browser-test.mjs +50 -0
- package/src/screens/regions.mjs +137 -0
- package/src/screens/regions.test.mjs +38 -0
- package/src/screens/session-files.mjs +39 -0
- package/src/screens/session-files.test.mjs +39 -0
- package/src/screens/setup.browser-test.mjs +49 -0
- package/src/screens/setup.mjs +78 -0
- package/src/screens/stack-auth.browser-test.mjs +30 -0
- package/src/screens/stack-auth.mjs +106 -0
- package/src/screens/stack-auth.test.mjs +65 -0
- package/src/screens/write-guard.mjs +26 -0
- package/src/stack/stack.mjs +131 -0
- package/src/stack/stack.test.mjs +40 -0
- package/src/stack/supervisor.mjs +30 -0
- package/templates/github/workflows/ci.yml +13 -5
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { PNG } from "pngjs";
|
|
5
|
+
import { targetSession } from "./stack-auth.mjs";
|
|
6
|
+
import { compareImages, gallery, sortReport } from "./compare.mjs";
|
|
7
|
+
import { stableCapture, findRegions, regionCrop, boxPair } from "./regions.mjs";
|
|
8
|
+
import { collectInventory, diffInventory, inventoryBox } from "./inventory.mjs";
|
|
9
|
+
import { openScreen } from "./catalog.mjs";
|
|
10
|
+
import { safeControl, installWriteGuard } from "./write-guard.mjs";
|
|
11
|
+
|
|
12
|
+
/** Branch: a typo must never silently skip a requested screen. */
|
|
13
|
+
export function selectScreens(screens, only) {
|
|
14
|
+
if (!only) return screens;
|
|
15
|
+
const names = only.split(",").map(name => name.trim());
|
|
16
|
+
for (const name of names) if (!screens.some(screen => screen.name === name)) throw new Error(`Unknown screen ${name}`);
|
|
17
|
+
return screens.filter(screen => names.includes(screen.name));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Record: bind a cached image to its viewport, target, navigation, and masks. */
|
|
21
|
+
export function captureKey(target, route, width, height) {
|
|
22
|
+
return createHash("sha256").update(JSON.stringify({ baseUrl: target.baseUrl, route, width, height })).digest("hex");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Ledger: a filtered rerun preserves rows for the same pair. */
|
|
26
|
+
export function mergeReport(previous, fresh) {
|
|
27
|
+
const keys = new Set(fresh.map(row => `${row.screen}@${row.width}`));
|
|
28
|
+
const targets = JSON.stringify(fresh[0]?.targets);
|
|
29
|
+
return sortReport([...previous.filter(row => JSON.stringify(row.targets) === targets && !keys.has(`${row.screen}@${row.width}`)), ...fresh]);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Branch: capture navigation excludes mutation controls. */
|
|
33
|
+
export function safeClick(control) {
|
|
34
|
+
return safeControl(control);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function readJson(file, fallback) {
|
|
38
|
+
return existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : fallback;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function writeJson(file, value) {
|
|
42
|
+
writeFileSync(`${file}.tmp`, `${JSON.stringify(value, null, 2)}\n`);
|
|
43
|
+
renameSync(`${file}.tmp`, file);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Pipeline: wait for page resources before recording the viewport. */
|
|
47
|
+
export async function capturePage(session, target, route, width, height, file, timeout, navigation = {}) {
|
|
48
|
+
const { page } = session;
|
|
49
|
+
await page.setViewportSize({ width, height });
|
|
50
|
+
if (route.open) await openScreen(page, target, route, { ...navigation, timeout });
|
|
51
|
+
const expected = new URL(route.path ?? page.url(), target.baseUrl);
|
|
52
|
+
const response = route.open ? null : await page.goto(expected.href, { waitUntil: "domcontentloaded", timeout });
|
|
53
|
+
if (response && response.status() >= 400) throw new Error(`Capture received HTTP ${response.status()}`);
|
|
54
|
+
await page.emulateMedia({ reducedMotion: "reduce" });
|
|
55
|
+
await page.addStyleTag({ content: "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}" });
|
|
56
|
+
// A full-screen viewer has no header, so an entry's own ready selector replaces the signed-in check.
|
|
57
|
+
if (!route.ready) await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
58
|
+
for (const step of route.clicks ?? []) {
|
|
59
|
+
const selector = typeof step === "string" ? step : step.selector;
|
|
60
|
+
const control = page.locator(selector).first();
|
|
61
|
+
if (step.optional) {
|
|
62
|
+
try { await control.waitFor({ state: "visible", timeout: Math.min(timeout, 1500) }); }
|
|
63
|
+
catch (error) { if (error.name === "TimeoutError") continue; throw error; }
|
|
64
|
+
}
|
|
65
|
+
const description = await control.evaluate(element => ({ type: element.getAttribute("type") ?? (element.tagName === "BUTTON" && element.closest("form") ? "submit" : ""), text: `${element.textContent} ${element.getAttribute("aria-label") ?? ""}` }));
|
|
66
|
+
if (!safeClick(description)) throw new Error("Capture navigation refuses a mutation control");
|
|
67
|
+
await control.click({ timeout });
|
|
68
|
+
}
|
|
69
|
+
if (route.ready) await page.locator(route.ready).first().waitFor({ state: "visible", timeout });
|
|
70
|
+
const actual = new URL(page.url());
|
|
71
|
+
if (actual.origin !== expected.origin || actual.pathname !== expected.pathname || actual.search !== expected.search) throw new Error("Capture reached a URL other than the mapped screen");
|
|
72
|
+
if (await page.locator('input[type="password"]:visible, [role="alert"][data-error]:visible').count()) throw new Error("Capture reached a sign-in or error page");
|
|
73
|
+
await page.mouse.move(0, 0);
|
|
74
|
+
// A page that polls never goes idle, so its entry sets `idle: false` and relies on `ready`.
|
|
75
|
+
if (route.idle !== false) await page.waitForLoadState("networkidle", { timeout });
|
|
76
|
+
await page.evaluate(() => document.fonts.ready);
|
|
77
|
+
const inventory = await collectInventory(page, [...(route.masks ?? []), ...(route.exclude ?? [])]);
|
|
78
|
+
writeJson(file.replace(/\.png$/, ".inventory.json"), inventory);
|
|
79
|
+
const capture = () => page.screenshot({ animations: "disabled", caret: "hide", fullPage: false, mask: (route.masks ?? []).map(selector => page.locator(selector)), maskColor: "#808080", timeout }).then(buffer => PNG.sync.read(buffer));
|
|
80
|
+
const full = await stableCapture(capture);
|
|
81
|
+
writeFileSync(file, PNG.sync.write(full.image));
|
|
82
|
+
const style = await page.addStyleTag({ content: "*,*::before,*::after{color:transparent!important;text-shadow:none!important;-webkit-text-fill-color:transparent!important}img,canvas,video,svg{visibility:hidden!important}*:has(>img),*:has(>canvas),*:has(>video),*:has(>svg){background:#808080!important}input,textarea{color:transparent!important}" });
|
|
83
|
+
const layout = await stableCapture(capture);
|
|
84
|
+
await style.evaluate(element => element.remove());
|
|
85
|
+
writeFileSync(file.replace(/\.png$/, ".layout.png"), PNG.sync.write(layout.image));
|
|
86
|
+
const unstable = new PNG({ width, height });
|
|
87
|
+
for (const mask of [full.unstable, layout.unstable].filter(Boolean)) for (let i = 3; i < mask.data.length; i += 4) if (mask.data[i]) unstable.data.set([255, 0, 0, 255], i - 3);
|
|
88
|
+
writeFileSync(file.replace(/\.png$/, ".unstable.png"), PNG.sync.write(unstable));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Pipeline: authenticate, capture each viewport, compare, and publish the gallery. */
|
|
92
|
+
export async function captureScreens(map, options, { chromium, say = console.error, sessionFactory = targetSession } = {}) {
|
|
93
|
+
const { targets, out, only, changed, timeout = 15000, signInTimeout = 180000, height = 900, allowWrites = false } = options;
|
|
94
|
+
if (targets.length !== 2 || targets.some(name => !map.targets[name])) throw new Error("Choose two targets from the map");
|
|
95
|
+
if (changed && !targets.includes(changed)) throw new Error("--changed must name one of the two targets");
|
|
96
|
+
const screens = selectScreens(map.screens, only);
|
|
97
|
+
for (const screen of screens) for (const name of targets) if (!screen.targets[name]) throw new Error(`Screen ${screen.name} lacks target ${name}`);
|
|
98
|
+
mkdirSync(out, { recursive: true });
|
|
99
|
+
const cacheFile = path.join(out, "captures.json");
|
|
100
|
+
const cache = readJson(cacheFile, {});
|
|
101
|
+
const sessions = new Map();
|
|
102
|
+
const fresh = [];
|
|
103
|
+
const failures = new Map();
|
|
104
|
+
try {
|
|
105
|
+
for (const name of targets) {
|
|
106
|
+
const session = await sessionFactory(chromium, map.targets[name], { timeout, signInTimeout, say, targetName: name, allowInteractive: false, allowWrites });
|
|
107
|
+
sessions.set(name, session);
|
|
108
|
+
await installWriteGuard(session.context, map.targets[name], { allowWrites });
|
|
109
|
+
}
|
|
110
|
+
for (const name of targets) {
|
|
111
|
+
const target = map.targets[name];
|
|
112
|
+
if (changed && changed !== name) {
|
|
113
|
+
for (const screen of screens) for (const width of map.widths) {
|
|
114
|
+
const relative = `${screen.name}/${name}@${width}.png`;
|
|
115
|
+
if (![relative, relative.replace(/\.png$/, ".layout.png"), relative.replace(/\.png$/, ".unstable.png"), relative.replace(/\.png$/, ".inventory.json")].every(file => existsSync(path.join(out, file))) || cache[relative] !== captureKey(target, screen.targets[name], width, height)) throw new Error(`Cached capture missing or stale: ${relative}; run both targets first`);
|
|
116
|
+
}
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const session = sessions.get(name);
|
|
120
|
+
for (const screen of screens) {
|
|
121
|
+
mkdirSync(path.join(out, screen.name), { recursive: true });
|
|
122
|
+
for (const width of map.widths) {
|
|
123
|
+
const relative = `${screen.name}/${name}@${width}.png`;
|
|
124
|
+
try {
|
|
125
|
+
await capturePage(session, target, screen.targets[name], width, height, path.join(out, relative), timeout, { targetName: name, screenName: screen.name, out });
|
|
126
|
+
} catch (error) {
|
|
127
|
+
failures.set(`${screen.name}@${width}`, { target: name, step: error.step ?? "Capture", screenshot: error.screenshot, message: error.message });
|
|
128
|
+
say(error.message);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
cache[relative] = captureKey(target, screen.targets[name], width, height);
|
|
132
|
+
writeJson(cacheFile, cache);
|
|
133
|
+
say(`Captured ${relative}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
await session.close();
|
|
137
|
+
sessions.delete(name);
|
|
138
|
+
}
|
|
139
|
+
for (const screen of screens) for (const width of map.widths) {
|
|
140
|
+
const error = failures.get(`${screen.name}@${width}`);
|
|
141
|
+
if (error) { fresh.push({ screen: screen.name, width, targets, error, regions: [], inventoryFindings: [] }); continue; }
|
|
142
|
+
const images = targets.map(name => PNG.sync.read(readFileSync(path.join(out, screen.name, `${name}@${width}.png`))));
|
|
143
|
+
const { pair, ...diff } = compareImages(...images);
|
|
144
|
+
const layouts = targets.map(name => PNG.sync.read(readFileSync(path.join(out, screen.name, `${name}@${width}.layout.png`))));
|
|
145
|
+
const unstable = new PNG({ width: layouts[0].width, height: layouts[0].height });
|
|
146
|
+
for (const name of targets) {
|
|
147
|
+
const mask = PNG.sync.read(readFileSync(path.join(out, screen.name, `${name}@${width}.unstable.png`)));
|
|
148
|
+
for (let i = 3; i < mask.data.length; i += 4) if (mask.data[i]) unstable.data.set([255, 0, 0, 255], i - 3);
|
|
149
|
+
}
|
|
150
|
+
const regions = findRegions(...layouts, { unstable: [unstable] });
|
|
151
|
+
for (const region of regions) {
|
|
152
|
+
region.crop = `${screen.name}/region-${region.id}@${width}.png`;
|
|
153
|
+
writeFileSync(path.join(out, region.crop), PNG.sync.write(regionCrop(...images, region.box)));
|
|
154
|
+
}
|
|
155
|
+
const inventories = targets.map(name => readJson(path.join(out, screen.name, `${name}@${width}.inventory.json`), []));
|
|
156
|
+
const inventoryFindings = diffInventory(...inventories);
|
|
157
|
+
for (const finding of inventoryFindings) {
|
|
158
|
+
finding.id += regions.length;
|
|
159
|
+
finding.box = inventoryBox(finding, images[0].width, images[0].height);
|
|
160
|
+
finding.crop = `${screen.name}/inventory-${finding.id}@${width}.png`;
|
|
161
|
+
writeFileSync(path.join(out, finding.crop), PNG.sync.write(regionCrop(...images, finding.box)));
|
|
162
|
+
}
|
|
163
|
+
const relative = `${screen.name}/pair@${width}.png`;
|
|
164
|
+
writeFileSync(path.join(out, relative), PNG.sync.write(boxPair(pair, [...regions, ...inventoryFindings])));
|
|
165
|
+
fresh.push({ screen: screen.name, width, targets, ...diff, regions, inventoryFindings, pair: relative });
|
|
166
|
+
}
|
|
167
|
+
const reportFile = path.join(out, "report.json");
|
|
168
|
+
const report = only ? mergeReport(readJson(reportFile, []), fresh) : sortReport(fresh);
|
|
169
|
+
writeJson(reportFile, report);
|
|
170
|
+
writeFileSync(path.join(out, "index.html"), gallery(report));
|
|
171
|
+
return report;
|
|
172
|
+
} finally {
|
|
173
|
+
for (const session of sessions.values()) await session.close();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { selectScreens, captureKey, mergeReport, safeClick } from "./capture.mjs";
|
|
4
|
+
|
|
5
|
+
test("only selects named screens and refuses unknown names", () => {
|
|
6
|
+
const screens = [{ name: "projects" }, { name: "photos" }, { name: "drawings" }];
|
|
7
|
+
assert.deepEqual(selectScreens(screens, "photos,drawings").map(s => s.name), ["photos", "drawings"]);
|
|
8
|
+
assert.throws(() => selectScreens(screens, "typo"), /Unknown/);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test("cached captures change identity when routes or masks change", () => {
|
|
12
|
+
const target = { baseUrl: "https://app.example" };
|
|
13
|
+
const key = captureKey(target, { path: "/projects" }, 390, 900);
|
|
14
|
+
assert.notEqual(captureKey(target, { path: "/photos" }, 390, 900), key);
|
|
15
|
+
assert.notEqual(captureKey(target, { path: "/projects", masks: ["main"] }, 390, 900), key);
|
|
16
|
+
assert.notEqual(captureKey(target, { path: "/projects" }, 390, 800), key);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("filtered report replaces matching rows and preserves other screens", () => {
|
|
20
|
+
const old = [{ screen: "photos", width: 390, targets: ["a", "b"], diffPercent: 50 }, { screen: "projects", width: 390, targets: ["a", "b"], diffPercent: 10 }];
|
|
21
|
+
const fresh = [{ screen: "photos", width: 390, targets: ["a", "b"], diffPercent: 0 }];
|
|
22
|
+
assert.deepEqual(mergeReport(old, fresh).map(r => [r.screen, r.diffPercent]), [["projects", 10], ["photos", 0]]);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("hosted navigation rejects mutation controls", () => {
|
|
26
|
+
for (const control of [{ type: "submit", text: "Continue" }, { type: "button", text: "Delete project" }, { type: "button", text: "Save" }, { type: "button", text: "Complete" }]) assert.equal(safeClick(control), false);
|
|
27
|
+
assert.equal(safeClick({ type: "button", text: "Photos" }), true);
|
|
28
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, existsSync, rmSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import { chromium } from "playwright";
|
|
7
|
+
import { captureScreens } from "./capture.mjs";
|
|
8
|
+
|
|
9
|
+
test("a failing catalog step records its screenshot while the other screen completes", async () => {
|
|
10
|
+
const out = mkdtempSync(path.join(os.tmpdir(), "qc-catalog-browser-"));
|
|
11
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
12
|
+
const target = { baseUrl: "https://screens.example", auth: { signedIn: "main" } };
|
|
13
|
+
const route = fail => ({ path: fail ? "/bad" : "/good", ready: "main", open: async (page, ctx) => {
|
|
14
|
+
await ctx.step("Navigate", () => page.goto(`${ctx.baseUrl}/${fail ? "bad" : "good"}`));
|
|
15
|
+
if (fail) await ctx.step("Open viewer", () => page.getByRole("button", { name: "Missing", exact: true }).click({ timeout: 100 }));
|
|
16
|
+
} });
|
|
17
|
+
try {
|
|
18
|
+
const report = await captureScreens({ widths: [200], targets: { a: target, b: target }, screens: ["bad", "good"].map(name => ({ name, targets: { a: route(name === "bad"), b: route(name === "bad") } })) }, { targets: ["a", "b"], out, timeout: 3000, height: 100 }, {
|
|
19
|
+
chromium, say: () => {}, sessionFactory: async () => {
|
|
20
|
+
const context = await browser.newContext({ serviceWorkers: "block" });
|
|
21
|
+
const page = await context.newPage();
|
|
22
|
+
await page.route("**/*", route => route.fulfill({ contentType: "text/html", body: '<main><h1>Fixture</h1><a href="/good">Good page</a></main>' }));
|
|
23
|
+
return { context, page, close: () => context.close() };
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
const bad = report.find(row => row.screen === "bad");
|
|
27
|
+
assert.equal(bad.error.step, "Open viewer");
|
|
28
|
+
assert.equal(existsSync(path.join(out, bad.error.screenshot)), true);
|
|
29
|
+
assert.equal(report.find(row => row.screen === "good").diffPercent, 0);
|
|
30
|
+
assert.equal(existsSync(path.join(out, "good/pair@200.png")), true);
|
|
31
|
+
} finally { await browser.close(); rmSync(out, { recursive: true, force: true }); }
|
|
32
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { privateRoot } from "./auth.mjs";
|
|
5
|
+
|
|
6
|
+
/** Record: catalog names are portable paths below the output directory. */
|
|
7
|
+
export function screen(entry) {
|
|
8
|
+
if (!/^[a-z0-9_-]+(?:\/[a-z0-9_-]+)*$/i.test(entry.name ?? "")) throw new Error("Invalid catalog screen name");
|
|
9
|
+
if (!entry.open || typeof entry.open !== "object") throw new Error(`Screen ${entry.name} requires open functions`);
|
|
10
|
+
return entry;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Resource: each area exports entries or an array of entries. */
|
|
14
|
+
export async function loadCatalog(directory) {
|
|
15
|
+
const entries = [];
|
|
16
|
+
const walk = async dir => {
|
|
17
|
+
for (const item of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
18
|
+
const file = path.join(dir, item.name);
|
|
19
|
+
if (item.isDirectory()) await walk(file);
|
|
20
|
+
else if (/\.(?:ts|mjs|js)$/.test(item.name) && !/\.d\.ts$/.test(item.name)) {
|
|
21
|
+
const module = await import(pathToFileURL(file).href);
|
|
22
|
+
for (const value of Object.values(module)) for (const entry of Array.isArray(value) ? value : [value]) {
|
|
23
|
+
if (entry?.name && entry?.open) entries.push(screen(entry));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
await walk(directory);
|
|
29
|
+
const names = new Set();
|
|
30
|
+
for (const entry of entries) {
|
|
31
|
+
if (names.has(entry.name)) throw new Error(`Duplicate catalog screen ${entry.name}`);
|
|
32
|
+
names.add(entry.name);
|
|
33
|
+
}
|
|
34
|
+
return entries;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Record: navigation receives fixture ids and names every fallible step. */
|
|
38
|
+
export function navigationContext(page, target, targetName, screenName, out) {
|
|
39
|
+
const file = path.join(privateRoot(), `fixtures-${targetName}.json`);
|
|
40
|
+
const fixtures = { ...(target.fixtures ?? {}), ...(existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}) };
|
|
41
|
+
return { baseUrl: target.baseUrl, fixtures, target: targetName, async step(name, action) {
|
|
42
|
+
try { return await action(); }
|
|
43
|
+
catch (cause) {
|
|
44
|
+
if (cause.step) throw cause;
|
|
45
|
+
const screenshot = `${screenName}/failure-${targetName}-${name.replace(/[^a-z0-9_-]/gi, "_")}.png`;
|
|
46
|
+
mkdirSync(path.dirname(path.join(out, screenshot)), { recursive: true });
|
|
47
|
+
await page.screenshot({ path: path.join(out, screenshot) }).catch(() => {});
|
|
48
|
+
throw Object.assign(new Error(`Screen ${screenName}, target ${targetName}, step ${name} failed`), { screen: screenName, target: targetName, step: name, screenshot });
|
|
49
|
+
}
|
|
50
|
+
} };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Pipeline: bind shared app navigation to each cloud or local target. */
|
|
54
|
+
export async function applyCatalog(map, mapFile) {
|
|
55
|
+
if (!map.catalog) return map;
|
|
56
|
+
const entries = await loadCatalog(path.resolve(path.dirname(mapFile), map.catalog));
|
|
57
|
+
map.screens = entries.map(entry => ({ name: entry.name, signatures: entry.signatures, targets: Object.fromEntries(Object.entries(map.targets).flatMap(([name, target]) => {
|
|
58
|
+
const family = target.family ?? name.split("-")[0];
|
|
59
|
+
const key = entry.open[name] ? name : family;
|
|
60
|
+
if (!entry.open[key]) return [];
|
|
61
|
+
const original = map.screens.find(item => item.name === entry.name)?.targets[name] ?? {};
|
|
62
|
+
return [[name, { ...original, path: entry.paths?.[key] ?? original.path, ready: entry.ready?.[key] ?? original.ready, masks: entry.masks?.[key] ?? original.masks, exclude: entry.exclude?.[key] ?? original.exclude, idle: entry.idle?.[key] ?? original.idle, open: entry.open[key], navigationSource: String(entry.open[key]) }]];
|
|
63
|
+
})) }));
|
|
64
|
+
return map;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Pipeline: catalog functions use named steps and an explicit ready state. */
|
|
68
|
+
export async function openScreen(page, target, route, { targetName, screenName, out, timeout = 15000 }) {
|
|
69
|
+
const ctx = navigationContext(page, target, targetName, screenName, out);
|
|
70
|
+
await ctx.step("Open screen", () => route.open(page, ctx));
|
|
71
|
+
if (route.ready) await ctx.step("Ready", () => page.locator(route.ready).first().waitFor({ state: "visible", timeout }));
|
|
72
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { loadCatalog, screen, navigationContext, applyCatalog } from "./catalog.mjs";
|
|
7
|
+
|
|
8
|
+
test("catalog loads TypeScript areas and rejects duplicate names", async () => {
|
|
9
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-catalog-"));
|
|
10
|
+
try {
|
|
11
|
+
writeFileSync(path.join(root, "area.ts"), 'export const entry = {name:"photos/viewer",ready:{mono:"main"},open:{mono:async (page: any) => page.goto("/photos")}}');
|
|
12
|
+
assert.equal((await loadCatalog(root))[0].name, "photos/viewer");
|
|
13
|
+
writeFileSync(path.join(root, "other.ts"), 'export const entry = {name:"photos/viewer",open:{}}');
|
|
14
|
+
await assert.rejects(loadCatalog(root), /Duplicate/);
|
|
15
|
+
assert.throws(() => screen({ name: "../escape", open: {} }), /name/);
|
|
16
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test("failed named step retains its name and screenshot", async () => {
|
|
20
|
+
const calls = [];
|
|
21
|
+
const page = { screenshot: async options => { calls.push(options.path); } };
|
|
22
|
+
const ctx = navigationContext(page, { baseUrl: "http://localhost:3000", fixtures: { project: "p" } }, "target", "photos/viewer", ".");
|
|
23
|
+
await assert.rejects(ctx.step("Open viewer", async () => { throw new Error("missing button"); }), error => error.step === "Open viewer" && error.screen === "photos/viewer" && error.target === "target" && Boolean(error.screenshot));
|
|
24
|
+
assert.equal(ctx.fixtures.project, "p");
|
|
25
|
+
assert.equal(calls.length, 1);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("catalog entries carry the idle option for each app family", async () => {
|
|
29
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-catalog-"));
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(path.join(root, "area.ts"), 'export const entry = {name:"drawings-pins",idle:{legacy:false},open:{legacy:async (page: any) => page.goto("/a"),mono:async (page: any) => page.goto("/b")}}');
|
|
32
|
+
const map = await applyCatalog({ catalog: root, targets: { "old-local": { family: "legacy" }, "new-local": { family: "mono" } }, screens: [] }, path.join(root, "map.json"));
|
|
33
|
+
assert.equal(map.screens[0].targets["old-local"].idle, false);
|
|
34
|
+
assert.equal(map.screens[0].targets["new-local"].idle, undefined);
|
|
35
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
36
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The screen commands launch Google Chrome as the `chrome` channel, and a machine may not have it.
|
|
2
|
+
|
|
3
|
+
const MISSING = /is not found at|Executable doesn't exist|not installed/i;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Why a test that launches Chrome cannot run here, or false when it can. `QC_REQUIRE_CHROME=1` makes a missing
|
|
7
|
+
* Chrome a failure, so CI never passes by skipping.
|
|
8
|
+
* @param {{launch: (options: object) => Promise<{close: () => Promise<void>}>}} chromium the Playwright browser type
|
|
9
|
+
* @returns {Promise<string | false>}
|
|
10
|
+
*/
|
|
11
|
+
export async function chromeMissing(chromium) {
|
|
12
|
+
if (process.env.QC_REQUIRE_CHROME === "1") return false;
|
|
13
|
+
try {
|
|
14
|
+
const browser = await chromium.launch({ channel: "chrome" });
|
|
15
|
+
await browser.close();
|
|
16
|
+
return false;
|
|
17
|
+
} catch (error) {
|
|
18
|
+
if (!MISSING.test(error?.message ?? "")) return false;
|
|
19
|
+
return "Google Chrome is not installed. Set QC_REQUIRE_CHROME=1 to fail instead of skip.";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import pixelmatch from "pixelmatch";
|
|
2
|
+
import { PNG } from "pngjs";
|
|
3
|
+
|
|
4
|
+
/** Pipeline: normalize dimensions and paint changed pixels over the right image. */
|
|
5
|
+
export function compareImages(left, right) {
|
|
6
|
+
const width = Math.max(left.width, right.width);
|
|
7
|
+
const height = Math.max(left.height, right.height);
|
|
8
|
+
const padded = [left, right].map(source => {
|
|
9
|
+
const image = new PNG({ width, height });
|
|
10
|
+
PNG.bitblt(source, image, 0, 0, source.width, source.height, 0, 0);
|
|
11
|
+
return image;
|
|
12
|
+
});
|
|
13
|
+
const diff = new PNG({ width, height });
|
|
14
|
+
const diffPixels = pixelmatch(padded[0].data, padded[1].data, diff.data, width, height, { threshold: 0.1, includeAA: true, diffMask: true, diffColor: [255, 0, 0] });
|
|
15
|
+
const pair = new PNG({ width: width * 2, height });
|
|
16
|
+
PNG.bitblt(padded[0], pair, 0, 0, width, height, 0, 0);
|
|
17
|
+
PNG.bitblt(padded[1], pair, 0, 0, width, height, width, 0);
|
|
18
|
+
for (let y = 0; y < height; y++) {
|
|
19
|
+
for (let x = 0; x < width; x++) {
|
|
20
|
+
const offset = (y * width + x) * 4;
|
|
21
|
+
if (diff.data[offset + 3]) diff.data.copy(pair.data, (y * width * 2 + width + x) * 4, offset, offset + 4);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return { pair, diffPixels, totalPixels: width * height, diffPercent: Number((100 * diffPixels / (width * height)).toFixed(4)) };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Ledger: list the greatest visual differences first. */
|
|
28
|
+
export function sortReport(rows) {
|
|
29
|
+
return [...rows].sort((a, b) => b.diffPercent - a.diffPercent || a.screen.localeCompare(b.screen) || a.width - b.width);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const escapeHtml = value => String(value).replace(/[&<>"']/g, ch => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ch]);
|
|
33
|
+
|
|
34
|
+
/** Fragment: a static gallery needs neither a server nor a script. */
|
|
35
|
+
export function gallery(rows) {
|
|
36
|
+
const failed = rows.filter(row => row.error).map(row => `<p>${escapeHtml(row.screen)}: ${escapeHtml(row.error.message)}${row.error.screenshot ? ` <a href="${escapeHtml(row.error.screenshot)}">Failure screenshot</a>` : ""}</p>`).join("");
|
|
37
|
+
if (failed) return gallery(rows.filter(row => !row.error)).replace("<h1>Screen pairs</h1>", `<h1>Screen pairs</h1>${failed}`);
|
|
38
|
+
const crops = rows.flatMap(row => [...(row.inventoryFindings ?? []), ...(row.regions ?? [])].filter(region => region.crop).map(region => `<figure><figcaption>${escapeHtml(row.screen)} @ ${row.width}px — ${escapeHtml(region.kind)} ${region.id}</figcaption><a href="${escapeHtml(region.crop)}"><img loading="lazy" src="${escapeHtml(region.crop)}" alt="${escapeHtml(region.kind)} region ${region.id}"></a></figure>`)).join("");
|
|
39
|
+
return `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Screen pairs</title><style>body{font:16px system-ui;margin:24px;background:#fafafa;color:#222}img{max-width:100%;border:1px solid #ccc}figure{margin:24px 0}figcaption{margin:8px 0}</style><h1>Screen pairs</h1><p>Left: baseline. Right: comparison, with differences in red.</p>${crops}${rows.map(row => `<figure><figcaption>${escapeHtml(row.screen)} @ ${row.width}px: ${row.diffPercent}% (${escapeHtml(row.targets.join(" → "))})</figcaption><a href="${escapeHtml(row.pair)}"><img loading="lazy" src="${escapeHtml(row.pair)}" alt="${escapeHtml(row.screen)} pair at ${row.width} pixels"></a></figure>`).join("")}</html>`;
|
|
40
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { PNG } from "pngjs";
|
|
4
|
+
import { compareImages, sortReport } from "./compare.mjs";
|
|
5
|
+
|
|
6
|
+
test("diff counts pixels and marks the right image in red", () => {
|
|
7
|
+
const left = new PNG({ width: 2, height: 1 });
|
|
8
|
+
left.data.fill(255);
|
|
9
|
+
const right = PNG.sync.read(PNG.sync.write(left));
|
|
10
|
+
right.data[0] = 0;
|
|
11
|
+
right.data[1] = 0;
|
|
12
|
+
right.data[2] = 0;
|
|
13
|
+
const result = compareImages(left, right);
|
|
14
|
+
assert.equal(result.diffPercent, 50);
|
|
15
|
+
assert.equal(result.diffPixels, 1);
|
|
16
|
+
assert.equal(result.pair.width, 4);
|
|
17
|
+
assert.deepEqual([...result.pair.data.subarray(8, 12)], [255, 0, 0, 255]);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("report sorts greatest differences first with stable screen and width order", () => {
|
|
21
|
+
assert.deepEqual(sortReport([{ screen: "b", width: 390, diffPercent: 0 }, { screen: "a", width: 390, diffPercent: 20 }, { screen: "a", width: 2514, diffPercent: 20 }]).map(r => `${r.screen}@${r.width}`), ["a@390", "a@2514", "b@390"]);
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("different dimensions count the extra area", () => {
|
|
25
|
+
const left = new PNG({ width: 1, height: 1 });
|
|
26
|
+
const right = new PNG({ width: 2, height: 1 });
|
|
27
|
+
left.data.fill(255);
|
|
28
|
+
right.data.fill(255);
|
|
29
|
+
assert.equal(compareImages(left, right).diffPercent, 50);
|
|
30
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { discover } from "./discovery.mjs";
|
|
9
|
+
|
|
10
|
+
test("one SPA URL exposes five states; writes and an automatic POST stay blocked", async () => {
|
|
11
|
+
let writes = 0;
|
|
12
|
+
const server = http.createServer((request, response) => {
|
|
13
|
+
if (request.method === "POST") writes++;
|
|
14
|
+
response.setHeader("content-type", "text/html");
|
|
15
|
+
response.end(`<main><h1>Workspace</h1><button role="tab" aria-selected="false" onclick="this.setAttribute('aria-selected','true')">Photos</button><button role="tab" aria-selected="false" onclick="this.setAttribute('aria-selected','true')">Drawings</button><button onclick="document.querySelector('dialog').showModal()">Open dialog</button><button onclick="document.querySelector('[role=menu]').hidden=false">Open menu</button><button onclick="fetch('/write',{method:'POST'})">Save</button><dialog aria-label="Details">Details</dialog><div role="menu" aria-label="Actions" hidden>Actions</div></main><script>fetch('/automatic',{method:'POST'})</script>`);
|
|
16
|
+
});
|
|
17
|
+
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
18
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
19
|
+
const context = await browser.newContext({ serviceWorkers: "block" });
|
|
20
|
+
const out = mkdtempSync(path.join(os.tmpdir(), "qc-discover-"));
|
|
21
|
+
try {
|
|
22
|
+
const result = await discover({ context, page: await context.newPage() }, { baseUrl: `http://127.0.0.1:${server.address().port}`, routes: ["/"], auth: { signedIn: "main" } }, { out, targetName: "fixture", widths: [390], depth: 1, timeout: 3000 });
|
|
23
|
+
assert.equal(result.states.length, 5);
|
|
24
|
+
assert.equal(result.errors.length, 0);
|
|
25
|
+
assert.equal(result.states.some(state => state.path.some(step => step.name === "Save")), false);
|
|
26
|
+
assert.equal(writes, 0);
|
|
27
|
+
assert.ok(result.blockedRequests > 0);
|
|
28
|
+
} finally { await browser.close(); await new Promise(resolve => server.close(resolve)); rmSync(out, { recursive: true, force: true }); }
|
|
29
|
+
});
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { safeControl, installWriteGuard } from "./write-guard.mjs";
|
|
5
|
+
|
|
6
|
+
const normalized = text => String(text ?? "").normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
|
|
7
|
+
const hash = text => createHash("sha256").update(text).digest("hex").slice(0, 16);
|
|
8
|
+
|
|
9
|
+
/** Record: source route patterns resolve only known fixture parameters. */
|
|
10
|
+
export function sourceRoutes(source, fixtures = {}) {
|
|
11
|
+
const result = [];
|
|
12
|
+
const names = { projectId: "project", folderId: "folder", photoId: "photo", drawingId: "drawing", id: "project" };
|
|
13
|
+
for (const match of source.matchAll(/\bpath\s*[:=]\s*["'](\/[^"']*)["']/g)) {
|
|
14
|
+
const pattern = match[1];
|
|
15
|
+
let missing = false;
|
|
16
|
+
const route = pattern.replace(/:([a-zA-Z]\w*)\??/g, (_, name) => {
|
|
17
|
+
const value = fixtures[name] ?? fixtures[names[name]];
|
|
18
|
+
if (!value) missing = true;
|
|
19
|
+
return encodeURIComponent(value ?? "");
|
|
20
|
+
});
|
|
21
|
+
result.push({ pattern, path: missing || route.includes("*") ? null : route });
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Resource: route extraction reads application source without loading its modules. */
|
|
27
|
+
export function readSourceRoutes(roots = [], fixtures = {}) {
|
|
28
|
+
const routes = [];
|
|
29
|
+
const walk = root => {
|
|
30
|
+
for (const item of readdirSync(root, { withFileTypes: true })) {
|
|
31
|
+
if (/^(?:node_modules|\.git|dist|build|coverage|\.worktree|\.next)$/.test(item.name)) continue;
|
|
32
|
+
const file = path.join(root, item.name);
|
|
33
|
+
if (item.isDirectory()) walk(file);
|
|
34
|
+
else if (/\.[jt]sx?$/.test(item.name) && !/\.(?:test|spec)\./.test(item.name) && statSync(file).size < 2000000) routes.push(...sourceRoutes(readFileSync(file, "utf8"), fixtures));
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
for (const root of roots) walk(root);
|
|
38
|
+
return [...new Map(routes.map(route => [route.pattern, route])).values()];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const locatorFor = (page, step) => step.testId ? page.getByTestId(step.testId) : page.getByRole(step.role, { name: step.name, exact: true });
|
|
42
|
+
|
|
43
|
+
/** Record: a UI signature identifies state independently of its data rows. */
|
|
44
|
+
export async function stateSignature(page, pattern) {
|
|
45
|
+
const read = async selector => page.locator(selector).evaluateAll(nodes => nodes.filter(node => node.getBoundingClientRect().width && node.getBoundingClientRect().height).map(node => node.getAttribute("aria-label") || node.textContent.trim()).join(" | "));
|
|
46
|
+
const dialogs = page.getByRole("dialog");
|
|
47
|
+
const dialog = await dialogs.count() ? await dialogs.last().ariaSnapshot() : "";
|
|
48
|
+
return JSON.stringify({ route: pattern, dialog: dialog.split("\n")[0].replace(/^\s*-\s*/, ""), tab: await read('[role="tab"][aria-selected="true"]'), menu: await read('[role="menu"]'), heading: await read('main h1,main [role="heading"][aria-level="1"],h1'), expanded: await read('[aria-expanded="true"]') });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function candidates(page) {
|
|
52
|
+
const controls = page.locator('button,[role="button"],[role="tab"],[role="menuitem"],[role="combobox"],[role="switch"],summary');
|
|
53
|
+
const result = [];
|
|
54
|
+
for (const control of await controls.all()) {
|
|
55
|
+
if (!await control.isVisible() || !await control.isEnabled()) continue;
|
|
56
|
+
const data = await control.evaluate(element => ({ type: element.getAttribute("type") ?? (element.tagName === "BUTTON" && element.closest("form") ? "submit" : ""), text: `${element.textContent} ${element.getAttribute("aria-label") ?? ""}`, testId: element.getAttribute("data-testid"), role: element.getAttribute("role") ?? (element.tagName === "SUMMARY" ? "button" : "button") }));
|
|
57
|
+
if (!safeControl(data)) continue;
|
|
58
|
+
const snapshot = await control.ariaSnapshot().catch(() => "");
|
|
59
|
+
const first = snapshot.split("\n")[0].match(/^-\s+([\w]+)(?:\s+"(.*?)")?/);
|
|
60
|
+
const step = { role: first?.[1] ?? data.role, name: first?.[2] ?? "", ...(data.testId ? { testId: data.testId } : {}) };
|
|
61
|
+
if (!step.testId && !step.name) continue;
|
|
62
|
+
if (await locatorFor(page, step).count() !== 1) continue;
|
|
63
|
+
result.push(step);
|
|
64
|
+
}
|
|
65
|
+
return result;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Pipeline: replay safe paths from every route and retain unique UI states. */
|
|
69
|
+
export async function discover(session, target, { out, targetName, widths = [2514, 390], depth = 4, timeout = 15000, allowWrites = false, maxStates = 500, say = () => {} } = {}) {
|
|
70
|
+
const { page, context } = session;
|
|
71
|
+
page.setDefaultTimeout(timeout);
|
|
72
|
+
const states = [], errors = [], unresolvedRoutes = [];
|
|
73
|
+
let blockedRequests = 0;
|
|
74
|
+
await installWriteGuard(context, target, { allowWrites, onBlocked: () => blockedRequests++ });
|
|
75
|
+
const discoveredRoutes = readSourceRoutes(target.sourceRoots, target.fixtures);
|
|
76
|
+
for (const route of discoveredRoutes) if (!route.path) unresolvedRoutes.push(route.pattern);
|
|
77
|
+
const starts = [...(target.routes ?? ["/"]).map(route => typeof route === "string" ? { path: route, pattern: route } : route), ...discoveredRoutes.filter(route => route.path)];
|
|
78
|
+
const origin = new URL(target.baseUrl).origin;
|
|
79
|
+
const seen = new Set();
|
|
80
|
+
const queuedRoutes = new Set();
|
|
81
|
+
const queue = [];
|
|
82
|
+
const addRoute = (route, width) => {
|
|
83
|
+
const key = `${width}:${route.path}`;
|
|
84
|
+
if (!queuedRoutes.has(key)) { queuedRoutes.add(key); queue.push({ route, width, path: [] }); }
|
|
85
|
+
};
|
|
86
|
+
for (const width of widths) for (const route of starts) addRoute(route, width);
|
|
87
|
+
mkdirSync(out, { recursive: true });
|
|
88
|
+
while (queue.length) {
|
|
89
|
+
if (states.length >= maxStates) { errors.push({ message: `State limit ${maxStates} reached; discovery is incomplete` }); break; }
|
|
90
|
+
const current = queue.shift();
|
|
91
|
+
try {
|
|
92
|
+
await page.setViewportSize({ width: current.width, height: 900 });
|
|
93
|
+
const response = await page.goto(new URL(current.route.path, target.baseUrl).href, { waitUntil: "domcontentloaded", timeout });
|
|
94
|
+
if (response?.status() >= 400) throw new Error(`HTTP ${response.status()}`);
|
|
95
|
+
for (const step of target.discoverySteps ?? []) {
|
|
96
|
+
const control = locatorFor(page, step);
|
|
97
|
+
if (await control.isVisible() && safeControl({ text: step.name })) await control.click({ timeout });
|
|
98
|
+
}
|
|
99
|
+
for (const step of current.path) await locatorFor(page, step).click({ timeout });
|
|
100
|
+
await page.waitForLoadState("networkidle", { timeout });
|
|
101
|
+
if (new URL(page.url()).origin !== origin) throw new Error("Discovery left the target origin");
|
|
102
|
+
await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
|
|
103
|
+
const actual = new URL(page.url());
|
|
104
|
+
const pattern = actual.pathname === new URL(current.route.path, target.baseUrl).pathname ? current.route.pattern : actual.pathname;
|
|
105
|
+
const signature = await stateSignature(page, pattern);
|
|
106
|
+
const key = `${current.width}:${signature}`;
|
|
107
|
+
if (seen.has(key)) continue;
|
|
108
|
+
seen.add(key);
|
|
109
|
+
const id = hash(key);
|
|
110
|
+
const thumbnail = `${targetName}-${id}.png`;
|
|
111
|
+
await page.screenshot({ path: path.join(out, thumbnail), animations: "disabled" });
|
|
112
|
+
const state = { id, signature, route: current.route.path, pattern, width: current.width, path: current.path, thumbnail };
|
|
113
|
+
states.push(state);
|
|
114
|
+
say(`Discovered ${targetName} ${current.width} ${pattern} ${id}`);
|
|
115
|
+
const links = await page.locator("a[href]").evaluateAll(nodes => nodes.map(node => node.href));
|
|
116
|
+
for (const href of links) {
|
|
117
|
+
const url = new URL(href);
|
|
118
|
+
if (url.origin === origin && !/logout|signout|delete|remove|complete/i.test(url.pathname)) addRoute({ path: url.pathname + url.search, pattern: url.pathname }, current.width);
|
|
119
|
+
}
|
|
120
|
+
if (current.path.length < depth) for (const step of await candidates(page)) queue.push({ ...current, path: [...current.path, step] });
|
|
121
|
+
} catch (error) { errors.push({ route: current.route.path, width: current.width, path: current.path, message: error.message }); }
|
|
122
|
+
}
|
|
123
|
+
const counts = Object.fromEntries([...new Set(states.map(state => state.pattern))].map(route => [route, states.filter(state => state.pattern === route).length]));
|
|
124
|
+
const result = { target: targetName, states, counts, errors, unresolvedRoutes, blockedRequests, complete: !errors.length && !unresolvedRoutes.length };
|
|
125
|
+
writeFileSync(path.join(out, `discovered-${targetName}.json`), JSON.stringify(result, null, 2));
|
|
126
|
+
return result;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function pairingText(state) {
|
|
130
|
+
const value = JSON.parse(state.signature);
|
|
131
|
+
const text = normalized([value.dialog, value.tab, value.menu, value.heading, value.expanded].filter(Boolean).join(" | "));
|
|
132
|
+
return `${state.width}:${text || value.route}`;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Pipeline: match identical state text once, retaining both parity gaps. */
|
|
136
|
+
export function pairStates(legacy, mono) {
|
|
137
|
+
const available = new Set(mono);
|
|
138
|
+
const result = legacy.map(left => {
|
|
139
|
+
const right = [...available].find(right => pairingText(left) === pairingText(right));
|
|
140
|
+
if (right) { available.delete(right); return { kind: "paired", legacy: left, mono: right }; }
|
|
141
|
+
return { kind: "legacy-only", legacy: left };
|
|
142
|
+
});
|
|
143
|
+
return [...result, ...[...available].map(right => ({ kind: "mono-only", mono: right }))];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Branch: every discovery needs a catalog signature or a written exclusion. */
|
|
147
|
+
export function catalogCoverage(states, entries, excluded = [], targetName) {
|
|
148
|
+
const signatures = entries.flatMap(entry => Array.isArray(entry.signatures) ? entry.signatures : entry.signatures?.[targetName] ?? entry.signatures?.[targetName?.split("-")[0]] ?? []);
|
|
149
|
+
const missing = states.filter(state => !signatures.some(signature => typeof signature === "string" ? signature === state.signature : signature.signature === state.signature && signature.width === state.width) && !excluded.some(item => item.signature === state.signature && (!item.target || item.target === targetName) && (!item.width || item.width === state.width) && item.reason?.trim()));
|
|
150
|
+
return { covered: states.length - missing.length, total: states.length, missing };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Fragment: scaffold selectors replay the recorded path through named steps. */
|
|
154
|
+
export function scaffoldEntry(state, family) {
|
|
155
|
+
const steps = state.path.map((step, index) => ` await ctx.step(${JSON.stringify(`${index + 1}. ${step.name || step.testId}`)}, () => ${step.testId ? `page.getByTestId(${JSON.stringify(step.testId)})` : `page.getByRole(${JSON.stringify(step.role)}, {name:${JSON.stringify(step.name)},exact:true})`}.click());`).join("\n");
|
|
156
|
+
const name = `discovered/${family}-${state.id ?? hash(state.signature)}`;
|
|
157
|
+
return `export const state${state.id ?? hash(state.signature)} = {\n name:${JSON.stringify(name)},\n signatures:{${JSON.stringify(family)}:[${JSON.stringify({ signature: state.signature, width: state.width })}]},\n open:{${JSON.stringify(family)}:async (page, ctx) => {\n await ctx.step("Navigate", () => page.goto(new URL(${JSON.stringify(state.route)},ctx.baseUrl).href));\n${steps}\n }}\n};\n`;
|
|
158
|
+
}
|