electron-cast 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +50 -20
- package/dist/electron/main.d.ts +15 -2
- package/dist/electron/main.js +202 -15
- package/dist/electron/main.js.map +1 -1
- package/dist/electron/preload.d.ts +13 -1
- package/dist/electron/preload.js +50 -1
- package/dist/electron/preload.js.map +1 -1
- package/dist/electron/presentation-envelope.d.ts +60 -0
- package/dist/electron/presentation-envelope.js +296 -0
- package/dist/electron/presentation-envelope.js.map +1 -0
- package/dist/electron/presentation-handler.d.ts +100 -0
- package/dist/electron/presentation-handler.js +487 -0
- package/dist/electron/presentation-handler.js.map +1 -0
- package/dist/electron/session-service.d.ts +8 -0
- package/dist/electron/session-service.js +30 -10
- package/dist/electron/session-service.js.map +1 -1
- package/dist/polyfill/presentation-standin.d.ts +13 -0
- package/dist/polyfill/presentation-standin.js +275 -0
- package/dist/polyfill/presentation-standin.js.map +1 -0
- package/package.json +4 -3
- package/src/electron/main.ts +199 -15
- package/src/electron/preload.ts +59 -1
- package/src/electron/presentation-envelope.ts +311 -0
- package/src/electron/presentation-handler.ts +518 -0
- package/src/electron/session-service.ts +35 -8
- package/src/polyfill/presentation-standin.ts +271 -0
package/src/electron/main.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { CastSessionService, type CastClientLike, type DeviceSource, type CastRe
|
|
|
2
2
|
import type { CastDevice } from "../discovery/index.ts";
|
|
3
3
|
import { CastDiscovery } from "../discovery/index.ts";
|
|
4
4
|
import { CastClient } from "../client/index.ts";
|
|
5
|
+
import { CastPresentationHandler, type PresentationConnectionHandle } from "./presentation-handler.ts";
|
|
5
6
|
|
|
6
7
|
export type { CastRequestInfo, DeviceChoice } from "./session-service.ts";
|
|
7
8
|
export type { CastDevice } from "../discovery/index.ts";
|
|
@@ -18,10 +19,14 @@ export interface WebContentsLike {
|
|
|
18
19
|
}
|
|
19
20
|
/** The subset of an Electron `IpcMainInvokeEvent` the manager needs. */
|
|
20
21
|
export interface IpcMainInvokeEventLike { sender: WebContentsLike; senderFrame: FrameLike | null }
|
|
21
|
-
/** The subset of an Electron `
|
|
22
|
+
/** The subset of an Electron `IpcMainEvent` the manager needs. */
|
|
23
|
+
export interface IpcMainEventLike { sender: WebContentsLike }
|
|
24
|
+
/** The subset of an Electron `IpcMain` the manager needs (`on`/`removeListener` unless `presentation: false`). */
|
|
22
25
|
export interface IpcMainLike {
|
|
23
26
|
handle(channel: string, listener: (event: IpcMainInvokeEventLike, ...args: any[]) => unknown): void;
|
|
24
27
|
removeHandler(channel: string): void;
|
|
28
|
+
on?(channel: string, listener: (event: IpcMainEventLike, ...args: any[]) => void): unknown;
|
|
29
|
+
removeListener?(channel: string, listener: (event: IpcMainEventLike, ...args: any[]) => void): unknown;
|
|
25
30
|
}
|
|
26
31
|
/** Dependencies of {@link createCastManager}; the Electron objects are passed in, never imported. */
|
|
27
32
|
export interface CastManagerOptions {
|
|
@@ -31,6 +36,12 @@ export interface CastManagerOptions {
|
|
|
31
36
|
discovery?: DeviceSource & { start(): Promise<void>; stop(): void }; // default new CastDiscovery()
|
|
32
37
|
createClient?(device: CastDevice): CastClientLike; // default new CastClient({ host, port })
|
|
33
38
|
channel?: string; // default "electron-cast"
|
|
39
|
+
/**
|
|
40
|
+
* Answer the preload's presentation mode (the page's own Google Cast SDK running on a stand-in Presentation API),
|
|
41
|
+
* which is the preload's default. Needs `ipcMain.on` and `ipcMain.removeListener`. Default true; false serves only
|
|
42
|
+
* the preload's `mode: "chromecast"`.
|
|
43
|
+
*/
|
|
44
|
+
presentation?: boolean;
|
|
34
45
|
}
|
|
35
46
|
/** The main-process cast manager. */
|
|
36
47
|
export interface CastManager {
|
|
@@ -39,22 +50,48 @@ export interface CastManager {
|
|
|
39
50
|
dispose(): Promise<void>;
|
|
40
51
|
}
|
|
41
52
|
|
|
53
|
+
/** Availability watches kept per webContents; the page never releases one, so the oldest are dropped. */
|
|
54
|
+
const MAX_WATCHES_PER_PAGE = 32;
|
|
55
|
+
/** Largest page-to-receiver message accepted (Cast messages are capped at 64 KiB on the wire). */
|
|
56
|
+
const MAX_MESSAGE_CHARS = 1 << 20;
|
|
57
|
+
|
|
58
|
+
/** The sending frame's origin; null when there is no frame. An unparseable URL gives "" so allowOrigin decides. */
|
|
59
|
+
function originOf(frame: FrameLike | null): string | null {
|
|
60
|
+
if (frame === null) return null;
|
|
61
|
+
if (typeof frame.origin === "string" && frame.origin !== "") return frame.origin;
|
|
62
|
+
try {
|
|
63
|
+
return new URL(frame.url).origin;
|
|
64
|
+
} catch {
|
|
65
|
+
return "";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
42
69
|
/**
|
|
43
70
|
* Wires the session service to Electron IPC: one invoke handler per app on
|
|
44
71
|
* `<channel>:call`, events sent back on `<channel>:event`. Each webContents is
|
|
45
|
-
* a sender that leaves its sessions when it is destroyed or navigates.
|
|
72
|
+
* a sender that leaves its sessions when it is destroyed or navigates. Unless
|
|
73
|
+
* `presentation: false` it also serves `<channel>:presentation` (see {@link CastManagerOptions.presentation}).
|
|
46
74
|
*/
|
|
47
75
|
export function createCastManager(options: CastManagerOptions): CastManager {
|
|
48
76
|
const channel = options.channel ?? "electron-cast";
|
|
77
|
+
if (options.presentation !== false && (typeof options.ipcMain.on !== "function" || typeof options.ipcMain.removeListener !== "function")) {
|
|
78
|
+
throw new TypeError("presentation mode needs ipcMain.on and ipcMain.removeListener");
|
|
79
|
+
}
|
|
49
80
|
const discovery = options.discovery ?? new CastDiscovery();
|
|
50
81
|
const createClient = options.createClient ?? ((d: CastDevice) => new CastClient({ host: d.host, port: d.port }));
|
|
51
82
|
const contents = new Map<number, WebContentsLike>();
|
|
83
|
+
let handler: CastPresentationHandler | undefined;
|
|
52
84
|
const service = new CastSessionService({
|
|
53
85
|
devices: discovery,
|
|
54
86
|
createClient,
|
|
55
87
|
selectDevice: options.selectDevice,
|
|
56
88
|
allowOrigin: options.allowOrigin,
|
|
57
89
|
emit(senderId, event) {
|
|
90
|
+
try {
|
|
91
|
+
handler?.onServiceEvent(senderId, event);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
console.error("electron-cast: presentation handler failed on a service event", err);
|
|
94
|
+
}
|
|
58
95
|
const wc = contents.get(senderId);
|
|
59
96
|
if (wc === undefined || wc.isDestroyed()) return;
|
|
60
97
|
try {
|
|
@@ -70,33 +107,179 @@ export function createCastManager(options: CastManagerOptions): CastManager {
|
|
|
70
107
|
if (contents.has(wc.id)) return;
|
|
71
108
|
contents.set(wc.id, wc);
|
|
72
109
|
wc.once("destroyed", () => {
|
|
110
|
+
presentation?.senderGone(wc.id);
|
|
73
111
|
contents.delete(wc.id);
|
|
74
112
|
service.senderGone(wc.id);
|
|
75
113
|
});
|
|
114
|
+
// A navigation ends the page's connections, but its sessions stay open (parked) so the next page can rejoin them
|
|
76
115
|
wc.on("did-navigate", () => {
|
|
77
|
-
|
|
116
|
+
presentation?.senderGone(wc.id);
|
|
117
|
+
service.senderNavigated(wc.id);
|
|
78
118
|
});
|
|
79
119
|
};
|
|
80
120
|
|
|
81
121
|
options.ipcMain.handle(`${channel}:call`, (event, method, params) => {
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
122
|
+
const origin = originOf(event.senderFrame);
|
|
123
|
+
if (origin === null) {
|
|
84
124
|
return Promise.resolve({ ok: false, code: "extension_missing", description: "No sender frame" });
|
|
85
125
|
}
|
|
86
|
-
let origin = "";
|
|
87
|
-
if (typeof frame.origin === "string" && frame.origin !== "") {
|
|
88
|
-
origin = frame.origin;
|
|
89
|
-
} else {
|
|
90
|
-
try {
|
|
91
|
-
origin = new URL(frame.url).origin;
|
|
92
|
-
} catch {
|
|
93
|
-
// invalid URL: keep "" so allowOrigin decides
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
126
|
watch(event.sender);
|
|
97
127
|
return service.handle({ id: event.sender.id, origin }, method, params);
|
|
98
128
|
});
|
|
99
129
|
|
|
130
|
+
/** Presentation mode: IPC for the page's stand-in Presentation API, answered by a CastPresentationHandler. */
|
|
131
|
+
const setUpPresentation = () => {
|
|
132
|
+
const ipc = options.ipcMain;
|
|
133
|
+
const on = ipc.on!.bind(ipc);
|
|
134
|
+
const off = ipc.removeListener!.bind(ipc);
|
|
135
|
+
const h = new CastPresentationHandler({ service });
|
|
136
|
+
handler = h;
|
|
137
|
+
const connections = new Map<string, { conn: PresentationConnectionHandle | null; wcId: number }>();
|
|
138
|
+
const watches = new Map<string, { ac: AbortController; wcId: number }>();
|
|
139
|
+
const sendTo = (wcId: number, payload: unknown): void => {
|
|
140
|
+
const wc = contents.get(wcId);
|
|
141
|
+
if (wc === undefined || wc.isDestroyed()) return;
|
|
142
|
+
try {
|
|
143
|
+
wc.send(`${channel}:presentation:event`, payload);
|
|
144
|
+
} catch {
|
|
145
|
+
// destroyed between the check and the send
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
const invalid = (description: string) => ({ ok: false, code: "InvalidAccessError", description });
|
|
149
|
+
const isId = (v: unknown): v is string => typeof v === "string" && v !== "" && v.length <= 256;
|
|
150
|
+
const isUrls = (v: unknown): v is string[] =>
|
|
151
|
+
Array.isArray(v) && v.length > 0 && v.length <= 16 && v.every((u) => typeof u === "string");
|
|
152
|
+
|
|
153
|
+
/** Finish a start/reconnect: register the connection and route its traffic to the page. */
|
|
154
|
+
const open = async (wcId: number, connectionId: string, opening: () => Promise<PresentationConnectionHandle>) => {
|
|
155
|
+
if (connections.has(connectionId)) return invalid("connectionId in use");
|
|
156
|
+
const slot: { conn: PresentationConnectionHandle | null; wcId: number } = { conn: null, wcId };
|
|
157
|
+
connections.set(connectionId, slot); // reserved while the picker or join is pending
|
|
158
|
+
let conn: PresentationConnectionHandle;
|
|
159
|
+
try {
|
|
160
|
+
conn = await opening();
|
|
161
|
+
} catch (err) {
|
|
162
|
+
if (connections.get(connectionId) === slot) connections.delete(connectionId);
|
|
163
|
+
const e = err as { name?: unknown; message?: unknown } | null;
|
|
164
|
+
const name = typeof e?.name === "string" && e.name !== "" && e.name !== "Error" ? e.name : "OperationError";
|
|
165
|
+
return { ok: false, code: name, description: typeof e?.message === "string" ? e.message : String(err) };
|
|
166
|
+
}
|
|
167
|
+
if (!contents.has(wcId) || connections.get(connectionId) !== slot) {
|
|
168
|
+
conn.close();
|
|
169
|
+
return { ok: false, code: "AbortError", description: "The page went away" };
|
|
170
|
+
}
|
|
171
|
+
slot.conn = conn;
|
|
172
|
+
conn.onclose = (state) => {
|
|
173
|
+
if (connections.get(connectionId) === slot) connections.delete(connectionId);
|
|
174
|
+
sendTo(wcId, { type: "statechange", connectionId, state });
|
|
175
|
+
};
|
|
176
|
+
// The stand-in registered this connectionId before calling, so it buffers anything sent before the reply.
|
|
177
|
+
conn.onmessage = (data) => sendTo(wcId, { type: "message", connectionId, data });
|
|
178
|
+
return { ok: true, value: { id: conn.id, url: conn.url } };
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
ipc.handle(`${channel}:presentation`, async (event, method, params) => {
|
|
182
|
+
const origin = originOf(event.senderFrame);
|
|
183
|
+
if (origin === null) return { ok: false, code: "NotAllowedError", description: "No sender frame" };
|
|
184
|
+
watch(event.sender);
|
|
185
|
+
const wcId = event.sender.id;
|
|
186
|
+
const p = (typeof params === "object" && params !== null ? params : {}) as Record<string, unknown>;
|
|
187
|
+
try {
|
|
188
|
+
switch (method) {
|
|
189
|
+
case "getAvailability": {
|
|
190
|
+
if (!isId(p.watchId) || !isUrls(p.urls)) return invalid("getAvailability expects { watchId, urls }");
|
|
191
|
+
const watchId = p.watchId;
|
|
192
|
+
const old = watches.get(watchId);
|
|
193
|
+
if (old !== undefined && old.wcId !== wcId) return invalid("watchId in use");
|
|
194
|
+
old?.ac.abort();
|
|
195
|
+
watches.delete(watchId);
|
|
196
|
+
const mine = [...watches].filter(([, w]) => w.wcId === wcId);
|
|
197
|
+
for (const [id, w] of mine.slice(0, Math.max(0, mine.length - (MAX_WATCHES_PER_PAGE - 1)))) {
|
|
198
|
+
w.ac.abort();
|
|
199
|
+
watches.delete(id);
|
|
200
|
+
}
|
|
201
|
+
const ac = new AbortController();
|
|
202
|
+
watches.set(watchId, { ac, wcId });
|
|
203
|
+
const available = await h.getAvailability({
|
|
204
|
+
urls: p.urls,
|
|
205
|
+
origin,
|
|
206
|
+
senderId: wcId,
|
|
207
|
+
signal: ac.signal,
|
|
208
|
+
onchange: (value) => sendTo(wcId, { type: "availability", watchId, value }),
|
|
209
|
+
});
|
|
210
|
+
return { ok: true, value: { available } };
|
|
211
|
+
}
|
|
212
|
+
case "stopWatching": {
|
|
213
|
+
const w = isId(p.watchId) ? watches.get(p.watchId) : undefined;
|
|
214
|
+
if (w !== undefined && w.wcId === wcId) {
|
|
215
|
+
w.ac.abort();
|
|
216
|
+
watches.delete(p.watchId as string);
|
|
217
|
+
}
|
|
218
|
+
return { ok: true, value: undefined };
|
|
219
|
+
}
|
|
220
|
+
case "start":
|
|
221
|
+
if (!isId(p.connectionId) || !isUrls(p.urls)) return invalid("start expects { connectionId, urls }");
|
|
222
|
+
{
|
|
223
|
+
const urls = p.urls;
|
|
224
|
+
return await open(wcId, p.connectionId, () => h.startPresentation({ urls, origin, senderId: wcId }));
|
|
225
|
+
}
|
|
226
|
+
case "reconnect":
|
|
227
|
+
if (!isId(p.connectionId) || !isUrls(p.urls) || !isId(p.presentationId)) {
|
|
228
|
+
return invalid("reconnect expects { connectionId, urls, presentationId }");
|
|
229
|
+
}
|
|
230
|
+
{
|
|
231
|
+
const { urls, presentationId } = p;
|
|
232
|
+
return await open(wcId, p.connectionId,
|
|
233
|
+
() => h.reconnectPresentation({ urls, origin, senderId: wcId, presentationId }));
|
|
234
|
+
}
|
|
235
|
+
case "close":
|
|
236
|
+
case "terminate": {
|
|
237
|
+
const c = isId(p.connectionId) ? connections.get(p.connectionId) : undefined;
|
|
238
|
+
if (c !== undefined && c.wcId === wcId && c.conn !== null) {
|
|
239
|
+
if (method === "close") c.conn.close();
|
|
240
|
+
else c.conn.terminate();
|
|
241
|
+
}
|
|
242
|
+
return { ok: true, value: undefined };
|
|
243
|
+
}
|
|
244
|
+
default:
|
|
245
|
+
return invalid(`unknown method: ${String(method)}`);
|
|
246
|
+
}
|
|
247
|
+
} catch (err) {
|
|
248
|
+
return { ok: false, code: "OperationError", description: err instanceof Error ? err.message : String(err) };
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
const onSend = (event: IpcMainEventLike, connectionId: unknown, data: unknown): void => {
|
|
253
|
+
if (typeof connectionId !== "string" || typeof data !== "string") return;
|
|
254
|
+
const c = connections.get(connectionId);
|
|
255
|
+
if (c === undefined || c.wcId !== event.sender.id || c.conn === null) return;
|
|
256
|
+
if (data.length > MAX_MESSAGE_CHARS) return;
|
|
257
|
+
c.conn.send(data);
|
|
258
|
+
};
|
|
259
|
+
on(`${channel}:presentation:send`, onSend);
|
|
260
|
+
|
|
261
|
+
return {
|
|
262
|
+
/** Close the page's connections and watches before the service drops it. */
|
|
263
|
+
senderGone(wcId: number): void {
|
|
264
|
+
h.senderGone(wcId);
|
|
265
|
+
for (const [id, c] of connections) if (c.wcId === wcId) connections.delete(id);
|
|
266
|
+
for (const [id, w] of watches) {
|
|
267
|
+
if (w.wcId !== wcId) continue;
|
|
268
|
+
w.ac.abort();
|
|
269
|
+
watches.delete(id);
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
dispose(): void {
|
|
273
|
+
ipc.removeHandler(`${channel}:presentation`);
|
|
274
|
+
off(`${channel}:presentation:send`, onSend);
|
|
275
|
+
for (const w of watches.values()) w.ac.abort();
|
|
276
|
+
watches.clear();
|
|
277
|
+
connections.clear();
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
};
|
|
281
|
+
const presentation = options.presentation !== false ? setUpPresentation() : undefined;
|
|
282
|
+
|
|
100
283
|
let disposed = false;
|
|
101
284
|
return {
|
|
102
285
|
start: () => discovery.start(),
|
|
@@ -105,6 +288,7 @@ export function createCastManager(options: CastManagerOptions): CastManager {
|
|
|
105
288
|
if (disposed) return;
|
|
106
289
|
disposed = true;
|
|
107
290
|
options.ipcMain.removeHandler(`${channel}:call`);
|
|
291
|
+
presentation?.dispose();
|
|
108
292
|
discovery.stop();
|
|
109
293
|
await service.dispose();
|
|
110
294
|
contents.clear();
|
package/src/electron/preload.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { installChromeCast } from "../polyfill/install.ts";
|
|
2
|
+
import { installPresentationStandIn } from "../polyfill/presentation-standin.ts";
|
|
2
3
|
import type { BridgeEvent, BridgeMethod, BridgeResult } from "../polyfill/bridge-types.ts";
|
|
3
4
|
|
|
4
5
|
/** The subset of an Electron `contextBridge` the bridge needs. */
|
|
@@ -10,6 +11,8 @@ export interface ContextBridgeLike {
|
|
|
10
11
|
export interface IpcRendererLike {
|
|
11
12
|
invoke(channel: string, ...args: unknown[]): Promise<unknown>;
|
|
12
13
|
on(channel: string, listener: (event: unknown, ...args: any[]) => void): unknown;
|
|
14
|
+
/** Needed in presentation mode (the default). */
|
|
15
|
+
send?(channel: string, ...args: unknown[]): void;
|
|
13
16
|
}
|
|
14
17
|
/** Dependencies of {@link installCastBridge}; the Electron objects are passed in, never imported. */
|
|
15
18
|
export interface CastBridgeOptions {
|
|
@@ -17,15 +20,31 @@ export interface CastBridgeOptions {
|
|
|
17
20
|
ipcRenderer: IpcRendererLike;
|
|
18
21
|
channel?: string; // default "electron-cast"
|
|
19
22
|
bridgeKey?: string; // default "__electronCastBridge"
|
|
23
|
+
/**
|
|
24
|
+
* "presentation" (default) installs a stand-in Presentation API, so the page's own copy of Google's Cast SDK
|
|
25
|
+
* loads and runs unmodified. "chromecast" installs electron-cast's own chrome.cast instead and blocks Google's
|
|
26
|
+
* loader scripts.
|
|
27
|
+
*/
|
|
28
|
+
mode?: "chromecast" | "presentation";
|
|
29
|
+
presentationBridgeKey?: string; // default "__electronCastPresentationBridge"
|
|
20
30
|
}
|
|
21
31
|
|
|
22
32
|
function describe(err: unknown): string {
|
|
23
33
|
return err instanceof Error ? err.message : String(err);
|
|
24
34
|
}
|
|
25
35
|
|
|
26
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Call from a preload script. Exposes the bridge and, before the page's scripts run, installs the Presentation API
|
|
38
|
+
* stand-in (default) or, with `mode: "chromecast"`, electron-cast's own chrome.cast.
|
|
39
|
+
*/
|
|
27
40
|
export function installCastBridge(options: CastBridgeOptions): void {
|
|
28
41
|
const channel = options.channel ?? "electron-cast";
|
|
42
|
+
const mode = options.mode ?? "presentation";
|
|
43
|
+
if (mode !== "presentation" && mode !== "chromecast") throw new TypeError(`unknown mode: ${String(mode)}`);
|
|
44
|
+
if (mode === "presentation") {
|
|
45
|
+
installPresentationBridge(options, channel);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
29
48
|
const bridgeKey = options.bridgeKey ?? "__electronCastBridge";
|
|
30
49
|
const bridge = {
|
|
31
50
|
/** Forward one bridge call to the main process; never rejects. */
|
|
@@ -55,3 +74,42 @@ export function installCastBridge(options: CastBridgeOptions): void {
|
|
|
55
74
|
options.contextBridge.exposeInMainWorld(bridgeKey, bridge);
|
|
56
75
|
options.contextBridge.executeInMainWorld({ func: installChromeCast, args: [bridgeKey] });
|
|
57
76
|
}
|
|
77
|
+
|
|
78
|
+
/** Presentation mode: expose the stand-in's bridge and install the stand-in; chrome.cast is left to Google's SDK. */
|
|
79
|
+
function installPresentationBridge(options: CastBridgeOptions, channel: string): void {
|
|
80
|
+
const key = options.presentationBridgeKey ?? "__electronCastPresentationBridge";
|
|
81
|
+
const ipc = options.ipcRenderer;
|
|
82
|
+
if (typeof ipc.send !== "function") throw new TypeError("presentation mode needs ipcRenderer.send");
|
|
83
|
+
const send = ipc.send.bind(ipc);
|
|
84
|
+
const bridge = {
|
|
85
|
+
/** Forward one call to the main process; never rejects. */
|
|
86
|
+
call(method: string, params: unknown): Promise<unknown> {
|
|
87
|
+
let invoked: Promise<unknown>;
|
|
88
|
+
try {
|
|
89
|
+
invoked = ipc.invoke(`${channel}:presentation`, method, params);
|
|
90
|
+
} catch (err) {
|
|
91
|
+
invoked = Promise.reject(err);
|
|
92
|
+
}
|
|
93
|
+
return invoked.then(
|
|
94
|
+
(result) => result,
|
|
95
|
+
(err: unknown) => ({ ok: false, code: "OperationError", description: describe(err) }),
|
|
96
|
+
);
|
|
97
|
+
},
|
|
98
|
+
/** Page -> main: one message on an open connection; the reply comes back in-band. */
|
|
99
|
+
send(connectionId: string, data: string): void {
|
|
100
|
+
send(`${channel}:presentation:send`, connectionId, data);
|
|
101
|
+
},
|
|
102
|
+
/** Relay `<channel>:presentation:event` payloads to the page, dropping the IPC event object. */
|
|
103
|
+
onEvent(listener: (event: unknown) => void): void {
|
|
104
|
+
ipc.on(`${channel}:presentation:event`, (_event, payload) => {
|
|
105
|
+
try {
|
|
106
|
+
listener(payload);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
console.error(err);
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
options.contextBridge.exposeInMainWorld(key, bridge);
|
|
114
|
+
options.contextBridge.executeInMainWorld({ func: installPresentationStandIn, args: [key] });
|
|
115
|
+
}
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
// Codec between Chromium's private Cast "router message" envelope (what Google's clank.js sender speaks over a
|
|
2
|
+
// PresentationConnection) and electron-cast's snapshot types. Pure module: no Electron imports.
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import type { ReceiverSnapshot, SessionSnapshot } from "../polyfill/bridge-types.ts";
|
|
5
|
+
|
|
6
|
+
/** The Cast media namespace; the only reserved namespace kept by {@link filterNamespaces}. */
|
|
7
|
+
export const MEDIA_NAMESPACE = "urn:x-cast:com.google.cast.media";
|
|
8
|
+
|
|
9
|
+
/** The fields parsed out of a presentation request URL. */
|
|
10
|
+
export interface PresentationUrl {
|
|
11
|
+
appId: string;
|
|
12
|
+
capabilities: string[];
|
|
13
|
+
clientId: string | null;
|
|
14
|
+
autoJoinPolicy: string;
|
|
15
|
+
defaultActionPolicy: string;
|
|
16
|
+
launchTimeout: number | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A validated inbound router message, with `timeoutMillis` dropped and object messages null-stripped. */
|
|
20
|
+
export interface ParsedEnvelope {
|
|
21
|
+
type: string;
|
|
22
|
+
message: unknown;
|
|
23
|
+
sequenceNumber?: number;
|
|
24
|
+
clientId: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const APP_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
|
|
28
|
+
|
|
29
|
+
/** Splits `<appId>(cap,cap)` into its parts; no suffix means no capabilities. */
|
|
30
|
+
function splitAppId(raw: string): { appId: string; capabilities: string[] } {
|
|
31
|
+
const open = raw.indexOf("(");
|
|
32
|
+
if (open === -1 || !raw.endsWith(")")) return { appId: raw, capabilities: [] };
|
|
33
|
+
return { appId: raw.slice(0, open), capabilities: raw.slice(open + 1, -1).split(",").filter((c) => c !== "") };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A positive integer millisecond count, or null for anything else. */
|
|
37
|
+
function parseLaunchTimeout(raw: string | null): number | null {
|
|
38
|
+
if (raw === null || !/^\d+$/.test(raw)) return null;
|
|
39
|
+
const n = Number(raw);
|
|
40
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Parses a presentation request URL (the legacy `https://google.com/cast#__castAppId__=...` form or
|
|
45
|
+
* `cast:<appId>?...`) into its launch fields, or null for anything that is not one of those forms.
|
|
46
|
+
*/
|
|
47
|
+
export function parsePresentationUrl(url: string): PresentationUrl | null {
|
|
48
|
+
if (typeof url !== "string" || url.length === 0 || url.length > 4096) return null;
|
|
49
|
+
const legacyPrefix = "https://google.com/cast#";
|
|
50
|
+
if (url.startsWith(legacyPrefix)) {
|
|
51
|
+
let appId: string | null = null;
|
|
52
|
+
let capabilities: string[] = [];
|
|
53
|
+
let clientId: string | null = null;
|
|
54
|
+
let autoJoinPolicy = "tab_and_origin_scoped";
|
|
55
|
+
let defaultActionPolicy = "create_session";
|
|
56
|
+
let launchTimeout: number | null = null;
|
|
57
|
+
for (const part of url.slice(legacyPrefix.length).split("/")) {
|
|
58
|
+
const eq = part.indexOf("=");
|
|
59
|
+
const key = eq === -1 ? part : part.slice(0, eq);
|
|
60
|
+
const value = eq === -1 ? "" : part.slice(eq + 1);
|
|
61
|
+
switch (key) {
|
|
62
|
+
case "__castAppId__": {
|
|
63
|
+
const split = splitAppId(value);
|
|
64
|
+
appId = split.appId;
|
|
65
|
+
capabilities = split.capabilities;
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
case "__castClientId__":
|
|
69
|
+
clientId = value === "" ? null : value;
|
|
70
|
+
break;
|
|
71
|
+
case "__castAutoJoinPolicy__":
|
|
72
|
+
if (value !== "") autoJoinPolicy = value;
|
|
73
|
+
break;
|
|
74
|
+
case "__castDefaultActionPolicy__":
|
|
75
|
+
if (value !== "") defaultActionPolicy = value;
|
|
76
|
+
break;
|
|
77
|
+
case "__castLaunchTimeout__":
|
|
78
|
+
launchTimeout = parseLaunchTimeout(value);
|
|
79
|
+
break;
|
|
80
|
+
case "__dialPostData__":
|
|
81
|
+
// Its base64 value may contain "/", which would break the split: stop parsing here.
|
|
82
|
+
return appId !== null && APP_ID_RE.test(appId)
|
|
83
|
+
? { appId, capabilities, clientId, autoJoinPolicy, defaultActionPolicy, launchTimeout }
|
|
84
|
+
: null;
|
|
85
|
+
default:
|
|
86
|
+
// Unknown keys and __dialAppName__ are ignored.
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return appId !== null && APP_ID_RE.test(appId)
|
|
91
|
+
? { appId, capabilities, clientId, autoJoinPolicy, defaultActionPolicy, launchTimeout }
|
|
92
|
+
: null;
|
|
93
|
+
}
|
|
94
|
+
if (url.startsWith("cast:")) {
|
|
95
|
+
const rest = url.slice("cast:".length);
|
|
96
|
+
const q = rest.indexOf("?");
|
|
97
|
+
const split = splitAppId(q === -1 ? rest : rest.slice(0, q));
|
|
98
|
+
if (!APP_ID_RE.test(split.appId)) return null;
|
|
99
|
+
const params = new URLSearchParams(q === -1 ? "" : rest.slice(q + 1));
|
|
100
|
+
const param = (k: string): string | null => {
|
|
101
|
+
const v = params.get(k);
|
|
102
|
+
return v === null || v === "" ? null : v;
|
|
103
|
+
};
|
|
104
|
+
const queryCaps = param("capabilities");
|
|
105
|
+
return {
|
|
106
|
+
appId: split.appId,
|
|
107
|
+
capabilities: split.capabilities.length > 0
|
|
108
|
+
? split.capabilities
|
|
109
|
+
: queryCaps !== null ? queryCaps.split(",").filter((c) => c !== "") : [],
|
|
110
|
+
clientId: param("clientId"),
|
|
111
|
+
autoJoinPolicy: param("autoJoinPolicy") ?? "tab_and_origin_scoped",
|
|
112
|
+
defaultActionPolicy: param("defaultActionPolicy") ?? "create_session",
|
|
113
|
+
launchTimeout: parseLaunchTimeout(param("launchTimeout")),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Deep-copies a value, dropping every object property whose value is null (null array elements are kept). */
|
|
120
|
+
export function stripNulls(v: unknown): unknown {
|
|
121
|
+
if (Array.isArray(v)) return v.map((x) => stripNulls(x));
|
|
122
|
+
if (v !== null && typeof v === "object") {
|
|
123
|
+
const out: Record<string, unknown> = {};
|
|
124
|
+
for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
|
|
125
|
+
if (val === null) continue;
|
|
126
|
+
out[k] = stripNulls(val);
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
return v;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Escapes the five HTML metacharacters, as Chromium's `base::EscapeForHTML` does for receiver names. */
|
|
134
|
+
export function escapeHtml(s: string): string {
|
|
135
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
|
136
|
+
.replace(/"/g, """).replace(/'/g, "'");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Chromium's receiver label: unpadded base64url of sha256(deviceId + per-process token). */
|
|
140
|
+
export function receiverLabel(deviceId: string, token: string): string {
|
|
141
|
+
return createHash("sha256").update(deviceId + token).digest("base64url");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Shapes a ReceiverSnapshot into the receiver object clank reads, with an escaped name and hashed label. */
|
|
145
|
+
export function toReceiver(r: ReceiverSnapshot, label: string) {
|
|
146
|
+
return {
|
|
147
|
+
label,
|
|
148
|
+
friendlyName: escapeHtml(r.friendlyName),
|
|
149
|
+
capabilities: r.capabilities,
|
|
150
|
+
volume: r.volume,
|
|
151
|
+
isActiveInput: r.isActiveInput ?? null,
|
|
152
|
+
displayStatus: null,
|
|
153
|
+
receiverType: "cast",
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Reserved namespaces Chromium never advertises to senders (the media namespace is not among them). */
|
|
158
|
+
const RESERVED_NAMESPACES = new Set([
|
|
159
|
+
"urn:x-cast:com.google.cast.tp.deviceauth",
|
|
160
|
+
"urn:x-cast:com.google.cast.tp.heartbeat",
|
|
161
|
+
"urn:x-cast:com.google.cast.tp.connection",
|
|
162
|
+
"urn:x-cast:com.google.cast.receiver",
|
|
163
|
+
"urn:x-cast:com.google.cast.remoting",
|
|
164
|
+
"urn:x-cast:com.google.cast.webrtc",
|
|
165
|
+
]);
|
|
166
|
+
|
|
167
|
+
/** Drops the reserved namespaces from a session's namespace list, keeping everything else in order. */
|
|
168
|
+
export function filterNamespaces(ns: { name: string }[]): { name: string }[] {
|
|
169
|
+
return ns.filter((n) => !RESERVED_NAMESPACES.has(n.name));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Shapes a SessionSnapshot into the new_session/update_session message clank's converter copies onto the session. */
|
|
173
|
+
export function toSession(s: SessionSnapshot, label: string, media?: object[]) {
|
|
174
|
+
const out: Record<string, unknown> = {
|
|
175
|
+
sessionId: s.sessionId,
|
|
176
|
+
appId: s.appId,
|
|
177
|
+
displayName: s.displayName ?? "",
|
|
178
|
+
appImages: s.appImages ?? [],
|
|
179
|
+
receiver: toReceiver(s.receiver, label),
|
|
180
|
+
transportId: s.transportId,
|
|
181
|
+
namespaces: filterNamespaces(s.namespaces),
|
|
182
|
+
statusText: s.statusText,
|
|
183
|
+
senderApps: s.senderApps ?? [],
|
|
184
|
+
};
|
|
185
|
+
if (media !== undefined) out.media = media;
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The receiver's supportedMediaCommands bitmask bits, in the order clank's supportsCommand expects. */
|
|
190
|
+
const MEDIA_COMMAND_BITS: Array<[number, string]> = [
|
|
191
|
+
[1, "pause"],
|
|
192
|
+
[2, "seek"],
|
|
193
|
+
[4, "stream_volume"],
|
|
194
|
+
[8, "stream_mute"],
|
|
195
|
+
[64, "queue_next"],
|
|
196
|
+
[128, "queue_prev"],
|
|
197
|
+
];
|
|
198
|
+
|
|
199
|
+
/** Converts a supportedMediaCommands bitmask (or passes through an array of strings) into command names. */
|
|
200
|
+
export function mediaCommands(v: unknown): string[] {
|
|
201
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
202
|
+
return MEDIA_COMMAND_BITS.filter(([bit]) => (v & bit) !== 0).map(([, name]) => name);
|
|
203
|
+
}
|
|
204
|
+
if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string");
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Shallow-copies a media-status entry, stamping its sessionId and converting its media commands to strings. */
|
|
209
|
+
export function toMediaEntry(entry: Record<string, unknown>, sessionId: string): Record<string, unknown> {
|
|
210
|
+
const out: Record<string, unknown> = { ...entry };
|
|
211
|
+
if ("supportedMediaCommands" in out) out.supportedMediaCommands = mediaCommands(out.supportedMediaCommands);
|
|
212
|
+
out.sessionId = sessionId;
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** True for objects made by an object literal or JSON.parse (and nothing else, including arrays). */
|
|
217
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
218
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
|
|
219
|
+
const proto = Object.getPrototypeOf(v);
|
|
220
|
+
return proto === Object.prototype || proto === null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Serialises an outbound Chromium router message; undefined/null/empty-object messages become null. */
|
|
224
|
+
export function envelope(type: string, message: unknown, clientId: string, sequenceNumber?: number): string {
|
|
225
|
+
const empty = message !== undefined && message !== null && isPlainObject(message) && Object.keys(message).length === 0;
|
|
226
|
+
const out: Record<string, unknown> = { type, message: message === undefined || message === null || empty ? null : message };
|
|
227
|
+
if (typeof sequenceNumber === "number") out.sequenceNumber = sequenceNumber;
|
|
228
|
+
out.timeoutMillis = 0;
|
|
229
|
+
out.clientId = clientId;
|
|
230
|
+
return JSON.stringify(out);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** The eight router message types Chromium's parser accepts; anything else is dropped. */
|
|
234
|
+
const ENVELOPE_TYPES = new Set([
|
|
235
|
+
"client_connect",
|
|
236
|
+
"app_message",
|
|
237
|
+
"v2_message",
|
|
238
|
+
"leave_session",
|
|
239
|
+
"receiver_action",
|
|
240
|
+
"new_session",
|
|
241
|
+
"update_session",
|
|
242
|
+
"error",
|
|
243
|
+
]);
|
|
244
|
+
|
|
245
|
+
/** Validates an inbound router message the way Chromium's CIM parser does, stripping nulls from object messages. */
|
|
246
|
+
export function parseEnvelope(raw: string): ParsedEnvelope | null {
|
|
247
|
+
let data: unknown;
|
|
248
|
+
try {
|
|
249
|
+
data = JSON.parse(raw);
|
|
250
|
+
} catch {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
if (!isPlainObject(data)) return null;
|
|
254
|
+
const { type, clientId, message, sequenceNumber } = data;
|
|
255
|
+
if (typeof type !== "string" || !ENVELOPE_TYPES.has(type)) return null;
|
|
256
|
+
if (typeof clientId !== "string" || clientId.length === 0) return null;
|
|
257
|
+
if (type === "app_message") {
|
|
258
|
+
if (!isPlainObject(message)) return null;
|
|
259
|
+
if (typeof message.sessionId !== "string" || typeof message.namespaceName !== "string") return null;
|
|
260
|
+
const inner = message.message;
|
|
261
|
+
if (!(typeof inner === "string" || isPlainObject(inner))) return null;
|
|
262
|
+
} else if (type === "v2_message") {
|
|
263
|
+
if (!isPlainObject(message)) return null;
|
|
264
|
+
if (typeof message.type !== "string" || typeof message.sessionId !== "string") return null;
|
|
265
|
+
} else if (!(typeof message === "string" || isPlainObject(message))) {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
const out: ParsedEnvelope = {
|
|
269
|
+
type,
|
|
270
|
+
message: typeof message === "string" ? message : stripNulls(message),
|
|
271
|
+
clientId,
|
|
272
|
+
};
|
|
273
|
+
if (typeof sequenceNumber === "number") out.sequenceNumber = sequenceNumber;
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The v2_message media request types clank sends; SET_VOLUME/STOP/LAUNCH are not among them. */
|
|
278
|
+
const MEDIA_REQUEST_TYPES = new Set([
|
|
279
|
+
"LOAD",
|
|
280
|
+
"QUEUE_LOAD",
|
|
281
|
+
"MEDIA_GET_STATUS",
|
|
282
|
+
"PLAY",
|
|
283
|
+
"PAUSE",
|
|
284
|
+
"SEEK",
|
|
285
|
+
"STOP_MEDIA",
|
|
286
|
+
"MEDIA_SET_VOLUME",
|
|
287
|
+
"EDIT_TRACKS_INFO",
|
|
288
|
+
"QUEUE_INSERT",
|
|
289
|
+
"QUEUE_UPDATE",
|
|
290
|
+
"QUEUE_REMOVE",
|
|
291
|
+
"QUEUE_REORDER",
|
|
292
|
+
]);
|
|
293
|
+
|
|
294
|
+
/** True when a v2_message type is one of the media requests forwarded to the receiver. */
|
|
295
|
+
export function isMediaRequest(type: string): boolean {
|
|
296
|
+
return MEDIA_REQUEST_TYPES.has(type);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Maps the media request types to the receiver's protocol names, leaving all other types unchanged. */
|
|
300
|
+
export function receiverMediaType(type: string): string {
|
|
301
|
+
switch (type) {
|
|
302
|
+
case "STOP_MEDIA":
|
|
303
|
+
return "STOP";
|
|
304
|
+
case "MEDIA_SET_VOLUME":
|
|
305
|
+
return "SET_VOLUME";
|
|
306
|
+
case "MEDIA_GET_STATUS":
|
|
307
|
+
return "GET_STATUS";
|
|
308
|
+
default:
|
|
309
|
+
return type;
|
|
310
|
+
}
|
|
311
|
+
}
|