Open History to see the last commit
1import {
2 chromium,
3 type Browser,
4 type BrowserContext,
5 type CDPSession,
6 type Page,
7} from "playwright-core";
8import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vite-plus/test";
9
10import * as ServerBrowserPage from "./ServerBrowserPage.ts";
11
12describe("server browser element refs", () => {
13 let browser: Browser;
14 let context: BrowserContext;
15 let page: Page;
16 let cdp: CDPSession;
17
18 beforeAll(async () => {
19 browser = await chromium.launch({ headless: true });
20 });
21 afterAll(async () => {
22 await browser?.close();
23 });
24 beforeEach(async () => {
25 context = await browser.newContext();
26 page = await context.newPage();
27 cdp = await context.newCDPSession(page);
28 });
29 afterEach(async () => {
30 await context.close();
31 });
32
33 const takeSnapshot = () =>
34 ServerBrowserPage.snapshot({
35 page,
36 cdp,
37 renderScale: 1,
38 consoleEntries: [],
39 networkEntries: [],
40 actionTimeline: [],
41 });
42 const locators = (tree: unknown) => {
43 expect(typeof tree).toBe("string");
44 return Array.from(
45 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
46 (match) => `aria-ref=${match[1]}`,
47 );
48 };
49 const buttonLocator = (tree: unknown, name: string) => {
50 const line = String(tree)
51 .split("\n")
52 .find((line) => line.includes(`button "${name}"`));
53 const locator = locators(line)[0];
54 expect(locator).toBeDefined();
55 return locator!;
56 };
57 const repeatedRows = `<ul>${Array.from({ length: 5 }, (_, i) => `<li>row ${i + 1}<button data-testid="delete-row" onclick="this.parentElement.remove()">delete</button></li>`).join("")}</ul>`;
58
59 it("clicks the fifth repeated delete control without touching row one", async () => {
60 await page.setContent(repeatedRows);
61 const result = await takeSnapshot();
62 const buttons = String(result.accessibilityTree)
63 .split("\n")
64 .filter((line) => line.includes('button "delete"'));
65 expect(buttons).toHaveLength(5);
66 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
67 expect(await page.locator("li").allTextContents()).toEqual([
68 "row 1delete",
69 "row 2delete",
70 "row 3delete",
71 "row 4delete",
72 ]);
73 });
74
75 it("returns from a click once it opens a dialog", async () => {
76 await page.setContent(
77 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
78 );
79 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
80 page.once("dialog", resolve),
81 );
82 await ServerBrowserPage.click(page, {
83 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
84 timeoutMs: 1_000,
85 });
86 await (await dialog).accept();
87 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
88 });
89
90 it("rejects ambiguous CSS controls without clicking any row", async () => {
91 await page.setContent(repeatedRows);
92 await expect(
93 ServerBrowserPage.click(page, {
94 selector: 'button[data-testid="delete-row"]',
95 timeoutMs: 1_000,
96 }),
97 ).rejects.toThrow(/strict mode violation/);
98 expect(await page.locator("li").count()).toBe(5);
99 });
100
101 it("does not retarget a removed ref to a replacement node", async () => {
102 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
103 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
104 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
105 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
106 expect(await page.locator("button").textContent()).toBe("replacement");
107 });
108
109 it("targets iframe input refs and preserves the parent form", async () => {
110 await page.setContent(
111 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
112 );
113 await page.frameLocator("iframe").getByRole("textbox").waitFor();
114 const result = await takeSnapshot();
115 const line = String(result.accessibilityTree)
116 .split("\n")
117 .find((line) => line.includes('textbox "child"'));
118 const locator = locators(line)[0]!;
119 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
120 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
121 "inside iframe",
122 );
123 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
124 });
125
126 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
127 await page.setContent(`
128 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
129 <input aria-label="Username" value="maria">
130 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
131 <input type="password" role="combobox" aria-label="Code" value="role-pass">
132 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
133 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
134 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
135 <iframe id="blank" src="javascript:false"></iframe>
136 <p>Order styled-pass-2</p>
137 <script>
138 // A frame that never commits a document, filled by its parent.
139 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
140 // Page script can't change the value the snapshot sees.
141 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
142 </script>`);
143 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
144 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
145 const result = await takeSnapshot();
146 const tree = String(result.accessibilityTree);
147 expect(tree).toContain('textbox "blank"');
148 expect(tree).not.toMatch(
149 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
150 );
151 expect(result.visibleText).not.toContain("editable-pass");
152 expect(result.visibleText).toContain("Order ••••••••-2");
153 expect(tree).toMatch(/row "password: •+"/);
154 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
155 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
156 expect(line).toMatch(/: •+$/);
157 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
158 expect(await page.locator("#pw").inputValue()).toBe("next");
159 });
160
161 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
162 await page.setContent(`
163 <input type="password" aria-label="PIN" value="123">
164 <input type="password" aria-label="Phrase" value="open sesame">
165 <p>PIN: 123. Code (123) id 1234</p>
166 <p>open sesame</p>`);
167 const text = (await takeSnapshot()).visibleText;
168 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
169 expect(text).not.toMatch(/open|sesame/);
170 await page.setContent(`
171 <p>${"x".repeat(19_995)}long-secret</p>
172 <input type="password" aria-label="Long" value="long-secret">`);
173 const cut = (await takeSnapshot()).visibleText;
174 expect(cut.length).toBe(20_000);
175 expect(cut.slice(-8)).toBe("xxx•••••");
176 });
177
178 it("shows a data: link or blocked data: navigation by media type only", async () => {
179 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
180 await page.setContent(`
181 <a download href="data:text/plain;charset="a,b",head PAYLOAD'tail">Key</a>
182 <a href="https://example.com/data:report,2026">Report</a>
183 <a href="#">data:text/plain,label</a>
184 <a href='"data:text/plain,relative'>Relative</a>
185 <a href=" data:text/plain,PAYLOAD">Spaced</a>
186 <a href="da	ta:text/plain,PAYLOAD">Tabbed</a>
187 <a href="data:text/plain,head
PAYLOAD">Separated</a>
188 <a href="data:PAYLOAD,x">Typeless</a>
189 <a href="data:text/plain,PAYLOAD">Vertical tab</a>
190 <a href="data:text/plain,PAYLOAD">Backspace</a>
191 <a id="controlled">Controlled</a>
192 <a id="escaped">Escaped</a>
193 <script>
194 controlled.href = "\\x01data:text/plain,PAYLOAD";
195 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
196 </script>`);
197 const tree = String((await takeSnapshot()).accessibilityTree);
198 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
199 expect(tree).toContain("/url: data:,…");
200 expect(tree).toContain("/url: https://example.com/data:report,2026");
201 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
202 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
203 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
204 });
205
206 it("redacts a data: link whose scheme a password value would mask", async () => {
207 await page.setContent(`
208 <input type="password" aria-label="Scheme" value="data">
209 <a download href="data:text/plain,PAYLOAD">Key</a>`);
210 const tree = String((await takeSnapshot()).accessibilityTree);
211 expect(tree).toContain("/url: ••••••••:text/plain,…");
212 expect(tree).not.toContain("PAYLOAD");
213 });
214
215 it("rejects refs from another tab", async () => {
216 await page.setContent("<button>same label</button>");
217 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
218 const other = await context.newPage();
219 await other.setContent("<button>same label</button>");
220 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
221 });
222
223 it("revokes refs after navigation even when labels are identical", async () => {
224 await page.goto("data:text/html,<button>continue</button>");
225 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
226 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
227 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
228 });
229
230 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
231 "does not allow native refs to bypass generation validation (%s)",
232 async (locator) => {
233 await page.setContent("<button>continue</button>");
234 await takeSnapshot();
235 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
236 },
237 );
238
239 it("preserves quoted attribute values containing ref engine text", async () => {
240 await page.setContent(
241 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
242 );
243 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
244 expect(await page.locator("button").textContent()).toBe("saved");
245 });
246});
247
248describe("server browser drag", () => {
249 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
250 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
251 const box = { x: 0, y: 0, width: 20, height: 20 };
252 const targetBox = Promise.withResolvers<typeof box>();
253 const page = {
254 locator: (selector: string) =>
255 selector === "#card"
256 ? {
257 scrollIntoViewIfNeeded: async () => {},
258 boundingBox: async () => box,
259 dragTo: () => Promise.reject(timedOut),
260 }
261 : { boundingBox: () => targetBox.promise },
262 } as unknown as Page;
263 const unobserved: Array<unknown> = [];
264 const onUnhandled = (reason: unknown) => unobserved.push(reason);
265 process.on("unhandledRejection", onUnhandled);
266 try {
267 let finished = false;
268 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
269 () => null,
270 (error: unknown) => error,
271 );
272 void settled.then(() => (finished = true));
273 // Two macrotask turns: Node reports a rejection nobody observed after the first.
274 for (let turn = 0; turn < 2; turn++) {
275 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
276 await new Promise((resolve) => setImmediate(resolve));
277 }
278 expect(finished).toBe(false);
279 targetBox.resolve(box);
280
281 expect(await settled).toBe(timedOut);
282 expect(unobserved).toEqual([]);
283 } finally {
284 process.off("unhandledRejection", onUnhandled);
285 }
286 });
287});