Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3import { createCdpRelayConnection, type CdpRelayTarget } from "./CdpRelay.ts";
4
5const makeTarget = (
6 send: CdpRelayTarget["send"],
7 setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {},
8): CdpRelayTarget => ({
9 send,
10 targetId: async () => "GUEST-TARGET",
11 url: () => "http://localhost:4719/",
12 title: () => "Fixture",
13 userAgent: () => "Electron",
14 setDownloadDirectory,
15});
16
17// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
18// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
19const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
20
21describe("CDP relay", () => {
22 it("announces only the tab's page, under its real target id", async () => {
23 const written: Array<Record<string, unknown>> = [];
24 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
25 written.push(JSON.parse(raw)),
26 );
27 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
28 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
29 await settle();
30 const attach = written.findIndex((message) => message["id"] === 1);
31 expect(written.slice(attach, attach + 2)).toEqual([
32 { id: 1, result: {} },
33 {
34 method: "Target.attachedToTarget",
35 params: expect.objectContaining({
36 sessionId: "t3-preview-page",
37 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
38 }),
39 },
40 ]);
41 expect(written).toContainEqual({
42 id: 2,
43 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
44 });
45 });
46
47 it("forwards page commands to the tab and lets a slow one finish last", async () => {
48 const pending: Array<() => void> = [];
49 const send = vi.fn(
50 (method: string) =>
51 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
52 );
53 const written: Array<Record<string, unknown>> = [];
54 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
55 written.push(JSON.parse(raw)),
56 );
57 relay.receive(
58 JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
59 );
60 relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" }));
61 pending[1]!();
62 await settle();
63 expect(written).toEqual([
64 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
65 ]);
66 pending[0]!();
67 await settle();
68 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined, undefined);
69 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session", undefined);
70 expect(written.at(-1)).toEqual({
71 id: 5,
72 result: { method: "Page.captureScreenshot" },
73 sessionId: "t3-preview-page",
74 });
75 });
76
77 it("resumes paused child frames, so cross-site iframes run", async () => {
78 const send = vi.fn(async () => ({}));
79 const relay = createCdpRelayConnection(makeTarget(send), () => {});
80 relay.receive(
81 JSON.stringify({
82 id: 1,
83 method: "Runtime.runIfWaitingForDebugger",
84 sessionId: "t3-preview-page",
85 }),
86 );
87 relay.receive(
88 JSON.stringify({
89 id: 2,
90 method: "Runtime.runIfWaitingForDebugger",
91 sessionId: "iframe-session",
92 }),
93 );
94 await settle();
95 expect(send.mock.calls).toEqual([
96 ["Runtime.runIfWaitingForDebugger", {}, "iframe-session", undefined],
97 ]);
98 });
99
100 // Playwright enables focus emulation on every page it connects to, and Chromium then
101 // counts the guest as captured: a preview the panel hides keeps its timers unthrottled.
102 it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => {
103 const send = vi.fn(async () => ({}));
104 const written: Array<Record<string, unknown>> = [];
105 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
106 written.push(JSON.parse(raw)),
107 );
108 relay.receive(
109 JSON.stringify({
110 id: 1,
111 method: "Emulation.setFocusEmulationEnabled",
112 params: { enabled: true },
113 sessionId: "t3-preview-page",
114 }),
115 );
116 await settle();
117 expect(written).toEqual([{ id: 1, result: {}, sessionId: "t3-preview-page" }]);
118 expect(send).not.toHaveBeenCalled();
119 });
120
121 it("routes tab events to the page session once the page is announced", async () => {
122 const written: Array<Record<string, unknown>> = [];
123 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
124 written.push(JSON.parse(raw)),
125 );
126 relay.event("Page.loadEventFired", {}, undefined);
127 expect(written).toEqual([]);
128 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
129 await settle();
130 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
131 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
132 expect(written.slice(-2)).toEqual([
133 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
134 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
135 ]);
136 });
137});
138
139describe("CDP relay extra sessions", () => {
140 it("gives a second page session the page's commands and events", async () => {
141 const send = vi.fn(async () => ({}));
142 const written: Array<Record<string, unknown>> = [];
143 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
144 written.push(JSON.parse(raw)),
145 );
146 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
147 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
148 await settle();
149 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
150 .sessionId;
151 relay.receive(
152 JSON.stringify({
153 id: 3,
154 method: "Target.attachToTarget",
155 params: { targetId: "GUEST-TARGET", flatten: true },
156 sessionId: browserSession,
157 }),
158 );
159 relay.receive(
160 JSON.stringify({
161 id: 4,
162 method: "Target.attachToTarget",
163 params: { targetId: "SOMETHING-ELSE" },
164 sessionId: browserSession,
165 }),
166 );
167 await settle();
168 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
169 .sessionId;
170 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
171 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
172 await settle();
173 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra);
174 written.length = 0;
175 relay.event("Page.screencastFrame", { data: "x" }, undefined);
176 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
177 });
178});
179
180describe("CDP relay downloads", () => {
181 it("applies the server's download directory and reports downloads on the root session", async () => {
182 const send = vi.fn(async () => ({}));
183 const directories: Array<string | null> = [];
184 const written: Array<Record<string, unknown>> = [];
185 const relay = createCdpRelayConnection(
186 makeTarget(send, (directory) => directories.push(directory)),
187 (raw) => written.push(JSON.parse(raw)),
188 );
189 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
190 relay.receive(
191 JSON.stringify({
192 id: 2,
193 method: "Browser.setDownloadBehavior",
194 params: {
195 behavior: "allowAndName",
196 browserContextId: "t3-preview",
197 downloadPath: "/srv/artifacts",
198 eventsEnabled: true,
199 },
200 }),
201 );
202 await settle();
203 expect(directories).toEqual(["/srv/artifacts"]);
204 expect(send).toHaveBeenCalledWith(
205 "Browser.setDownloadBehavior",
206 { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },
207 undefined,
208 );
209 written.length = 0;
210 relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
211 expect(written).toEqual([
212 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
213 ]);
214 });
215});