@myrialabs/clopen 0.4.21 → 0.4.22

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.
Files changed (86) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -0,0 +1,1277 @@
1
+ /**
2
+ * Host Bridge Client Script
3
+ *
4
+ * Runs inside the headless page and re-points the capability APIs that a real
5
+ * browser answers from the device — geolocation, camera/microphone, screen
6
+ * capture, speech recognition, clipboard, notifications — at the *viewer's*
7
+ * browser instead. Headless Chrome has none of those, so without this every one
8
+ * of them fails outright and the preview stops behaving like a browser the
9
+ * moment a page asks for anything real.
10
+ *
11
+ * Also stands in for the Fullscreen API. Real fullscreen collapses the surface
12
+ * Chrome composites to the browser *window* and leaves it there, so the preview
13
+ * comes back cropped and zoomed with no way out — the exit affordance lives in
14
+ * browser chrome that does not exist here. A CSS-based fullscreen leaves the
15
+ * captured surface alone and stays exitable, and
16
+ * the requests Chrome makes on the page's behalf — the button on its own media
17
+ * controls, which is C++ and never touches these patches — are caught after the
18
+ * fact and converted. Picture-in-Picture, which has no such equivalent, is
19
+ * reported as unavailable instead of dropping the video into a window nobody can
20
+ * see.
21
+ *
22
+ * Runs in **every** frame. Cross-origin frames have no binding of their own, so
23
+ * they relay through the top frame over `postMessage`, keyed by the same
24
+ * randomised name the binding uses.
25
+ */
26
+ export function hostBridgeScript(bindingName: string) {
27
+ const scope = window as unknown as Record<string, unknown>;
28
+ if (scope.__clopenHostBridgeReady) return;
29
+ scope.__clopenHostBridgeReady = true;
30
+
31
+ const RELAY_KEY = `${bindingName}R`;
32
+ const EVENT_HOOK = `${bindingName}E`;
33
+
34
+ interface BridgeError {
35
+ name?: string;
36
+ message?: string;
37
+ code?: number;
38
+ }
39
+
40
+ interface BridgeResponse {
41
+ ok: boolean;
42
+ result?: unknown;
43
+ error?: BridgeError;
44
+ }
45
+
46
+ function namedError(name: string, message: string, code?: number): Error {
47
+ const error = new Error(message);
48
+ error.name = name;
49
+ if (typeof code === 'number') {
50
+ (error as Error & { code?: number }).code = code;
51
+ }
52
+ return error;
53
+ }
54
+
55
+ function unwrap(response: BridgeResponse): unknown {
56
+ if (!response.ok) {
57
+ throw namedError(
58
+ response.error?.name || 'NotAllowedError',
59
+ response.error?.message || 'Permission denied',
60
+ response.error?.code
61
+ );
62
+ }
63
+ return response.result;
64
+ }
65
+
66
+ // ── Transport ───────────────────────────────────────────────────────────
67
+
68
+ const relayWaiters = new Map<string, (response: BridgeResponse) => void>();
69
+ let relaySeq = 0;
70
+
71
+ /**
72
+ * Round-trip one request to the viewer.
73
+ *
74
+ * The binding only exists where Chrome installed it — the main frame and any
75
+ * same-process iframe. Everything else (a cross-origin embed, which is most
76
+ * of them under site isolation) hops through the top frame instead, which is
77
+ * why an embedded page could not open a picker or ask for a camera.
78
+ */
79
+ function call(kind: string, payload?: unknown): Promise<any> {
80
+ const binding = scope[bindingName] as ((raw: string) => Promise<string>) | undefined;
81
+
82
+ if (typeof binding === 'function') {
83
+ return binding(JSON.stringify({ kind, payload })).then((raw: string) =>
84
+ unwrap(JSON.parse(raw) as BridgeResponse)
85
+ );
86
+ }
87
+
88
+ if (window === window.top) {
89
+ return Promise.reject(namedError('NotSupportedError', 'Preview host bridge is unavailable'));
90
+ }
91
+
92
+ relaySeq += 1;
93
+ const id = `${relaySeq}`;
94
+
95
+ return new Promise((resolve, reject) => {
96
+ relayWaiters.set(id, (response) => {
97
+ try {
98
+ resolve(unwrap(response));
99
+ } catch (error) {
100
+ reject(error);
101
+ }
102
+ });
103
+
104
+ try {
105
+ window.top?.postMessage({ [RELAY_KEY]: { id, kind, payload } }, '*');
106
+ } catch {
107
+ relayWaiters.delete(id);
108
+ reject(namedError('NotSupportedError', 'Preview host bridge is unreachable'));
109
+ }
110
+
111
+ setTimeout(() => {
112
+ if (!relayWaiters.delete(id)) return;
113
+ reject(namedError('AbortError', 'Preview host bridge timed out'));
114
+ }, 180000);
115
+ });
116
+ }
117
+
118
+ window.addEventListener('message', (event: MessageEvent) => {
119
+ const data = event.data as Record<string, any> | null;
120
+ if (!data || typeof data !== 'object') return;
121
+
122
+ // Top frame: forward a child's request and post the answer back.
123
+ const request = data[RELAY_KEY];
124
+ if (request && window === window.top) {
125
+ const binding = scope[bindingName] as ((raw: string) => Promise<string>) | undefined;
126
+ const source = event.source as WindowProxy | null;
127
+ if (!source) return;
128
+
129
+ const reply = (response: BridgeResponse) => {
130
+ try {
131
+ source.postMessage({ [`${RELAY_KEY}Reply`]: { id: request.id, response } }, '*');
132
+ } catch {
133
+ // Frame went away mid-flight.
134
+ }
135
+ };
136
+
137
+ if (typeof binding !== 'function') {
138
+ reply({ ok: false, error: { name: 'NotSupportedError', message: 'Bridge unavailable' } });
139
+ return;
140
+ }
141
+
142
+ binding(JSON.stringify({ kind: request.kind, payload: request.payload }))
143
+ .then((raw: string) => reply(JSON.parse(raw) as BridgeResponse))
144
+ .catch((error: Error) => reply({ ok: false, error: { name: error.name, message: error.message } }));
145
+ return;
146
+ }
147
+
148
+ // Child frame: settle the promise the relay is holding.
149
+ const replyPayload = data[`${RELAY_KEY}Reply`];
150
+ if (replyPayload) {
151
+ const waiter = relayWaiters.get(replyPayload.id);
152
+ if (waiter) {
153
+ relayWaiters.delete(replyPayload.id);
154
+ waiter(replyPayload.response);
155
+ }
156
+ return;
157
+ }
158
+
159
+ // Top frame broadcasts host events down to children.
160
+ const forwarded = data[`${RELAY_KEY}Event`];
161
+ if (forwarded) {
162
+ deliverEvent(forwarded.kind, forwarded.payload, false);
163
+ }
164
+ });
165
+
166
+ // ── Host → page events ──────────────────────────────────────────────────
167
+ //
168
+ // The request/response channel cannot carry a stream, and speech recognition
169
+ // is a stream: results keep arriving until the page stops listening.
170
+
171
+ const eventListeners = new Map<string, Set<(payload: any) => void>>();
172
+
173
+ function onHostEvent(kind: string, listener: (payload: any) => void): () => void {
174
+ let listeners = eventListeners.get(kind);
175
+ if (!listeners) {
176
+ listeners = new Set();
177
+ eventListeners.set(kind, listeners);
178
+ }
179
+ listeners.add(listener);
180
+ return () => listeners?.delete(listener);
181
+ }
182
+
183
+ function deliverEvent(kind: string, payload: unknown, broadcast: boolean): void {
184
+ const listeners = eventListeners.get(kind);
185
+ if (listeners) {
186
+ for (const listener of Array.from(listeners)) {
187
+ try {
188
+ listener(payload);
189
+ } catch {
190
+ // A page listener throwing must not stop the rest.
191
+ }
192
+ }
193
+ }
194
+
195
+ // Only the top frame receives the injected call, so it repeats the event
196
+ // to every child — the frame that asked may be several levels down.
197
+ if (!broadcast) return;
198
+ for (let i = 0; i < window.frames.length; i += 1) {
199
+ try {
200
+ window.frames[i].postMessage({ [`${RELAY_KEY}Event`]: { kind, payload } }, '*');
201
+ } catch {
202
+ // Cross-origin child that refused the post; nothing to do.
203
+ }
204
+ }
205
+ }
206
+
207
+ // Entry point the backend calls into with `page.evaluate`.
208
+ scope[EVENT_HOOK] = (raw: string) => {
209
+ try {
210
+ const parsed = JSON.parse(raw) as { kind: string; payload: unknown };
211
+ deliverEvent(parsed.kind, parsed.payload, true);
212
+ } catch {
213
+ // Malformed event — ignore.
214
+ }
215
+ };
216
+
217
+ /**
218
+ * Wrap a replacement so it reports itself as the built-in it stands in for.
219
+ * Bot-detection scripts read `Function.prototype.toString` far more often
220
+ * than they probe behaviour.
221
+ */
222
+ function nativeLike<T extends (...args: never[]) => unknown>(fn: T, name: string): T {
223
+ try {
224
+ Object.defineProperty(fn, 'name', { value: name, configurable: true });
225
+ return new Proxy(fn, {
226
+ get(target, prop, receiver) {
227
+ if (prop === 'toString') {
228
+ return function toString() {
229
+ return `function ${name}() { [native code] }`;
230
+ };
231
+ }
232
+ return Reflect.get(target, prop, receiver);
233
+ }
234
+ }) as T;
235
+ } catch {
236
+ return fn;
237
+ }
238
+ }
239
+
240
+ function define(target: object, key: string, value: unknown): void {
241
+ try {
242
+ Object.defineProperty(target, key, { value, configurable: true, writable: true });
243
+ } catch {
244
+ try {
245
+ (target as Record<string, unknown>)[key] = value;
246
+ } catch {
247
+ // Frozen prototype — leave the original in place.
248
+ }
249
+ }
250
+ }
251
+
252
+ // ── Geolocation ─────────────────────────────────────────────────────────
253
+ // Answered by the viewer's device, so the page sees the location of the
254
+ // person actually looking at it rather than the server's datacentre.
255
+ const geolocation = navigator.geolocation;
256
+ if (geolocation) {
257
+ const watchers = new Map<number, ReturnType<typeof setInterval>>();
258
+ let watchSeq = 0;
259
+
260
+ // Fixed cadence rather than honouring `maximumAge`: each poll may surface
261
+ // a permission prompt on the viewer, so a page asking for 100ms updates
262
+ // must not be able to drive that.
263
+ const WATCH_INTERVAL_MS = 15000;
264
+
265
+ const toPosition = (raw: Record<string, number | null>) => ({
266
+ coords: {
267
+ latitude: raw.latitude,
268
+ longitude: raw.longitude,
269
+ accuracy: raw.accuracy,
270
+ altitude: raw.altitude ?? null,
271
+ altitudeAccuracy: raw.altitudeAccuracy ?? null,
272
+ heading: raw.heading ?? null,
273
+ speed: raw.speed ?? null
274
+ },
275
+ timestamp: raw.timestamp || Date.now()
276
+ });
277
+
278
+ const toPositionError = (error: Error & { code?: number }) => ({
279
+ code: typeof error.code === 'number' ? error.code : 1,
280
+ message: error.message || 'User denied Geolocation',
281
+ PERMISSION_DENIED: 1,
282
+ POSITION_UNAVAILABLE: 2,
283
+ TIMEOUT: 3
284
+ });
285
+
286
+ const requestPosition = (
287
+ success?: (position: unknown) => void,
288
+ failure?: (error: unknown) => void,
289
+ options?: PositionOptions
290
+ ) => {
291
+ call('geolocation', {
292
+ enableHighAccuracy: !!options?.enableHighAccuracy,
293
+ timeout: options?.timeout,
294
+ maximumAge: options?.maximumAge
295
+ })
296
+ .then((raw) => {
297
+ if (typeof success === 'function') success(toPosition(raw));
298
+ })
299
+ .catch((error: Error & { code?: number }) => {
300
+ if (typeof failure === 'function') failure(toPositionError(error));
301
+ });
302
+ };
303
+
304
+ define(
305
+ geolocation,
306
+ 'getCurrentPosition',
307
+ nativeLike(function getCurrentPosition(
308
+ success?: (position: unknown) => void,
309
+ failure?: (error: unknown) => void,
310
+ options?: PositionOptions
311
+ ) {
312
+ requestPosition(success, failure, options);
313
+ } as never, 'getCurrentPosition')
314
+ );
315
+
316
+ define(
317
+ geolocation,
318
+ 'watchPosition',
319
+ nativeLike(function watchPosition(
320
+ success?: (position: unknown) => void,
321
+ failure?: (error: unknown) => void,
322
+ options?: PositionOptions
323
+ ) {
324
+ watchSeq += 1;
325
+ const id = watchSeq;
326
+ requestPosition(success, failure, options);
327
+ watchers.set(id, setInterval(() => requestPosition(success, failure, options), WATCH_INTERVAL_MS));
328
+ return id;
329
+ } as never, 'watchPosition')
330
+ );
331
+
332
+ define(
333
+ geolocation,
334
+ 'clearWatch',
335
+ nativeLike(function clearWatch(id: number) {
336
+ const handle = watchers.get(id);
337
+ if (handle !== undefined) {
338
+ clearInterval(handle);
339
+ watchers.delete(id);
340
+ }
341
+ } as never, 'clearWatch')
342
+ );
343
+ }
344
+
345
+ // ── Camera / microphone / screen ────────────────────────────────────────
346
+ const mediaDevices = navigator.mediaDevices;
347
+ if (mediaDevices) {
348
+ const ICE_SERVERS = [
349
+ { urls: 'stun:stun.l.google.com:19302' },
350
+ { urls: 'stun:stun1.l.google.com:19302' }
351
+ ];
352
+
353
+ /** Resolve once ICE gathering settles, or give up and send what we have. */
354
+ function waitForIce(pc: RTCPeerConnection): Promise<void> {
355
+ if (pc.iceGatheringState === 'complete') return Promise.resolve();
356
+ return new Promise((resolve) => {
357
+ let settled = false;
358
+ const finish = () => {
359
+ if (settled) return;
360
+ settled = true;
361
+ pc.removeEventListener('icegatheringstatechange', onChange);
362
+ resolve();
363
+ };
364
+ const onChange = () => {
365
+ if (pc.iceGatheringState === 'complete') finish();
366
+ };
367
+ pc.addEventListener('icegatheringstatechange', onChange);
368
+ // Non-trickle signalling: a slow or unreachable STUN server must
369
+ // not stall the request forever, host candidates alone are enough
370
+ // whenever the viewer and the server share a network.
371
+ setTimeout(finish, 2500);
372
+ });
373
+ }
374
+
375
+ async function requestHostMedia(
376
+ constraints: MediaStreamConstraints,
377
+ display: boolean
378
+ ): Promise<MediaStream> {
379
+ const wantsVideo = display ? true : !!constraints?.video;
380
+ const wantsAudio = !!constraints?.audio;
381
+ if (!wantsVideo && !wantsAudio) {
382
+ throw namedError('TypeError', 'At least one of audio and video must be requested');
383
+ }
384
+
385
+ const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
386
+ const stream = new MediaStream();
387
+ const expectedTracks = (wantsVideo ? 1 : 0) + (wantsAudio ? 1 : 0);
388
+
389
+ let markReady: () => void = () => {};
390
+ const tracksReady = new Promise<void>((resolve) => {
391
+ markReady = resolve;
392
+ });
393
+
394
+ pc.ontrack = (event) => {
395
+ stream.addTrack(event.track);
396
+ if (stream.getTracks().length >= expectedTracks) markReady();
397
+ };
398
+
399
+ if (wantsAudio) pc.addTransceiver('audio', { direction: 'recvonly' });
400
+ if (wantsVideo) pc.addTransceiver('video', { direction: 'recvonly' });
401
+
402
+ let sessionId = '';
403
+ try {
404
+ const offer = await pc.createOffer();
405
+ await pc.setLocalDescription(offer);
406
+ await waitForIce(pc);
407
+
408
+ const answer = await call('media-request', {
409
+ video: wantsVideo,
410
+ audio: wantsAudio,
411
+ display,
412
+ constraints: JSON.parse(JSON.stringify(constraints ?? {})),
413
+ sdp: pc.localDescription?.sdp || ''
414
+ });
415
+
416
+ sessionId = answer.sessionId;
417
+ await pc.setRemoteDescription({ type: 'answer', sdp: answer.sdp });
418
+
419
+ await Promise.race([
420
+ tracksReady,
421
+ new Promise((_, reject) =>
422
+ setTimeout(() => reject(namedError('NotReadableError', 'Timed out waiting for host media')), 15000)
423
+ )
424
+ ]);
425
+ } catch (error) {
426
+ try {
427
+ pc.close();
428
+ } catch {
429
+ // Already closed.
430
+ }
431
+ if (sessionId) call('media-stop', { sessionId }).catch(() => {});
432
+ throw error;
433
+ }
434
+
435
+ // Tear the relay down when the page releases the last track, the way
436
+ // a real capture releases the device.
437
+ let released = false;
438
+ const releaseIfDone = () => {
439
+ if (released) return;
440
+ if (!stream.getTracks().every((track) => track.readyState === 'ended')) return;
441
+ released = true;
442
+ try {
443
+ pc.close();
444
+ } catch {
445
+ // Already closed.
446
+ }
447
+ call('media-stop', { sessionId }).catch(() => {});
448
+ };
449
+
450
+ for (const track of stream.getTracks()) {
451
+ const nativeStop = track.stop.bind(track);
452
+ define(
453
+ track,
454
+ 'stop',
455
+ nativeLike(function stop() {
456
+ nativeStop();
457
+ releaseIfDone();
458
+ } as never, 'stop')
459
+ );
460
+ track.addEventListener('ended', releaseIfDone);
461
+ }
462
+
463
+ return stream;
464
+ }
465
+
466
+ define(
467
+ mediaDevices,
468
+ 'getUserMedia',
469
+ nativeLike(function getUserMedia(constraints: MediaStreamConstraints) {
470
+ return requestHostMedia(constraints, false);
471
+ } as never, 'getUserMedia')
472
+ );
473
+
474
+ // The preview's own capture pipeline calls getDisplayMedia to grab this
475
+ // tab's compositor output. Keep the real implementation reachable under a
476
+ // private name *before* replacing it — routing that internal call at the
477
+ // viewer would ask for their camera on every single page load.
478
+ const nativeGetDisplayMedia = mediaDevices.getDisplayMedia?.bind(mediaDevices);
479
+ if (nativeGetDisplayMedia) {
480
+ scope.__clopenNativeGetDisplayMedia = nativeGetDisplayMedia;
481
+ }
482
+
483
+ // Screen sharing is the same relay with a different source on the viewer's
484
+ // side, so a page that offers "share your screen" works end to end.
485
+ define(
486
+ mediaDevices,
487
+ 'getDisplayMedia',
488
+ nativeLike(function getDisplayMedia(constraints: MediaStreamConstraints) {
489
+ return requestHostMedia(constraints ?? { video: true }, true);
490
+ } as never, 'getDisplayMedia')
491
+ );
492
+
493
+ const originalEnumerateDevices = mediaDevices.enumerateDevices?.bind(mediaDevices);
494
+ define(
495
+ mediaDevices,
496
+ 'enumerateDevices',
497
+ nativeLike(function enumerateDevices() {
498
+ return call('media-devices')
499
+ .then((devices: MediaDeviceInfo[]) =>
500
+ devices.map((device) => ({
501
+ deviceId: device.deviceId,
502
+ groupId: device.groupId,
503
+ kind: device.kind,
504
+ label: device.label,
505
+ toJSON() {
506
+ return device;
507
+ }
508
+ }))
509
+ )
510
+ .catch(() => (originalEnumerateDevices ? originalEnumerateDevices() : []));
511
+ } as never, 'enumerateDevices')
512
+ );
513
+ }
514
+
515
+ // ── Speech recognition ──────────────────────────────────────────────────
516
+ // Headless Chrome ships no speech engine, so the API exists and always fails
517
+ // with `not-allowed`. The viewer's browser has both the engine and the
518
+ // microphone permission, so recognition runs there and streams back.
519
+ {
520
+ let sessionSeq = 0;
521
+
522
+ class HostSpeechRecognition extends EventTarget {
523
+ lang = '';
524
+ continuous = false;
525
+ interimResults = false;
526
+ maxAlternatives = 1;
527
+
528
+ onresult: ((event: Event) => void) | null = null;
529
+ onerror: ((event: Event) => void) | null = null;
530
+ onend: ((event: Event) => void) | null = null;
531
+ onstart: ((event: Event) => void) | null = null;
532
+ onaudiostart: ((event: Event) => void) | null = null;
533
+ onspeechstart: ((event: Event) => void) | null = null;
534
+
535
+ #sessionId = '';
536
+ #unsubscribe: Array<() => void> = [];
537
+ #running = false;
538
+
539
+ #emit(type: string, init: Record<string, unknown> = {}) {
540
+ const event = new Event(type) as Event & Record<string, unknown>;
541
+ Object.assign(event, init);
542
+ this.dispatchEvent(event);
543
+ const handler = (this as unknown as Record<string, ((e: Event) => void) | null>)[`on${type}`];
544
+ if (typeof handler === 'function') handler(event);
545
+ }
546
+
547
+ #teardown() {
548
+ for (const off of this.#unsubscribe) off();
549
+ this.#unsubscribe = [];
550
+ this.#running = false;
551
+ }
552
+
553
+ start() {
554
+ if (this.#running) {
555
+ throw namedError('InvalidStateError', 'recognition has already started');
556
+ }
557
+ sessionSeq += 1;
558
+ this.#sessionId = `speech-${sessionSeq}-${Date.now()}`;
559
+ this.#running = true;
560
+
561
+ const matches = (payload: any) => payload?.sessionId === this.#sessionId;
562
+
563
+ this.#unsubscribe.push(
564
+ onHostEvent('speech-result', (payload) => {
565
+ if (!matches(payload)) return;
566
+
567
+ // SpeechRecognitionEvent shape: results is an indexed,
568
+ // array-like collection of alternatives with a final flag.
569
+ const results = (payload.results ?? []).map((entry: any) => {
570
+ const alternatives = (entry.alternatives ?? []).map((alt: any) => ({
571
+ transcript: alt.transcript ?? '',
572
+ confidence: alt.confidence ?? 0
573
+ }));
574
+ return Object.assign(alternatives, {
575
+ isFinal: !!entry.isFinal,
576
+ length: alternatives.length,
577
+ item: (index: number) => alternatives[index]
578
+ });
579
+ });
580
+
581
+ this.#emit('result', {
582
+ resultIndex: payload.resultIndex ?? 0,
583
+ results: Object.assign(results, {
584
+ length: results.length,
585
+ item: (index: number) => results[index]
586
+ })
587
+ });
588
+ })
589
+ );
590
+
591
+ this.#unsubscribe.push(
592
+ onHostEvent('speech-error', (payload) => {
593
+ if (!matches(payload)) return;
594
+ this.#emit('error', { error: payload.error || 'aborted', message: payload.message || '' });
595
+ })
596
+ );
597
+
598
+ this.#unsubscribe.push(
599
+ onHostEvent('speech-end', (payload) => {
600
+ if (!matches(payload)) return;
601
+ this.#teardown();
602
+ this.#emit('end');
603
+ })
604
+ );
605
+
606
+ call('speech-start', {
607
+ sessionId: this.#sessionId,
608
+ lang: this.lang,
609
+ continuous: this.continuous,
610
+ interimResults: this.interimResults,
611
+ maxAlternatives: this.maxAlternatives
612
+ })
613
+ .then(() => {
614
+ this.#emit('start');
615
+ this.#emit('audiostart');
616
+ })
617
+ .catch((error: Error) => {
618
+ this.#teardown();
619
+ this.#emit('error', {
620
+ error: error.name === 'NotAllowedError' ? 'not-allowed' : 'service-not-allowed',
621
+ message: error.message
622
+ });
623
+ this.#emit('end');
624
+ });
625
+ }
626
+
627
+ stop() {
628
+ if (!this.#running) return;
629
+ call('speech-stop', { sessionId: this.#sessionId, abort: false }).catch(() => {});
630
+ }
631
+
632
+ abort() {
633
+ if (!this.#running) return;
634
+ call('speech-stop', { sessionId: this.#sessionId, abort: true }).catch(() => {});
635
+ this.#teardown();
636
+ this.#emit('end');
637
+ }
638
+ }
639
+
640
+ try {
641
+ Object.defineProperty(HostSpeechRecognition, 'name', {
642
+ value: 'SpeechRecognition',
643
+ configurable: true
644
+ });
645
+ define(scope, 'SpeechRecognition', HostSpeechRecognition);
646
+ define(scope, 'webkitSpeechRecognition', HostSpeechRecognition);
647
+ } catch {
648
+ // Locked down — leave the (non-functional) original in place.
649
+ }
650
+ }
651
+
652
+ // ── Fullscreen ──────────────────────────────────────────────────────────
653
+ // Chrome's real fullscreen resizes the surface it composites down to the
654
+ // browser window, and leaves it there once the fullscreen ends. The page goes
655
+ // on being laid out against the emulated viewport the whole time, so what the
656
+ // preview captures is that layout seen through a window-sized hole: zoomed,
657
+ // cropped at the right and the bottom, and stuck that way until a reload,
658
+ // because nothing in the page ever noticed. A CSS fullscreen gives the page
659
+ // what it asked for and leaves the surface alone.
660
+ //
661
+ // Which means *every* spelling has to be covered, not just the standard one.
662
+ // A single unpatched entry point — `video.webkitEnterFullscreen()`, which
663
+ // media players still reach for — hands the renderer straight to Chrome, and
664
+ // that is exactly the cropped state that then survives the exit.
665
+ {
666
+ const STYLE_ID = '__clopen-fullscreen-style';
667
+ const MAX_Z = 2147483647;
668
+ /** How long the exit hint stays up before fading, as in Chrome itself. */
669
+ const EXIT_HINT_MS = 3200;
670
+ /** What counts as "the user is still there" and brings the hint back. */
671
+ const ACTIVITY_EVENTS = ['mousemove', 'touchstart', 'keydown'];
672
+
673
+ let fullscreenElement: Element | null = null;
674
+ let exitButton: HTMLElement | null = null;
675
+ let hideHintTimer: ReturnType<typeof setTimeout> | undefined;
676
+
677
+ // Captured before the patches further down shadow them. Every replacement
678
+ // below is installed as an *own* property of `document`, while the real
679
+ // `fullscreenElement` and `exitFullscreen` live on `Document.prototype` — so
680
+ // the originals stay reachable, and reading them is the only way to tell an
681
+ // actual browser fullscreen from the one this shim fakes.
682
+ const readNativeElement = ((): (() => Element | null) => {
683
+ for (const key of ['fullscreenElement', 'webkitFullscreenElement']) {
684
+ const descriptor = Object.getOwnPropertyDescriptor(Document.prototype, key);
685
+ if (descriptor?.get) return descriptor.get.bind(document) as () => Element | null;
686
+ }
687
+ return () => null;
688
+ })();
689
+
690
+ const nativeExit = ((): (() => unknown) | null => {
691
+ const target = document as Document & { webkitExitFullscreen?: () => unknown };
692
+ const fn = target.exitFullscreen || target.webkitExitFullscreen;
693
+ return typeof fn === 'function' ? fn.bind(document) : null;
694
+ })();
695
+
696
+ const ensureStyle = () => {
697
+ if (document.getElementById(STYLE_ID)) return;
698
+ const style = document.createElement('style');
699
+ style.id = STYLE_ID;
700
+ // `100%` of the fixed containing block, not `100vw`/`100vh`: viewport
701
+ // units include the scrollbar gutter, so the element overhung the
702
+ // visible area by however wide that is.
703
+ //
704
+ // The black background is scoped to replaced content, which is the only
705
+ // thing `object-fit: contain` letterboxes and therefore the only place
706
+ // bars need filling. Applied to everything, it repainted a fullscreened
707
+ // container black over whatever background the page had given it.
708
+ style.textContent = `
709
+ [data-clopen-fullscreen] {
710
+ position: fixed !important;
711
+ inset: 0 !important;
712
+ width: 100% !important;
713
+ height: 100% !important;
714
+ max-width: none !important;
715
+ max-height: none !important;
716
+ min-width: 0 !important;
717
+ min-height: 0 !important;
718
+ margin: 0 !important;
719
+ z-index: ${MAX_Z} !important;
720
+ }
721
+ video[data-clopen-fullscreen],
722
+ img[data-clopen-fullscreen],
723
+ canvas[data-clopen-fullscreen] {
724
+ object-fit: contain !important;
725
+ background: #000 !important;
726
+ }
727
+ html.clopen-fullscreen-active, body.clopen-fullscreen-active {
728
+ overflow: hidden !important;
729
+ }
730
+ `;
731
+ (document.head || document.documentElement).appendChild(style);
732
+ };
733
+
734
+ /**
735
+ * Bring the hint back and start its countdown again.
736
+ *
737
+ * It stays clickable while faded — the fade is there so the corner of a
738
+ * video is not permanently covered, not to withdraw the way out. A phone
739
+ * has no pointer to move, so a tap has to land on something.
740
+ */
741
+ const revealExitButton = () => {
742
+ if (!exitButton) return;
743
+ exitButton.style.opacity = '1';
744
+ clearTimeout(hideHintTimer);
745
+ hideHintTimer = setTimeout(() => {
746
+ if (exitButton) exitButton.style.opacity = '0.12';
747
+ }, EXIT_HINT_MS);
748
+ };
749
+
750
+ /**
751
+ * The exit affordance.
752
+ *
753
+ * Rendered inside the page on purpose: it is then part of the captured
754
+ * frame and answers a normal click or tap, so it works on a phone and on
755
+ * a second viewer's screen. Anything app-side would need a channel of its
756
+ * own and would still miss the pages that swallow Escape.
757
+ *
758
+ * It fades the way Chrome's own "Press Esc to exit full screen" notice
759
+ * does and returns on the next sign of life. A badge pinned over the
760
+ * corner of a video for the whole of playback is not what full screen
761
+ * looks like anywhere else.
762
+ */
763
+ const showExitButton = () => {
764
+ if (exitButton) {
765
+ revealExitButton();
766
+ return;
767
+ }
768
+
769
+ const button = document.createElement('button');
770
+ button.type = 'button';
771
+ button.setAttribute('data-clopen-fullscreen-ui', '');
772
+ button.textContent = 'Exit full screen (Esc)';
773
+ button.style.cssText = [
774
+ 'position:fixed',
775
+ 'top:12px',
776
+ 'right:12px',
777
+ `z-index:${MAX_Z}`,
778
+ 'margin:0',
779
+ 'padding:6px 12px',
780
+ 'border:0',
781
+ 'border-radius:9999px',
782
+ 'font:500 12px/1.4 system-ui,-apple-system,Segoe UI,sans-serif',
783
+ 'color:#fff',
784
+ 'background:rgba(15,23,42,0.82)',
785
+ 'box-shadow:0 2px 10px rgba(0,0,0,0.45)',
786
+ 'cursor:pointer',
787
+ 'opacity:1',
788
+ 'transition:opacity 220ms ease'
789
+ ].join(';');
790
+ button.addEventListener('click', (event) => {
791
+ event.preventDefault();
792
+ event.stopPropagation();
793
+ void exit();
794
+ });
795
+ (document.body || document.documentElement).appendChild(button);
796
+ exitButton = button;
797
+
798
+ // Capture phase: a player that swallows pointer events over its own
799
+ // surface would otherwise keep the hint from ever coming back.
800
+ for (const type of ACTIVITY_EVENTS) {
801
+ document.addEventListener(type, revealExitButton, true);
802
+ }
803
+ revealExitButton();
804
+ };
805
+
806
+ const removeChrome = () => {
807
+ clearTimeout(hideHintTimer);
808
+ hideHintTimer = undefined;
809
+ for (const type of ACTIVITY_EVENTS) {
810
+ document.removeEventListener(type, revealExitButton, true);
811
+ }
812
+ exitButton?.remove();
813
+ exitButton = null;
814
+ };
815
+
816
+ /**
817
+ * Chrome fires this *on the element*; listeners on `document` only see it
818
+ * because it bubbles. Dispatching it on `document` alone therefore never
819
+ * reached a player that listens on its own container — which left the page
820
+ * convinced it was still fullscreen after the exit, laying out its content
821
+ * for a viewport it no longer had.
822
+ */
823
+ const notify = (target: EventTarget | null) => {
824
+ const on = target && (target as Node).isConnected ? target : document;
825
+ for (const type of ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange']) {
826
+ on.dispatchEvent(new Event(type, { bubbles: true, composed: true }));
827
+ }
828
+ };
829
+
830
+ const clearMarks = (element: Element | null) => {
831
+ if (!element) return;
832
+ element.removeAttribute('data-clopen-fullscreen');
833
+ };
834
+
835
+ const enter = (element: Element) => {
836
+ ensureStyle();
837
+ if (fullscreenElement && fullscreenElement !== element) clearMarks(fullscreenElement);
838
+
839
+ fullscreenElement = element;
840
+ // The root and the body already fill the viewport; pinning them as
841
+ // fixed boxes only breaks their own layout.
842
+ if (element !== document.documentElement && element !== document.body) {
843
+ element.setAttribute('data-clopen-fullscreen', '');
844
+ }
845
+ document.documentElement.classList.add('clopen-fullscreen-active');
846
+ document.body?.classList.add('clopen-fullscreen-active');
847
+ showExitButton();
848
+ notify(element);
849
+ return Promise.resolve();
850
+ };
851
+
852
+ const exit = () => {
853
+ const previous = fullscreenElement;
854
+ if (!previous) return Promise.resolve();
855
+
856
+ clearMarks(previous);
857
+ fullscreenElement = null;
858
+ document.documentElement.classList.remove('clopen-fullscreen-active');
859
+ document.body?.classList.remove('clopen-fullscreen-active');
860
+ removeChrome();
861
+ notify(previous);
862
+ return Promise.resolve();
863
+ };
864
+
865
+ /**
866
+ * Read the current element, dropping it if the page has since replaced it.
867
+ *
868
+ * A re-render (any framework will do) can detach the node that went
869
+ * fullscreen. Reporting a detached element keeps the page in fullscreen
870
+ * mode forever with nothing on screen to leave it by — so the read itself
871
+ * is where that state gets cleaned up.
872
+ */
873
+ const currentElement = (): Element | null => {
874
+ if (fullscreenElement && !fullscreenElement.isConnected) void exit();
875
+ return fullscreenElement;
876
+ };
877
+
878
+ // A fresh function per name: `nativeLike` stamps `fn.name`, so one shared
879
+ // implementation would end up reporting whichever alias was installed last.
880
+ const enterFrom = (name: string) =>
881
+ nativeLike(function (this: Element) {
882
+ return enter(this);
883
+ } as never, name);
884
+
885
+ for (const key of [
886
+ 'requestFullscreen',
887
+ 'webkitRequestFullscreen',
888
+ 'webkitRequestFullScreen',
889
+ 'mozRequestFullScreen',
890
+ 'msRequestFullscreen'
891
+ ]) {
892
+ define(Element.prototype, key, enterFrom(key));
893
+ }
894
+
895
+ // Media players reach for these before the standard API when they think
896
+ // they are on iOS. In Chrome they are real, and they are real *browser*
897
+ // fullscreen — the one path that wrecks the emulated viewport.
898
+ if (typeof HTMLVideoElement !== 'undefined') {
899
+ define(HTMLVideoElement.prototype, 'webkitEnterFullscreen', enterFrom('webkitEnterFullscreen'));
900
+ define(HTMLVideoElement.prototype, 'webkitEnterFullScreen', enterFrom('webkitEnterFullScreen'));
901
+ define(HTMLVideoElement.prototype, 'webkitExitFullscreen', nativeLike(function webkitExitFullscreen() {
902
+ return exit();
903
+ } as never, 'webkitExitFullscreen'));
904
+ try {
905
+ Object.defineProperty(HTMLVideoElement.prototype, 'webkitSupportsFullscreen', {
906
+ configurable: true,
907
+ get: () => true
908
+ });
909
+ Object.defineProperty(HTMLVideoElement.prototype, 'webkitDisplayingFullscreen', {
910
+ configurable: true,
911
+ get(this: Element) {
912
+ return currentElement() === this;
913
+ }
914
+ });
915
+ } catch {
916
+ // Already non-configurable in this engine.
917
+ }
918
+ }
919
+
920
+ for (const key of ['exitFullscreen', 'webkitExitFullscreen', 'webkitCancelFullScreen', 'mozCancelFullScreen', 'msExitFullscreen']) {
921
+ define(document, key, nativeLike(function exitFullscreen() {
922
+ return exit();
923
+ } as never, key));
924
+ }
925
+
926
+ try {
927
+ for (const key of ['fullscreenElement', 'webkitFullscreenElement', 'mozFullScreenElement', 'msFullscreenElement']) {
928
+ Object.defineProperty(document, key, {
929
+ configurable: true,
930
+ get: () => currentElement()
931
+ });
932
+ }
933
+ for (const key of ['fullscreenEnabled', 'webkitFullscreenEnabled', 'mozFullScreenEnabled', 'msFullscreenEnabled']) {
934
+ Object.defineProperty(document, key, { configurable: true, get: () => true });
935
+ }
936
+ for (const key of ['webkitIsFullScreen', 'mozFullScreen']) {
937
+ Object.defineProperty(document, key, { configurable: true, get: () => currentElement() !== null });
938
+ }
939
+ } catch {
940
+ // Already non-configurable in this engine.
941
+ }
942
+
943
+ // Escape is how every browser leaves fullscreen. It stays, but it is no
944
+ // longer the only way out — a preview is often driven from a phone, where
945
+ // there is no Escape key to press.
946
+ document.addEventListener(
947
+ 'keydown',
948
+ (event: KeyboardEvent) => {
949
+ if (event.key === 'Escape' && fullscreenElement) {
950
+ event.preventDefault();
951
+ void exit();
952
+ }
953
+ },
954
+ true
955
+ );
956
+
957
+ // ── Fullscreen that never went through JavaScript ────────────────────
958
+ //
959
+ // The fullscreen button on a `<video controls>` bar is not scripted. Chrome
960
+ // draws those controls itself and its button asks for fullscreen from C++,
961
+ // so every patch above is stepped over and the surface collapses after all
962
+ // — the zoomed, cropped, unexitable frame this whole block exists to avoid.
963
+ // Double-clicking a video takes the same route.
964
+ //
965
+ // Nothing inside the page can stop that from happening. It can, however, be
966
+ // seen the instant it does, and undone: leave Chrome's fullscreen and replay
967
+ // the request as the CSS one, which is indistinguishable to the person who
968
+ // pressed the button.
969
+ //
970
+ // The round trip is hidden from the page. Left visible it reads as fullscreen
971
+ // starting and immediately ending, which is precisely how a player decides
972
+ // the user backed out — and it would then tear down its own fullscreen
973
+ // layout underneath us.
974
+ let unwinding = false;
975
+ let unwindTimer: ReturnType<typeof setTimeout> | undefined;
976
+
977
+ const finishUnwind = () => {
978
+ unwinding = false;
979
+ clearTimeout(unwindTimer);
980
+ unwindTimer = undefined;
981
+ };
982
+
983
+ const onNativeFullscreenChange = (event: Event) => {
984
+ // Synthetic events are this shim's own, and they are the ones the page
985
+ // is meant to hear.
986
+ if (!event.isTrusted) return;
987
+
988
+ const native = readNativeElement();
989
+
990
+ if (unwinding) {
991
+ event.stopImmediatePropagation();
992
+ // Chrome fires the prefixed alias alongside the standard event, so
993
+ // the pair has to clear before the guard drops — a same-task reset
994
+ // would let the second one through as a spurious exit.
995
+ if (!native) setTimeout(finishUnwind, 0);
996
+ return;
997
+ }
998
+
999
+ // A trusted exit with nothing left in fullscreen is Chrome tidying up
1000
+ // after itself; there is nothing to convert.
1001
+ if (!native) return;
1002
+
1003
+ event.stopImmediatePropagation();
1004
+ unwinding = true;
1005
+
1006
+ /**
1007
+ * Have the host re-assert the emulated viewport.
1008
+ *
1009
+ * Unconditionally, because the page cannot tell whether it is needed.
1010
+ * What Chrome's fullscreen strands is the surface it composites — the
1011
+ * frames the capture is cut from collapse to the window and stay there
1012
+ * after the exit. The layout viewport is untouched throughout, so
1013
+ * `innerWidth` and everything measurable from here reports business as
1014
+ * usual while the preview is quietly cropped.
1015
+ */
1016
+ let restoreSent = false;
1017
+ const restoreHost = () => {
1018
+ if (restoreSent) return;
1019
+ restoreSent = true;
1020
+ void call('viewport-restore').catch(() => {
1021
+ // No bridge in this frame and no top frame to relay through; the
1022
+ // CSS fullscreen still stands regardless.
1023
+ });
1024
+ };
1025
+
1026
+ // A promise that never settles, or a browser that fires no closing
1027
+ // event, must not wedge every later toggle — or skip the restore.
1028
+ unwindTimer = setTimeout(() => {
1029
+ finishUnwind();
1030
+ restoreHost();
1031
+ }, 2000);
1032
+
1033
+ try {
1034
+ const result = nativeExit?.() as Promise<void> | undefined;
1035
+ if (result && typeof result.then === 'function') {
1036
+ // One frame after the exit resolves: the renderer resizes back
1037
+ // asynchronously, and measuring before it has would report the
1038
+ // fullscreen geometry and ask for a restore that is not needed.
1039
+ result.then(
1040
+ () => requestAnimationFrame(restoreHost),
1041
+ () => {
1042
+ finishUnwind();
1043
+ restoreHost();
1044
+ }
1045
+ );
1046
+ } else {
1047
+ requestAnimationFrame(restoreHost);
1048
+ }
1049
+ } catch {
1050
+ finishUnwind();
1051
+ restoreHost();
1052
+ }
1053
+
1054
+ // The same element twice means the built-in button was pressed while
1055
+ // this shim already had it full screen — which, to whoever pressed it,
1056
+ // is the request to come back out.
1057
+ if (fullscreenElement === native) void exit();
1058
+ else void enter(native);
1059
+ };
1060
+
1061
+ for (const type of ['fullscreenchange', 'webkitfullscreenchange']) {
1062
+ document.addEventListener(type, onNativeFullscreenChange, true);
1063
+ }
1064
+
1065
+ // A video going fullscreen usually also asks to lock orientation, which
1066
+ // would throw here and abort the page's own handler.
1067
+ const orientation = (screen as unknown as { orientation?: Record<string, unknown> }).orientation;
1068
+ if (orientation) {
1069
+ define(orientation, 'lock', nativeLike(function lock() {
1070
+ return Promise.resolve();
1071
+ } as never, 'lock'));
1072
+ if (typeof orientation.unlock !== 'function') {
1073
+ define(orientation, 'unlock', nativeLike(function unlock() {} as never, 'unlock'));
1074
+ }
1075
+ }
1076
+ }
1077
+
1078
+ // ── Picture-in-Picture ──────────────────────────────────────────────────
1079
+ // The fullscreen problem again, minus any way to answer it: Picture-in-Picture
1080
+ // moves the video into an operating-system window, and a headless renderer has
1081
+ // no windows. The video leaves the page and is simply never seen again. The
1082
+ // button that sends it there is Chrome's own, so it cannot be intercepted on
1083
+ // the way out either.
1084
+ //
1085
+ // So the preview presents itself as a browser where the feature is unavailable
1086
+ // — a state the web already knows how to handle. The built-in button drops out
1087
+ // of the controls, feature detection reports it off, and a scripted request is
1088
+ // refused the way a policy-blocked one is.
1089
+ {
1090
+ const withhold = (event: Event) => {
1091
+ const video = event.target as HTMLVideoElement | null;
1092
+ if (!video || typeof HTMLVideoElement === 'undefined') return;
1093
+ if (video instanceof HTMLVideoElement && !video.disablePictureInPicture) {
1094
+ video.disablePictureInPicture = true;
1095
+ }
1096
+ };
1097
+
1098
+ // Media events do not bubble, but a capture listener still sees them on the
1099
+ // way down to the target — which catches every video, including ones added
1100
+ // later, without watching the whole document for them.
1101
+ for (const type of ['loadstart', 'loadedmetadata', 'play']) {
1102
+ document.addEventListener(type, withhold, true);
1103
+ }
1104
+
1105
+ try {
1106
+ Object.defineProperty(document, 'pictureInPictureEnabled', {
1107
+ configurable: true,
1108
+ get: () => false
1109
+ });
1110
+ } catch {
1111
+ // Already non-configurable in this engine.
1112
+ }
1113
+
1114
+ if (typeof HTMLVideoElement !== 'undefined') {
1115
+ define(
1116
+ HTMLVideoElement.prototype,
1117
+ 'requestPictureInPicture',
1118
+ nativeLike(function requestPictureInPicture() {
1119
+ return Promise.reject(
1120
+ namedError('SecurityError', 'Picture-in-Picture is not available in this preview')
1121
+ );
1122
+ } as never, 'requestPictureInPicture')
1123
+ );
1124
+ }
1125
+
1126
+ // Whatever still slips through — a Chrome build with different controls, a
1127
+ // route added later — must not take the video off screen for good.
1128
+ document.addEventListener(
1129
+ 'enterpictureinpicture',
1130
+ () => {
1131
+ const exitPip = (document as Document & { exitPictureInPicture?: () => Promise<void> })
1132
+ .exitPictureInPicture;
1133
+ try {
1134
+ void exitPip?.call(document).catch(() => {});
1135
+ } catch {
1136
+ // Nothing else to try; the video is out of reach either way.
1137
+ }
1138
+ },
1139
+ true
1140
+ );
1141
+ }
1142
+
1143
+ // ── Clipboard ───────────────────────────────────────────────────────────
1144
+ // The headless clipboard is invisible to the user; theirs is the one that
1145
+ // matters, and it is the one a paste in another app will read from.
1146
+ const clipboard = navigator.clipboard;
1147
+ if (clipboard) {
1148
+ define(
1149
+ clipboard,
1150
+ 'readText',
1151
+ nativeLike(function readText() {
1152
+ return call('clipboard-read').then((text: string) => text ?? '');
1153
+ } as never, 'readText')
1154
+ );
1155
+
1156
+ define(
1157
+ clipboard,
1158
+ 'writeText',
1159
+ nativeLike(function writeText(text: string) {
1160
+ return call('clipboard-write', { text: String(text ?? '') }).then(() => undefined);
1161
+ } as never, 'writeText')
1162
+ );
1163
+ }
1164
+
1165
+ // ── Notifications ───────────────────────────────────────────────────────
1166
+ const NativeNotification = scope.Notification as (typeof Notification) | undefined;
1167
+ if (NativeNotification) {
1168
+ let permission: NotificationPermission = 'default';
1169
+
1170
+ class HostNotification extends EventTarget {
1171
+ static get permission(): NotificationPermission {
1172
+ return permission;
1173
+ }
1174
+
1175
+ static requestPermission(callback?: (result: NotificationPermission) => void): Promise<NotificationPermission> {
1176
+ return call('notification-permission')
1177
+ .then((granted: boolean) => {
1178
+ permission = granted ? 'granted' : 'denied';
1179
+ if (typeof callback === 'function') callback(permission);
1180
+ return permission;
1181
+ })
1182
+ .catch(() => {
1183
+ permission = 'denied';
1184
+ if (typeof callback === 'function') callback(permission);
1185
+ return permission;
1186
+ });
1187
+ }
1188
+
1189
+ title: string;
1190
+ body: string;
1191
+ icon: string;
1192
+ tag: string;
1193
+ data: unknown;
1194
+ onclick: ((event: Event) => void) | null = null;
1195
+ onclose: ((event: Event) => void) | null = null;
1196
+ onerror: ((event: Event) => void) | null = null;
1197
+ onshow: ((event: Event) => void) | null = null;
1198
+
1199
+ constructor(title: string, options?: NotificationOptions) {
1200
+ super();
1201
+ this.title = String(title ?? '');
1202
+ this.body = options?.body ?? '';
1203
+ this.icon = options?.icon ?? '';
1204
+ this.tag = options?.tag ?? '';
1205
+ this.data = options?.data;
1206
+
1207
+ call('notification-show', {
1208
+ title: this.title,
1209
+ body: this.body,
1210
+ icon: this.icon,
1211
+ tag: this.tag
1212
+ })
1213
+ .then(() => {
1214
+ const event = new Event('show');
1215
+ this.dispatchEvent(event);
1216
+ if (typeof this.onshow === 'function') this.onshow(event);
1217
+ })
1218
+ .catch(() => {
1219
+ const event = new Event('error');
1220
+ this.dispatchEvent(event);
1221
+ if (typeof this.onerror === 'function') this.onerror(event);
1222
+ });
1223
+ }
1224
+
1225
+ close() {
1226
+ const event = new Event('close');
1227
+ this.dispatchEvent(event);
1228
+ if (typeof this.onclose === 'function') this.onclose(event);
1229
+ }
1230
+ }
1231
+
1232
+ try {
1233
+ Object.defineProperty(HostNotification, 'name', { value: 'Notification', configurable: true });
1234
+ Object.defineProperty(scope, 'Notification', {
1235
+ value: HostNotification,
1236
+ configurable: true,
1237
+ writable: true
1238
+ });
1239
+ } catch {
1240
+ // Notification is locked down — keep the native (non-functional) one.
1241
+ }
1242
+ }
1243
+
1244
+ // ── Permissions ─────────────────────────────────────────────────────────
1245
+ // Report `prompt` for everything the bridge owns: the real answer lives in
1246
+ // the viewer's browser and is only known once the page actually asks, so
1247
+ // claiming `denied` up front would make pages hide features that do work.
1248
+ const permissions = navigator.permissions;
1249
+ if (permissions?.query) {
1250
+ const BRIDGED = new Set([
1251
+ 'geolocation',
1252
+ 'camera',
1253
+ 'microphone',
1254
+ 'notifications',
1255
+ 'clipboard-read',
1256
+ 'clipboard-write',
1257
+ 'speaker-selection',
1258
+ 'display-capture'
1259
+ ]);
1260
+ const originalQuery = permissions.query.bind(permissions);
1261
+
1262
+ define(
1263
+ permissions,
1264
+ 'query',
1265
+ nativeLike(function query(descriptor: PermissionDescriptor) {
1266
+ if (descriptor && BRIDGED.has(descriptor.name as string)) {
1267
+ const status = new EventTarget() as PermissionStatus;
1268
+ Object.defineProperty(status, 'name', { value: descriptor.name, configurable: true });
1269
+ Object.defineProperty(status, 'state', { value: 'prompt', configurable: true });
1270
+ Object.defineProperty(status, 'onchange', { value: null, writable: true, configurable: true });
1271
+ return Promise.resolve(status);
1272
+ }
1273
+ return originalQuery(descriptor);
1274
+ } as never, 'query')
1275
+ );
1276
+ }
1277
+ }