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

CdpRelay.test.ts

356 lines13.7 KB

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​
17const makeRelay = (target: CdpRelayTarget, write: (raw: string) => void) =>
18 createCdpRelayConnection(target, write, () => {});
19​
20// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
21// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
22const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
23​
24describe("CDP relay", () => {
25 it("announces only the tab's page, under its real target id", async () => {
26 const written: Array<Record<string, unknown>> = [];
27 const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
28 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
29 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
30 await settle();
31 const attach = written.findIndex((message) => message["id"] === 1);
32 expect(written.slice(attach, attach + 2)).toEqual([
33 { id: 1, result: {} },
34 {
35 method: "Target.attachedToTarget",
36 params: expect.objectContaining({
37 sessionId: "t3-preview-page",
38 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
39 }),
40 },
41 ]);
42 expect(written).toContainEqual({
43 id: 2,
44 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
45 });
46 });
47​
48 it("forwards page commands to the tab and lets a slow one finish last", async () => {
49 const pending: Array<() => void> = [];
50 const send = vi.fn(
51 (method: string) =>
52 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
53 );
54 const written: Array<Record<string, unknown>> = [];
55 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
56 relay.receive(
57 JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
58 );
59 relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" }));
60 pending[1]!();
61 await settle();
62 expect(written).toEqual([
63 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
64 ]);
65 pending[0]!();
66 await settle();
67 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined, undefined);
68 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session", undefined);
69 expect(written.at(-1)).toEqual({
70 id: 5,
71 result: { method: "Page.captureScreenshot" },
72 sessionId: "t3-preview-page",
73 });
74 });
75​
76 it("resumes paused child frames, so cross-site iframes run", async () => {
77 const send = vi.fn(async () => ({}));
78 const relay = makeRelay(makeTarget(send), () => {});
79 relay.receive(
80 JSON.stringify({
81 id: 1,
82 method: "Runtime.runIfWaitingForDebugger",
83 sessionId: "t3-preview-page",
84 }),
85 );
86 relay.receive(
87 JSON.stringify({
88 id: 2,
89 method: "Runtime.runIfWaitingForDebugger",
90 sessionId: "iframe-session",
91 }),
92 );
93 await settle();
94 expect(send.mock.calls).toEqual([
95 ["Runtime.runIfWaitingForDebugger", {}, "iframe-session", undefined],
96 ]);
97 });
98​
99 // Playwright enables focus emulation on every page it connects to, and Chromium then
100 // counts the guest as captured: a preview the panel hides keeps its timers unthrottled.
101 it("acknowledges Playwright's focus emulation without forcing it onto the guest", async () => {
102 const send = vi.fn(async () => ({}));
103 const written: Array<Record<string, unknown>> = [];
104 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
105 relay.receive(
106 JSON.stringify({
107 id: 1,
108 method: "Emulation.setFocusEmulationEnabled",
109 params: { enabled: true },
110 sessionId: "t3-preview-page",
111 }),
112 );
113 await settle();
114 expect(written).toEqual([{ id: 1, result: {}, sessionId: "t3-preview-page" }]);
115 expect(send).not.toHaveBeenCalled();
116 });
117​
118 it("routes tab events to the page session once the page is announced", async () => {
119 const written: Array<Record<string, unknown>> = [];
120 const relay = makeRelay(makeTarget(vi.fn()), (raw) => written.push(JSON.parse(raw)));
121 relay.event("Page.loadEventFired", {}, undefined);
122 expect(written).toEqual([]);
123 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
124 await settle();
125 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
126 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
127 expect(written.slice(-2)).toEqual([
128 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
129 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
130 ]);
131 });
132});
133​
134describe("CDP relay extra sessions", () => {
135 it("gives a second page session the page's commands and events", async () => {
136 const send = vi.fn(async () => ({}));
137 const written: Array<Record<string, unknown>> = [];
138 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
139 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
140 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
141 await settle();
142 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
143 .sessionId;
144 relay.receive(
145 JSON.stringify({
146 id: 3,
147 method: "Target.attachToTarget",
148 params: { targetId: "GUEST-TARGET", flatten: true },
149 sessionId: browserSession,
150 }),
151 );
152 relay.receive(
153 JSON.stringify({
154 id: 4,
155 method: "Target.attachToTarget",
156 params: { targetId: "SOMETHING-ELSE" },
157 sessionId: browserSession,
158 }),
159 );
160 await settle();
161 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
162 .sessionId;
163 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
164 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
165 await settle();
166 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined, extra);
167 written.length = 0;
168 relay.event("Page.screencastFrame", { data: "x" }, undefined);
169 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
170 });
171});
172​
173describe("CDP relay downloads", () => {
174 it("captures preview downloads without changing the default browser context", async () => {
175 const send = vi.fn(async () => ({}));
176 const directories: Array<string | null> = [];
177 const written: Array<Record<string, unknown>> = [];
178 const relay = makeRelay(
179 makeTarget(send, (directory) => directories.push(directory)),
180 (raw) => written.push(JSON.parse(raw)),
181 );
182 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
183 relay.receive(
184 JSON.stringify({
185 id: 2,
186 method: "Browser.setDownloadBehavior",
187 params: {
188 behavior: "allowAndName",
189 browserContextId: "t3-preview",
190 downloadPath: "/srv/artifacts",
191 eventsEnabled: true,
192 },
193 }),
194 );
195 await settle();
196 expect(directories).toEqual(["/srv/artifacts"]);
197 expect(send.mock.calls).toEqual([
198 ["Page.setDownloadBehavior", { behavior: "default" }, undefined],
199 ]);
200 written.length = 0;
201 relay.event("Page.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
202 relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");
203 expect(written).toEqual([
204 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
205 { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } },
206 ]);
207 });
208​
209 it("keeps denial scoped to the preview and restores Electron's save handling when allowed", async () => {
210 const send = vi.fn(async () => ({}));
211 const directories: Array<string | null> = [];
212 const relay = makeRelay(
213 makeTarget(send, (directory) => directories.push(directory)),
214 () => {},
215 );
216 for (const [id, behavior] of ["deny", "allowAndName"].entries()) {
217 relay.receive(
218 JSON.stringify({
219 id,
220 method: "Browser.setDownloadBehavior",
221 params: { behavior, downloadPath: "/srv/artifacts" },
222 }),
223 );
224 await settle();
225 }
226 expect(directories).toEqual([null, "/srv/artifacts"]);
227 expect(send.mock.calls).toEqual([
228 ["Page.setDownloadBehavior", { behavior: "deny" }, undefined],
229 ["Page.setDownloadBehavior", { behavior: "default" }, undefined],
230 ]);
231 });
232​
233 it("does not publish download events when the connection has disabled them", async () => {
234 const written: Array<Record<string, unknown>> = [];
235 const relay = makeRelay(makeTarget(vi.fn(async () => ({}))), (raw) =>
236 written.push(JSON.parse(raw)),
237 );
238 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
239 relay.receive(
240 JSON.stringify({
241 id: 2,
242 method: "Browser.setDownloadBehavior",
243 params: { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: false },
244 }),
245 );
246 await settle();
247 written.length = 0;
248 relay.event("Page.downloadWillBegin", { guid: "g1" }, "");
249 relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");
250 expect(written).toEqual([]);
251 });
252​
253 it.each([false, true])(
254 "keeps the previous download configuration (events enabled: %s) when configuration fails",
255 async (enabled) => {
256 const send = vi
257 .fn(async () => ({}))
258 .mockResolvedValueOnce({})
259 .mockRejectedValueOnce(new Error("Page command rejected"));
260 const written: Array<Record<string, unknown>> = [];
261 let directory: string | null = null;
262 const relay = makeRelay(
263 makeTarget(send, (value) => {
264 directory = value;
265 }),
266 (raw) => written.push(JSON.parse(raw)),
267 );
268 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
269 for (const [id, eventsEnabled] of [enabled, !enabled].entries()) {
270 relay.receive(
271 JSON.stringify({
272 id: id + 2,
273 method: "Browser.setDownloadBehavior",
274 params: {
275 behavior: id === 1 && enabled ? "deny" : "allowAndName",
276 downloadPath: id === 0 ? "/srv/artifacts" : "/srv/new-artifacts",
277 eventsEnabled,
278 },
279 }),
280 );
281 await settle();
282 }
283 expect(written).toContainEqual({
284 id: 3,
285 error: { code: -32000, message: "Page command rejected" },
286 });
287 expect(directory).toBe("/srv/artifacts");
288 written.length = 0;
289 relay.event("Page.downloadWillBegin", { guid: "g1" }, "");
290 relay.event("Page.downloadProgress", { guid: "g1", state: "completed" }, "");
291 expect(written).toEqual(
292 enabled
293 ? [
294 { method: "Browser.downloadWillBegin", params: { guid: "g1" } },
295 { method: "Browser.downloadProgress", params: { guid: "g1", state: "completed" } },
296 ]
297 : [],
298 );
299 },
300 );
301});
302​
303describe("CDP relay payload budget", () => {
304 // 2,048 references to one 40 KiB string: about 80 MiB once serialized, little memory here.
305 const oversized = Array(2048).fill("x".repeat(40 * 1024));
306​
307 it("fails only an oversized reply and still returns a large screenshot", async () => {
308 const screenshot = "A".repeat(16 * 1024 * 1024);
309 const send = vi.fn(async (method: string) =>
310 method === "DOM.getDocument" ? { nodes: oversized } : { data: screenshot },
311 );
312 const written: Array<Record<string, unknown>> = [];
313 const relay = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw)));
314 relay.receive(
315 JSON.stringify({ id: 1, method: "DOM.getDocument", sessionId: "t3-preview-page" }),
316 );
317 relay.receive(
318 JSON.stringify({ id: 2, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
319 );
320 await settle();
321​
322 const replies = written.map(({ id, error, result }) => ({
323 id,
324 error,
325 size: (result as { data?: string } | undefined)?.data?.length,
326 }));
327 expect(replies).toEqual([
328 { id: 1, error: { code: -32000, message: "CDP payload too large" }, size: undefined },
329 { id: 2, error: undefined, size: screenshot.length },
330 ]);
331 });
332​
333 it.each([
334 { args: oversized },
335 { args: "\u0001".repeat(12 * 1024 * 1024) },
336 { args: Array(2_700_000).fill(-0.0000010000000000000002) },
337 ])("closes instead of dropping an oversized event (%#)", async ({ args }) => {
338 const written: Array<Record<string, unknown>> = [];
339 const close = vi.fn();
340 const relay = createCdpRelayConnection(
341 makeTarget(vi.fn()),
342 (raw) => written.push(JSON.parse(raw)),
343 close,
344 );
345 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
346 await settle();
347 written.length = 0;
348​
349 relay.event("Runtime.consoleAPICalled", { args }, "");
350 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
351​
352 relay.receive(JSON.stringify({ id: 2, method: "Target.setAutoAttach" }));
353 expect(close).toHaveBeenCalledOnce();
354 expect(written.map((message) => message["method"])).toEqual([]);
355 });
356});