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("shows a data: page's own URL by media type only", async () => {
216 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
217 expect((await takeSnapshot()).url).toBe("data:text/html,…");
218 });
219
220 it("rejects refs from another tab", async () => {
221 await page.setContent("<button>same label</button>");
222 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
223 const other = await context.newPage();
224 await other.setContent("<button>same label</button>");
225 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
226 });
227
228 it("revokes refs after navigation even when labels are identical", async () => {
229 await page.goto("data:text/html,<button>continue</button>");
230 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
231 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
232 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
233 });
234
235 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
236 "does not allow native refs to bypass generation validation (%s)",
237 async (locator) => {
238 await page.setContent("<button>continue</button>");
239 await takeSnapshot();
240 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
241 },
242 );
243
244 it("preserves quoted attribute values containing ref engine text", async () => {
245 await page.setContent(
246 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
247 );
248 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
249 expect(await page.locator("button").textContent()).toBe("saved");
250 });
251});
252
253describe("server browser snapshot screenshot", () => {
254 let browser: Browser;
255 let context: BrowserContext;
256
257 beforeAll(async () => {
258 // ServerBrowserContexts launches with these, and the capture scale depends on them.
259 browser = await chromium.launch({
260 headless: true,
261 args: ["--disable-gpu", "--force-device-scale-factor=2"],
262 });
263 });
264 afterAll(async () => {
265 await browser?.close();
266 });
267 beforeEach(async () => {
268 context = await browser.newContext({
269 viewport: { width: 1280, height: 800 },
270 deviceScaleFactor: 2,
271 });
272 });
273 afterEach(async () => {
274 await context.close();
275 });
276
277 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
278 const halves = (overlay: string) => `
279 <style>
280 body { margin: 0; background: white; }
281 .half { position: absolute; top: 0; width: 640px; height: 800px; }
282 .overlay { position: fixed; inset: 0; ${overlay} }
283 </style>
284 <div class="half" style="left: 0; background: #2563eb"></div>
285 <div class="half" style="left: 640px; background: #ef4444"></div>
286 <div class="overlay"></div>`;
287
288 const screenshotOf = async (html: string) => {
289 const page = await context.newPage();
290 await page.setContent(html);
291 const { screenshot } = await ServerBrowserPage.snapshot({
292 page,
293 cdp: await context.newCDPSession(page),
294 renderScale: 2,
295 consoleEntries: [],
296 networkEntries: [],
297 actionTimeline: [],
298 });
299 // The server has no DOM types, so the decoder runs as page source.
300 const points = [
301 [0.15, 0.75],
302 [0.85, 0.25],
303 [0.85, 0.75],
304 ];
305 const pixels = (await page.evaluate(`(async () => {
306 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
307 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
308 const canvas = document.createElement("canvas");
309 canvas.width = bitmap.width;
310 canvas.height = bitmap.height;
311 const context = canvas.getContext("2d");
312 context.drawImage(bitmap, 0, 0);
313 return ${JSON.stringify(points)}.map(([x, y]) =>
314 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
315 );
316 })()`)) as Array<[number, number, number, number]>;
317 return { screenshot, pixels };
318 };
319 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
320 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
321
322 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
323 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
324
325 expect({
326 size: [screenshot.width, screenshot.height],
327 colors: pixels.map(colorOf),
328 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
329 });
330
331 it("captures a plain page at the shrunk size with its content in place", async () => {
332 const { screenshot, pixels } = await screenshotOf(halves(""));
333
334 expect({
335 size: [screenshot.width, screenshot.height],
336 colors: pixels.map(colorOf),
337 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
338 });
339
340 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
341 const page = await context.newPage();
342 await page.goto("data:text/xml,<a/>");
343 const { screenshot } = await ServerBrowserPage.snapshot({
344 page,
345 cdp: await context.newCDPSession(page),
346 renderScale: 2,
347 consoleEntries: [],
348 networkEntries: [],
349 actionTimeline: [],
350 });
351
352 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
353 });
354});
355
356describe("server browser drag", () => {
357 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
358 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
359 const box = { x: 0, y: 0, width: 20, height: 20 };
360 const targetBox = Promise.withResolvers<typeof box>();
361 const page = {
362 locator: (selector: string) =>
363 selector === "#card"
364 ? {
365 scrollIntoViewIfNeeded: async () => {},
366 boundingBox: async () => box,
367 dragTo: () => Promise.reject(timedOut),
368 }
369 : { boundingBox: () => targetBox.promise },
370 } as unknown as Page;
371 const unobserved: Array<unknown> = [];
372 const onUnhandled = (reason: unknown) => unobserved.push(reason);
373 process.on("unhandledRejection", onUnhandled);
374 try {
375 let finished = false;
376 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
377 () => null,
378 (error: unknown) => error,
379 );
380 void settled.then(() => (finished = true));
381 // Two macrotask turns: Node reports a rejection nobody observed after the first.
382 for (let turn = 0; turn < 2; turn++) {
383 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
384 await new Promise((resolve) => setImmediate(resolve));
385 }
386 expect(finished).toBe(false);
387 targetBox.resolve(box);
388
389 expect(await settled).toBe(timedOut);
390 expect(unobserved).toEqual([]);
391 } finally {
392 process.off("unhandledRejection", onUnhandled);
393 }
394 });
395});
396
397describe("server browser net errors", () => {
398 it.each([
399 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
400 [
401 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
402 "ERR_HTTP2_PROTOCOL_ERROR",
403 -2,
404 ],
405 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
406 ])("reads the whole error name from %j", (errorText, description, code) => {
407 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
408 });
409});