Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerBrowserPage.test.ts

390 lines16.1 KB

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&nbsp;sesame">
165 <p>PIN: 123. Code (123) id 1234</p>
166 <p>open&nbsp;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=&quot;a,b&quot;,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&#9;ta:text/plain,PAYLOAD">Tabbed</a>
187 <a href="data:text/plain,head&#x2028;PAYLOAD">Separated</a>
188 <a href="data:PAYLOAD,x">Typeless</a>
189 <a href="&#11;data:text/plain,PAYLOAD">Vertical tab</a>
190 <a href="&#8;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 snapshot screenshot", () => {
249 let browser: Browser;
250 let context: BrowserContext;
251​
252 beforeAll(async () => {
253 // ServerBrowserContexts launches with these, and the capture scale depends on them.
254 browser = await chromium.launch({
255 headless: true,
256 args: ["--disable-gpu", "--force-device-scale-factor=2"],
257 });
258 });
259 afterAll(async () => {
260 await browser?.close();
261 });
262 beforeEach(async () => {
263 context = await browser.newContext({
264 viewport: { width: 1280, height: 800 },
265 deviceScaleFactor: 2,
266 });
267 });
268 afterEach(async () => {
269 await context.close();
270 });
271​
272 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
273 const halves = (overlay: string) => `
274 <style>
275 body { margin: 0; background: white; }
276 .half { position: absolute; top: 0; width: 640px; height: 800px; }
277 .overlay { position: fixed; inset: 0; ${overlay} }
278 </style>
279 <div class="half" style="left: 0; background: #2563eb"></div>
280 <div class="half" style="left: 640px; background: #ef4444"></div>
281 <div class="overlay"></div>`;
282​
283 const screenshotOf = async (html: string) => {
284 const page = await context.newPage();
285 await page.setContent(html);
286 const { screenshot } = await ServerBrowserPage.snapshot({
287 page,
288 cdp: await context.newCDPSession(page),
289 renderScale: 2,
290 consoleEntries: [],
291 networkEntries: [],
292 actionTimeline: [],
293 });
294 // The server has no DOM types, so the decoder runs as page source.
295 const points = [
296 [0.15, 0.75],
297 [0.85, 0.25],
298 [0.85, 0.75],
299 ];
300 const pixels = (await page.evaluate(`(async () => {
301 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
302 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
303 const canvas = document.createElement("canvas");
304 canvas.width = bitmap.width;
305 canvas.height = bitmap.height;
306 const context = canvas.getContext("2d");
307 context.drawImage(bitmap, 0, 0);
308 return ${JSON.stringify(points)}.map(([x, y]) =>
309 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
310 );
311 })()`)) as Array<[number, number, number, number]>;
312 return { screenshot, pixels };
313 };
314 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
315 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
316​
317 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
318 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
319​
320 expect({
321 size: [screenshot.width, screenshot.height],
322 colors: pixels.map(colorOf),
323 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
324 });
325​
326 it("captures a plain page at the shrunk size with its content in place", async () => {
327 const { screenshot, pixels } = await screenshotOf(halves(""));
328​
329 expect({
330 size: [screenshot.width, screenshot.height],
331 colors: pixels.map(colorOf),
332 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
333 });
334​
335 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
336 const page = await context.newPage();
337 await page.goto("data:text/xml,<a/>");
338 const { screenshot } = await ServerBrowserPage.snapshot({
339 page,
340 cdp: await context.newCDPSession(page),
341 renderScale: 2,
342 consoleEntries: [],
343 networkEntries: [],
344 actionTimeline: [],
345 });
346​
347 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
348 });
349});
350​
351describe("server browser drag", () => {
352 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
353 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
354 const box = { x: 0, y: 0, width: 20, height: 20 };
355 const targetBox = Promise.withResolvers<typeof box>();
356 const page = {
357 locator: (selector: string) =>
358 selector === "#card"
359 ? {
360 scrollIntoViewIfNeeded: async () => {},
361 boundingBox: async () => box,
362 dragTo: () => Promise.reject(timedOut),
363 }
364 : { boundingBox: () => targetBox.promise },
365 } as unknown as Page;
366 const unobserved: Array<unknown> = [];
367 const onUnhandled = (reason: unknown) => unobserved.push(reason);
368 process.on("unhandledRejection", onUnhandled);
369 try {
370 let finished = false;
371 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
372 () => null,
373 (error: unknown) => error,
374 );
375 void settled.then(() => (finished = true));
376 // Two macrotask turns: Node reports a rejection nobody observed after the first.
377 for (let turn = 0; turn < 2; turn++) {
378 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
379 await new Promise((resolve) => setImmediate(resolve));
380 }
381 expect(finished).toBe(false);
382 targetBox.resolve(box);
383​
384 expect(await settled).toBe(timedOut);
385 expect(unobserved).toEqual([]);
386 } finally {
387 process.off("unhandledRejection", onUnhandled);
388 }
389 });
390});