| 1 | import assert from "node:assert/strict"; |
| 2 | import { test } from "node:test"; |
| 3 | import { runInContext } from "node:vm"; |
| 4 | import { JSDOM } from "jsdom"; |
| 5 | import { DocumentRegistry } from "./documents.js"; |
| 6 | import { BROWSER_ERR_STALE_REFERENCE } from "./errors.js"; |
| 7 | import { FakeFrame, FakePage } from "./fakeGuestViews.js"; |
| 8 | import { LOCATE_SCRIPT_SOURCE, RESOLVE_SCRIPT_SOURCE, scriptCall, SELECT_SCRIPT_SOURCE, type LocateOutput, type ResolveOutput, type SelectOutput } from "./pageScripts.js"; |
| 9 | import { resolveRef } from "./refResolver.js"; |
| 10 | import { RpcError } from "../rpc.js"; |
| 11 | import { REGISTRY_KEY, takeSnapshot } from "./snapshot.js"; |
| 12 | import type { SnapshotOutput } from "./snapshotScript.js"; |
| 13 | import { SNAPSHOT_SCRIPT_SOURCE } from "./pageScripts.js"; |
| 14 | |
| 15 | // Script outputs are plain data but live in the page realm; deepStrictEqual |
| 16 | // compares prototypes, so JSON round-trip them before asserting. |
| 17 | const plain = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T; |
| 18 | |
| 19 | // jsdom has no layout: rects come from data-rect="x,y,w,h" (default 10x10) |
| 20 | // and elementFromPoint answers with whatever the test pinned. |
| 21 | function page(html: string) { |
| 22 | const dom = new JSDOM(`<!doctype html><html><body>${html}</body></html>`, { runScripts: "outside-only", pretendToBeVisual: true, url: "https://site.test/page" }); |
| 23 | const win = dom.window; |
| 24 | const computed = win.getComputedStyle.bind(win); |
| 25 | win.getComputedStyle = (element) => computed(element); |
| 26 | const hit: { element: Element | null } = { element: null }; |
| 27 | win.Element.prototype.getBoundingClientRect = function (this: Element) { |
| 28 | const spec = this.getAttribute("data-rect"); |
| 29 | const [x, y, width, height] = spec ? spec.split(",").map(Number) : [0, 0, 10, 10]; |
| 30 | return { x, y, width, height, left: x, top: y, right: x + width, bottom: y + height, toJSON: () => ({}) } as DOMRect; |
| 31 | }; |
| 32 | win.document.elementFromPoint = () => hit.element; |
| 33 | const context = dom.getInternalVMContext(); |
| 34 | const run = (code: string) => runInContext(code, context) as unknown; |
| 35 | const snapshot = (input: Partial<{ snapshotId: string; prefix: string; selector: string; budget: number }> = {}) => |
| 36 | run(scriptCall(SNAPSHOT_SCRIPT_SOURCE, { key: REGISTRY_KEY, snapshotId: "snap-1", prefix: "", selector: "", budget: 4000, ...input })) as SnapshotOutput; |
| 37 | const refFor = (selector: string) => { |
| 38 | const registry = run(`window[${JSON.stringify(REGISTRY_KEY)}]`) as { refs: Map<string, Element> }; |
| 39 | const element = win.document.querySelector(selector); |
| 40 | const ref = [...registry.refs].find(([, value]) => value === element)?.[0]; |
| 41 | assert.ok(ref, `missing ref for ${selector}`); |
| 42 | return ref; |
| 43 | }; |
| 44 | return { dom, win, hit, run, snapshot, refFor }; |
| 45 | } |
| 46 | |
| 47 | test("the snapshot walker emits roles, names, states and refs one node per line", () => { |
| 48 | const { snapshot } = page(` |
| 49 | <nav aria-label="Main"><a href="/home">Home</a><a>no href</a></nav> |
| 50 | <h2>Sign in</h2> |
| 51 | <form> |
| 52 | <label for="u">Username</label><input id="u" value="ann" placeholder="user"> |
| 53 | <input type="password" aria-label="Password" value="secret"> |
| 54 | <input type="checkbox" checked aria-label="Remember"> <button disabled>Go</button> |
| 55 | <select aria-label="Role"><option value="a">Admin</option><option value="b" selected>Basic</option></select> |
| 56 | <div hidden>hidden text</div><span aria-hidden="true">assistive only</span> |
| 57 | <p>Some <b>bold</b> text</p> |
| 58 | <div tabindex="0">Clickable card</div> |
| 59 | <textarea aria-label="Bio">hello</textarea> |
| 60 | <img alt="Logo"><img alt=""> |
| 61 | <input type="file" aria-label="Attach"> |
| 62 | <table><tr><th>Name</th><td>Ann</td></tr></table> |
| 63 | <ul><li>one</li><li data-rect="0,0,0,0">zero size</li></ul> |
| 64 | <details open><summary>More</summary>body</details> |
| 65 | </form>`); |
| 66 | const out = snapshot(); |
| 67 | for (const pattern of [/navigation "Main" ref=e\d+/, /link "Home" ref=e\d+/, /heading "Sign in" \[level=2\]/, /textbox "Username"/, /checkbox "Remember" \[checked\]/, /button "Go" \[disabled\]/, /option "Basic" \[selected\]/, /textbox "Bio"/, /img "Logo"/, /cell "Ann"/]) assert.match(out.tree, pattern); |
| 68 | assert.ok(out.refs > 10); |
| 69 | assert.match(out.docId, /^\d+(\.\d+)?:[a-z0-9]+$/); |
| 70 | assert.equal(out.tree.includes("secret"), false, "password values never appear"); |
| 71 | }); |
| 72 | |
| 73 | test("semantic queries expose ambiguity and pierce shadow DOM without exposing password values", () => { |
| 74 | const p = page('<button>Save</button><button>Save</button><input type="password" role="textbox" aria-label="Credential" value="do-not-expose"><div id="host"></div>'); |
| 75 | p.win.document.querySelector("#host")!.attachShadow({ mode: "open" }).innerHTML = '<button data-testid="shadow-save">Shadow save</button>'; |
| 76 | const observed = p.snapshot(); |
| 77 | assert.equal(observed.tree.includes("do-not-expose"), false); |
| 78 | const query = (criteria: object) => plain(p.run(scriptCall("pageQuery", { key: REGISTRY_KEY, snapshotId: "snap-1", docId: observed.docId, prefix: "", ...criteria }))) as { count: number; refs: string[]; ambiguous: boolean; error?: string }; |
| 79 | assert.equal(query({ role: "button", name: "Save" }).count, 2); |
| 80 | assert.equal(query({ role: "button", name: "Save" }).ambiguous, true); |
| 81 | assert.equal(query({ testId: "shadow-save" }).count, 1); |
| 82 | p.snapshot({ snapshotId: "new" }); |
| 83 | assert.equal(query({ text: "Save" }).error, "stale_document"); |
| 84 | p.dom.window.close(); |
| 85 | }); |
| 86 | |
| 87 | test("the walker honours selector scoping, the node budget and a stable document identity", () => { |
| 88 | const { snapshot, run } = page(`<main><button>A</button><button>B</button><button>C</button></main><aside><a href="#">x</a></aside>`); |
| 89 | const first = snapshot({ budget: 2 }); |
| 90 | assert.equal(first.tree.split("\n").length, 3); |
| 91 | assert.ok(first.truncated > 0); |
| 92 | assert.equal(first.nodes, 2); |
| 93 | const scoped = snapshot({ selector: "aside", prefix: "f2", snapshotId: "snap-2" }); |
| 94 | assert.match(scoped.tree, /link "x" ref=f2e\d+/); |
| 95 | assert.equal(snapshot({ selector: "#nope" }).tree, '(no element matches selector "#nope")'); |
| 96 | assert.equal(scoped.docId, first.docId, "the identity survives re-snapshots of the same document"); |
| 97 | const registry = run(`window[${JSON.stringify(REGISTRY_KEY)}]`) as { snapshotId: string; refs: Map<string, Element> }; |
| 98 | assert.equal(registry.snapshotId, "snap-1", "the latest snapshot owns the registry"); |
| 99 | assert.equal(run(`Object.keys(window).includes(${JSON.stringify(REGISTRY_KEY)})`), false, "the registry is not enumerable"); |
| 100 | }); |
| 101 | |
| 102 | test("resolve, locate and select validate the snapshot token and the document identity", () => { |
| 103 | const { snapshot, run, hit, win, refFor } = page(`<button data-rect="100,50,80,30">Go</button><select aria-label="S"><option value="1">One</option><option value="2">Two</option></select><input type="file" aria-label="F">`); |
| 104 | const out = snapshot(); |
| 105 | const buttonRef = refFor("button"), selectRef = refFor("select"), fileRef = refFor("input"); |
| 106 | const resolve = (ref: string, extra: Record<string, unknown> = {}) => |
| 107 | plain(run(scriptCall(RESOLVE_SCRIPT_SOURCE, { key: REGISTRY_KEY, snapshotId: "snap-1", docId: out.docId, ref, scroll: true, ...extra })) as ResolveOutput); |
| 108 | const resolved = resolve(buttonRef); |
| 109 | assert.deepEqual(resolved, { ok: true, x: 100, y: 50, width: 80, height: 30, tag: "button", type: "", disabled: false, editable: false, frameOffsetKnown: true }); |
| 110 | assert.deepEqual(resolve(buttonRef, { snapshotId: "old" }), { ok: false, reason: "stale" }); |
| 111 | assert.deepEqual(resolve(buttonRef, { docId: "other" }), { ok: false, reason: "stale" }); |
| 112 | assert.deepEqual(resolve("e99"), { ok: false, reason: "stale" }); |
| 113 | hit.element = win.document.querySelector("select"); |
| 114 | assert.deepEqual(resolve(buttonRef), { ok: false, reason: "element is covered by another element" }); |
| 115 | hit.element = null; |
| 116 | win.document.querySelector("button")?.remove(); |
| 117 | assert.deepEqual(resolve(buttonRef), { ok: false, reason: "element is no longer in the document" }); |
| 118 | |
| 119 | const located = plain(run(scriptCall(LOCATE_SCRIPT_SOURCE, { key: REGISTRY_KEY, snapshotId: "snap-1", docId: out.docId, ref: fileRef })) as LocateOutput); |
| 120 | assert.deepEqual(located, { ok: true, tag: "input", type: "file", path: "html > body:nth-child(2) > input:nth-child(2)" }); |
| 121 | |
| 122 | const changes: string[] = []; |
| 123 | win.document.querySelector("select")?.addEventListener("change", () => changes.push("change")); |
| 124 | const selected = plain(run(scriptCall(SELECT_SCRIPT_SOURCE, { key: REGISTRY_KEY, snapshotId: "snap-1", docId: out.docId, ref: selectRef, options: ["Two"] })) as SelectOutput); |
| 125 | assert.deepEqual(selected, { ok: true, selected: ["2"] }); |
| 126 | assert.equal((win.document.querySelector("select") as HTMLSelectElement).value, "2"); |
| 127 | assert.deepEqual(changes, ["change"]); |
| 128 | assert.deepEqual(plain(run(scriptCall(SELECT_SCRIPT_SOURCE, { key: REGISTRY_KEY, snapshotId: "snap-1", docId: out.docId, ref: selectRef, options: ["Nine"] }))), { ok: false, reason: "no option matches the requested values" }); |
| 129 | }); |
| 130 | |
| 131 | test("takeSnapshot assembles the main frame and reachable child frames under one token", async () => { |
| 132 | const main = page(`<h1>Top</h1><iframe title="Login frame"></iframe>`); |
| 133 | const child = page(`<button>Inside</button>`); |
| 134 | const broken = page(`<p>never seen</p>`); |
| 135 | const fake = new FakePage(7); |
| 136 | fake.url = "https://site.test/page"; |
| 137 | fake.title = "Site"; |
| 138 | const childFrame = new FakeFrame(701, "https://login.test/", (code) => child.run(code)); |
| 139 | const brokenFrame = new FakeFrame(702, "https://cross.test/", () => { |
| 140 | throw new Error("cross-origin"); |
| 141 | }); |
| 142 | fake.mainFrame.children.push(childFrame, brokenFrame); |
| 143 | childFrame.parent = fake.mainFrame; |
| 144 | brokenFrame.parent = fake.mainFrame; |
| 145 | fake.debugger.respond = (method, raw) => { |
| 146 | const params = raw as Record<string, unknown>; |
| 147 | if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main", url: fake.url }, childFrames: [{ frame: { id: "child", url: childFrame.url } }, { frame: { id: "broken", url: brokenFrame.url } }] } }; |
| 148 | if (method === "Page.createIsolatedWorld") return { executionContextId: params.frameId === "main" ? 0 : params.frameId === "child" ? 1 : 2 }; |
| 149 | if (method === "DOM.describeNode") return { node: { frameId: params.objectId } }; |
| 150 | if (method === "Target.getTargets") return { targetInfos: [] }; |
| 151 | if (method === "Runtime.evaluate") { |
| 152 | if (params.contextId === 0) return { result: { objectId: String(params.expression).includes("window.frames[0]") ? "child" : "broken" } }; |
| 153 | if (params.contextId === 2) throw new Error("frame crashed"); |
| 154 | return { result: { value: child.run(String(params.expression)) } }; |
| 155 | } |
| 156 | return {}; |
| 157 | }; |
| 158 | fake.run = (code, frame) => code.includes("reasonix:pageFrameGeometry") ? { x: 5, y: 5, scaleX: 1, scaleY: 1 } : (frame === fake.mainFrame ? main.run(code) : broken.run(code)); |
| 159 | const documents = new DocumentRegistry(() => "tok-1"); |
| 160 | const result = await takeSnapshot(fake, "tab-1", 3, "", documents); |
| 161 | assert.equal(result.documentToken, "tok-1"); |
| 162 | assert.equal(result.url, "https://site.test/page"); |
| 163 | assert.equal(result.title, "Site"); |
| 164 | assert.ok(result.refs >= 2); |
| 165 | assert.match(result.tree, /heading "Top" \[level=1\]/); |
| 166 | assert.match(result.tree, /frame f1 "https:\/\/login.test\/"/); |
| 167 | assert.match(result.tree, /button "Inside" ref=f1e\d+/); |
| 168 | const binding = documents.lookup("tok-1"); |
| 169 | assert.ok(binding); |
| 170 | assert.equal(binding.epoch, 3); |
| 171 | assert.deepEqual(binding.frames.map((frame) => [frame.prefix, frame.frameTreeNodeId]), [["", 700], ["f1", 701]]); |
| 172 | |
| 173 | const inside = await resolveRef(fake, binding, child.refFor("button"), false); |
| 174 | assert.ok(inside.ok); |
| 175 | assert.equal(inside.value.frame, childFrame); |
| 176 | assert.equal(inside.value.element.tag, "button"); |
| 177 | await assert.rejects(resolveRef(fake, binding, "f3e1", false), (error: unknown) => error instanceof RpcError && error.code === BROWSER_ERR_STALE_REFERENCE); |
| 178 | await assert.rejects(resolveRef(fake, binding, "bogus", false), (error: unknown) => error instanceof RpcError && error.code === BROWSER_ERR_STALE_REFERENCE); |
| 179 | |
| 180 | const documents2 = new DocumentRegistry(() => "tok-2"); |
| 181 | await takeSnapshot(fake, "tab-1", 4, "", documents2); |
| 182 | await assert.rejects(resolveRef(fake, binding, "e1", false), (error: unknown) => error instanceof RpcError && error.code === BROWSER_ERR_STALE_REFERENCE, "the older snapshot's refs are stale once a newer one exists"); |
| 183 | }); |
| 184 |