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.
18const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
19
20describe("CDP relay", () => {
21 it("announces only the tab's page, under its real target id", async () => {
22 const written: Array<Record<string, unknown>> = [];
23 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
24 written.push(JSON.parse(raw)),
25 );
26 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
27 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
28 await settle();
29 const attach = written.findIndex((message) => message["id"] === 1);
30 // The page is announced right after the auto-attach reply, never before it.
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 // A slow screenshot must not hold up the reply behind it.
62 pending[1]!();
63 await settle();
64 expect(written).toEqual([
65 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
66 ]);
67 pending[0]!();
68 await settle();
69 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined);
70 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session");
71 expect(written.at(-1)).toEqual({
72 id: 5,
73 result: { method: "Page.captureScreenshot" },
74 sessionId: "t3-preview-page",
75 });
76 });
77
78 it("routes tab events to the page session once the page is announced", async () => {
79 const written: Array<Record<string, unknown>> = [];
80 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
81 written.push(JSON.parse(raw)),
82 );
83 relay.event("Page.loadEventFired", {}, undefined);
84 expect(written).toEqual([]);
85 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
86 await settle();
87 // Electron passes an empty session id for the page's own events.
88 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
89 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
90 expect(written.slice(-2)).toEqual([
91 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
92 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
93 ]);
94 });
95});
96
97describe("CDP relay extra sessions", () => {
98 it("gives a second page session the page's commands and events", async () => {
99 const send = vi.fn(async () => ({}));
100 const written: Array<Record<string, unknown>> = [];
101 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
102 written.push(JSON.parse(raw)),
103 );
104 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
105 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
106 await settle();
107 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
108 .sessionId;
109 relay.receive(
110 JSON.stringify({
111 id: 3,
112 method: "Target.attachToTarget",
113 params: { targetId: "GUEST-TARGET", flatten: true },
114 sessionId: browserSession,
115 }),
116 );
117 relay.receive(
118 JSON.stringify({
119 id: 4,
120 method: "Target.attachToTarget",
121 params: { targetId: "SOMETHING-ELSE" },
122 sessionId: browserSession,
123 }),
124 );
125 await settle();
126 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
127 .sessionId;
128 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
129 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
130 await settle();
131 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined);
132 written.length = 0;
133 relay.event("Page.screencastFrame", { data: "x" }, undefined);
134 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
135 });
136});
137
138describe("CDP relay downloads", () => {
139 it("applies the server's download directory and reports downloads on the root session", async () => {
140 const send = vi.fn(async () => ({}));
141 const directories: Array<string | null> = [];
142 const written: Array<Record<string, unknown>> = [];
143 const relay = createCdpRelayConnection(
144 makeTarget(send, (directory) => directories.push(directory)),
145 (raw) => written.push(JSON.parse(raw)),
146 );
147 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
148 relay.receive(
149 JSON.stringify({
150 id: 2,
151 method: "Browser.setDownloadBehavior",
152 params: {
153 behavior: "allowAndName",
154 browserContextId: "t3-preview",
155 downloadPath: "/srv/artifacts",
156 eventsEnabled: true,
157 },
158 }),
159 );
160 await settle();
161 expect(directories).toEqual(["/srv/artifacts"]);
162 // The tab's own debugger has no such context, so the id stays here.
163 expect(send).toHaveBeenCalledWith(
164 "Browser.setDownloadBehavior",
165 { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },
166 undefined,
167 );
168 written.length = 0;
169 relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
170 expect(written).toEqual([
171 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
172 ]);
173 });
174});