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(/textbox "Username" [^\n]*: maria$/m);
184 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
185 expect(line).toMatch(/: •+$/);
186 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
187 expect(await page.locator("#pw").inputValue()).toBe("next");
188 });
189
190 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
191 await page.setContent(`
192 <input type="password" aria-label="PIN" value="123">
193 <input type="password" aria-label="Phrase" value="open sesame">
194 <p>PIN: 123. Code (123) id 1234</p>
195 <p>open sesame</p>`);
196 const text = (await takeSnapshot()).visibleText;
197 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
198 expect(text).not.toMatch(/open|sesame/);
199 await page.setContent(`
200 <p>${"x".repeat(19_995)}long-secret</p>
201 <input type="password" aria-label="Long" value="long-secret">`);
202 const cut = (await takeSnapshot()).visibleText;
203 expect(cut.length).toBe(20_000);
204 expect(cut.slice(-8)).toBe("xxx•••••");
205 });
206
207 it("shows a data: link or blocked data: navigation by media type only", async () => {
208 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
209 await page.setContent(`
210 <a download href="data:text/plain;charset="a,b",head PAYLOAD'tail">Key</a>
211 <a href="https://example.com/data:report,2026">Report</a>
212 <a href="#">data:text/plain,label</a>
213 <a href='"data:text/plain,relative'>Relative</a>
214 <a href=" data:text/plain,PAYLOAD">Spaced</a>
215 <a href="da	ta:text/plain,PAYLOAD">Tabbed</a>
216 <a href="data:text/plain,head
PAYLOAD">Separated</a>
217 <a href="data:PAYLOAD,x">Typeless</a>
218 <a href="data:text/plain,PAYLOAD">Vertical tab</a>
219 <a href="data:text/plain,PAYLOAD">Backspace</a>
220 <a id="controlled">Controlled</a>
221 <a id="escaped">Escaped</a>
222 <script>
223 controlled.href = "\\x01data:text/plain,PAYLOAD";
224 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
225 </script>`);
226 const tree = String((await takeSnapshot()).accessibilityTree);
227 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
228 expect(tree).toContain("/url: data:,…");
229 expect(tree).toContain("/url: https://example.com/data:report,2026");
230 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
231 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
232 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
233 });
234
235 it("redacts a data: link whose scheme a password value would mask", async () => {
236 await page.setContent(`
237 <input type="password" aria-label="Scheme" value="data">
238 <a download href="data:text/plain,PAYLOAD">Key</a>`);
239 const tree = String((await takeSnapshot()).accessibilityTree);
240 expect(tree).toContain("/url: ••••••••:text/plain,…");
241 expect(tree).not.toContain("PAYLOAD");
242 });
243
244 it("shows a data: page's own URL by media type only", async () => {
245 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
246 expect((await takeSnapshot()).url).toBe("data:text/html,…");
247 });
248
249 it("rejects refs from another tab", async () => {
250 await page.setContent("<button>same label</button>");
251 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
252 const other = await context.newPage();
253 await other.setContent("<button>same label</button>");
254 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
255 });
256
257 it("revokes refs after navigation even when labels are identical", async () => {
258 await page.goto("data:text/html,<button>continue</button>");
259 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
260 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
261 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
262 });
263
264 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
265 "does not allow native refs to bypass generation validation (%s)",
266 async (locator) => {
267 await page.setContent("<button>continue</button>");
268 await takeSnapshot();
269 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
270 },
271 );
272
273 it("preserves quoted attribute values containing ref engine text", async () => {
274 await page.setContent(
275 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
276 );
277 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
278 expect(await page.locator("button").textContent()).toBe("saved");
279 });
280
281 it("evaluates top-level await and returns the last expression's value", async () => {
282 await page.setContent("<title>Ready</title>");
283 const result = await ServerBrowserPage.evaluate(
284 cdp,
285 { expression: "await Promise.resolve(); document.title" },
286 5_000,
287 );
288 expect(result).toBe("Ready");
289 });
290
291 it("still awaits the promise an async function returns", async () => {
292 const result = await ServerBrowserPage.evaluate(
293 cdp,
294 { expression: "(async () => { await 0; return 1 })()" },
295 5_000,
296 );
297 expect(result).toBe(1);
298 });
299
300 it("does not rerun an expression whose SyntaxError is thrown at runtime", async () => {
301 const evaluation = ServerBrowserPage.evaluate(
302 cdp,
303 { expression: "window.runs = (window.runs ?? 0) + 1; new Function('await 0')" },
304 5_000,
305 );
306 await expect(evaluation).rejects.toThrow("await is only valid");
307 expect(await page.evaluate("window.runs")).toBe(1);
308 });
309
310 it("does not rerun an expression whose awaited browser call rejects with a SyntaxError", async () => {
311 let posts = 0;
312 await page.route("http://preview.test/**", (route) => {
313 if (route.request().method() === "POST") posts++;
314 return route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" });
315 });
316 await page.goto("http://preview.test/");
317 const evaluation = ServerBrowserPage.evaluate(
318 cdp,
319 {
320 expression:
321 "(async () => { const r = await fetch('/api', { method: 'POST' }); return r.json() })()",
322 },
323 5_000,
324 );
325 await expect(evaluation).rejects.toThrow("is not valid JSON");
326 expect(posts).toBe(1);
327 });
328
329 it("returns the result of a top-level await expression that reloads the page", async () => {
330 await page.route("http://preview.test/", (route) =>
331 route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" }),
332 );
333 await page.goto("http://preview.test/");
334 const result = await ServerBrowserPage.evaluate(
335 cdp,
336 { expression: "await 0; location.reload(); ({ clicked: true })" },
337 5_000,
338 );
339 expect(result).toEqual({ clicked: true });
340 });
341});
342
343describe("server browser snapshot screenshot", () => {
344 let browser: Browser;
345 let context: BrowserContext;
346
347 beforeAll(async () => {
348 // ServerBrowserContexts launches with these, and the capture scale depends on them.
349 browser = await chromium.launch({
350 headless: true,
351 args: ["--disable-gpu", "--force-device-scale-factor=2"],
352 });
353 });
354 afterAll(async () => {
355 await browser?.close();
356 });
357 beforeEach(async () => {
358 context = await browser.newContext({
359 viewport: { width: 1280, height: 800 },
360 deviceScaleFactor: 2,
361 });
362 });
363 afterEach(async () => {
364 await context.close();
365 });
366
367 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
368 const halves = (overlay: string) => `
369 <style>
370 body { margin: 0; background: white; }
371 .half { position: absolute; top: 0; width: 640px; height: 800px; }
372 .overlay { position: fixed; inset: 0; ${overlay} }
373 </style>
374 <div class="half" style="left: 0; background: #2563eb"></div>
375 <div class="half" style="left: 640px; background: #ef4444"></div>
376 <div class="overlay"></div>`;
377
378 const screenshotOf = async (html: string) => {
379 const page = await context.newPage();
380 await page.setContent(html);
381 const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot({
382 page,
383 cdp: await context.newCDPSession(page),
384 renderScale: 2,
385 fullScreenshot: true,
386 consoleEntries: [],
387 networkEntries: [],
388 actionTimeline: [],
389 });
390 // The server has no DOM types, so the decoder runs as page source.
391 const points = [
392 [0.15, 0.75],
393 [0.85, 0.25],
394 [0.85, 0.75],
395 ];
396 const pixels = (await page.evaluate(`(async () => {
397 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
398 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
399 const canvas = document.createElement("canvas");
400 canvas.width = bitmap.width;
401 canvas.height = bitmap.height;
402 const context = canvas.getContext("2d");
403 context.drawImage(bitmap, 0, 0);
404 return ${JSON.stringify(points)}.map(([x, y]) =>
405 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
406 );
407 })()`)) as Array<[number, number, number, number]>;
408 return { screenshot, fullScreenshot, pixels };
409 };
410 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
411 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
412
413 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
414 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
415
416 expect({
417 size: [screenshot.width, screenshot.height],
418 colors: pixels.map(colorOf),
419 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
420 });
421
422 it("captures a plain page at the shrunk size with its content in place", async () => {
423 const { screenshot, fullScreenshot, pixels } = await screenshotOf(halves(""));
424
425 expect({
426 size: [screenshot.width, screenshot.height],
427 fullSize: [fullScreenshot?.width, fullScreenshot?.height],
428 colors: pixels.map(colorOf),
429 }).toEqual({ size: [1280, 800], fullSize: [2560, 1600], colors: ["blue", "red", "red"] });
430 });
431
432 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
433 const page = await context.newPage();
434 await page.goto("data:text/xml,<a/>");
435 const { screenshot } = await ServerBrowserPage.snapshot({
436 page,
437 cdp: await context.newCDPSession(page),
438 renderScale: 2,
439 consoleEntries: [],
440 networkEntries: [],
441 actionTimeline: [],
442 });
443
444 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
445 });
446});
447
448describe("server browser drag", () => {
449 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
450 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
451 const box = { x: 0, y: 0, width: 20, height: 20 };
452 const targetBox = Promise.withResolvers<typeof box>();
453 const page = {
454 locator: (selector: string) =>
455 selector === "#card"
456 ? {
457 scrollIntoViewIfNeeded: async () => {},
458 boundingBox: async () => box,
459 dragTo: () => Promise.reject(timedOut),
460 }
461 : { boundingBox: () => targetBox.promise },
462 } as unknown as Page;
463 const unobserved: Array<unknown> = [];
464 const onUnhandled = (reason: unknown) => unobserved.push(reason);
465 process.on("unhandledRejection", onUnhandled);
466 try {
467 let finished = false;
468 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
469 () => null,
470 (error: unknown) => error,
471 );
472 void settled.then(() => (finished = true));
473 // Two macrotask turns: Node reports a rejection nobody observed after the first.
474 for (let turn = 0; turn < 2; turn++) {
475 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
476 await new Promise((resolve) => setImmediate(resolve));
477 }
478 expect(finished).toBe(false);
479 targetBox.resolve(box);
480
481 expect(await settled).toBe(timedOut);
482 expect(unobserved).toEqual([]);
483 } finally {
484 process.off("unhandledRejection", onUnhandled);
485 }
486 });
487});
488
489describe("server browser evaluate", () => {
490 it("does not retry a parse error that arrives after the timeout", async () => {
491 vi.useFakeTimers();
492 try {
493 const classic = Promise.withResolvers<unknown>();
494 const send = vi.fn((method: string) =>
495 method === "Runtime.evaluate" ? classic.promise : Promise.resolve({}),
496 );
497 const cdp = { send } as unknown as CDPSession;
498 const evaluation = ServerBrowserPage.evaluate(cdp, { expression: "await 0; 1" }, 10);
499 const rejected = expect(evaluation).rejects.toMatchObject({
500 tag: "PreviewAutomationTimeoutError",
501 });
502 await vi.advanceTimersByTimeAsync(10);
503 await rejected;
504 classic.resolve({
505 result: { type: "object" },
506 exceptionDetails: {
507 text: "Uncaught",
508 scriptId: "4",
509 exception: { type: "object", className: "SyntaxError" },
510 },
511 });
512 await classic.promise;
513 expect(send.mock.calls.map(([method]) => method)).toEqual([
514 "Runtime.evaluate",
515 "Runtime.terminateExecution",
516 ]);
517 } finally {
518 vi.useRealTimers();
519 }
520 });
521});
522
523describe("server browser net errors", () => {
524 it.each([
525 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
526 [
527 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
528 "ERR_HTTP2_PROTOCOL_ERROR",
529 -2,
530 ],
531 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
532 ])("reads the whole error name from %j", (errorText, description, code) => {
533 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
534 });
535});