@open-wa/screencaster 5.0.0 → 5.2.0

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/src/server.ts ADDED
@@ -0,0 +1,861 @@
1
+ // ────────────────────────────────────────────────────────────
2
+ // @open-wa/screencaster/server
3
+ //
4
+ // Server-side screencast orchestrator using Hono's WebSocket
5
+ // helpers. Runtime-agnostic — works on Node.js, Bun, Deno, etc.
6
+ //
7
+ // Usage:
8
+ // import { createNodeWebSocket } from '@hono/node-ws';
9
+ // import { createScreencastRoute, ScreencastManager } from '@open-wa/screencaster/server';
10
+ //
11
+ // const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
12
+ // const manager = new ScreencastManager();
13
+ // app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
14
+ //
15
+ // // Later, once the browser page is ready:
16
+ // manager.setPage(page);
17
+ // ────────────────────────────────────────────────────────────
18
+
19
+ import type { Context } from 'hono';
20
+ import type {
21
+ IScreencastPage,
22
+ IScreencastCDPSession,
23
+ ScreencastOptions,
24
+ ServerMessage,
25
+ ClientMessage,
26
+ FrameMessage,
27
+ NavStateMessage,
28
+ } from './types';
29
+ import { DEFAULT_SCREENCAST_OPTIONS, Modifiers, SPECIAL_KEYS } from './types';
30
+
31
+ // Re-export types for convenience
32
+ export type { IScreencastPage, IScreencastCDPSession, ScreencastOptions } from './types';
33
+
34
+ // ────── Debug logger ──────
35
+
36
+ const TAG = '[SC:server]';
37
+ let _frameCount = 0;
38
+ let _lastFrameLogTime = 0;
39
+
40
+ function ts(): string {
41
+ return Date.now().toString();
42
+ }
43
+
44
+ function dbg(...args: unknown[]): void {
45
+ if (process.env.DEBUG_SCREENCAST) console.log(ts(), TAG, ...args);
46
+ }
47
+
48
+ function dbgWarn(...args: unknown[]): void {
49
+ if (process.env.DEBUG_SCREENCAST) console.warn(ts(), TAG, ...args);
50
+ }
51
+
52
+ function dbgErr(...args: unknown[]): void {
53
+ if (process.env.DEBUG_SCREENCAST) console.error(ts(), TAG, ...args);
54
+ }
55
+
56
+ // ────── Types for Hono WebSocket ──────
57
+
58
+ /**
59
+ * Hono's upgradeWebSocket helper signature.
60
+ * We accept this as a parameter to avoid importing any runtime-specific adapter.
61
+ */
62
+ type UpgradeWebSocket = (
63
+ handler: (c: Context) => HonoWSHandlers | Promise<HonoWSHandlers>
64
+ ) => (c: Context) => Response | Promise<Response>;
65
+
66
+ interface HonoWSHandlers {
67
+ onOpen?: (evt: unknown, ws: HonoWSContext) => void;
68
+ onMessage?: (evt: { data: unknown }, ws: HonoWSContext) => void;
69
+ onClose?: (evt: unknown, ws: HonoWSContext) => void;
70
+ onError?: (evt: unknown, ws: HonoWSContext) => void;
71
+ }
72
+
73
+ interface HonoWSContext {
74
+ send(data: string | ArrayBuffer | Uint8Array): void;
75
+ close(code?: number, reason?: string): void;
76
+ readyState: number;
77
+ }
78
+
79
+ // ────── ScreencastManager ──────
80
+
81
+ interface ViewportSize {
82
+ width: number;
83
+ height: number;
84
+ }
85
+
86
+ /**
87
+ * ScreencastManager owns the CDP session lifecycle and frame distribution.
88
+ * It is page-agnostic at construction — call setPage() once the browser is ready.
89
+ */
90
+ export class ScreencastManager {
91
+ private page: IScreencastPage | null = null;
92
+ private cdpSession: IScreencastCDPSession | null = null;
93
+ private clients = new Set<HonoWSContext>();
94
+ private isScreencasting = false;
95
+ private currentOptions: Required<ScreencastOptions> = { ...DEFAULT_SCREENCAST_OPTIONS };
96
+ private viewport: ViewportSize = { width: 1280, height: 720 };
97
+ private cdpLock: Promise<void> = Promise.resolve();
98
+ private frameHandler: ((...args: unknown[]) => void) | null = null;
99
+ private navigationHandler: ((...args: unknown[]) => void) | null = null;
100
+ private pageNavigationHandler: ((frame: unknown) => void) | null = null;
101
+ private destroyed = false;
102
+
103
+ /**
104
+ * Bind a CDP-capable page. Can be called multiple times
105
+ * (e.g., when the session restarts).
106
+ */
107
+ async setPage(page: IScreencastPage): Promise<void> {
108
+ dbg('setPage() called, page.isClosed():', page.isClosed());
109
+
110
+ // Clean up previous session
111
+ await this.executeInLock(() => this.teardownCDP());
112
+
113
+ this.page = page;
114
+ dbg('setPage() — calling page.cdp() to create CDP session...');
115
+ this.cdpSession = await page.cdp();
116
+ dbg('setPage() — CDP session obtained:', !!this.cdpSession);
117
+ dbg('setPage() — CDP session type:', typeof this.cdpSession);
118
+ dbg('setPage() — CDP session keys:', this.cdpSession ? Object.keys(this.cdpSession as any).slice(0, 15) : 'null');
119
+
120
+ // Set up frame listener
121
+ this.setupFrameListener();
122
+
123
+ // If we already have clients, start screencasting
124
+ dbg('setPage() — clients waiting:', this.clients.size);
125
+ if (this.clients.size > 0) {
126
+ dbg('setPage() — auto-starting screencast for waiting clients');
127
+ await this.executeInLock(() => this.startScreencast());
128
+ }
129
+
130
+ // Notify all clients that the page is bound
131
+ dbg('setPage() — broadcasting ready:true');
132
+ this.broadcast({ type: 'ready', bound: true });
133
+ }
134
+
135
+ /**
136
+ * Unbind the current page (session ended, browser closed).
137
+ */
138
+ async clearPage(): Promise<void> {
139
+ dbg('clearPage() called');
140
+ await this.executeInLock(() => this.teardownCDP());
141
+ this.page = null;
142
+ this.cdpSession = null;
143
+ this.broadcast({ type: 'ready', bound: false });
144
+ }
145
+
146
+ /**
147
+ * Whether a page is currently bound.
148
+ */
149
+ get isBound(): boolean {
150
+ const bound = this.page !== null && !this.page.isClosed();
151
+ return bound;
152
+ }
153
+
154
+ /**
155
+ * Number of connected viewers.
156
+ */
157
+ get clientCount(): number {
158
+ return this.clients.size;
159
+ }
160
+
161
+ // ────── Client management ──────
162
+
163
+ addClient(ws: HonoWSContext): void {
164
+ this.clients.add(ws);
165
+ dbg('addClient() — total clients:', this.clients.size, '| isBound:', this.isBound, '| isScreencasting:', this.isScreencasting, '| ws.readyState:', ws.readyState);
166
+
167
+ // Listen to the raw underlying ws for transport-level diagnostics
168
+ const rawWs = (ws as any).raw;
169
+ if (rawWs && typeof rawWs.on === 'function') {
170
+ rawWs.on('close', (code: number, reason: Uint8Array) => {
171
+ dbg('RAW_WS:close — code:', code, '| reason:', reason?.toString(), '| rawWs.readyState:', rawWs.readyState);
172
+ });
173
+ rawWs.on('error', (err: Error) => {
174
+ dbgErr('RAW_WS:error —', err.message);
175
+ });
176
+ // Log socket-level events
177
+ const socket = rawWs._socket;
178
+ if (socket) {
179
+ socket.once('close', (hadError: boolean) => {
180
+ dbg('TCP_SOCKET:close — hadError:', hadError);
181
+ });
182
+ socket.once('error', (err: Error) => {
183
+ dbgErr('TCP_SOCKET:error —', err.message);
184
+ });
185
+ }
186
+ }
187
+
188
+ // Send current state
189
+ this.sendTo(ws, { type: 'ready', bound: this.isBound });
190
+
191
+ // Auto-start if we have a page and this is the first client
192
+ if (this.isBound && !this.isScreencasting) {
193
+ dbg('addClient() — auto-starting screencast (first client with bound page)');
194
+ this.executeInLock(() => this.startScreencast()).catch(this.logError);
195
+ this.executeInLock(() => this.sendNavState()).catch(this.logError);
196
+ } else {
197
+ dbg('addClient() — NOT auto-starting. isBound:', this.isBound, 'isScreencasting:', this.isScreencasting);
198
+ }
199
+ }
200
+
201
+ removeClient(ws: HonoWSContext): void {
202
+ this.clients.delete(ws);
203
+ dbg('removeClient() — total clients:', this.clients.size, '| isScreencasting:', this.isScreencasting);
204
+
205
+ // Auto-stop when no clients remain
206
+ if (this.clients.size === 0 && this.isScreencasting) {
207
+ dbg('removeClient() — no clients left, stopping screencast');
208
+ this.stopScreencast().catch(this.logError);
209
+ }
210
+ }
211
+
212
+ // ────── Message handling ──────
213
+
214
+ async handleMessage(ws: HonoWSContext, raw: unknown): Promise<void> {
215
+ let msg: ClientMessage;
216
+ try {
217
+ msg = JSON.parse(typeof raw === 'string' ? raw : String(raw)) as ClientMessage;
218
+ } catch {
219
+ dbgWarn('handleMessage() — invalid JSON from client:', typeof raw === 'string' ? raw.slice(0, 100) : typeof raw);
220
+ this.sendTo(ws, { type: 'error', message: 'Invalid JSON' });
221
+ return;
222
+ }
223
+
224
+ // Log all messages except high-frequency ones (mouse moves, acks)
225
+ if (msg.type !== 'mouse' && msg.type !== 'ack') {
226
+ dbg('handleMessage():', msg.type, JSON.stringify(msg).slice(0, 200));
227
+ }
228
+
229
+ try {
230
+ switch (msg.type) {
231
+ case 'start':
232
+ if (msg.options) {
233
+ this.currentOptions = { ...DEFAULT_SCREENCAST_OPTIONS, ...msg.options };
234
+ dbg('handleMessage(start) — options updated:', JSON.stringify(this.currentOptions));
235
+ }
236
+ dbg('handleMessage(start) — isBound:', this.isBound, '| isScreencasting:', this.isScreencasting);
237
+ if (this.isBound) {
238
+ await this.executeInLock(async () => {
239
+ await this.startScreencast();
240
+ await this.sendNavState();
241
+ });
242
+ } else {
243
+ dbgWarn('handleMessage(start) — page not bound, cannot start');
244
+ }
245
+ break;
246
+
247
+ case 'stop':
248
+ dbg('handleMessage(stop)');
249
+ await this.executeInLock(() => this.stopScreencast());
250
+ this.sendTo(ws, { type: 'stopped' });
251
+ break;
252
+
253
+ case 'ack':
254
+ // No-op: ACKs are now handled server-side immediately in the frame handler.
255
+ // Kept for backward compatibility with older clients.
256
+ dbg('handleMessage(ack) — no-op (server-side ACK), sessionId:', msg.sessionId);
257
+ break;
258
+
259
+ case 'mouse':
260
+ await this.executeInLock(() => this.handleMouse(msg));
261
+ break;
262
+
263
+ case 'key':
264
+ dbg('handleMessage(key):', msg.action, msg.key, msg.code);
265
+ await this.executeInLock(() => this.handleKey(msg));
266
+ break;
267
+
268
+ case 'scroll':
269
+ await this.executeInLock(() => this.handleScroll(msg));
270
+ break;
271
+
272
+ case 'navigate':
273
+ dbg('handleMessage(navigate):', msg.url);
274
+ await this.executeInLock(() => this.handleNavigate(msg.url));
275
+ break;
276
+
277
+ case 'go-back':
278
+ dbg('handleMessage(go-back)');
279
+ await this.executeInLock(() => this.handleGoBack());
280
+ break;
281
+
282
+ case 'go-forward':
283
+ dbg('handleMessage(go-forward)');
284
+ await this.executeInLock(() => this.handleGoForward());
285
+ break;
286
+
287
+ case 'resize':
288
+ dbg('handleMessage(resize):', msg.width, 'x', msg.height);
289
+ await this.executeInLock(() => this.handleResize(msg.width, msg.height));
290
+ break;
291
+
292
+ default:
293
+ dbgWarn('handleMessage() — unknown message type:', (msg as any).type);
294
+ }
295
+ } catch (err) {
296
+ dbgErr('handleMessage() — error processing', msg.type, ':', err instanceof Error ? err.message : err);
297
+ this.sendTo(ws, {
298
+ type: 'error',
299
+ message: err instanceof Error ? err.message : 'Unknown error',
300
+ });
301
+ }
302
+ }
303
+
304
+ // ────── Screencast lifecycle ──────
305
+
306
+ private async startScreencast(): Promise<void> {
307
+ dbg('startScreencast() — cdpSession:', !!this.cdpSession, '| isScreencasting:', this.isScreencasting, '| destroyed:', this.destroyed);
308
+ if (!this.cdpSession || this.isScreencasting || this.destroyed) {
309
+ dbg('startScreencast() — SKIPPING (guard failed)');
310
+ return;
311
+ }
312
+
313
+ // Set flag synchronously BEFORE the async CDP call to prevent
314
+ // concurrent callers from passing the guard (race between
315
+ // addClient fire-and-forget and handleMessage('start')).
316
+ this.isScreencasting = true;
317
+
318
+ try {
319
+ const params = {
320
+ format: this.currentOptions.format,
321
+ quality: this.currentOptions.quality,
322
+ maxWidth: this.currentOptions.maxWidth,
323
+ maxHeight: this.currentOptions.maxHeight,
324
+ everyNthFrame: this.currentOptions.everyNthFrame,
325
+ };
326
+ dbg('startScreencast() — sending Page.startScreencast with params:', JSON.stringify(params));
327
+ await this.cdpSession.send('Page.startScreencast', params);
328
+ _frameCount = 0;
329
+ _lastFrameLogTime = Date.now();
330
+ dbg('startScreencast() — ✅ SUCCESS, screencast is now running');
331
+ } catch (err) {
332
+ this.isScreencasting = false;
333
+ dbgErr('startScreencast() — ❌ FAILED:', err instanceof Error ? err.message : err);
334
+ dbgErr('startScreencast() — full error:', err);
335
+ this.logError(err);
336
+ }
337
+ }
338
+
339
+ private async stopScreencast(): Promise<void> {
340
+ dbg('stopScreencast() — cdpSession:', !!this.cdpSession, '| isScreencasting:', this.isScreencasting);
341
+ if (!this.cdpSession || !this.isScreencasting) return;
342
+
343
+ try {
344
+ await this.cdpSession.send('Page.stopScreencast');
345
+ dbg('stopScreencast() — ✅ stopped');
346
+ } catch (err) {
347
+ dbgWarn('stopScreencast() — error (session may be closed):', err instanceof Error ? err.message : err);
348
+ // Session may already be closed
349
+ }
350
+ this.isScreencasting = false;
351
+ }
352
+
353
+ private async executeInLock<T>(fn: () => Promise<T>): Promise<T> {
354
+ const next = this.cdpLock.then(fn);
355
+ this.cdpLock = next.then(() => { }).catch(() => { });
356
+ return next;
357
+ }
358
+
359
+ // ackFrame() removed — ACKs are now handled server-side immediately in the frame handler.
360
+
361
+ private setupFrameListener(): void {
362
+ dbg('setupFrameListener() — cdpSession:', !!this.cdpSession);
363
+ if (!this.cdpSession) return;
364
+
365
+ // The CDP session from driver-interface uses .send() only.
366
+ // We need to subscribe to events. The underlying session
367
+ // is obtained via page.cdp(), which in puppeteer returns
368
+ // a CDPSession with an .on() method. We access it via
369
+ // the raw unwrap() to set up the event listener.
370
+ const rawSession = this.cdpSession as unknown as {
371
+ on?: (event: string, handler: (...args: unknown[]) => void) => void;
372
+ off?: (event: string, handler: (...args: unknown[]) => void) => void;
373
+ };
374
+
375
+ dbg('setupFrameListener() — rawSession.on:', typeof rawSession.on, '| rawSession.off:', typeof rawSession.off);
376
+
377
+ if (typeof rawSession.on !== 'function') {
378
+ dbgErr('setupFrameListener() — ❌ CDP session does NOT support .on() event subscriptions!');
379
+ dbgErr('setupFrameListener() — session prototype chain:', Object.getPrototypeOf(this.cdpSession)?.constructor?.name);
380
+ console.warn('[screencaster] CDP session does not support event subscriptions');
381
+ return;
382
+ }
383
+
384
+ // Clean up any previous handler
385
+ if (this.frameHandler && typeof rawSession.off === 'function') {
386
+ dbg('setupFrameListener() — cleaning up previous frame handler');
387
+ rawSession.off('Page.screencastFrame', this.frameHandler);
388
+ }
389
+
390
+ dbg('setupFrameListener() — registering Page.screencastFrame handler');
391
+
392
+ // Keep a local ref to cdpSession for the closure — avoids stale this.cdpSession
393
+ const session = this.cdpSession;
394
+
395
+ this.frameHandler = ((...args: unknown[]) => {
396
+ _frameCount++;
397
+ const now = Date.now();
398
+ const params = args[0] as Record<string, unknown>;
399
+ const { data, sessionId, metadata } = params as {
400
+ data: string;
401
+ sessionId: number;
402
+ metadata: FrameMessage['metadata'];
403
+ };
404
+
405
+ // Log every frame for the first 5, then every 30th frame or every 5 seconds
406
+ if (_frameCount <= 5 || _frameCount % 30 === 0 || (now - _lastFrameLogTime) > 5000) {
407
+ dbg(`📦 FRAME #${_frameCount} | sessionId: ${sessionId} | dataLen: ${data?.length ?? 'null'} | hasMetadata: ${!!metadata} | clients: ${this.clients.size}`);
408
+ if (metadata) {
409
+ dbg(` metadata: ${metadata.deviceWidth}x${metadata.deviceHeight} | pageScale: ${metadata.pageScaleFactor} | offsetTop: ${metadata.offsetTop}`);
410
+ }
411
+ _lastFrameLogTime = now;
412
+ }
413
+
414
+ // Update viewport from metadata
415
+ if (metadata) {
416
+ this.viewport = {
417
+ width: metadata.deviceWidth || this.viewport.width,
418
+ height: metadata.deviceHeight || this.viewport.height,
419
+ };
420
+ }
421
+
422
+ const frame: FrameMessage = {
423
+ type: 'frame',
424
+ data,
425
+ sessionId,
426
+ metadata: metadata || {
427
+ width: this.viewport.width,
428
+ height: this.viewport.height,
429
+ timestamp: Date.now(),
430
+ offsetTop: 0,
431
+ pageScaleFactor: 1,
432
+ deviceWidth: this.viewport.width,
433
+ deviceHeight: this.viewport.height,
434
+ },
435
+ };
436
+
437
+ // Broadcast frame to all connected clients
438
+ this.broadcast(frame);
439
+
440
+ // CRITICAL: ACK the frame immediately server-side to keep
441
+ // frames flowing. The POC does this — delegating ACKs to
442
+ // the client round-trip caused frame starvation.
443
+ session.send('Page.screencastFrameAck', { sessionId }).catch(() => {
444
+ // Session might be closed after navigation, ignore
445
+ });
446
+
447
+ if (_frameCount <= 3) {
448
+ dbg(` → ACK sent server-side for sessionId: ${sessionId}`);
449
+ }
450
+ }) as (...args: unknown[]) => void;
451
+
452
+ rawSession.on('Page.screencastFrame', this.frameHandler);
453
+ dbg('setupFrameListener() — ✅ Page.screencastFrame handler registered');
454
+
455
+ // ── CDP-level navigation listener (Page.frameNavigated) ──
456
+ dbg('setupFrameListener() — registering Page.frameNavigated handler (CDP)');
457
+
458
+ // Clean up any previous navigation handler
459
+ if (this.navigationHandler && typeof rawSession.off === 'function') {
460
+ dbg('setupFrameListener() — cleaning up previous CDP navigation handler');
461
+ rawSession.off('Page.frameNavigated', this.navigationHandler);
462
+ }
463
+
464
+ this.navigationHandler = (async (...navArgs: unknown[]) => {
465
+ const frame = navArgs[0] as { frame?: { parentId?: string; url?: string } };
466
+ const isMainFrame = frame.frame && !frame.frame.parentId;
467
+ dbg('CDP:Page.frameNavigated fired | isMainFrame:', isMainFrame, '| url:', frame.frame?.url?.slice(0, 80));
468
+
469
+ // Only care about main frame (no parentId)
470
+ if (isMainFrame) {
471
+ dbg('CDP:Page.frameNavigated — main frame navigation detected, resetting screencast');
472
+ // Navigation stops screencast automatically
473
+ this.isScreencasting = false;
474
+
475
+ await this.sendNavState();
476
+
477
+ // Restart if we have clients
478
+ if (this.clients.size > 0) {
479
+ dbg('CDP:Page.frameNavigated — restarting screencast for', this.clients.size, 'clients');
480
+ await this.startScreencast();
481
+ }
482
+ }
483
+ }) as (...args: unknown[]) => void;
484
+
485
+ rawSession.on('Page.frameNavigated', this.navigationHandler);
486
+
487
+ // ── Page-level navigation listener (high-level, like the POC) ──
488
+ // This is a secondary/fallback signal that uses the IPage driver's
489
+ // high-level event, which is more reliable across CDP session resets.
490
+ if (this.page && typeof (this.page as any).on === 'function') {
491
+ // Clean up any previous page-level handler
492
+ if (this.pageNavigationHandler && typeof (this.page as any).off === 'function') {
493
+ dbg('setupFrameListener() — cleaning up previous page-level navigation handler');
494
+ (this.page as any).off('framenavigated', this.pageNavigationHandler);
495
+ }
496
+
497
+ this.pageNavigationHandler = async (_frame: unknown) => {
498
+ dbg('PAGE:framenavigated fired (high-level) — isScreencasting:', this.isScreencasting);
499
+ // Only act if screencast stopped (CDP event may have already handled it)
500
+ if (!this.isScreencasting && this.clients.size > 0) {
501
+ dbg('PAGE:framenavigated — screencast not running, restarting for', this.clients.size, 'clients');
502
+ await this.sendNavState();
503
+ await this.startScreencast();
504
+ } else {
505
+ dbg('PAGE:framenavigated — screencast already running or no clients, no action needed');
506
+ }
507
+ };
508
+
509
+ (this.page as any).on('framenavigated', this.pageNavigationHandler);
510
+ dbg('setupFrameListener() — ✅ page-level framenavigated listener registered');
511
+ } else {
512
+ dbgWarn('setupFrameListener() — page does not support .on() events, skipping page-level navigation listener');
513
+ }
514
+
515
+ // Enable Page events so we receive frameNavigated
516
+ dbg('setupFrameListener() — sending Page.enable');
517
+ this.cdpSession.send('Page.enable').catch((err) => {
518
+ dbgErr('setupFrameListener() — Page.enable failed:', err instanceof Error ? err.message : err);
519
+ this.logError(err);
520
+ });
521
+ dbg('setupFrameListener() — ✅ setup complete');
522
+ }
523
+
524
+ private async sendNavState(): Promise<void> {
525
+ dbg('sendNavState() — cdpSession:', !!this.cdpSession);
526
+ if (!this.cdpSession) return;
527
+
528
+ try {
529
+ const history = await this.cdpSession.send<{
530
+ currentIndex: number;
531
+ entries: unknown[];
532
+ }>('Page.getNavigationHistory');
533
+
534
+ if (!history) {
535
+ dbgWarn('sendNavState() — getNavigationHistory returned null/undefined');
536
+ return;
537
+ }
538
+
539
+ const { currentIndex, entries } = history;
540
+ const url = this.page?.isClosed() ? '' : (await this.getPageUrl());
541
+ const nav: NavStateMessage = {
542
+ type: 'nav-state',
543
+ url,
544
+ canGoBack: currentIndex > 0,
545
+ canGoForward: currentIndex < entries.length - 1,
546
+ };
547
+
548
+ dbg('sendNavState() — broadcasting:', JSON.stringify({ url: url.slice(0, 60), canGoBack: nav.canGoBack, canGoForward: nav.canGoForward, entries: entries.length }));
549
+ this.broadcast(nav);
550
+ } catch (err) {
551
+ dbgWarn('sendNavState() — error:', err instanceof Error ? err.message : err);
552
+ // Page might not be ready yet
553
+ }
554
+ }
555
+
556
+ private async getPageUrl(): Promise<string> {
557
+ if (!this.cdpSession) return '';
558
+ try {
559
+ const result = await this.cdpSession.send<{ result: { value: string } }>(
560
+ 'Runtime.evaluate',
561
+ { expression: 'window.location.href' }
562
+ );
563
+ return result?.result?.value || '';
564
+ } catch {
565
+ return '';
566
+ }
567
+ }
568
+
569
+ // ────── Input forwarding ──────
570
+
571
+ private async handleMouse(msg: { action: string; x: number; y: number; button?: string }): Promise<void> {
572
+ if (!this.cdpSession) return;
573
+
574
+ const x = msg.x * this.viewport.width;
575
+ const y = msg.y * this.viewport.height;
576
+
577
+ const cdpButton = msg.button === 'right' ? 'right'
578
+ : msg.button === 'middle' ? 'middle'
579
+ : 'left';
580
+
581
+ const cdpType = msg.action === 'move' ? 'mouseMoved'
582
+ : msg.action === 'down' ? 'mousePressed'
583
+ : 'mouseReleased';
584
+
585
+ await this.cdpSession.send('Input.dispatchMouseEvent', {
586
+ type: cdpType,
587
+ x,
588
+ y,
589
+ button: cdpButton,
590
+ clickCount: msg.action === 'down' ? 1 : 0,
591
+ });
592
+ }
593
+
594
+ private async handleKey(msg: { action: string; key: string; code: string; modifiers?: number }): Promise<void> {
595
+ if (!this.cdpSession) return;
596
+
597
+ const modifiers = msg.modifiers || 0;
598
+ const type = msg.action === 'down' ? 'keyDown' : 'keyUp';
599
+
600
+ // For printable single chars on keyDown, also send a char event
601
+ if (msg.action === 'down' && msg.key.length === 1 && !SPECIAL_KEYS.has(msg.key)) {
602
+ await this.cdpSession.send('Input.dispatchKeyEvent', {
603
+ type: 'keyDown',
604
+ key: msg.key,
605
+ code: msg.code,
606
+ modifiers,
607
+ windowsVirtualKeyCode: msg.key.charCodeAt(0),
608
+ nativeVirtualKeyCode: msg.key.charCodeAt(0),
609
+ });
610
+ // Follow with a char event for text input
611
+ await this.cdpSession.send('Input.dispatchKeyEvent', {
612
+ type: 'char',
613
+ text: msg.key,
614
+ key: msg.key,
615
+ code: msg.code,
616
+ modifiers,
617
+ });
618
+ } else {
619
+ await this.cdpSession.send('Input.dispatchKeyEvent', {
620
+ type,
621
+ key: msg.key,
622
+ code: msg.code,
623
+ modifiers,
624
+ });
625
+ }
626
+ }
627
+
628
+ private async handleScroll(msg: { deltaX: number; deltaY: number; x: number; y: number }): Promise<void> {
629
+ if (!this.cdpSession) return;
630
+
631
+ const x = msg.x * this.viewport.width;
632
+ const y = msg.y * this.viewport.height;
633
+
634
+ await this.cdpSession.send('Input.dispatchMouseEvent', {
635
+ type: 'mouseWheel',
636
+ x,
637
+ y,
638
+ deltaX: msg.deltaX,
639
+ deltaY: msg.deltaY,
640
+ });
641
+ }
642
+
643
+ private async handleNavigate(url: string): Promise<void> {
644
+ if (!this.cdpSession) return;
645
+
646
+ await this.cdpSession.send('Page.navigate', { url });
647
+ }
648
+
649
+ private async handleGoBack(): Promise<void> {
650
+ if (!this.cdpSession) return;
651
+
652
+ const history = await this.cdpSession.send<{
653
+ currentIndex: number;
654
+ entries: { id: number }[];
655
+ }>('Page.getNavigationHistory');
656
+
657
+ if (history && history.currentIndex > 0) {
658
+ const entry = history.entries[history.currentIndex - 1];
659
+ await this.cdpSession.send('Page.navigateToHistoryEntry', { entryId: entry.id });
660
+ }
661
+ }
662
+
663
+ private async handleGoForward(): Promise<void> {
664
+ if (!this.cdpSession) return;
665
+
666
+ const history = await this.cdpSession.send<{
667
+ currentIndex: number;
668
+ entries: { id: number }[];
669
+ }>('Page.getNavigationHistory');
670
+
671
+ if (history && history.currentIndex < history.entries.length - 1) {
672
+ const entry = history.entries[history.currentIndex + 1];
673
+ await this.cdpSession.send('Page.navigateToHistoryEntry', { entryId: entry.id });
674
+ }
675
+ }
676
+
677
+ private async handleResize(width: number, height: number): Promise<void> {
678
+ if (!this.cdpSession) return;
679
+
680
+ try {
681
+ const w = Math.floor(width);
682
+ const h = Math.floor(height);
683
+
684
+ dbg('handleResize() — updating viewport and stopping screencast | new size:', w, 'x', h);
685
+
686
+ // 1. Update options and viewport immediately so mouse clicks are accurate
687
+ this.currentOptions.maxWidth = w;
688
+ this.currentOptions.maxHeight = h;
689
+ this.viewport = { width: w, height: h };
690
+
691
+ // 2. Tell the browser to actually resize the viewport
692
+ // This ensures responsive layouts (media queries) are triggered.
693
+ await this.cdpSession.send('Emulation.setDeviceMetricsOverride', {
694
+ width: w,
695
+ height: h,
696
+ deviceScaleFactor: 1,
697
+ mobile: false,
698
+ screenOrientation: { angle: 0, type: 'portraitPrimary' }
699
+ });
700
+
701
+ // 3. Restart screencast to apply new max dimensions to the stream
702
+ if (this.isScreencasting) {
703
+ dbg('handleResize() — restarting screencast');
704
+ await this.stopScreencast();
705
+ await this.startScreencast();
706
+ }
707
+ } catch (err) {
708
+ dbgErr('handleResize() — error:', err instanceof Error ? err.message : err);
709
+ this.logError(err);
710
+ }
711
+ }
712
+
713
+ // ────── Utilities ──────
714
+
715
+ private broadcast(msg: ServerMessage): void {
716
+ const payload = JSON.stringify(msg);
717
+ let sent = 0;
718
+ let skipped = 0;
719
+ for (const ws of this.clients) {
720
+ if (ws.readyState === 1 /* OPEN */) {
721
+ try {
722
+ ws.send(payload);
723
+ sent++;
724
+ } catch (err) {
725
+ dbgErr('broadcast() — send failed for a client:', err instanceof Error ? err.message : err);
726
+ skipped++;
727
+ }
728
+ } else {
729
+ skipped++;
730
+ }
731
+ }
732
+ // Only log broadcast stats for non-frame messages (frames are too frequent)
733
+ if (msg.type !== 'frame') {
734
+ dbg(`broadcast(${msg.type}) — sent: ${sent}, skipped: ${skipped}, total: ${this.clients.size}`);
735
+ }
736
+ }
737
+
738
+ private sendTo(ws: HonoWSContext, msg: ServerMessage): void {
739
+ dbg(`sendTo(${msg.type}) — ws.readyState: ${ws.readyState}`);
740
+ if (ws.readyState === 1 /* OPEN */) {
741
+ ws.send(JSON.stringify(msg));
742
+ } else {
743
+ dbgWarn(`sendTo(${msg.type}) — ws not OPEN (readyState: ${ws.readyState}), dropping`);
744
+ }
745
+ }
746
+
747
+ private logError = (err: unknown): void => {
748
+ dbgErr('logError:', err instanceof Error ? err.stack || err.message : err);
749
+ };
750
+
751
+ private async teardownCDP(): Promise<void> {
752
+ dbg('teardownCDP() — isScreencasting:', this.isScreencasting, '| hasFrameHandler:', !!this.frameHandler, '| hasNavHandler:', !!this.navigationHandler, '| hasPageNavHandler:', !!this.pageNavigationHandler, '| hasCdpSession:', !!this.cdpSession);
753
+
754
+ if (this.isScreencasting) {
755
+ await this.stopScreencast();
756
+ }
757
+
758
+ // Clean up CDP-level handlers
759
+ if (this.cdpSession) {
760
+ const rawSession = this.cdpSession as unknown as {
761
+ off?: (event: string, handler: (...args: unknown[]) => void) => void;
762
+ };
763
+ if (typeof rawSession.off === 'function') {
764
+ if (this.frameHandler) {
765
+ dbg('teardownCDP() — removing Page.screencastFrame handler');
766
+ rawSession.off('Page.screencastFrame', this.frameHandler);
767
+ }
768
+ if (this.navigationHandler) {
769
+ dbg('teardownCDP() — removing Page.frameNavigated handler');
770
+ rawSession.off('Page.frameNavigated', this.navigationHandler);
771
+ }
772
+ }
773
+ }
774
+ this.frameHandler = null;
775
+ this.navigationHandler = null;
776
+
777
+ // Clean up page-level navigation handler
778
+ if (this.pageNavigationHandler && this.page && typeof (this.page as any).off === 'function') {
779
+ dbg('teardownCDP() — removing page-level framenavigated handler');
780
+ (this.page as any).off('framenavigated', this.pageNavigationHandler);
781
+ }
782
+ this.pageNavigationHandler = null;
783
+
784
+ dbg('teardownCDP() — ✅ complete');
785
+ }
786
+
787
+ async destroy(): Promise<void> {
788
+ dbg('destroy() called, clients:', this.clients.size);
789
+ this.destroyed = true;
790
+ await this.executeInLock(() => this.teardownCDP());
791
+
792
+ // Close all client connections
793
+ for (const ws of this.clients) {
794
+ ws.close(1001, 'Server shutting down');
795
+ }
796
+ this.clients.clear();
797
+ this.page = null;
798
+ this.cdpSession = null;
799
+ dbg('destroy() — ✅ complete');
800
+ }
801
+ }
802
+
803
+ // ────── Route Factory ──────
804
+
805
+ /**
806
+ * Creates a Hono route handler for the screencast WebSocket endpoint.
807
+ *
808
+ * @param upgradeWebSocket - The `upgradeWebSocket` helper from a Hono WebSocket adapter
809
+ * (e.g., `@hono/node-ws`, `hono/bun`, `hono/deno`).
810
+ * @param manager - A `ScreencastManager` instance that handles CDP orchestration.
811
+ * @returns A Hono handler function — register it with `app.get('/screencast', handler)`.
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * // Node.js
816
+ * import { createNodeWebSocket } from '@hono/node-ws';
817
+ * const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
818
+ * const manager = new ScreencastManager();
819
+ * app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
820
+ * // After server.listen():
821
+ * injectWebSocket(server);
822
+ *
823
+ * // Bun
824
+ * import { createBunWebSocket } from 'hono/bun';
825
+ * const { upgradeWebSocket, websocket } = createBunWebSocket();
826
+ * const manager = new ScreencastManager();
827
+ * app.get('/screencast', createScreencastRoute(upgradeWebSocket, manager));
828
+ * export default { fetch: app.fetch, websocket };
829
+ * ```
830
+ */
831
+ export function createScreencastRoute(
832
+ upgradeWebSocket: UpgradeWebSocket,
833
+ manager: ScreencastManager,
834
+ ) {
835
+ dbg('createScreencastRoute() — route factory invoked');
836
+
837
+ return upgradeWebSocket((_c) => ({
838
+ onOpen(_evt, ws) {
839
+ dbg('WS:onOpen — new connection, ws.readyState:', ws.readyState);
840
+ manager.addClient(ws);
841
+ },
842
+
843
+ onMessage(evt, ws) {
844
+ manager.handleMessage(ws, evt.data).catch((err) => {
845
+ dbgErr('WS:onMessage — unhandled error:', err);
846
+ });
847
+ },
848
+
849
+ onClose(evt, ws) {
850
+ const closeEvt = evt as { code?: number; reason?: string; wasClean?: boolean };
851
+ dbg('WS:onClose — connection closed | code:', closeEvt.code, '| reason:', closeEvt.reason, '| wasClean:', closeEvt.wasClean, '| ws.readyState:', ws.readyState);
852
+ manager.removeClient(ws);
853
+ },
854
+
855
+ onError(evt, ws) {
856
+ const errEvt = evt as { error?: Error; message?: string };
857
+ dbgErr('WS:onError — connection error | message:', errEvt.message, '| error:', errEvt.error);
858
+ manager.removeClient(ws);
859
+ },
860
+ }));
861
+ }