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,27 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { safeControl, permitsRequest } from "./write-guard.mjs";
|
|
4
|
+
import { pairStates, catalogCoverage, scaffoldEntry, sourceRoutes } from "./discovery.mjs";
|
|
5
|
+
|
|
6
|
+
test("write guard blocks mutations in English and Japanese and allows local opt-in", () => {
|
|
7
|
+
for (const name of ["Save", "Delete project", "送信", "保存", "確定", "竣工にする", "アップロード", "登録"]) assert.equal(safeControl({ text: name }), false);
|
|
8
|
+
assert.equal(safeControl({ text: "Photos" }), true);
|
|
9
|
+
assert.equal(permitsRequest("POST", "http://localhost/api", { baseUrl: "http://localhost" }), false);
|
|
10
|
+
assert.equal(permitsRequest("POST", "http://localhost/api", { baseUrl: "http://localhost" }, true), true);
|
|
11
|
+
assert.equal(permitsRequest("POST", "https://other.test/x", { baseUrl: "http://localhost" }, true), false);
|
|
12
|
+
assert.equal(permitsRequest("POST", "https://cloud.test/api", { baseUrl: "https://cloud.test" }, true), false);
|
|
13
|
+
assert.equal(permitsRequest("POST", "https://tenant.auth0.com/u/login", { baseUrl: "https://cloud.test", auth: { domain: "tenant.auth0.com" } }), true);
|
|
14
|
+
assert.equal(permitsRequest("POST", "https://tenant.auth0.com/api/users", { baseUrl: "https://cloud.test", auth: { domain: "tenant.auth0.com" } }), false);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("pairing is one-to-one and coverage requires an entry or a reason", () => {
|
|
18
|
+
const state = title => ({ signature: JSON.stringify({ heading: title, tab: "", menu: "", dialog: "", route: "/" }), width: 390, route: "/", path: [] });
|
|
19
|
+
const old = [state("Projects"), state("Legacy")];
|
|
20
|
+
const next = [state("Projects"), state("Mono")];
|
|
21
|
+
const pairs = pairStates(old, next);
|
|
22
|
+
assert.deepEqual(pairs.map(item => item.kind), ["paired", "legacy-only", "mono-only"]);
|
|
23
|
+
assert.equal(catalogCoverage(old, [{ signatures: [old[0].signature] }], [{ signature: old[1].signature, reason: "Legacy settings" }]).missing.length, 0);
|
|
24
|
+
assert.equal(catalogCoverage(old, [], [{ signature: old[1].signature, reason: "" }]).missing.length, 2);
|
|
25
|
+
assert.match(scaffoldEntry({ ...old[0], path: [{ role: "tab", name: "Photos" }] }, "mono"), /getByRole\("tab"/);
|
|
26
|
+
assert.deepEqual(sourceRoutes('<Route path="/projects/:projectId"/><Route path="/login"/>', { project: "p" }).map(item => item.path), ["/projects/p", "/login"]);
|
|
27
|
+
});
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const normalize = value => String(value ?? "").normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
|
|
2
|
+
const key = item => `${item.role}:${normalize(item.name)}`;
|
|
3
|
+
const roles = new Set(["textbox", "searchbox", "combobox", "checkbox", "radio", "spinbutton", "slider", "switch", "button", "link", "tab", "menuitem", "menuitemcheckbox", "menuitemradio", "heading", "columnheader"]);
|
|
4
|
+
|
|
5
|
+
/** Pipeline: read accessible names from Playwright snapshots and attach field metadata in page order. */
|
|
6
|
+
export async function collectInventory(page, excludes = []) {
|
|
7
|
+
const selector = 'input,textarea,select,button,a[href],h1,h2,h3,h4,h5,h6,th,[role]';
|
|
8
|
+
const elements = page.locator(selector);
|
|
9
|
+
const inventory = [];
|
|
10
|
+
for (let index = 0; index < await elements.count(); index++) {
|
|
11
|
+
const element = elements.nth(index);
|
|
12
|
+
const metadata = await element.evaluate((node, omitted) => {
|
|
13
|
+
if (omitted.some(selector => node.closest(selector))) return null;
|
|
14
|
+
const style = getComputedStyle(node);
|
|
15
|
+
const rect = node.getBoundingClientRect();
|
|
16
|
+
if (!rect.width || !rect.height || style.visibility === "hidden" || style.display === "none") return null;
|
|
17
|
+
const type = node.tagName === "SELECT" ? "select" : node.getAttribute("type") ?? (node.tagName === "TEXTAREA" ? "textarea" : "");
|
|
18
|
+
if (type === "hidden") return null;
|
|
19
|
+
return { type, label: Array.from(node.labels ?? []).map(label => label.textContent.trim()).join(" "), placeholder: node.getAttribute("placeholder") ?? "", state: { disabled: node.matches(":disabled") || node.getAttribute("aria-disabled") === "true", required: node.required === true || node.getAttribute("aria-required") === "true", checked: "checked" in node ? node.checked : node.getAttribute("aria-checked"), selected: node.getAttribute("aria-selected"), value: node.tagName === "SELECT" ? node.selectedOptions[0]?.textContent?.trim() ?? "" : undefined }, box: { x: Math.max(0, rect.x), y: Math.max(0, rect.y), width: rect.width, height: rect.height } };
|
|
20
|
+
}, excludes);
|
|
21
|
+
if (!metadata) continue;
|
|
22
|
+
const snapshot = await element.ariaSnapshot();
|
|
23
|
+
const match = snapshot.match(/^- (\w+)(?: "((?:\\.|[^"\\])*)")?/);
|
|
24
|
+
if (!match || !roles.has(match[1])) continue;
|
|
25
|
+
let name = match[2] ?? "";
|
|
26
|
+
try { name = JSON.parse(`"${name}"`); } catch { /* Names from older Playwright snapshots can contain literal newlines. */ }
|
|
27
|
+
inventory.push({ role: match[1], name, ...metadata });
|
|
28
|
+
}
|
|
29
|
+
return inventory;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Pipeline: align role and normalized name, then reconcile moves, renames, types, and states. */
|
|
33
|
+
export function diffInventory(left, right) {
|
|
34
|
+
const rows = Array.from({ length: left.length + 1 }, () => new Uint32Array(right.length + 1));
|
|
35
|
+
for (let i = left.length - 1; i >= 0; i--) for (let j = right.length - 1; j >= 0; j--) rows[i][j] = key(left[i]) === key(right[j]) ? rows[i + 1][j + 1] + 1 : Math.max(rows[i + 1][j], rows[i][j + 1]);
|
|
36
|
+
const aligned = [], unmatchedLeft = [], unmatchedRight = [];
|
|
37
|
+
let i = 0, j = 0;
|
|
38
|
+
while (i < left.length || j < right.length) {
|
|
39
|
+
if (i < left.length && j < right.length && key(left[i]) === key(right[j])) aligned.push([i++, j++]);
|
|
40
|
+
else if (i < left.length && (j === right.length || rows[i + 1][j] >= rows[i][j + 1])) unmatchedLeft.push(i++);
|
|
41
|
+
else unmatchedRight.push(j++);
|
|
42
|
+
}
|
|
43
|
+
const findings = [];
|
|
44
|
+
const add = (kind, a, b) => findings.push({ id: findings.length + 1, kind, left: a === undefined ? null : left[a], right: b === undefined ? null : right[b], leftIndex: a ?? null, rightIndex: b ?? null });
|
|
45
|
+
for (const [a, b] of aligned) {
|
|
46
|
+
if (left[a].type !== right[b].type) add("type", a, b);
|
|
47
|
+
if (JSON.stringify(left[a].state) !== JSON.stringify(right[b].state)) add("state", a, b);
|
|
48
|
+
}
|
|
49
|
+
const used = new Set();
|
|
50
|
+
for (const a of unmatchedLeft) {
|
|
51
|
+
let b = unmatchedRight.find(b => !used.has(b) && key(left[a]) === key(right[b]));
|
|
52
|
+
if (b !== undefined) { used.add(b); add("moved", a, b); continue; }
|
|
53
|
+
b = unmatchedRight.find(b => !used.has(b) && normalize(left[a].name) === normalize(right[b].name));
|
|
54
|
+
if (b !== undefined) { used.add(b); add("type", a, b); continue; }
|
|
55
|
+
b = unmatchedRight.find(b => !used.has(b) && left[a].role === right[b].role && Math.abs(a - b) <= 1);
|
|
56
|
+
if (b !== undefined) { used.add(b); add("renamed", a, b); continue; }
|
|
57
|
+
add("missing", a, undefined);
|
|
58
|
+
}
|
|
59
|
+
for (const b of unmatchedRight) if (!used.has(b)) add("extra", undefined, b);
|
|
60
|
+
return findings;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Record: cover the visible part of either element with one crop. */
|
|
64
|
+
export function inventoryBox(finding, width, height) {
|
|
65
|
+
const boxes = [finding.left?.box, finding.right?.box].filter(Boolean);
|
|
66
|
+
const x = Math.min(width - 1, Math.max(0, Math.floor(Math.min(...boxes.map(box => box.x)))));
|
|
67
|
+
const y = Math.min(height - 1, Math.max(0, Math.floor(Math.min(...boxes.map(box => box.y)))));
|
|
68
|
+
return { x, y, width: Math.max(1, Math.min(width - x, Math.ceil(Math.max(...boxes.map(box => box.x + box.width))) - x)), height: Math.max(1, Math.min(height - y, Math.ceil(Math.max(...boxes.map(box => box.y + box.height))) - y)) };
|
|
69
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { diffInventory } from "./inventory.mjs";
|
|
4
|
+
const field = (name, role = "textbox", type = "text", state = {}) => ({ role, name, type, state, box: { x: 0, y: 0, width: 100, height: 30 } });
|
|
5
|
+
test("a removed field is missing", () => assert.equal(diffInventory([field("Email")], [])[0].kind, "missing"));
|
|
6
|
+
test("a renamed button is renamed", () => assert.equal(diffInventory([field("Continue", "button")], [field("Next", "button")])[0].kind, "renamed"));
|
|
7
|
+
test("swapped fields report a move", () => assert.ok(diffInventory([field("A"), field("B")], [field("B"), field("A")]).some(f => f.kind === "moved")));
|
|
8
|
+
test("a text input against a select reports type", () => assert.equal(diffInventory([field("Country")], [field("Country", "combobox", "select")])[0].kind, "type"));
|
|
9
|
+
test("a disabled field reports state", () => assert.equal(diffInventory([field("Email")], [field("Email", "textbox", "text", { disabled: true })])[0].kind, "state"));
|
|
10
|
+
test("identical inventories have no findings", () => assert.deepEqual(diffInventory([field("Email")], [field(" Email ")]), []));
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { resolveStackTargets } from "./stack-auth.mjs";
|
|
4
|
+
|
|
5
|
+
const namePattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
|
|
6
|
+
const text = (value) => typeof value === "string" && value.length > 0;
|
|
7
|
+
const requireValue = (condition, message) => { if (!condition) throw new Error(message); };
|
|
8
|
+
|
|
9
|
+
/** Branch: seed credentials belong only to a loopback origin. */
|
|
10
|
+
export function requireLocalhost(value) {
|
|
11
|
+
const url = new URL(value);
|
|
12
|
+
requireValue(["http:", "https:"].includes(url.protocol) && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && !url.username && !url.password, "seed-login requires localhost");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Record: validate the map before opening a browser or creating output files. */
|
|
16
|
+
export function parseMap(input) {
|
|
17
|
+
requireValue(input && typeof input === "object", "Expected a screen map");
|
|
18
|
+
requireValue(Array.isArray(input.widths) && input.widths.length > 0 && input.widths.every(w => Number.isInteger(w) && w > 0 && w <= 10000), "widths must contain positive integers up to 10000");
|
|
19
|
+
requireValue(input.targets && Object.keys(input.targets).length >= 2, "At least two targets are required");
|
|
20
|
+
for (const [name, target] of Object.entries(input.targets)) {
|
|
21
|
+
requireValue(namePattern.test(name) && name !== "pair", "Invalid target name");
|
|
22
|
+
const url = new URL(target.baseUrl);
|
|
23
|
+
requireValue(["http:", "https:"].includes(url.protocol) && !url.username && !url.password && url.port !== "5432", "Targets require HTTP URLs without credentials");
|
|
24
|
+
const auth = target.auth;
|
|
25
|
+
requireValue(auth && text(auth.signedIn), "auth.signedIn must identify a signed-in page");
|
|
26
|
+
if (auth.mode === "browser-session") {
|
|
27
|
+
requireValue(text(auth.domain) && /^[a-z0-9]+(?:[.-][a-z0-9]+)*$/i.test(auth.domain), "Invalid Auth0 domain");
|
|
28
|
+
} else if (auth.mode === "form") {
|
|
29
|
+
requireLocalhost(target.baseUrl);
|
|
30
|
+
for (const field of ["userSelector", "passwordSelector", "submitSelector"]) requireValue(text(auth[field]), `form requires ${field}`);
|
|
31
|
+
} else {
|
|
32
|
+
requireValue(auth.mode === "seed-login", "Unknown auth mode");
|
|
33
|
+
requireLocalhost(target.baseUrl);
|
|
34
|
+
for (const field of ["seedFile", "userField", "passwordField", "userSelector", "passwordSelector", "submitSelector"]) requireValue(text(auth[field]), `seed-login requires ${field}`);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
requireValue(Array.isArray(input.screens) && input.screens.length > 0, "screens must be a nonempty array");
|
|
38
|
+
const names = new Set();
|
|
39
|
+
for (const screen of input.screens) {
|
|
40
|
+
requireValue(namePattern.test(screen.name) && !names.has(screen.name), "Invalid or duplicate screen name");
|
|
41
|
+
names.add(screen.name);
|
|
42
|
+
requireValue(screen.targets && Object.keys(screen.targets).length >= 2, "Each screen needs two targets");
|
|
43
|
+
for (const [name, route] of Object.entries(screen.targets)) {
|
|
44
|
+
requireValue(input.targets[name], `Unknown target ${name}`);
|
|
45
|
+
requireValue(text(route.path) && route.path.startsWith("/") && !route.path.startsWith("//") && !route.path.includes("\\"), "Screen paths must stay on the target origin");
|
|
46
|
+
requireValue(new URL(route.path, input.targets[name].baseUrl).origin === new URL(input.targets[name].baseUrl).origin, "Screen path changes origin");
|
|
47
|
+
if (route.masks !== undefined) requireValue(Array.isArray(route.masks) && route.masks.every(text), "masks must contain selectors");
|
|
48
|
+
if (route.clicks !== undefined) requireValue(Array.isArray(route.clicks) && route.clicks.every(step => text(step) || (step && text(step.selector) && typeof step.optional === "boolean")), "clicks must contain selectors or optional navigation steps");
|
|
49
|
+
if (route.ready !== undefined) requireValue(text(route.ready), "ready must be a selector");
|
|
50
|
+
if (route.idle !== undefined) requireValue(typeof route.idle === "boolean", "idle must be true or false");
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return input;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Resource: resolve a seed file relative to its map. */
|
|
57
|
+
export function loadMap(file, { targets } = {}) {
|
|
58
|
+
const map = parseMap(resolveStackTargets(JSON.parse(readFileSync(file, "utf8")), targets));
|
|
59
|
+
if (map.catalog) map.catalog = path.resolve(path.dirname(file), map.catalog);
|
|
60
|
+
for (const target of Object.values(map.targets)) if (target.setup) target.setup = path.resolve(path.dirname(file), target.setup);
|
|
61
|
+
for (const target of Object.values(map.targets)) if (target.auth.mode === "seed-login") target.auth.seedFile = path.resolve(path.dirname(file), target.auth.seedFile);
|
|
62
|
+
return map;
|
|
63
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { parseMap, requireLocalhost } from "./map.mjs";
|
|
4
|
+
|
|
5
|
+
const fixture = () => ({ widths: [2514, 390], targets: { old: { baseUrl: "https://old.example", auth: { mode: "browser-session", domain: "tenant.auth0.com", signedIn: "[data-user]" } }, next: { baseUrl: "http://localhost:5173", auth: { mode: "browser-session", domain: "tenant.auth0.com", signedIn: "[data-user]" } } }, screens: [{ name: "projects", targets: { old: { path: "/projects" }, next: { path: "/projects" } } }] });
|
|
6
|
+
|
|
7
|
+
test("map preserves widths and resolves target paths", () => {
|
|
8
|
+
const map = parseMap(fixture());
|
|
9
|
+
assert.deepEqual(map.widths, [2514, 390]);
|
|
10
|
+
assert.equal(map.screens[0].targets.old.path, "/projects");
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test("map rejects traversal, duplicate names, unknown targets, and invalid widths", () => {
|
|
14
|
+
for (const mutate of [m => m.screens[0].name = "../escape", m => m.screens.push(m.screens[0]), m => m.widths = [0], m => m.screens[0].targets.unknown = { path: "/" }, m => m.screens[0].targets.old.path = "https://evil.example", m => m.targets.old.auth.domain = "../tenant"]) {
|
|
15
|
+
const map = fixture();
|
|
16
|
+
mutate(map);
|
|
17
|
+
assert.throws(() => parseMap(map));
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("seed login accepts only exact loopback hosts", () => {
|
|
22
|
+
for (const url of ["http://localhost:3000", "http://127.0.0.1:3000", "http://[::1]:3000"]) assert.doesNotThrow(() => requireLocalhost(url));
|
|
23
|
+
for (const url of ["https://cloud.example", "http://localhost.evil", "http://127.0.0.2", "file:///tmp", "http://localhost@evil.example"]) assert.throws(() => requireLocalhost(url));
|
|
24
|
+
const map = fixture();
|
|
25
|
+
map.targets.old.auth = { mode: "seed-login", signedIn: "main", seedFile: "seed.json", userField: "username", passwordField: "password", userSelector: "#user", passwordSelector: "#password", submitSelector: "#login" };
|
|
26
|
+
assert.throws(() => parseMap(map), /localhost/);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("map accepts optional navigation for onboarding and rejects malformed steps", () => {
|
|
30
|
+
const map = fixture();
|
|
31
|
+
map.screens[0].targets.old.clicks = [{ selector: "[data-guide-skip]", optional: true }];
|
|
32
|
+
assert.doesNotThrow(() => parseMap(map));
|
|
33
|
+
map.screens[0].targets.old.clicks = [{ optional: true }];
|
|
34
|
+
assert.throws(() => parseMap(map));
|
|
35
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { runScreens } from "../cli/screens.mjs";
|
|
9
|
+
|
|
10
|
+
for (const mode of ["form", "seed-login"]) for (const allowWrites of [false, true]) {
|
|
11
|
+
test(`open ${mode} ${allowWrites ? "permits" : "blocks"} localhost POST`, async t => {
|
|
12
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-open-"));
|
|
13
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
14
|
+
t.mock.method(os, "homedir", () => root);
|
|
15
|
+
let posts = 0;
|
|
16
|
+
const server = http.createServer((request, response) => {
|
|
17
|
+
if (request.method === "POST") { posts++; response.end("ok"); return; }
|
|
18
|
+
response.setHeader("content-type", "text/html");
|
|
19
|
+
response.end('<main>Screen</main><script>fetch("/write", { method: "POST" }).then(() => window.result = "sent", () => window.result = "blocked")</script>');
|
|
20
|
+
});
|
|
21
|
+
t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
|
|
22
|
+
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
23
|
+
const baseUrl = `http://127.0.0.1:${server.address().port}`;
|
|
24
|
+
const auth = { mode, signedIn: "main", userSelector: "#user", passwordSelector: "#secret", submitSelector: "button", seedFile: "unused.json", userField: "user", passwordField: "secret" };
|
|
25
|
+
const target = { baseUrl, auth };
|
|
26
|
+
const mapFile = path.join(root, "map.json");
|
|
27
|
+
writeFileSync(mapFile, JSON.stringify({ widths: [390], targets: { local: target, other: target }, screens: [{ name: "screen", targets: { local: { path: "/screen" }, other: { path: "/screen" } } }] }));
|
|
28
|
+
const browser = await chromium.launch({ channel: "chrome" });
|
|
29
|
+
t.after(() => browser.close());
|
|
30
|
+
const context = await browser.newContext({ serviceWorkers: "block" });
|
|
31
|
+
const page = await context.newPage();
|
|
32
|
+
let passedOptions;
|
|
33
|
+
const messages = [];
|
|
34
|
+
const running = runScreens(["open", "screen", "--map", mapFile, "--target", "local", ...(allowWrites ? ["--allow-writes"] : [])], {
|
|
35
|
+
say: message => messages.push(message),
|
|
36
|
+
sessionFactory: async (_chromium, _target, options) => {
|
|
37
|
+
passedOptions = options;
|
|
38
|
+
return { context, page, close: () => context.close() };
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
await page.waitForURL(`${baseUrl}/screen`, { timeout: 5000 });
|
|
42
|
+
await page.waitForFunction(() => window.result, { timeout: 5000 });
|
|
43
|
+
const result = await page.evaluate(() => window.result);
|
|
44
|
+
await page.close();
|
|
45
|
+
assert.equal(await running, 0, messages.join("\n"));
|
|
46
|
+
assert.equal(result, allowWrites ? "sent" : "blocked");
|
|
47
|
+
assert.equal(posts, allowWrites ? 1 : 0);
|
|
48
|
+
assert.equal(passedOptions.allowWrites, allowWrites);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import pixelmatch from "pixelmatch";
|
|
2
|
+
import { PNG } from "pngjs";
|
|
3
|
+
|
|
4
|
+
function difference(a, b) {
|
|
5
|
+
if (a.width !== b.width || a.height !== b.height) throw new Error("Capture dimensions differ");
|
|
6
|
+
const mask = new PNG({ width: a.width, height: a.height });
|
|
7
|
+
pixelmatch(a.data, b.data, mask.data, a.width, a.height, { threshold: 0.1, includeAA: true, diffMask: true });
|
|
8
|
+
return mask;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Pipeline: accept two identical captures, or preserve the final unstable pixels after three retries. */
|
|
12
|
+
export async function stableCapture(capture) {
|
|
13
|
+
for (let attempt = 0; attempt <= 3; attempt++) {
|
|
14
|
+
const first = await capture();
|
|
15
|
+
const image = await capture();
|
|
16
|
+
const mask = difference(first, image);
|
|
17
|
+
if (!mask.data.some((value, index) => index % 4 === 3 && value)) return { image, unstable: null };
|
|
18
|
+
if (attempt === 3) return { image, unstable: mask };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function components(mask, gap) {
|
|
23
|
+
const cell = Math.max(1, gap);
|
|
24
|
+
const columns = Math.ceil(mask.width / cell);
|
|
25
|
+
const rows = Math.ceil(mask.height / cell);
|
|
26
|
+
const occupied = new Uint8Array(columns * rows);
|
|
27
|
+
for (let y = 0; y < mask.height; y++) for (let x = 0; x < mask.width; x++) {
|
|
28
|
+
if (mask.data[(y * mask.width + x) * 4 + 3]) occupied[Math.floor(y / cell) * columns + Math.floor(x / cell)] = 1;
|
|
29
|
+
}
|
|
30
|
+
const boxes = [];
|
|
31
|
+
for (let i = 0; i < occupied.length; i++) {
|
|
32
|
+
if (!occupied[i]) continue;
|
|
33
|
+
const queue = [i];
|
|
34
|
+
occupied[i] = 0;
|
|
35
|
+
let x0 = columns, y0 = rows, x1 = 0, y1 = 0;
|
|
36
|
+
for (let cursor = 0; cursor < queue.length; cursor++) {
|
|
37
|
+
const index = queue[cursor], x = index % columns, y = Math.floor(index / columns);
|
|
38
|
+
x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);
|
|
39
|
+
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
|
40
|
+
const nx = x + dx, ny = y + dy, next = ny * columns + nx;
|
|
41
|
+
if (nx >= 0 && nx < columns && ny >= 0 && ny < rows && occupied[next]) { occupied[next] = 0; queue.push(next); }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
let minX = mask.width, minY = mask.height, maxX = -1, maxY = -1;
|
|
45
|
+
for (let y = y0 * cell; y < Math.min(mask.height, (y1 + 1) * cell); y++) for (let x = x0 * cell; x < Math.min(mask.width, (x1 + 1) * cell); x++) {
|
|
46
|
+
if (!mask.data[(y * mask.width + x) * 4 + 3]) continue;
|
|
47
|
+
minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y);
|
|
48
|
+
}
|
|
49
|
+
boxes.push({ x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 });
|
|
50
|
+
}
|
|
51
|
+
return boxes;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const color = (image, x, y) => image.data.readUInt32LE((y * image.width + x) * 4);
|
|
55
|
+
function uniform(image, box) {
|
|
56
|
+
const x0 = Math.max(0, box.x - 1), y0 = Math.max(0, box.y - 1);
|
|
57
|
+
const first = color(image, x0, y0);
|
|
58
|
+
for (let y = y0; y < Math.min(image.height, box.y + box.height + 1); y++) for (let x = x0; x < Math.min(image.width, box.x + box.width + 1); x++) if (color(image, x, y) !== first) return false;
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function shifted(a, b, box) {
|
|
63
|
+
const x0 = Math.max(0, box.x - 2), y0 = Math.max(0, box.y - 2);
|
|
64
|
+
const x1 = Math.min(a.width, box.x + box.width + 2), y1 = Math.min(a.height, box.y + box.height + 2);
|
|
65
|
+
const matches = (dx, dy, stride) => {
|
|
66
|
+
let compared = 0;
|
|
67
|
+
for (let y = y0; y < y1; y += stride) for (let x = x0; x < x1; x += stride) {
|
|
68
|
+
if (x + dx < 0 || x + dx >= b.width || y + dy < 0 || y + dy >= b.height) return false;
|
|
69
|
+
if (color(a, x, y) !== color(b, x + dx, y + dy)) return false;
|
|
70
|
+
compared++;
|
|
71
|
+
}
|
|
72
|
+
return compared > 0;
|
|
73
|
+
};
|
|
74
|
+
const stride = Math.max(1, Math.floor(Math.sqrt(box.width * box.height / 1000)));
|
|
75
|
+
for (let distance = 1; distance <= 40; distance++) for (const [dx, dy] of [[0, distance], [0, -distance], [distance, 0], [-distance, 0]]) {
|
|
76
|
+
if (matches(dx, dy, stride) && matches(dx, dy, 1)) return { dx, dy };
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Pipeline: dilate differences on a grid, join components, and classify layout findings. */
|
|
82
|
+
export function findRegions(left, right, { unstable = [], gap = 6 } = {}) {
|
|
83
|
+
const mask = difference(left, right);
|
|
84
|
+
const instability = unstable.length === 2 && unstable[0]?.width ? difference(...unstable) : unstable.filter(Boolean)[0];
|
|
85
|
+
const unstableBoxes = instability ? components(instability, gap) : [];
|
|
86
|
+
if (instability) for (let i = 3; i < mask.data.length; i += 4) if (instability.data[i]) mask.data[i] = 0;
|
|
87
|
+
const regions = components(mask, gap).map(box => {
|
|
88
|
+
const shift = uniform(left, box) || uniform(right, box) ? null : shifted(left, right, box);
|
|
89
|
+
return { box, kind: shift ? "shift" : uniform(right, box) && !uniform(left, box) ? "missing" : uniform(left, box) && !uniform(right, box) ? "extra" : "changed", ...(shift ? { shift } : {}) };
|
|
90
|
+
});
|
|
91
|
+
for (let i = 0; i < regions.length; i++) for (let j = i + 1; j < regions.length; j++) {
|
|
92
|
+
const a = regions[i], b = regions[j];
|
|
93
|
+
if (a.kind !== "shift" || b.kind !== "shift" || a.shift.dx !== b.shift.dx || a.shift.dy !== b.shift.dy) continue;
|
|
94
|
+
if (Math.max(a.box.x, b.box.x) - Math.min(a.box.x + a.box.width, b.box.x + b.box.width) > 40 || Math.max(a.box.y, b.box.y) - Math.min(a.box.y + a.box.height, b.box.y + b.box.height) > 40) continue;
|
|
95
|
+
const x = Math.min(a.box.x, b.box.x), y = Math.min(a.box.y, b.box.y);
|
|
96
|
+
a.box = { x, y, width: Math.max(a.box.x + a.box.width, b.box.x + b.box.width) - x, height: Math.max(a.box.y + a.box.height, b.box.y + b.box.height) - y };
|
|
97
|
+
regions.splice(j--, 1);
|
|
98
|
+
}
|
|
99
|
+
regions.push(...unstableBoxes.map(box => ({ box, kind: "unstable" })));
|
|
100
|
+
regions.sort((a, b) => b.box.width * b.box.height - a.box.width * a.box.height);
|
|
101
|
+
for (const [index, region] of regions.entries()) {
|
|
102
|
+
region.id = index + 1;
|
|
103
|
+
if (region.kind === "shift") region.causedBy = regions.find(other => other !== region && other.kind !== "unstable" && other.kind !== "shift" && other.box.y <= region.box.y)?.id ?? null;
|
|
104
|
+
}
|
|
105
|
+
return regions;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Fragment: show baseline, comparison, and pixel difference with padding and nearest-neighbor scaling. */
|
|
109
|
+
export function regionCrop(left, right, box, padding = 8) {
|
|
110
|
+
const x = Math.max(0, box.x - padding), y = Math.max(0, box.y - padding);
|
|
111
|
+
const width = Math.min(left.width, box.x + box.width + padding) - x;
|
|
112
|
+
const height = Math.min(left.height, box.y + box.height + padding) - y;
|
|
113
|
+
const diff = difference(left, right);
|
|
114
|
+
const scale = Math.max(1, Math.ceil(600 / (width * 3)));
|
|
115
|
+
const crop = new PNG({ width: width * 3 * scale, height: height * scale });
|
|
116
|
+
[left, right, diff].forEach((source, panel) => {
|
|
117
|
+
for (let cy = 0; cy < height * scale; cy++) for (let cx = 0; cx < width * scale; cx++) {
|
|
118
|
+
const offset = ((y + Math.floor(cy / scale)) * source.width + x + Math.floor(cx / scale)) * 4;
|
|
119
|
+
source.data.copy(crop.data, (cy * crop.width + panel * width * scale + cx) * 4, offset, offset + 4);
|
|
120
|
+
}
|
|
121
|
+
});
|
|
122
|
+
return crop;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const digits = ["111101101101111", "010110010010111", "111001111100111", "111001111001111", "101101111001001", "111100111001111", "111100111101111", "111001001001001", "111101111101111", "111101111001111"];
|
|
126
|
+
/** Fragment: draw numbered boxes on both halves of the pair. */
|
|
127
|
+
export function boxPair(pair, regions) {
|
|
128
|
+
const half = pair.width / 2;
|
|
129
|
+
const pixel = (x, y) => { if (x >= 0 && x < pair.width && y >= 0 && y < pair.height) pair.data.set([255, 0, 0, 255], (y * pair.width + x) * 4); };
|
|
130
|
+
for (const region of regions) for (const offset of [0, half]) {
|
|
131
|
+
const { x, y, width, height } = region.box;
|
|
132
|
+
for (let dx = 0; dx < width; dx++) { pixel(x + offset + dx, y); pixel(x + offset + dx, y + height - 1); }
|
|
133
|
+
for (let dy = 0; dy < height; dy++) { pixel(x + offset, y + dy); pixel(x + offset + width - 1, y + dy); }
|
|
134
|
+
for (const [index, digit] of String(region.id).split("").entries()) for (let i = 0; i < 15; i++) if (digits[Number(digit)][i] === "1") for (let sy = 0; sy < 2; sy++) for (let sx = 0; sx < 2; sx++) pixel(offset + x + index * 8 + i % 3 * 2 + sx, Math.max(0, y - 12) + Math.floor(i / 3) * 2 + sy);
|
|
135
|
+
}
|
|
136
|
+
return pair;
|
|
137
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { PNG } from "pngjs";
|
|
4
|
+
import { findRegions, stableCapture, regionCrop } from "./regions.mjs";
|
|
5
|
+
|
|
6
|
+
function image(box) {
|
|
7
|
+
const png = new PNG({ width: 120, height: 80 });
|
|
8
|
+
png.data.fill(255);
|
|
9
|
+
if (box) for (let y = box.y; y < box.y + box.height; y++) for (let x = box.x; x < box.x + box.width; x++) png.data.set([20, 40, 80, 255], (y * png.width + x) * 4);
|
|
10
|
+
return png;
|
|
11
|
+
}
|
|
12
|
+
test("unchanged layout finds zero regions", () => assert.deepEqual(findRegions(image(), image()), []));
|
|
13
|
+
test("a four pixel translation is one shift", () => {
|
|
14
|
+
const regions = findRegions(image({ x: 20, y: 20, width: 40, height: 20 }), image({ x: 20, y: 24, width: 40, height: 20 }));
|
|
15
|
+
assert.equal(regions.length, 1);
|
|
16
|
+
assert.equal(regions[0].kind, "shift");
|
|
17
|
+
assert.deepEqual(regions[0].shift, { dx: 0, dy: 4 });
|
|
18
|
+
});
|
|
19
|
+
test("removed and added controls receive directional kinds", () => {
|
|
20
|
+
const box = image({ x: 20, y: 20, width: 40, height: 20 });
|
|
21
|
+
assert.equal(findRegions(box, image())[0].kind, "missing");
|
|
22
|
+
assert.equal(findRegions(image(), box)[0].kind, "extra");
|
|
23
|
+
});
|
|
24
|
+
test("unstable areas never become layout findings", () => {
|
|
25
|
+
const a = image({ x: 20, y: 20, width: 40, height: 20 });
|
|
26
|
+
assert.equal(findRegions(a, image(), { unstable: [a, image()] })[0].kind, "unstable");
|
|
27
|
+
});
|
|
28
|
+
test("double capture retries three times and retains the instability mask", async () => {
|
|
29
|
+
let calls = 0;
|
|
30
|
+
const result = await stableCapture(async () => ++calls % 2 ? image() : image({ x: 20, y: 20, width: 40, height: 20 }));
|
|
31
|
+
assert.equal(calls, 8);
|
|
32
|
+
assert.ok(result.unstable);
|
|
33
|
+
});
|
|
34
|
+
test("region crops contain three padded panels scaled to 600 pixels", () => {
|
|
35
|
+
const crop = regionCrop(image(), image(), { x: 20, y: 20, width: 10, height: 10 });
|
|
36
|
+
assert.ok(crop.width >= 600);
|
|
37
|
+
assert.ok(crop.height > 0);
|
|
38
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { open, mkdir, rename, rm } from "node:fs/promises";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { setTimeout } from "node:timers/promises";
|
|
5
|
+
|
|
6
|
+
/** Resource: one process owns each session while it reads, refreshes, and saves. */
|
|
7
|
+
export async function withFileLock(file, action, { timeout = 240000 } = {}) {
|
|
8
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
9
|
+
const lock = `${file}.lock`;
|
|
10
|
+
const started = Date.now();
|
|
11
|
+
let handle;
|
|
12
|
+
while (!handle) {
|
|
13
|
+
try { handle = await open(lock, "wx", 0o600); }
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (error.code !== "EEXIST") throw error;
|
|
16
|
+
if (Date.now() - started >= timeout) throw new Error("Session lock wait expired");
|
|
17
|
+
await setTimeout(50);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
try { return await action(); }
|
|
21
|
+
finally { await handle.close(); await rm(lock, { force: true }); }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Resource: readers see either the complete old JSON or the complete new JSON. */
|
|
25
|
+
export async function atomicJson(file, value) {
|
|
26
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
27
|
+
let handle;
|
|
28
|
+
try {
|
|
29
|
+
handle = await open(temporary, "wx", 0o600);
|
|
30
|
+
await handle.writeFile(JSON.stringify(value));
|
|
31
|
+
await handle.sync();
|
|
32
|
+
await handle.close();
|
|
33
|
+
handle = undefined;
|
|
34
|
+
await rename(temporary, file);
|
|
35
|
+
} finally {
|
|
36
|
+
if (handle) await handle.close();
|
|
37
|
+
await rm(temporary, { force: true });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { atomicJson, withFileLock } from "./session-files.mjs";
|
|
8
|
+
|
|
9
|
+
test("parallel processes serialize ledger updates and leave complete private JSON files", async () => {
|
|
10
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-lock-"));
|
|
11
|
+
const file = path.join(root, "ledger.json");
|
|
12
|
+
const module = new URL("./session-files.mjs", import.meta.url).href;
|
|
13
|
+
const code = `import { readFileSync } from 'node:fs'; import { atomicJson, withFileLock } from ${JSON.stringify(module)}; const file = process.argv[1]; for(let i=0;i<10;i++) await withFileLock(file, async () => { const value = JSON.parse(readFileSync(file)); await new Promise(r => setTimeout(r, 2)); await atomicJson(file, { count: value.count + 1 }); });`;
|
|
14
|
+
try {
|
|
15
|
+
await atomicJson(file, { count: 0 });
|
|
16
|
+
await Promise.all(Array.from({ length: 4 }, () => new Promise((resolve, reject) => {
|
|
17
|
+
const child = spawn(process.execPath, ["--input-type=module", "-e", code, file]);
|
|
18
|
+
let stderr = "";
|
|
19
|
+
child.stderr.on("data", data => stderr += data);
|
|
20
|
+
child.on("error", reject);
|
|
21
|
+
child.on("exit", code => code === 0 ? resolve() : reject(new Error(stderr)));
|
|
22
|
+
})));
|
|
23
|
+
assert.deepEqual(JSON.parse(readFileSync(file)), { count: 40 });
|
|
24
|
+
assert.deepEqual(readdirSync(root), ["ledger.json"]);
|
|
25
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("a failed writer releases its lock and preserves the previous JSON", async () => {
|
|
29
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-lock-fail-"));
|
|
30
|
+
const file = path.join(root, "state.json");
|
|
31
|
+
try {
|
|
32
|
+
await atomicJson(file, { old: true });
|
|
33
|
+
await assert.rejects(withFileLock(file, async () => { throw new Error("failed"); }), /failed/);
|
|
34
|
+
assert.deepEqual(JSON.parse(readFileSync(file)), { old: true });
|
|
35
|
+
await withFileLock(file, () => atomicJson(file, { renewed: true }));
|
|
36
|
+
assert.deepEqual(JSON.parse(readFileSync(file)), { renewed: true });
|
|
37
|
+
assert.deepEqual(readdirSync(root), ["state.json"]);
|
|
38
|
+
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
39
|
+
});
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
import { setupLocal, fixturePlan } from "./setup.mjs";
|
|
9
|
+
|
|
10
|
+
test("setup refuses cloud before launching a browser", async () => {
|
|
11
|
+
await assert.rejects(setupLocal({ baseUrl: "https://cloud.example" }, "cloud", {}), /localhost/);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test("local UI setup makes real requests, resumes ids, and creates no duplicates", async () => {
|
|
15
|
+
const records = new Map();
|
|
16
|
+
let writes = 0;
|
|
17
|
+
const server = http.createServer((request, response) => {
|
|
18
|
+
const kind = new URL(request.url, "http://localhost").searchParams.get("kind");
|
|
19
|
+
if (request.method === "POST") { records.set(kind, `id-${kind}`); writes++; response.writeHead(303, { location: `/?kind=${kind}` }).end(); return; }
|
|
20
|
+
response.setHeader("content-type", "text/html");
|
|
21
|
+
response.end(`<main>${records.has(kind) ? `<a data-testid="record" href="/records/${records.get(kind)}">QC-PARITY-TEST</a>` : '<form method="post"><label>Name<input name="name"></label><button>Create</button></form>'}</main>`);
|
|
22
|
+
});
|
|
23
|
+
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
24
|
+
const root = mkdtempSync(path.join(os.tmpdir(), "qc-setup-"));
|
|
25
|
+
const browser = await chromium.launch({ channel: "chrome", headless: true });
|
|
26
|
+
const target = { baseUrl: `http://127.0.0.1:${server.address().port}`, auth: { signedIn: "main" } };
|
|
27
|
+
const adapter = Object.fromEntries(fixturePlan.map(item => [item.kind, {
|
|
28
|
+
async find(page, ctx) {
|
|
29
|
+
await page.goto(`${ctx.baseUrl}/?kind=${item.kind}`);
|
|
30
|
+
return await page.getByTestId("record").count() ? (await page.getByTestId("record").getAttribute("href")).split("/").at(-1) : null;
|
|
31
|
+
},
|
|
32
|
+
async create(page, ctx) {
|
|
33
|
+
await page.getByRole("textbox", { name: "Name" }).fill(ctx.item.name);
|
|
34
|
+
await page.getByRole("button", { name: "Create" }).click();
|
|
35
|
+
await page.getByTestId("record").waitFor();
|
|
36
|
+
return (await page.getByTestId("record").getAttribute("href")).split("/").at(-1);
|
|
37
|
+
},
|
|
38
|
+
}]));
|
|
39
|
+
const sessionFactory = async () => { const context = await browser.newContext({ serviceWorkers: "block" }); return { context, page: await context.newPage(), close: () => context.close() }; };
|
|
40
|
+
try {
|
|
41
|
+
const options = { chromium, adapter, stateRoot: root, sessionFactory, timeout: 3000 };
|
|
42
|
+
const first = await setupLocal(target, "fixture", options);
|
|
43
|
+
assert.equal(Object.keys(first).length, fixturePlan.length);
|
|
44
|
+
assert.equal(writes, fixturePlan.length);
|
|
45
|
+
assert.deepEqual(await setupLocal(target, "fixture", options), first);
|
|
46
|
+
assert.equal(writes, fixturePlan.length);
|
|
47
|
+
assert.deepEqual(JSON.parse(readFileSync(path.join(root, "fixtures-fixture.json"))), first);
|
|
48
|
+
} finally { await browser.close(); await new Promise(resolve => server.close(resolve)); rmSync(root, { recursive: true, force: true }); }
|
|
49
|
+
});
|