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

ServerBrowserPage.test.ts

1,059 lines40.9 KB

1import { PreviewAutomationEvaluateInput } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import {
4 chromium,
5 type Browser,
6 type BrowserContext,
7 type CDPSession,
8 type Page,
9} from "playwright-core";
10import {
11 afterAll,
12 afterEach,
13 beforeAll,
14 beforeEach,
15 describe,
16 expect,
17 it,
18 vi,
19} from "vite-plus/test";
20​
21import * as ServerBrowserPage from "./ServerBrowserPage.ts";
22import { SessionControl } from "./SessionControl.ts";
23​
24const decodeEvaluateInput = Schema.decodeUnknownSync(PreviewAutomationEvaluateInput);
25​
26describe("JPEG screenshot dimensions", () => {
27 const encode = (bytes: number[]) => Buffer.from(bytes).toString("base64");
28 const frame = [0xff, 0xd8, 0xff, 0xc0, 0, 7, 8, 0, 24, 0, 32];
29​
30 it("reads valid dimensions and rejects invalid or incomplete frames", () => {
31 expect(ServerBrowserPage.jpegSize(encode(frame))).toEqual({ width: 32, height: 24 });
32 for (const bytes of [
33 [],
34 [0xff, 0xd8, 0xff, 0xe1, 0, 20, 1],
35 frame.slice(0, -1),
36 [...frame.slice(0, 7), 0, 0, 0, 32],
37 [...frame.slice(0, 9), 0, 0],
38 ]) {
39 expect(() => ServerBrowserPage.jpegSize(encode(bytes))).toThrow("Invalid JPEG screenshot.");
40 }
41 });
42});
43​
44describe("snapshot deadline diagnostics", () => {
45 const never = () => new Promise<never>(() => {});
46 const stalledSnapshot = async (options: {
47 readonly stalled?: "metrics";
48 readonly page?: Partial<Record<keyof Page, unknown>>;
49 readonly advanceMs: number;
50 }) => {
51 vi.useFakeTimers();
52 try {
53 const frame = {};
54 const page = {
55 viewportSize: () => ({ width: 1280, height: 800 }),
56 mainFrame: () => frame,
57 frames: () => [frame],
58 on: () => {},
59 evaluate: async () => ({
60 url: "about:blank",
61 title: "",
62 loading: false,
63 visibleText: "",
64 }),
65 ariaSnapshot: async () => "",
66 ...options.page,
67 } as unknown as Page;
68 const cdp = {
69 send: async (method: string) => {
70 if (options.stalled === "metrics") return never();
71 if (method === "Page.captureScreenshot") return { data: "" };
72 if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
73 if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
74 if (method === "Runtime.evaluate") return { result: { value: [] } };
75 throw new Error(`Unexpected command: ${method}`);
76 },
77 } as unknown as CDPSession;
78 const captured = ServerBrowserPage.snapshot({
79 page,
80 cdp,
81 renderScale: options.stalled === "metrics" ? "display" : 1,
82 consoleEntries: [],
83 networkEntries: [],
84 actionTimeline: [],
85 }).catch((error: unknown) => error);
86 await vi.advanceTimersByTimeAsync(options.advanceMs);
87 return await captured;
88 } finally {
89 vi.useRealTimers();
90 }
91 };
92​
93 it("identifies a stalled metrics read", async () => {
94 expect(await stalledSnapshot({ stalled: "metrics", advanceMs: 10_000 })).toMatchObject({
95 tag: "PreviewAutomationTimeoutError",
96 detail: { timeoutMs: 10_000, pendingStages: ["metrics"] },
97 });
98 });
99​
100 it("keeps an accessibility tree that hit its own timeout", async () => {
101 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
102 const captured = await stalledSnapshot({
103 page: { ariaSnapshot: () => Promise.reject(timedOut) },
104 advanceMs: 0,
105 });
106 expect(captured).toMatchObject({
107 tag: "PreviewAutomationTimeoutError",
108 detail: { timeoutMs: 10_000 },
109 });
110 expect((captured as ServerBrowserPage.ServerBrowserOperationError).detail).toMatchObject({
111 pendingStages: expect.arrayContaining(["accessibility tree"]),
112 });
113 });
114​
115 it("omits a timed-out stage after it succeeds on retry", async () => {
116 let attempts = 0;
117 const timedOut = Object.assign(new Error("Timeout exceeded"), { name: "TimeoutError" });
118 expect(
119 await stalledSnapshot({
120 page: {
121 evaluate: never,
122 ariaSnapshot: async () => {
123 if (attempts++ === 0) throw timedOut;
124 return "";
125 },
126 },
127 advanceMs: 10_000,
128 }),
129 ).toMatchObject({ detail: { timeoutMs: 10_000, pendingStages: ["page state"] } });
130 });
131​
132 it.each(["elementHandle", "contentFrame"] as const)(
133 "identifies stalled iframe %s lookup",
134 async (stage) => {
135 const main = {};
136 const child = { evaluate: never, parentFrame: () => main };
137 const captured = await stalledSnapshot({
138 page: {
139 mainFrame: () => main,
140 frames: () => [main, child],
141 context: () => ({
142 newCDPSession: () =>
143 Promise.reject(new Error("Only this preview tab's page can be attached")),
144 }),
145 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
146 locator: () => ({
147 elementHandle:
148 stage === "elementHandle" ? never : async () => ({ contentFrame: never }),
149 }),
150 },
151 advanceMs: 10_000,
152 });
153 expect(captured).toMatchObject({
154 detail: { timeoutMs: 10_000, pendingStages: expect.arrayContaining(["frames"]) },
155 });
156 },
157 );
158​
159 it("reports a frame that didn't answer as the frame's own timeout", async () => {
160 const main = {};
161 // A desktop tab refuses frame sessions, so the frame is read in its own world.
162 const child = { evaluate: never, parentFrame: () => main };
163 const captured = await stalledSnapshot({
164 page: {
165 mainFrame: () => main,
166 frames: () => [main, child],
167 context: () => ({
168 newCDPSession: () =>
169 Promise.reject(new Error("Only this preview tab's page can be attached")),
170 }),
171 ariaSnapshot: async () => "- iframe [ref=f1]:\n - text: inside",
172 locator: () => ({
173 elementHandle: async () => ({ contentFrame: async () => child, dispose: async () => {} }),
174 }),
175 },
176 // Both attempts wait out the frame; neither reaches the capture deadline.
177 advanceMs: 2_000,
178 });
179 expect(captured).toMatchObject({
180 tag: "PreviewAutomationTimeoutError",
181 detail: { timeoutMs: 1_000, pendingStages: ["frames"] },
182 });
183 });
184});
185​
186describe("server browser capture deadlines", () => {
187 it("releases control after an unanswered capture and ignores its late reply", async () => {
188 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
189 try {
190 const captured = Promise.withResolvers<{ data: string }>();
191 const send = vi.fn(async (method: string) =>
192 method === "Page.captureScreenshot"
193 ? captured.promise
194 : { result: { value: "still responsive" } },
195 );
196 const cdp = { send } as unknown as CDPSession;
197 const control = new SessionControl("agent");
198 let outcome: unknown;
199 const capture = control
200 .agent("agent", () => ServerBrowserPage.captureViewport(cdp, { format: "png" }))
201 .catch((cause: unknown) => {
202 outcome = cause;
203 });
204 const evaluation = control.agent("agent", () =>
205 ServerBrowserPage.evaluate(cdp, { expression: "document.title" }, 1_000),
206 );
207​
208 await vi.advanceTimersByTimeAsync(3_000);
209 expect(outcome).toMatchObject({
210 tag: "PreviewAutomationExecutionError",
211 message: expect.stringContaining("not producing screenshot frames"),
212 });
213 await capture;
214 expect(await evaluation).toBe("still responsive");
215 expect(vi.getTimerCount()).toBe(0);
216​
217 captured.resolve({ data: "late-frame" });
218 await captured.promise;
219 expect(outcome).toBeInstanceOf(ServerBrowserPage.ServerBrowserOperationError);
220 expect(send.mock.calls.map(([method]) => method)).toEqual([
221 "Page.captureScreenshot",
222 "Runtime.evaluate",
223 ]);
224 } finally {
225 vi.useRealTimers();
226 }
227 });
228});
229​
230describe("server browser element refs", () => {
231 let browser: Browser;
232 let context: BrowserContext;
233 let page: Page;
234 let cdp: CDPSession;
235​
236 beforeAll(async () => {
237 browser = await chromium.launch({ headless: true });
238 });
239 afterAll(async () => {
240 await browser?.close();
241 });
242 beforeEach(async () => {
243 context = await browser.newContext();
244 page = await context.newPage();
245 cdp = await context.newCDPSession(page);
246 });
247 afterEach(async () => {
248 await context.close();
249 });
250​
251 const takeSnapshot = () =>
252 ServerBrowserPage.snapshot({
253 page,
254 cdp,
255 renderScale: 1,
256 consoleEntries: [],
257 networkEntries: [],
258 actionTimeline: [],
259 });
260 const locators = (tree: unknown) => {
261 expect(typeof tree).toBe("string");
262 return Array.from(
263 String(tree).matchAll(/\[ref=([^\]]+)\]/g),
264 (match) => `aria-ref=${match[1]}`,
265 );
266 };
267 const buttonLocator = (tree: unknown, name: string) => {
268 const line = String(tree)
269 .split("\n")
270 .find((line) => line.includes(`button "${name}"`));
271 const locator = locators(line)[0];
272 expect(locator).toBeDefined();
273 return locator!;
274 };
275 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>`;
276​
277 it("does not report an empty interactiveElements list beside a tree full of controls", async () => {
278 await page.setContent(
279 `<a href="#signin">Sign in</a><button>Open menu</button><button>Dismiss local database notice</button>`,
280 );
281 const result = await takeSnapshot();
282 expect(buttonLocator(result.accessibilityTree, "Open menu")).toBeDefined();
283 expect(String(result.accessibilityTree)).toContain('link "Sign in"');
284 const elements = (
285 result as { readonly interactiveElements?: ReadonlyArray<{ readonly name: string }> }
286 ).interactiveElements;
287 if (elements !== undefined) {
288 expect(elements.map((element) => element.name)).toEqual(
289 expect.arrayContaining(["Sign in", "Open menu", "Dismiss local database notice"]),
290 );
291 }
292 });
293​
294 it("clicks the fifth repeated delete control without touching row one", async () => {
295 await page.setContent(repeatedRows);
296 const result = await takeSnapshot();
297 const buttons = String(result.accessibilityTree)
298 .split("\n")
299 .filter((line) => line.includes('button "delete"'));
300 expect(buttons).toHaveLength(5);
301 await ServerBrowserPage.click(page, { locator: locators(buttons[4])[0]!, timeoutMs: 1_000 });
302 expect(await page.locator("li").allTextContents()).toEqual([
303 "row 1delete",
304 "row 2delete",
305 "row 3delete",
306 "row 4delete",
307 ]);
308 });
309​
310 it("returns from a click once it opens a dialog", async () => {
311 await page.setContent(
312 `<button onclick="document.body.dataset.answer = String(confirm('sure?'))">Confirm</button>`,
313 );
314 const dialog = new Promise<import("playwright-core").Dialog>((resolve) =>
315 page.once("dialog", resolve),
316 );
317 await ServerBrowserPage.click(page, {
318 locator: buttonLocator((await takeSnapshot()).accessibilityTree, "Confirm"),
319 timeoutMs: 1_000,
320 });
321 await (await dialog).accept();
322 await expect.poll(() => page.locator("body").getAttribute("data-answer")).toBe("true");
323 });
324​
325 it("rejects ambiguous CSS controls without clicking any row", async () => {
326 await page.setContent(repeatedRows);
327 await expect(
328 ServerBrowserPage.click(page, {
329 selector: 'button[data-testid="delete-row"]',
330 timeoutMs: 1_000,
331 }),
332 ).rejects.toThrow(/strict mode violation/);
333 expect(await page.locator("li").count()).toBe(5);
334 });
335​
336 it("tells a click target that matches nothing from one that never becomes clickable", async () => {
337 await page.setContent(`<button hidden>hidden</button>`);
338 const failure = (selector: string) =>
339 ServerBrowserPage.click(page, { selector, timeoutMs: 500 }).then(
340 () => expect.unreachable(),
341 ServerBrowserPage.toOperationError,
342 );
343​
344 const absent = await failure(".definitely-no-such-t3-target");
345 expect(absent.tag).toBe("PreviewAutomationTimeoutError");
346 expect(absent.message).toBe(
347 '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.',
348 );
349 expect(absent.cause).toMatchObject({ name: "TimeoutError" });
350 const hidden = await failure("button");
351 expect(hidden.tag).toBe("PreviewAutomationTimeoutError");
352 expect(hidden.message).toBe(
353 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout. Playwright last saw: element is not visible.',
354 );
355 });
356​
357 it("gives a late target only the click's remaining time, not a fresh timeout", async () => {
358 await page.setContent(`<script>
359 setTimeout(() => document.body.insertAdjacentHTML("beforeend",
360 '<button id="save" disabled onclick="document.body.dataset.clicked = 1">Save</button>'), 1000);
361 setTimeout(() => document.querySelector("#save").disabled = false, 2500);
362 </script>`);
363 await expect(
364 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 2_000 }),
365 ).rejects.toThrow();
366 expect(await page.locator("body").getAttribute("data-clicked")).toBeNull();
367 });
368​
369 it("does not retarget a removed ref to a replacement node", async () => {
370 await page.setContent("<button onclick=\"this.textContent='clicked'\">original</button>");
371 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original");
372 await page.setContent("<button onclick=\"this.textContent='clicked'\">replacement</button>");
373 await expect(ServerBrowserPage.click(page, { locator, timeoutMs: 100 })).rejects.toThrow();
374 expect(await page.locator("button").textContent()).toBe("replacement");
375 });
376​
377 it("targets iframe input refs and preserves the parent form", async () => {
378 await page.setContent(
379 '<input aria-label="parent"><iframe srcdoc="<input aria-label=child>"></iframe>',
380 );
381 await page.frameLocator("iframe").getByRole("textbox").waitFor();
382 const result = await takeSnapshot();
383 const line = String(result.accessibilityTree)
384 .split("\n")
385 .find((line) => line.includes('textbox "child"'));
386 const locator = locators(line)[0]!;
387 await ServerBrowserPage.type(page, { locator, text: "inside iframe", clear: true });
388 expect(await page.frameLocator("iframe").getByRole("textbox").inputValue()).toBe(
389 "inside iframe",
390 );
391 expect(await page.getByRole("textbox", { name: "parent" }).inputValue()).toBe("");
392 });
393​
394 it("types after a click by coordinates into a shadow-root field, and refuses a field inside an editable frame", async () => {
395 await page.setContent(
396 `<div id="host"></div><div contenteditable="true"><iframe srcdoc="<input id=inner>"></iframe></div><script>document.getElementById("host").attachShadow({mode:"open"}).innerHTML = "<input id=field>";</script>`,
397 );
398 const field = page.locator("#host #field");
399 const box = (await field.boundingBox())!;
400 await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
401 await ServerBrowserPage.type(page, { text: "shadow" });
402 expect(await field.inputValue()).toBe("shadow");
403​
404 // Refused for now: focus inside a frame cannot be checked from the top document.
405 const inner = page.frameLocator("iframe").locator("#inner");
406 await inner.click();
407 await expect(ServerBrowserPage.type(page, { text: "frame" })).rejects.toMatchObject({
408 tag: "PreviewAutomationTargetNotEditableError",
409 });
410 expect(await inner.inputValue()).toBe("");
411 });
412​
413 it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => {
414 await page.setContent(`
415 <table><tr><td>password:</td><td><input id="pw" type="password" aria-label="Password"></td></tr></table>
416 <input aria-label="Username" value="maria">
417 <input type="password" aria-label='saved" [ref=e2]: x' placeholder="hint" value="saved-pass">
418 <input type="password" role="combobox" aria-label="Code" value="role-pass">
419 <input aria-label="PIN" style="-webkit-text-security: disc" value="styled-pass">
420 <div contenteditable style="-webkit-text-security: disc">editable-pass</div>
421 <iframe srcdoc="<input type=password aria-label=child value=frame-pass>"></iframe>
422 <iframe id="blank" src="javascript:false"></iframe>
423 <p>Order styled-pass-2</p>
424 <script>
425 // A frame that never commits a document, filled by its parent.
426 blank.contentDocument.body.innerHTML = "<input type=password aria-label=blank value=blank-pass>";
427 // Page script can't change the value the snapshot sees.
428 Object.defineProperty(HTMLInputElement.prototype, "value", { get: () => "" });
429 </script>`);
430 await page.frameLocator("iframe[srcdoc]").getByRole("textbox").waitFor();
431 await ServerBrowserPage.type(page, { locator: "#pw", text: "typed-pass" });
432 const result = await takeSnapshot();
433 const tree = String(result.accessibilityTree);
434 expect(tree).toContain('textbox "blank"');
435 expect(tree).not.toMatch(
436 /typed-pass|saved-pass|role-pass|styled-pass|editable-pass|frame-pass|blank-pass/,
437 );
438 expect(result.visibleText).not.toContain("editable-pass");
439 expect(result.visibleText).toContain("Order ••••••••-2");
440 expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m);
441 const line = tree.split("\n").find((line) => line.includes('textbox "Password"'));
442 expect(line).toMatch(/: •+$/);
443 await ServerBrowserPage.type(page, { locator: locators(line)[0]!, text: "next", clear: true });
444 expect(await page.locator("#pw").inputValue()).toBe("next");
445 });
446​
447 it("masks dotted values in page text next to punctuation, with odd spaces, and at the cut", async () => {
448 await page.setContent(`
449 <input type="password" aria-label="PIN" value="123">
450 <input type="password" aria-label="Phrase" value="open&nbsp;sesame">
451 <p>PIN: 123. Code (123) id 1234</p>
452 <p>open&nbsp;sesame</p>`);
453 const text = (await takeSnapshot()).visibleText;
454 expect(text).toContain("PIN: ••••••••. Code (••••••••) id 1234");
455 expect(text).not.toMatch(/open|sesame/);
456 await page.setContent(`
457 <p>${"x".repeat(19_995)}long-secret</p>
458 <input type="password" aria-label="Long" value="long-secret">`);
459 const cut = (await takeSnapshot()).visibleText;
460 expect(cut.length).toBe(20_000);
461 expect(cut.slice(-8)).toBe("xxx•••••");
462 });
463​
464 it("shows a data: link or blocked data: navigation by media type only", async () => {
465 // Chromium keeps raw spaces and quotes in both, so a payload can't be cut at either.
466 await page.setContent(`
467 <a download href="data:text/plain;charset=&quot;a,b&quot;,head PAYLOAD'tail">Key</a>
468 <a href="https://example.com/data:report,2026">Report</a>
469 <a href="#">data:text/plain,label</a>
470 <a href='"data:text/plain,relative'>Relative</a>
471 <a href=" data:text/plain,PAYLOAD">Spaced</a>
472 <a href="da&#9;ta:text/plain,PAYLOAD">Tabbed</a>
473 <a href="data:text/plain,head&#x2028;PAYLOAD">Separated</a>
474 <a href="data:PAYLOAD,x">Typeless</a>
475 <a href="&#11;data:text/plain,PAYLOAD">Vertical tab</a>
476 <a href="&#8;data:text/plain,PAYLOAD">Backspace</a>
477 <a id="controlled">Controlled</a>
478 <a id="escaped">Escaped</a>
479 <script>
480 controlled.href = "\\x01data:text/plain,PAYLOAD";
481 escaped.href = "\\x02da\\tta:text/plain,PAYLOAD";
482 </script>`);
483 const tree = String((await takeSnapshot()).accessibilityTree);
484 expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8);
485 expect(tree).toContain("/url: data:,…");
486 expect(tree).toContain("/url: https://example.com/data:report,2026");
487 expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/);
488 expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/);
489 expect(tree).toContain('/url: "\\"data:text/plain,relative"');
490 });
491​
492 it("redacts a data: link whose scheme a password value would mask", async () => {
493 await page.setContent(`
494 <input type="password" aria-label="Scheme" value="data">
495 <a download href="data:text/plain,PAYLOAD">Key</a>`);
496 const tree = String((await takeSnapshot()).accessibilityTree);
497 expect(tree).toContain("/url: ••••••••:text/plain,…");
498 expect(tree).not.toContain("PAYLOAD");
499 });
500​
501 it("shows a data: page's own URL by media type only", async () => {
502 await page.goto("data:text/html,<title>Key</title>PAYLOAD");
503 expect((await takeSnapshot()).url).toBe("data:text/html,…");
504 });
505​
506 it("rejects refs from another tab", async () => {
507 await page.setContent("<button>same label</button>");
508 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label");
509 const other = await context.newPage();
510 await other.setContent("<button>same label</button>");
511 await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/);
512 });
513​
514 it("revokes refs after navigation even when labels are identical", async () => {
515 await page.goto("data:text/html,<button>continue</button>");
516 const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue");
517 await page.goto("data:text/html,<button>continue</button><p>new document</p>");
518 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
519 });
520​
521 it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])(
522 "does not allow native refs to bypass generation validation (%s)",
523 async (locator) => {
524 await page.setContent("<button>continue</button>");
525 await takeSnapshot();
526 await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/);
527 },
528 );
529​
530 it("preserves quoted attribute values containing ref engine text", async () => {
531 await page.setContent(
532 '<button data-example=" >> aria-ref=e1" onclick="this.textContent=\'saved\'">save</button>',
533 );
534 await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' });
535 expect(await page.locator("button").textContent()).toBe("saved");
536 });
537​
538 it("evaluates top-level await and returns the last expression's value", async () => {
539 await page.setContent("<title>Ready</title>");
540 const result = await ServerBrowserPage.evaluate(
541 cdp,
542 { expression: "await Promise.resolve(); document.title" },
543 5_000,
544 );
545 expect(result).toBe("Ready");
546 });
547​
548 it("returns object contents even when a legacy caller asks for a remote reference", async () => {
549 const input = decodeEvaluateInput({
550 expression: "({ answer: 42, nested: { ready: true } })",
551 returnByValue: false,
552 });
553 const result = await ServerBrowserPage.evaluate(cdp, input, 5_000);
554 expect(result).toEqual({ answer: 42, nested: { ready: true } });
555 });
556​
557 it("still awaits the promise an async function returns", async () => {
558 const result = await ServerBrowserPage.evaluate(
559 cdp,
560 { expression: "(async () => { await 0; return 1 })()" },
561 5_000,
562 );
563 expect(result).toBe(1);
564 });
565​
566 it("does not rerun an expression whose SyntaxError is thrown at runtime", async () => {
567 const evaluation = ServerBrowserPage.evaluate(
568 cdp,
569 { expression: "window.runs = (window.runs ?? 0) + 1; new Function('await 0')" },
570 5_000,
571 );
572 await expect(evaluation).rejects.toThrow("await is only valid");
573 expect(await page.evaluate("window.runs")).toBe(1);
574 });
575​
576 it("does not rerun an expression whose awaited browser call rejects with a SyntaxError", async () => {
577 let posts = 0;
578 await page.route("http://preview.test/**", (route) => {
579 if (route.request().method() === "POST") posts++;
580 return route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" });
581 });
582 await page.goto("http://preview.test/");
583 const evaluation = ServerBrowserPage.evaluate(
584 cdp,
585 {
586 expression:
587 "(async () => { const r = await fetch('/api', { method: 'POST' }); return r.json() })()",
588 },
589 5_000,
590 );
591 await expect(evaluation).rejects.toThrow("is not valid JSON");
592 expect(posts).toBe(1);
593 });
594​
595 it("returns the result of a top-level await expression that reloads the page", async () => {
596 await page.route("http://preview.test/", (route) =>
597 route.fulfill({ contentType: "text/html", body: "<title>Ready</title>" }),
598 );
599 await page.goto("http://preview.test/");
600 const result = await ServerBrowserPage.evaluate(
601 cdp,
602 { expression: "await 0; location.reload(); ({ clicked: true })" },
603 5_000,
604 );
605 expect(result).toEqual({ clicked: true });
606 });
607});
608​
609describe("server browser snapshot screenshot", () => {
610 let browser: Browser;
611 let context: BrowserContext;
612​
613 beforeAll(async () => {
614 // ServerBrowserContexts launches with these, and the capture scale depends on them.
615 browser = await chromium.launch({
616 headless: true,
617 args: ["--disable-gpu", "--force-device-scale-factor=2"],
618 });
619 });
620 afterAll(async () => {
621 await browser?.close();
622 });
623 beforeEach(async () => {
624 context = await browser.newContext({
625 viewport: { width: 1280, height: 800 },
626 deviceScaleFactor: 2,
627 });
628 });
629 afterEach(async () => {
630 await context.close();
631 });
632​
633 // Blue on the left half and red on the right, so a mirrored left half shows up on the right.
634 const halves = (overlay: string) => `
635 <style>
636 body { margin: 0; background: white; }
637 .half { position: absolute; top: 0; width: 640px; height: 800px; }
638 .overlay { position: fixed; inset: 0; ${overlay} }
639 </style>
640 <div class="half" style="left: 0; background: #2563eb"></div>
641 <div class="half" style="left: 640px; background: #ef4444"></div>
642 <div class="overlay"></div>`;
643​
644 const screenshotOf = async (html: string) => {
645 const page = await context.newPage();
646 await page.setContent(html);
647 const input = {
648 page,
649 cdp: await context.newCDPSession(page),
650 renderScale: 2,
651 fullScreenshot: true,
652 consoleEntries: [],
653 networkEntries: [],
654 actionTimeline: [],
655 };
656 const { screenshot, fullScreenshot } = await ServerBrowserPage.snapshot(input);
657 // The server has no DOM types, so the decoder runs as page source.
658 const points = [
659 [0.15, 0.75],
660 [0.85, 0.25],
661 [0.85, 0.75],
662 ];
663 const pixels = (await page.evaluate(`(async () => {
664 const bytes = Uint8Array.from(atob(${JSON.stringify(screenshot.data)}), (char) => char.charCodeAt(0));
665 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
666 const canvas = document.createElement("canvas");
667 canvas.width = bitmap.width;
668 canvas.height = bitmap.height;
669 const context = canvas.getContext("2d");
670 context.drawImage(bitmap, 0, 0);
671 return ${JSON.stringify(points)}.map(([x, y]) =>
672 Array.from(context.getImageData(x * bitmap.width, y * bitmap.height, 1, 1).data),
673 );
674 })()`)) as Array<[number, number, number, number]>;
675 return { screenshot, fullScreenshot, pixels, input };
676 };
677 const colorOf = ([red, green, blue]: readonly [number, number, number, number]) =>
678 blue - red > 100 ? "blue" : red - blue > 100 ? "red" : `rgb(${red}, ${green}, ${blue})`;
679​
680 it("captures a blurred backdrop-filter page as rendered, not mirrored", async () => {
681 const { screenshot, pixels } = await screenshotOf(halves("backdrop-filter: blur(4px);"));
682​
683 expect({
684 size: [screenshot.width, screenshot.height],
685 colors: pixels.map(colorOf),
686 }).toEqual({ size: [1280, 800], colors: ["blue", "red", "red"] });
687 });
688​
689 it("captures a plain page at the shrunk size with its content in place", async () => {
690 const { screenshot, fullScreenshot, pixels, input } = await screenshotOf(halves(""));
691 const metadata = await ServerBrowserPage.snapshotMetadata(input);
692​
693 expect({
694 size: [screenshot.width, screenshot.height],
695 fullSize: [fullScreenshot?.width, fullScreenshot?.height],
696 metadataSize: metadata.screenshot,
697 colors: pixels.map(colorOf),
698 }).toEqual({
699 size: [1280, 800],
700 fullSize: [2560, 1600],
701 metadataSize: { width: 1280, height: 800 },
702 colors: ["blue", "red", "red"],
703 });
704 });
705​
706 it("records the destination of a finite entrance animation without waiting on infinite ones", async () => {
707 const page = await context.newPage();
708 await page.setContent(`
709 <style>
710 body { margin: 0; background: #2563eb; }
711 @keyframes enter { from { opacity: 0; } to { opacity: 1; } }
712 @keyframes pulse { from { opacity: 0.5; } to { opacity: 1; } }
713 button { animation: pulse 2s infinite; }
714 #paused { animation: enter 2s paused; }
715 #overlay { display: none; position: fixed; inset: 0; background: #ef4444; }
716 #overlay.open { display: block; animation: enter 200ms both; }
717 </style>
718 <button onclick="document.querySelector('#overlay').classList.add('open')">Open</button>
719 <div id="paused"></div>
720 <div id="overlay"></div>
721 `);
722 await page.getByRole("button", { name: "Open" }).click();
723 const frame = await ServerBrowserPage.captureFinalRecordingFrame(
724 await context.newCDPSession(page),
725 80,
726 );
727 expect(frame).toBeDefined();
728 const pixel = (await page.evaluate(`(async () => {
729 const bytes = Uint8Array.from(atob(${JSON.stringify(frame)}), char => char.charCodeAt(0));
730 const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" }));
731 const canvas = document.createElement("canvas");
732 canvas.width = bitmap.width;
733 canvas.height = bitmap.height;
734 const context = canvas.getContext("2d");
735 context.drawImage(bitmap, 0, 0);
736 return Array.from(context.getImageData(bitmap.width / 2, bitmap.height / 2, 1, 1).data);
737 })()`)) as [number, number, number, number];
738 expect(colorOf(pixel)).toBe("red");
739 });
740​
741 it("shrinks the screenshot of an XML document, whose createElement makes no canvas", async () => {
742 const page = await context.newPage();
743 await page.goto("data:text/xml,<a/>");
744 const { screenshot } = await ServerBrowserPage.snapshot({
745 page,
746 cdp: await context.newCDPSession(page),
747 renderScale: 2,
748 consoleEntries: [],
749 networkEntries: [],
750 actionTimeline: [],
751 });
752​
753 expect([screenshot.width, screenshot.height]).toEqual([1280, 800]);
754 });
755});
756​
757describe("server browser drag", () => {
758 it("fails the drag, not the server, when it times out while the cursor is still moving", async () => {
759 const timedOut = new Error("locator.dragTo: Timeout 30000ms exceeded.");
760 const box = { x: 0, y: 0, width: 20, height: 20 };
761 const targetBox = Promise.withResolvers<typeof box>();
762 const page = {
763 locator: (selector: string) =>
764 selector === "#card"
765 ? {
766 scrollIntoViewIfNeeded: async () => {},
767 boundingBox: async () => box,
768 dragTo: () => Promise.reject(timedOut),
769 }
770 : { boundingBox: () => targetBox.promise },
771 } as unknown as Page;
772 const unobserved: Array<unknown> = [];
773 const onUnhandled = (reason: unknown) => unobserved.push(reason);
774 process.on("unhandledRejection", onUnhandled);
775 try {
776 let finished = false;
777 const settled = ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }).then(
778 () => null,
779 (error: unknown) => error,
780 );
781 void settled.then(() => (finished = true));
782 // Two macrotask turns: Node reports a rejection nobody observed after the first.
783 for (let turn = 0; turn < 2; turn++) {
784 // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
785 await new Promise((resolve) => setImmediate(resolve));
786 }
787 expect(finished).toBe(false);
788 targetBox.resolve(box);
789​
790 expect(await settled).toBe(timedOut);
791 expect(unobserved).toEqual([]);
792 } finally {
793 process.off("unhandledRejection", onUnhandled);
794 }
795 });
796​
797 it("moves the mouse after dragstart, so pages that track a drag with mousemove see it", async () => {
798 const browser = await chromium.launch({ headless: true });
799 try {
800 const page = await browser.newPage();
801 await page.setContent(`
802 <div style="display:flex;gap:40px">
803 <div id="source" draggable="true" style="width:200px;height:120px">source</div>
804 <div id="target" style="width:200px;height:120px">target</div>
805 </div>
806 <script>
807 window.events = [];
808 let dragging = false;
809 source.addEventListener("dragstart", (event) => {
810 event.preventDefault();
811 dragging = true;
812 events.push("dragstart");
813 });
814 addEventListener("mousemove", () => dragging && events.push("mousemove"));
815 addEventListener("mouseup", () => events.push("mouseup"));
816 </script>`);
817​
818 await ServerBrowserPage.drag(page, { source: "#source", target: "#target" });
819​
820 const events = (await page.evaluate("window.events")) as Array<string>;
821 expect(events.slice(0, 2)).toEqual(["dragstart", "mousemove"]);
822 expect(events.at(-1)).toBe("mouseup");
823 } finally {
824 await browser.close();
825 }
826 });
827});
828​
829describe("server browser action timeout", () => {
830 type StepOptions = { readonly timeout?: number };
831 it.each([
832 {
833 action: "hover",
834 act: (page: Page) => ServerBrowserPage.hover(page, { selector: "#a", timeoutMs: 9_000 }),
835 last: ["#a.hover 1"],
836 },
837 {
838 action: "drag",
839 act: (page: Page) =>
840 ServerBrowserPage.drag(page, { source: "#a", target: "#b", timeoutMs: 9_000 }),
841 last: ["#a.dragTo 1", "#b.boundingBox 1"],
842 },
843 ])("gives the $action's steps one shared timeout", async ({ act, last }) => {
844 let now = 0;
845 using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
846 const steps: Array<string> = [];
847 const box = { x: 0, y: 0, width: 20, height: 20 };
848 const page = {
849 locator: (selector: string) => {
850 const record = (step: string, options: StepOptions) =>
851 steps.push(`${selector}.${step} ${options.timeout}`);
852 return {
853 // Each step that finds the target takes 5 of the 9 seconds.
854 scrollIntoViewIfNeeded: async (options: StepOptions) => {
855 record("scrollIntoViewIfNeeded", options);
856 now += 5_000;
857 },
858 boundingBox: async (options: StepOptions) => {
859 record("boundingBox", options);
860 now += 5_000;
861 return box;
862 },
863 hover: async (options: StepOptions) => record("hover", options),
864 dragTo: async (_target: unknown, options: StepOptions) => record("dragTo", options),
865 };
866 },
867 } as unknown as Page;
868​
869 await act(page);
870​
871 expect(steps).toEqual(["#a.scrollIntoViewIfNeeded 9000", "#a.boundingBox 4000", ...last]);
872 });
873});
874​
875describe("server browser click", () => {
876 it("clicks a target the page replaced while it was being scrolled into view", async () => {
877 let scrolls = 0;
878 const clicks: Array<unknown> = [];
879 const page = {
880 locator: () => ({
881 // Playwright resolves the node once; a page re-rendering it detaches that node.
882 scrollIntoViewIfNeeded: async () => {
883 if (scrolls++ === 0) {
884 throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM");
885 }
886 },
887 boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }),
888 click: async (options: unknown) => {
889 clicks.push(options);
890 },
891 count: async () => 1,
892 }),
893 once: () => {},
894 off: () => {},
895 } as unknown as Page;
896​
897 await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({
898 x: 10,
899 y: 10,
900 });
901 expect(clicks).toHaveLength(1);
902 });
903​
904 it("retries a replaced target only within the action's timeout", async () => {
905 vi.useFakeTimers();
906 try {
907 const timeouts: Array<number | undefined> = [];
908 const clicks: Array<unknown> = [];
909 const detached = new Error(
910 "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM",
911 );
912 const page = {
913 locator: () => ({
914 scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => {
915 timeouts.push(options?.timeout);
916 vi.advanceTimersByTime(60);
917 throw detached;
918 },
919 click: async (options: unknown) => {
920 clicks.push(options);
921 },
922 }),
923 } as unknown as Page;
924​
925 await expect(
926 ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }),
927 ).rejects.toBe(detached);
928 expect(timeouts).toEqual([100, 40]);
929 expect(clicks).toHaveLength(0);
930 } finally {
931 vi.useRealTimers();
932 }
933 });
934});
935​
936describe("server browser evaluate", () => {
937 it("does not retry a parse error that arrives after the timeout", async () => {
938 vi.useFakeTimers();
939 try {
940 const classic = Promise.withResolvers<unknown>();
941 const send = vi.fn((method: string) =>
942 method === "Runtime.evaluate" ? classic.promise : Promise.resolve({}),
943 );
944 const cdp = { send } as unknown as CDPSession;
945 const evaluation = ServerBrowserPage.evaluate(cdp, { expression: "await 0; 1" }, 10);
946 const rejected = expect(evaluation).rejects.toMatchObject({
947 tag: "PreviewAutomationTimeoutError",
948 });
949 await vi.advanceTimersByTimeAsync(10);
950 await rejected;
951 classic.resolve({
952 result: { type: "object" },
953 exceptionDetails: {
954 text: "Uncaught",
955 scriptId: "4",
956 exception: { type: "object", className: "SyntaxError" },
957 },
958 });
959 await classic.promise;
960 expect(send.mock.calls.map(([method]) => method)).toEqual([
961 "Runtime.evaluate",
962 "Runtime.terminateExecution",
963 ]);
964 } finally {
965 vi.useRealTimers();
966 }
967 });
968});
969​
970describe("server browser type", () => {
971 // As on a desktop tab whose Playwright utility world never answers.
972 const stalledPage = (focusAnswer: () => Promise<unknown>, typed: string[]) =>
973 ({
974 locator: () => ({ last: () => ({ count: () => new Promise<number>(() => {}) }) }),
975 evaluate: focusAnswer,
976 keyboard: { insertText: async (text: string) => void typed.push(text) },
977 }) as unknown as Page;
978​
979 it("types into the focused field when Playwright's utility world never answers", async () => {
980 vi.useFakeTimers();
981 try {
982 const typed: string[] = [];
983 let outcome: unknown = "pending";
984 const page = stalledPage(async () => true, typed);
985 void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then(
986 () => (outcome = "typed"),
987 (error: unknown) => (outcome = error),
988 );
989 await vi.advanceTimersByTimeAsync(300);
990 expect(outcome).toBe("typed");
991 expect(typed).toEqual(["hello"]);
992 } finally {
993 vi.useRealTimers();
994 }
995 });
996​
997 it("stops at its timeout without typing when the page never answers", async () => {
998 vi.useFakeTimers();
999 try {
1000 const typed: string[] = [];
1001 let outcome: unknown = "pending";
1002 const page = stalledPage(() => new Promise(() => {}), typed);
1003 void ServerBrowserPage.type(page, { text: "hello", timeoutMs: 300 }).then(
1004 () => (outcome = "typed"),
1005 (error: unknown) => (outcome = error),
1006 );
1007 await vi.advanceTimersByTimeAsync(300);
1008 expect(outcome).toMatchObject({
1009 tag: "PreviewAutomationTimeoutError",
1010 detail: { timeoutMs: 300 },
1011 });
1012 expect(typed).toEqual([]);
1013 } finally {
1014 vi.useRealTimers();
1016 });
1017});
1018​
1019describe("server browser unresponsive script", () => {
1020 it("leaves a page that answers alone", async () => {
1021 const send = vi.fn(async (_method: string) => ({}));
1022 await ServerBrowserPage.stopUnresponsiveScript({ send } as unknown as CDPSession);
1023 expect(send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
1024 });
1025});
1026​
1027describe("server browser wait", () => {
1028 it("ends at its timeout when a check never answers", async () => {
1029 // As on a desktop tab whose Playwright utility world never answers.
1030 const page = {
1031 locator: () => ({ count: () => new Promise<number>(() => {}) }),
1032 } as unknown as Page;
1033 vi.useFakeTimers();
1034 try {
1035 let failure: unknown;
1036 void ServerBrowserPage.waitFor(page, { selector: "button", timeoutMs: 300 }).catch(
1037 (error: unknown) => (failure = error),
1038 );
1039 await vi.advanceTimersByTimeAsync(300);
1040 expect(failure).toMatchObject({ tag: "PreviewAutomationTimeoutError" });
1041 } finally {
1042 vi.useRealTimers();
1044 });
1045});
1046​
1047describe("server browser net errors", () => {
1048 it.each([
1049 ["net::ERR_CONNECTION_REFUSED", "ERR_CONNECTION_REFUSED", -102],
1051 "page.goto: net::ERR_HTTP2_PROTOCOL_ERROR at https://localhost:5173/",
1052 "ERR_HTTP2_PROTOCOL_ERROR",
1053 -2,
1054 ],
1055 ["net::ERR_TLS13_DOWNGRADE_DETECTED", "ERR_TLS13_DOWNGRADE_DETECTED", -2],
1056 ])("reads the whole error name from %j", (errorText, description, code) => {
1057 expect(ServerBrowserPage.parseNetError(errorText)).toEqual({ description, code });
1058 });
1059});