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

CdpRelay.ts

249 lines8.9 KB

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;
20​
21export interface CdpRelayConnection {
22 readonly receive: (raw: string) => void;
23 readonly event: (method: string, params: unknown, sessionId: string | undefined) => void;
25​
26interface CdpCommand {
27 readonly id: number;
28 readonly method: string;
29 readonly params?: Record<string, unknown>;
30 readonly sessionId?: string;
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​
39// CDP values are plain JSON data, so their serialized size can be bounded before
40// JSON.stringify allocates it. A string counts at its length unless it holds a
41// character JSON may escape, which can take six code units.
42const MAX_CDP_PAYLOAD_SIZE = 64 * 1024 * 1024;
43const MAY_ESCAPE = /[^\x20\x21\x23-\x5b\x5d-\ud7ff\ue000-\uffff]/;
44const serializedSize = (text: string) =>
45 (MAY_ESCAPE.test(text) ? text.length * 6 : text.length) + 3;
46​
47const fitsPayloadBudget = (message: unknown) => {
48 let remaining = MAX_CDP_PAYLOAD_SIZE;
49 const visit = (value: unknown): boolean => {
50 remaining -= typeof value === "string" ? serializedSize(value) : 26;
51 if (remaining < 0) return false;
52 if (typeof value !== "object" || value === null) return true;
53 if (Array.isArray(value)) return value.every(visit);
54 return Object.entries(value).every(([key, item]) => {
55 remaining -= serializedSize(key);
56 return visit(item);
57 });
58 };
59 return visit(message);
60};
61​
62const BROWSER_CONTEXT_ID = "t3-preview";
63const ANNOUNCE = Symbol("announce");
64const PAGE_SESSION_ID = "t3-preview-page";
65​
66const ACKNOWLEDGED = new Set([
67 "Target.setDiscoverTargets",
68 "Browser.grantPermissions",
69 "Browser.resetPermissions",
70 "Browser.cancelDownload",
71]);
72​
73export function createCdpRelayConnection(
74 target: CdpRelayTarget,
75 write: (message: string) => void,
76 close: () => void,
77): CdpRelayConnection {
78 let closed = false;
79 const send = (message: Record<string, unknown>) => {
80 if (closed) return;
81 if (fitsPayloadBudget(message)) {
82 write(JSON.stringify(message));
83 return;
84 }
85 // An error reply fails only that command. A dropped event would leave
86 // Playwright out of step with the page, so the relay closes instead.
87 if (typeof message["id"] === "number") {
88 write(
89 JSON.stringify({
90 id: message["id"],
91 error: { code: -32000, message: "CDP payload too large" },
92 ...(message["sessionId"] === undefined ? {} : { sessionId: message["sessionId"] }),
93 }),
94 );
95 return;
96 }
97 closed = true;
98 close();
99 };
100 let attached = false;
101 /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */
102 const sessions = new Map<string, "browser" | "page">([[PAGE_SESSION_ID, "page"]]);
103 let sessionSequence = 0;
104 const newSession = (kind: "browser" | "page") => {
105 const sessionId = `t3-preview-${kind}-${++sessionSequence}`;
106 sessions.set(sessionId, kind);
107 return sessionId;
108 };
109 const targetInfo = async () => ({
110 targetId: await target.targetId(),
111 type: "page",
112 title: target.title(),
113 url: target.url(),
114 attached: true,
115 canAccessOpener: false,
116 browserContextId: BROWSER_CONTEXT_ID,
117 });
118​
119 const browserCommand = async (command: CdpCommand): Promise<unknown> => {
120 if (ACKNOWLEDGED.has(command.method)) return {};
121 switch (command.method) {
122 case "Browser.setDownloadBehavior": {
123 const directory = command.params?.["downloadPath"];
124 const allowed = command.params?.["behavior"] !== "deny" && typeof directory === "string";
125 target.setDownloadDirectory(allowed ? directory : null);
126 const { browserContextId: _ignored, ...params } = command.params ?? {};
127 return target.send("Browser.setDownloadBehavior", params, undefined);
128 }
129 case "Browser.getVersion":
130 return {
131 protocolVersion: "1.3",
132 product: "Electron",
133 revision: "",
134 userAgent: target.userAgent(),
135 jsVersion: "",
136 };
137 case "Target.getTargetInfo":
138 return {
139 targetInfo: {
140 targetId: "browser",
141 type: "browser",
142 title: "",
143 url: "",
144 attached: true,
145 canAccessOpener: false,
146 },
147 };
148 case "Target.getBrowserContexts":
149 return { browserContextIds: [] };
150 case "Target.getTargets":
151 return { targetInfos: [await targetInfo()] };
152 case "Target.attachToBrowserTarget":
153 return { sessionId: newSession("browser") };
154 case "Target.attachToTarget": {
155 const targetId = command.params?.["targetId"];
156 if (targetId !== (await target.targetId()))
157 throw new Error("Only this preview tab's page can be attached.");
158 return { sessionId: newSession("page") };
159 }
160 case "Target.detachFromTarget": {
161 const sessionId = command.params?.["sessionId"];
162 if (typeof sessionId === "string" && sessionId !== PAGE_SESSION_ID) {
163 sessions.delete(sessionId);
164 target.sessionDetached?.(sessionId);
165 }
166 return {};
167 }
168 case "Target.setAutoAttach": {
169 if (attached) return {};
170 attached = true;
171 const info = await targetInfo();
172 return {
173 [ANNOUNCE]: {
174 method: "Target.attachedToTarget",
175 params: { sessionId: PAGE_SESSION_ID, targetInfo: info, waitingForDebugger: false },
176 },
177 };
178 }
179 default:
180 throw new Error(`Not supported for a desktop preview tab: ${command.method}`);
181 }
182 };
183​
184 const pageCommand = (command: CdpCommand): Promise<unknown> => {
185 const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId;
186 const owner =
187 child === undefined && command.sessionId !== PAGE_SESSION_ID ? command.sessionId : undefined;
188 // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command.
189 if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) {
190 return Promise.resolve({});
191 }
192 // Playwright asks for this on every page; the host emulates focus only while it is in use.
193 if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({});
194 return target.send(command.method, command.params ?? {}, child, owner);
195 };
196​
197 return {
198 receive: (raw) => {
199 if (closed) return;
200 let command: unknown;
201 try {
202 command = JSON.parse(raw);
203 } catch {
204 return;
205 }
206 if (!isCommand(command)) return;
207 const result =
208 command.sessionId === undefined || sessions.get(command.sessionId) === "browser"
209 ? browserCommand(command)
210 : pageCommand(command);
211 const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId };
212 // Reply as commands finish so slow commands cannot block later replies.
213 void result.then(
214 (value) => {
215 const announce =
216 typeof value === "object" && value !== null && ANNOUNCE in value
217 ? (value as { [ANNOUNCE]: Record<string, unknown> })[ANNOUNCE]
218 : undefined;
219 send({ id: command.id, result: announce ? {} : (value ?? {}), ...route });
220 if (announce) send(announce);
221 },
222 (cause: unknown) =>
223 send({
224 id: command.id,
225 error: {
226 code: -32000,
227 message: cause instanceof Error ? cause.message : String(cause),
228 },
229 ...route,
230 }),
231 );
232 },
233 event: (method, params, sessionId) => {
234 if (!attached) return;
235 // Download events are the browser's; Playwright listens on its root session.
236 if (method.startsWith("Browser.download")) {
237 send({ method, params });
238 return;
239 }
240 // Electron reports the page's own events with an empty session id.
241 if (sessionId) {
242 send({ method, params, sessionId });
243 return;
244 }
245 for (const [id, kind] of sessions)
246 if (kind === "page") send({ method, params, sessionId: id });
247 },
248 };