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("tells a click target that matches nothing from one that never becomes clickable", async () => {
102 await page.setContent(`<button hidden>hidden</button>`);
103 const failure = (selector: string) =>
104 ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
105 () => expect.unreachable(),
106 ServerBrowserPage.toOperationError,
107 );
108
109 const absent = await failure(".definitely-no-such-t3-target");
110 expect(absent.tag).toBe("PreviewAutomationTimeoutError");
111 expect(absent.message).toBe(
112 'The click may have happened and removed its target or navigated; check the page before retrying. No element matches ".definitely-no-such-t3-target" after the timeout; take a fresh snapshot and use its locator.',
113 );
114 expect(absent.cause).toMatchObject({ name: "TimeoutError" });
115 const hidden = await failure("button");
116 expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
117 expect(hidden.message).toBe(
118 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout.',
119 );
120 });
121
122 it("does not retarget a removed ref to a replacement node", async () => {
123 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
124 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
125 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
126 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
127 expect(await page.locator("button").textContent()).toBe("replacement");
128 });
129
130 it("targets iframe input refs and preserves the parent form", async () => {
131 await page.setContent(
132 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
133 );
134 await page.frameLocator("iframe").getByRole("textbox").waitFor();
135 const result = await takeSnapshot();
136 const line = String(result.accessibilityTree)
137 .split("\n")
138 .find((line) => line.includes('textbox "child"'));
139 const locator = locators(line)[0]!;
140 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
141 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
142 "inside iframe",
143 );
144 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
145 });
146
147 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
148 await page.setContent(`
149 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
150 <input aria-label="Username" value="maria">
151 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
152 <input type="password" role="combobox" aria-label="Code" value="role-pass">
153 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
154 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
155 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
156 <iframe id="blank" src="javascript:false"></iframe>
157 <p>Order styled-pass-2</p>
158 <script>
159 // A frame that never commits a document, filled by its parent.
160 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
161 // Page script can't change the value the snapshot sees.
162 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
163 </script>`);
164 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
165 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
166 const result = await takeSnapshot();
167 const tree = String(result.accessibilityTree);
168 expect(tree).toContain('textbox "blank"');
169 expect(tree).not.toMatch(
170 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
171 );
172 expect(result.visibleText).not.toContain("editable-pass");
173 expect(result.visibleText).toContain("Order ••••••••-2");
174 expect(tree).toMatch(/row "password: •+"/);
175 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
176 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
177 expect(line).toMatch(/: •+$/);
178 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
179 expect(await page.locator("#pw").inputValue()).toBe("next");
180 });
181
182 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
183 await page.setContent(`
184 <input type="password" aria-label="PIN" value="123">
185 <input type="password" aria-label="Phrase" value="open sesame">
186 <p>PIN: 123. Code (123) id 1234</p>
187 <p>open sesame</p>`);
188 const text = (await takeSnapshot()).visibleText;
189 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
190 expect(text).not.toMatch(/open|sesame/);
191 await page.setContent(`
192 <p>${"x".repeat(19_995)}long-secret</p>
193 <input type="password" aria-label="Long" value="long-secret">`);
194 const cut = (await takeSnapshot()).visibleText;
195 expect(cut.length).toBe(20_000);
196 expect(cut.slice(-8)).toBe("xxx•••••");
197 });
198
199 it("shows a data: link or blocked data: navigation by media type only", async () => {
200 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
201 await page.setContent(`
202 <a download href="data:text/plain;charset="a,b",head PAYLOAD'tail">Key</a>
203 <a href="https://example.com/data:report,2026">Report</a>
204 <a href="#">data:text/plain,label</a>
205 <a href='"data:text/plain,relative'>Relative</a>
206 <a href=" data:text/plain,PAYLOAD">Spaced</a>
207 <a href="da	ta:text/plain,PAYLOAD">Tabbed</a>
208 <a href="data:text/plain,head
PAYLOAD">Separated</a>
209 <a href="data:PAYLOAD,x">Typeless</a>
210 <a href="data:text/plain,PAYLOAD">Vertical tab</a>
211 <a href="data:text/plain,PAYLOAD">Backspace</a>
212 <a id="controlled">Controlled</a>
213 <a id="escaped">Escaped</a>
214 <script>
215 controlled.href = "\\x01data:text/plain,PAYLOAD";
216 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
217 </script>`);
218 const tree = String((await takeSnapshot()).accessibilityTree);
219 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
220 expect(tree).toContain("/url: data:,…");
221 expect(tree).toContain("/url: https://example.com/data:report,2026");
222 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
223 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
224 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
225 });
226
227 it("redacts a data: link whose scheme a password value would mask", async () => {
228 await page.setContent(`
229 <input type="password" aria-label="Scheme" value="data">
230 <a download href="data:text/plain,PAYLOAD">Key</a>`);
231 const tree = String((await takeSnapshot()).accessibilityTree);
232 expect(tree).toContain("/url: ••••••••:text/plain,…");
233 expect(tree).not.toContain("PAYLOAD");
234 });
235
236 it("shows a data: page's own URL by media type only", async () => {
237 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
238 expect((await takeSnapshot()).url).toBe("data:text/html,…");
239 });
240
241 it("rejects refs from another tab", async () => {
242 await page.setContent("<button>same label</button>");
243 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
244 const other = await context.newPage();
245 await other.setContent("<button>same label</button>");
246 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
247 });
248
249 it("revokes refs after navigation even when labels are identical", async () => {
250 await page.goto("data:text/html,<button>continue</button>");
251 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
252 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
253 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
254 });
255
256 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
257 "does not allow native refs to bypass generation validation (%s)",
258 async (locator) => {
259 await page.setContent("<button>continue</button>");
260 await takeSnapshot();
261 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
262 },
263 );
264
265 it("preserves quoted attribute values containing ref engine text", async () => {
266 await page.setContent(
267 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
268 );
269 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
270 expect(await page.locator("button").textContent()).toBe("saved");
271 });
272});
273
274describe("server browser snapshot screenshot", () => {
275 let browser: Browser;
276 let context: BrowserContext;
277
278 beforeAll(async () => {
279 // ServerBrowserContexts launches with these, and the capture scale depends on them.
280 browser = await chromium.launch({
281 headless: true,
282 args: ["--disable-gpu", "--force-device-scale-factor=2"],
283 });
284 });
285 afterAll(async () => {
286 await browser?.close();
287 });
288 beforeEach(async () => {
289 context = await browser.newContext({
290 viewport: { width: 1280, height: 800 },
291 deviceScaleFactor: 2,
292 });
293 });
294 afterEach(async () => {
295 await context.close();
296 });
297
298 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
299 const halves = (overlay: string) => `
300 <style>
301 body { margin: 0; background: white; }
302 .half { position: absolute; top: 0; width: 640px; height: 800px; }
303 .overlay { position: fixed; inset: 0; ${overlay} }
304 </style>
305 <div class="half" style="left: 0; background: #2563eb"></div>
306 <div class="half" style="left: 640px; background: #ef4444"></div>
307 <div class="overlay"></div>`;
308
309 const screenshotOf = async (html: string) => {
310 const page = await context.newPage();
311 await page.setContent(html);
312 const { screenshot } = await ServerBrowserPage.snapshot({
313 page,
314 cdp: await context.newCDPSession(page),
315 renderScale: 2,
316 consoleEntries: [],
317 networkEntries: [],
318 actionTimeline: [],
319 });
320 // The server has no DOM types, so the decoder runs as page source.
321 const points = [
322 [0.15, 0.75],
323 [0.85, 0.25],
324 [0.85, 0.75],
325 ];
326 const pixels = (await page.evaluate(`(async () => {
327 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
328 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
329 const canvas = document.createElement("canvas");
330 canvas.width = bitmap.width;
331 canvas.height = bitmap.height;
332 const context = canvas.getContext("2d");
333 context.drawImage(bitmap, 0, 0);
334 return ${JSON.stringify(points)}.map(([x, y]) =>
335 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
336 );
337 })()`)) as Array<[number, number, number, number]>;
338 return { screenshot, pixels };
339 };
340 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
341 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
342
343 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
344 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
345
346 expect({
347 size: [screenshot.width, screenshot.height],
348 colors: pixels.map(colorOf),
349 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
350 });
351
352 it("captures a plain page at the shrunk size with its content in place", async () => {
353 const { screenshot, pixels } = await screenshotOf(halves(""));
354
355 expect({
356 size: [screenshot.width, screenshot.height],
357 colors: pixels.map(colorOf),
358 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
359 });
360
361 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
362 const page = await context.newPage();
363 await page.goto("data:text/xml,<a/>");
364 const { screenshot } = await ServerBrowserPage.snapshot({
365 page,
366 cdp: await context.newCDPSession(page),
367 renderScale: 2,
368 consoleEntries: [],
369 networkEntries: [],
370 actionTimeline: [],
371 });
372
373 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
374 });
375});
376
377describe("server browser drag", () => {
378 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
379 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
380 const box = { x: 0, y: 0, width: 20, height: 20 };
381 const targetBox = Promise.withResolvers<typeof box>();
382 const page = {
383 locator: (selector: string) =>
384 selector === "#card"
385 ? {
386 scrollIntoViewIfNeeded: async () => {},
387 boundingBox: async () => box,
388 dragTo: () => Promise.reject(timedOut),
389 }
390 : { boundingBox: () => targetBox.promise },
391 } as unknown as Page;
392 const unobserved: Array<unknown> = [];
393 const onUnhandled = (reason: unknown) => unobserved.push(reason);
394 process.on("unhandledRejection", onUnhandled);
395 try {
396 let finished = false;
397 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
398 () => null,
399 (error: unknown) => error,
400 );
401 void settled.then(() => (finished = true));
402 // Two macrotask turns: Node reports a rejection nobody observed after the first.
403 for (let turn = 0; turn < 2; turn++) {
404 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
405 await new Promise((resolve) => setImmediate(resolve));
406 }
407 expect(finished).toBe(false);
408 targetBox.resolve(box);
409
410 expect(await settled).toBe(timedOut);
411 expect(unobserved).toEqual([]);
412 } finally {
413 process.off("unhandledRejection", onUnhandled);
414 }
415 });
416});
417
418describe("server browser net errors", () => {
419 it.each([
420 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
421 [
422 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
423 "ERR_HTTP2_PROTOCOL_ERROR",
424 -2,
425 ],
426 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
427 ])("reads the whole error name from %j", (errorText, description, code) => {
428 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
429 });
430});