Open History to see the last commit
1// Electron allows one debugger per webContents; share the manager's attachment.
2
3export interface CdpRelayTarget {
4 readonly send: (
5 method: string,
6 params: Record<string, unknown>,
7 sessionId: string | undefined,
8 /** The extra session that sent it, such as a viewer's; the main connection has none. */
9 owner?: string,
10 ) => Promise<unknown>;
11 readonly sessionDetached?: (owner: string) => void;
12 /** The page's own CDP target id; Playwright keys the main frame by it. */
13 readonly targetId: () => Promise<string>;
14 readonly url: () => string;
15 readonly title: () => string;
16 readonly userAgent: () => string;
17 /** The desktop and its server share a disk; download paths need no translation. */
18 readonly setDownloadDirectory: (directory: string | null) => void;
19}
20
21export interface CdpRelayConnection {
22 readonly receive: (raw: string) => void;
23 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
24}
25
26interface CdpCommand {
27 readonly id: number;
28 readonly method: string;
29 readonly params?: Record<string, unknown>;
30 readonly sessionId?: string;
31}
32
33const isCommand = (value: unknown): value is CdpCommand =>
34 typeof value === "object" &&
35 value !== null &&
36 typeof (value as { id?: unknown }).id === "number" &&
37 typeof (value as { method?: unknown }).method === "string";
38
39const BROWSER_CONTEXT_ID = "t3-preview";
40const ANNOUNCE = Symbol("announce");
41const PAGE_SESSION_ID = "t3-preview-page";
42
43const ACKNOWLEDGED = new Set([
44 "Target.setDiscoverTargets",
45 "Browser.grantPermissions",
46 "Browser.resetPermissions",
47 "Browser.cancelDownload",
48]);
49
50export function createCdpRelayConnection(
51 target: CdpRelayTarget,
52 write: (message: string) => void,
53): CdpRelayConnection {
54 const send = (message: Record<string, unknown>) => write(JSON.stringify(message));
55 let attached = false;
56 /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
57 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
58 let sessionSequence = 0;
59 const newSession = (kind: "browser" | "page") => {
60 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
61 sessions.set(sessionId, kind);
62 return sessionId;
63 };
64 const targetInfo = async () => ({
65 targetId: await target.targetId(),
66 type: "page",
67 title: target.title(),
68 url: target.url(),
69 attached: true,
70 canAccessOpener: false,
71 browserContextId: BROWSER_CONTEXT_ID,
72 });
73
74 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
75 if (ACKNOWLEDGED.has(command.method)) return {};
76 switch (command.method) {
77 case "Browser.setDownloadBehavior": {
78 const directory = command.params?.["downloadPath"];
79 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
80 target.setDownloadDirectory(allowed ? directory : null);
81 const { browserContextId: _ignored, ...params } = command.params ?? {};
82 return target.send("Browser.setDownloadBehavior", params, undefined);
83 }
84 case "Browser.getVersion":
85 return {
86 protocolVersion: "1.3",
87 product: "Electron",
88 revision: "",
89 userAgent: target.userAgent(),
90 jsVersion: "",
91 };
92 case "Target.getTargetInfo":
93 return {
94 targetInfo: {
95 targetId: "browser",
96 type: "browser",
97 title: "",
98 url: "",
99 attached: true,
100 canAccessOpener: false,
101 },
102 };
103 case "Target.getBrowserContexts":
104 return { browserContextIds: [] };
105 case "Target.getTargets":
106 return { targetInfos: [await targetInfo()] };
107 case "Target.attachToBrowserTarget":
108 return { sessionId: newSession("browser") };
109 case "Target.attachToTarget": {
110 const targetId = command.params?.["targetId"];
111 if (targetId !== (await target.targetId()))
112 throw new Error("Only this preview tab's page can be attached.");
113 return { sessionId: newSession("page") };
114 }
115 case "Target.detachFromTarget": {
116 const sessionId = command.params?.["sessionId"];
117 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
118 sessions.delete(sessionId);
119 target.sessionDetached?.(sessionId);
120 }
121 return {};
122 }
123 case "Target.setAutoAttach": {
124 if (attached) return {};
125 attached = true;
126 const info = await targetInfo();
127 return {
128 [ANNOUNCE]: {
129 method: "Target.attachedToTarget",
130 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
131 },
132 };
133 }
134 default:
135 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
136 }
137 };
138
139 const pageCommand = (command: CdpCommand): Promise<unknown> => {
140 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
141 const owner =
142 child === undefined && command.sessionId !== PAGE_SESSION_ID ? command.sessionId : undefined;
143 // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command.
144 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
145 return Promise.resolve({});
146 }
147 // Playwright asks for this on every page; the host emulates focus only while it is in use.
148 if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
149 return target.send(command.method, command.params ?? {}, child, owner);
150 };
151
152 return {
153 receive: (raw) => {
154 let command: unknown;
155 try {
156 command = JSON.parse(raw);
157 } catch {
158 return;
159 }
160 if (!isCommand(command)) return;
161 const result =
162 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
163 ? browserCommand(command)
164 : pageCommand(command);
165 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
166 // Reply as commands finish so slow commands cannot block later replies.
167 void result.then(
168 (value) => {
169 const announce =
170 typeof value === "object" && value !== null && ANNOUNCE in value
171 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
172 : undefined;
173 send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
174 if (announce) send(announce);
175 },
176 (cause: unknown) =>
177 send({
178 id: command.id,
179 error: {
180 code: -32000,
181 message: cause instanceof Error ? cause.message : String(cause),
182 },
183 ...route,
184 }),
185 );
186 },
187 event: (method, params, sessionId) => {
188 if (!attached) return;
189 // Download events are the browser's; Playwright listens on its root session.
190 if (method.startsWith("Browser.download")) {
191 send({ method, params });
192 return;
193 }
194 // Electron reports the page's own events with an empty session id.
195 if (sessionId) {
196 send({ method, params, sessionId });
197 return;
198 }
199 for (const [id, kind] of sessions)
200 if (kind === "page") send({ method, params, sessionId: id });
201 },
202 };
203}