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 {
9 afterAll,
10 afterEach,
11 beforeAll,
12 beforeEach,
13 describe,
14 expect,
15 it,
16 vi,
17} from "vite-plus/test";
18
19import * as ServerBrowserPage from "./ServerBrowserPage.ts";
20
21describe("server browser element refs", () => {
22 let browser: Browser;
23 let context: BrowserContext;
24 let page: Page;
25 let cdp: CDPSession;
26
27 beforeAll(async () => {
28 browser = await chromium.launch({ headless: true });
29 });
30 afterAll(async () => {
31 await browser?.close();
32 });
33 beforeEach(async () => {
34 context = await browser.newContext();
35 page = await context.newPage();
36 cdp = await context.newCDPSession(page);
37 });
38 afterEach(async () => {
39 await context.close();
40 });
41
42 const takeSnapshot = () =>
43 ServerBrowserPage.snapshot({
44 page,
45 cdp,
46 renderScale: 1,
47 consoleEntries: [],
48 networkEntries: [],
49 actionTimeline: [],
50 });
51 const locators = (tree: unknown) => {
52 expect(typeof tree).toBe("string");
53 return Array.from(
54 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
55 (match) => `aria-ref=${match[1]}`,
56 );
57 };
58 const buttonLocator = (tree: unknown, name: string) => {
59 const line = String(tree)
60 .split("\n")
61 .find((line) => line.includes(`button "${name}"`));
62 const locator = locators(line)[0];
63 expect(locator).toBeDefined();
64 return locator!;
65 };
66 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>`;
67
68 it("clicks the fifth repeated delete control without touching row one", async () => {
69 await page.setContent(repeatedRows);
70 const result = await takeSnapshot();
71 const buttons = String(result.accessibilityTree)
72 .split("\n")
73 .filter((line) => line.includes('button "delete"'));
74 expect(buttons).toHaveLength(5);
75 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
76 expect(await page.locator("li").allTextContents()).toEqual([
77 "row 1delete",
78 "row 2delete",
79 "row 3delete",
80 "row 4delete",
81 ]);
82 });
83
84 it("returns from a click once it opens a dialog", async () => {
85 await page.setContent(
86 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
87 );
88 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
89 page.once("dialog", resolve),
90 );
91 await ServerBrowserPage.click(page, {
92 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
93 timeoutMs: 1_000,
94 });
95 await (await dialog).accept();
96 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
97 });
98
99 it("rejects ambiguous CSS controls without clicking any row", async () => {
100 await page.setContent(repeatedRows);
101 await expect(
102 ServerBrowserPage.click(page, {
103 selector: 'button[data-testid="delete-row"]',
104 timeoutMs: 1_000,
105 }),
106 ).rejects.toThrow(/strict mode violation/);
107 expect(await page.locator("li").count()).toBe(5);
108 });
109
110 it("tells a click target that matches nothing from one that never becomes clickable", async () => {
111 await page.setContent(`<button hidden>hidden</button>`);
112 const failure = (selector: string) =>
113 ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
114 () => expect.unreachable(),
115 ServerBrowserPage.toOperationError,
116 );
117
118 const absent = await failure(".definitely-no-such-t3-target");
119 expect(absent.tag).toBe("PreviewAutomationTimeoutError");
120 expect(absent.message).toBe(
121 '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.',
122 );
123 expect(absent.cause).toMatchObject({ name: "TimeoutError" });
124 const hidden = await failure("button");
125 expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
126 expect(hidden.message).toBe(
127 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout.',
128 );
129 });
130
131 it("does not retarget a removed ref to a replacement node", async () => {
132 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
133 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
134 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
135 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
136 expect(await page.locator("button").textContent()).toBe("replacement");
137 });
138
139 it("targets iframe input refs and preserves the parent form", async () => {
140 await page.setContent(
141 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
142 );
143 await page.frameLocator("iframe").getByRole("textbox").waitFor();
144 const result = await takeSnapshot();
145 const line = String(result.accessibilityTree)
146 .split("\n")
147 .find((line) => line.includes('textbox "child"'));
148 const locator = locators(line)[0]!;
149 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
150 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
151 "inside iframe",
152 );
153 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
154 });
155
156 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
157 await page.setContent(`
158 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
159 <input aria-label="Username" value="maria">
160 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
161 <input type="password" role="combobox" aria-label="Code" value="role-pass">
162 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
163 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
164 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
165 <iframe id="blank" src="javascript:false"></iframe>
166 <p>Order styled-pass-2</p>
167 <script>
168 // A frame that never commits a document, filled by its parent.
169 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
170 // Page script can't change the value the snapshot sees.
171 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
172 </script>`);
173 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
174 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
175 const result = await takeSnapshot();
176 const tree = String(result.accessibilityTree);
177 expect(tree).toContain('textbox "blank"');
178 expect(tree).not.toMatch(
179 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
180 );
181 expect(result.visibleText).not.toContain("editable-pass");
182 expect(result.visibleText).toContain("Order ••••••••-2");
183 expect(tree).toMatch(/row "password: •+"/);
184 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
185 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
186 expect(line).toMatch(/: •+$/);
187 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
188 expect(await page.locator("#pw").inputValue()).toBe("next");
189 });
190
191 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
192 await page.setContent(`
193 <input type="password" aria-label="PIN" value="123">
194 <input type="password" aria-label="Phrase" value="open sesame">
195 <p>PIN: 123. Code (123) id 1234</p>
196 <p>open sesame</p>`);
197 const text = (await takeSnapshot()).visibleText;
198 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
199 expect(text).not.toMatch(/open|sesame/);
200 await page.setContent(`
201 <p>${"x".repeat(19_995)}long-secret</p>
202 <input type="password" aria-label="Long" value="long-secret">`);
203 const cut = (await takeSnapshot()).visibleText;
204 expect(cut.length).toBe(20_000);
205 expect(cut.slice(-8)).toBe("xxx•••••");
206 });
207
208 it("shows a data: link or blocked data: navigation by media type only", async () => {
209 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
210 await page.setContent(`
211 <a download href="data:text/plain;charset="a,b",head PAYLOAD'tail">Key</a>
212 <a href="https://example.com/data:report,2026">Report</a>
213 <a href="#">data:text/plain,label</a>
214 <a href='"data:text/plain,relative'>Relative</a>
215 <a href=" data:text/plain,PAYLOAD">Spaced</a>
216 <a href="da	ta:text/plain,PAYLOAD">Tabbed</a>
217 <a href="data:text/plain,head
PAYLOAD">Separated</a>
218 <a href="data:PAYLOAD,x">Typeless</a>
219 <a href="data:text/plain,PAYLOAD">Vertical tab</a>
220 <a href="data:text/plain,PAYLOAD">Backspace</a>
221 <a id="controlled">Controlled</a>
222 <a id="escaped">Escaped</a>
223 <script>
224 controlled.href = "\\x01data:text/plain,PAYLOAD";
225 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
226 </script>`);
227 const tree = String((await takeSnapshot()).accessibilityTree);
228 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
229 expect(tree).toContain("/url: data:,…");
230 expect(tree).toContain("/url: https://example.com/data:report,2026");
231 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
232 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
233 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
234 });
235
236 it("redacts a data: link whose scheme a password value would mask", async () => {
237 await page.setContent(`
238 <input type="password" aria-label="Scheme" value="data">
239 <a download href="data:text/plain,PAYLOAD">Key</a>`);
240 const tree = String((await takeSnapshot()).accessibilityTree);
241 expect(tree).toContain("/url: ••••••••:text/plain,…");
242 expect(tree).not.toContain("PAYLOAD");
243 });
244
245 it("shows a data: page's own URL by media type only", async () => {
246 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
247 expect((await takeSnapshot()).url).toBe("data:text/html,…");
248 });
249
250 it("rejects refs from another tab", async () => {
251 await page.setContent("<button>same label</button>");
252 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
253 const other = await context.newPage();
254 await other.setContent("<button>same label</button>");
255 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
256 });
257
258 it("revokes refs after navigation even when labels are identical", async () => {
259 await page.goto("data:text/html,<button>continue</button>");
260 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
261 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
262 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
263 });
264
265 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
266 "does not allow native refs to bypass generation validation (%s)",
267 async (locator) => {
268 await page.setContent("<button>continue</button>");
269 await takeSnapshot();
270 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
271 },
272 );
273
274 it("preserves quoted attribute values containing ref engine text", async () => {
275 await page.setContent(
276 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
277 );
278 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
279 expect(await page.locator("button").textContent()).toBe("saved");
280 });
281
282 it("evaluates top-level await and returns the last expression's value", async () => {
283 await page.setContent("<title>Ready</title>");
284 const result = await ServerBrowserPage.evaluate(
285 cdp,
286 { expression: "await Promise.resolve(); document.title" },
287 5_000,
288 );
289 expect(result).toBe("Ready");
290 });
291
292 it("still awaits the promise an async function returns", async () => {
293 const result = await ServerBrowserPage.evaluate(
294 cdp,
295 { expression: "(async () => { await 0; return 1 })()" },
296 5_000,
297 );
298 expect(result).toBe(1);
299 });
300
301 it("does not rerun an expression whose SyntaxError is thrown at runtime", async () => {
302 const evaluation = ServerBrowserPage.evaluate(
303 cdp,
304 { expression: "window.runs = (window.runs ?? 0) + 1; new Function('await 0')" },
305 5_000,
306 );
307 await expect(evaluation).rejects.toThrow("await is only valid");
308 expect(await page.evaluate("window.runs")).toBe(1);
309 });
310
311 it("does not rerun an expression whose awaited browser call rejects with a SyntaxError", async () => {
312 let posts = 0;
313 await page.route("http://preview.test/**", (route) => {
314 if (route.request().method() === "POST") posts++;
315 return route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" });
316 });
317 await page.goto("http://preview.test/");
318 const evaluation = ServerBrowserPage.evaluate(
319 cdp,
320 {
321 expression:
322 "(async () => { const r = await fetch('/api', { method: 'POST' }); return r.json() })()",
323 },
324 5_000,
325 );
326 await expect(evaluation).rejects.toThrow("is not valid JSON");
327 expect(posts).toBe(1);
328 });
329
330 it("returns the result of a top-level await expression that reloads the page", async () => {
331 await page.route("http://preview.test/", (route) =>
332 route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" }),
333 );
334 await page.goto("http://preview.test/");
335 const result = await ServerBrowserPage.evaluate(
336 cdp,
337 { expression: "await 0; location.reload(); ({ clicked: true })" },
338 5_000,
339 );
340 expect(result).toEqual({ clicked: true });
341 });
342});
343
344describe("server browser snapshot screenshot", () => {
345 let browser: Browser;
346 let context: BrowserContext;
347
348 beforeAll(async () => {
349 // ServerBrowserContexts launches with these, and the capture scale depends on them.
350 browser = await chromium.launch({
351 headless: true,
352 args: ["--disable-gpu", "--force-device-scale-factor=2"],
353 });
354 });
355 afterAll(async () => {
356 await browser?.close();
357 });
358 beforeEach(async () => {
359 context = await browser.newContext({
360 viewport: { width: 1280, height: 800 },
361 deviceScaleFactor: 2,
362 });
363 });
364 afterEach(async () => {
365 await context.close();
366 });
367
368 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
369 const halves = (overlay: string) => `
370 <style>
371 body { margin: 0; background: white; }
372 .half { position: absolute; top: 0; width: 640px; height: 800px; }
373 .overlay { position: fixed; inset: 0; ${overlay} }
374 </style>
375 <div class="half" style="left: 0; background: #2563eb"></div>
376 <div class="half" style="left: 640px; background: #ef4444"></div>
377 <div class="overlay"></div>`;
378
379 const screenshotOf = async (html: string) => {
380 const page = await context.newPage();
381 await page.setContent(html);
382 const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot({
383 page,
384 cdp: await context.newCDPSession(page),
385 renderScale: 2,
386 fullScreenshot: true,
387 consoleEntries: [],
388 networkEntries: [],
389 actionTimeline: [],
390 });
391 // The server has no DOM types, so the decoder runs as page source.
392 const points = [
393 [0.15, 0.75],
394 [0.85, 0.25],
395 [0.85, 0.75],
396 ];
397 const pixels = (await page.evaluate(`(async () => {
398 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
399 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
400 const canvas = document.createElement("canvas");
401 canvas.width = bitmap.width;
402 canvas.height = bitmap.height;
403 const context = canvas.getContext("2d");
404 context.drawImage(bitmap, 0, 0);
405 return ${JSON.stringify(points)}.map(([x, y]) =>
406 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
407 );
408 })()`)) as Array<[number, number, number, number]>;
409 return { screenshot, fullScreenshot, pixels };
410 };
411 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
412 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
413
414 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
415 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
416
417 expect({
418 size: [screenshot.width, screenshot.height],
419 colors: pixels.map(colorOf),
420 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
421 });
422
423 it("captures a plain page at the shrunk size with its content in place", async () => {
424 const { screenshot, fullScreenshot, pixels } = await screenshotOf(halves(""));
425
426 expect({
427 size: [screenshot.width, screenshot.height],
428 fullSize: [fullScreenshot?.width, fullScreenshot?.height],
429 colors: pixels.map(colorOf),
430 }).toEqual({ size: [1280, 800], fullSize: [2560, 1600], colors: ["blue", "red", "red"] });
431 });
432
433 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
434 const page = await context.newPage();
435 await page.goto("data:text/xml,<a/>");
436 const { screenshot } = await ServerBrowserPage.snapshot({
437 page,
438 cdp: await context.newCDPSession(page),
439 renderScale: 2,
440 consoleEntries: [],
441 networkEntries: [],
442 actionTimeline: [],
443 });
444
445 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
446 });
447});
448
449describe("server browser drag", () => {
450 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
451 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
452 const box = { x: 0, y: 0, width: 20, height: 20 };
453 const targetBox = Promise.withResolvers<typeof box>();
454 const page = {
455 locator: (selector: string) =>
456 selector === "#card"
457 ? {
458 scrollIntoViewIfNeeded: async () => {},
459 boundingBox: async () => box,
460 dragTo: () => Promise.reject(timedOut),
461 }
462 : { boundingBox: () => targetBox.promise },
463 } as unknown as Page;
464 const unobserved: Array<unknown> = [];
465 const onUnhandled = (reason: unknown) => unobserved.push(reason);
466 process.on("unhandledRejection", onUnhandled);
467 try {
468 let finished = false;
469 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
470 () => null,
471 (error: unknown) => error,
472 );
473 void settled.then(() => (finished = true));
474 // Two macrotask turns: Node reports a rejection nobody observed after the first.
475 for (let turn = 0; turn < 2; turn++) {
476 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
477 await new Promise((resolve) => setImmediate(resolve));
478 }
479 expect(finished).toBe(false);
480 targetBox.resolve(box);
481
482 expect(await settled).toBe(timedOut);
483 expect(unobserved).toEqual([]);
484 } finally {
485 process.off("unhandledRejection", onUnhandled);
486 }
487 });
488});
489
490describe("server browser evaluate", () => {
491 it("does not retry a parse error that arrives after the timeout", async () => {
492 vi.useFakeTimers();
493 try {
494 const classic = Promise.withResolvers<unknown>();
495 const send = vi.fn((method: string) =>
496 method === "Runtime.evaluate" ? classic.promise : Promise.resolve({}),
497 );
498 const cdp = { send } as unknown as CDPSession;
499 const evaluation = ServerBrowserPage.evaluate(cdp, { expression: "await 0; 1" }, 10);
500 const rejected = expect(evaluation).rejects.toMatchObject({
501 tag: "PreviewAutomationTimeoutError",
502 });
503 await vi.advanceTimersByTimeAsync(10);
504 await rejected;
505 classic.resolve({
506 result: { type: "object" },
507 exceptionDetails: {
508 text: "Uncaught",
509 scriptId: "4",
510 exception: { type: "object", className: "SyntaxError" },
511 },
512 });
513 await classic.promise;
514 expect(send.mock.calls.map(([method]) => method)).toEqual([
515 "Runtime.evaluate",
516 "Runtime.terminateExecution",
517 ]);
518 } finally {
519 vi.useRealTimers();
520 }
521 });
522});
523
524describe("server browser net errors", () => {
525 it.each([
526 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
527 [
528 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
529 "ERR_HTTP2_PROTOCOL_ERROR",
530 -2,
531 ],
532 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
533 ])("reads the whole error name from %j", (errorText, description, code) => {
534 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
535 });
536});