@open-wa/screencaster 5.0.0-alpha.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/LICENSE.md +67 -0
- package/README.md +19 -0
- package/dist/client.cjs +287 -0
- package/dist/client.d.cts +71 -0
- package/dist/client.d.cts.map +1 -0
- package/dist/client.d.mts +71 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +288 -0
- package/dist/client.mjs.map +1 -0
- package/dist/server.cjs +588 -0
- package/dist/server.d.cts +107 -0
- package/dist/server.d.cts.map +1 -0
- package/dist/server.d.mts +107 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +588 -0
- package/dist/server.mjs.map +1 -0
- package/dist/types.cjs +57 -0
- package/dist/types.d.cts +147 -0
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.mts +147 -0
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +56 -0
- package/dist/types.mjs.map +1 -0
- package/package.json +62 -0
package/dist/client.mjs
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
//#region src/client.ts
|
|
2
|
+
const TAG = "[SC:client]";
|
|
3
|
+
let _frameCount = 0;
|
|
4
|
+
let _lastFrameLogTime = 0;
|
|
5
|
+
let _lastFrameSize = 0;
|
|
6
|
+
function ts() {
|
|
7
|
+
return Date.now().toString();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Check if debug logging is enabled.
|
|
11
|
+
* Support Node.js process.env and browser localStorage.
|
|
12
|
+
*/
|
|
13
|
+
function isDebugEnabled() {
|
|
14
|
+
try {
|
|
15
|
+
if (typeof process !== "undefined" && process.env?.DEBUG_SCREENCAST) return true;
|
|
16
|
+
if (typeof localStorage !== "undefined" && localStorage.getItem("DEBUG_SCREENCAST")) return true;
|
|
17
|
+
} catch {}
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const DEBUG = isDebugEnabled();
|
|
21
|
+
function dbg(...args) {
|
|
22
|
+
if (DEBUG) console.log(ts(), TAG, ...args);
|
|
23
|
+
}
|
|
24
|
+
function dbgWarn(...args) {
|
|
25
|
+
if (DEBUG) console.warn(ts(), TAG, ...args);
|
|
26
|
+
}
|
|
27
|
+
function dbgErr(...args) {
|
|
28
|
+
if (DEBUG) console.error(ts(), TAG, ...args);
|
|
29
|
+
}
|
|
30
|
+
var ScreencastClient = class {
|
|
31
|
+
ws = null;
|
|
32
|
+
_state = "idle";
|
|
33
|
+
listeners = /* @__PURE__ */ new Map();
|
|
34
|
+
reconnectTimer = null;
|
|
35
|
+
destroyed = false;
|
|
36
|
+
url;
|
|
37
|
+
autoStart;
|
|
38
|
+
defaultOptions;
|
|
39
|
+
autoReconnect;
|
|
40
|
+
reconnectDelay;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.url = options.url;
|
|
43
|
+
this.autoStart = options.autoStart ?? false;
|
|
44
|
+
this.defaultOptions = options.defaultOptions;
|
|
45
|
+
this.autoReconnect = options.autoReconnect ?? false;
|
|
46
|
+
this.reconnectDelay = options.reconnectDelay ?? 2e3;
|
|
47
|
+
dbg("constructor() — url:", this.url, "| autoStart:", this.autoStart, "| autoReconnect:", this.autoReconnect, "| reconnectDelay:", this.reconnectDelay);
|
|
48
|
+
if (this.defaultOptions) dbg("constructor() — defaultOptions:", JSON.stringify(this.defaultOptions));
|
|
49
|
+
}
|
|
50
|
+
get state() {
|
|
51
|
+
return this._state;
|
|
52
|
+
}
|
|
53
|
+
setState(s) {
|
|
54
|
+
if (this._state === s) return;
|
|
55
|
+
const prev = this._state;
|
|
56
|
+
this._state = s;
|
|
57
|
+
dbg(`setState() — ${prev} → ${s}`);
|
|
58
|
+
this.emit("state-change", s);
|
|
59
|
+
}
|
|
60
|
+
connect() {
|
|
61
|
+
dbg("connect() — ws:", !!this.ws, "| destroyed:", this.destroyed);
|
|
62
|
+
if (this.ws || this.destroyed) {
|
|
63
|
+
dbg("connect() — SKIPPING (already connected or destroyed)");
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
this.setState("connecting");
|
|
67
|
+
dbg("connect() — creating WebSocket to:", this.url);
|
|
68
|
+
try {
|
|
69
|
+
this.ws = new WebSocket(this.url);
|
|
70
|
+
} catch (err) {
|
|
71
|
+
dbgErr("connect() — WebSocket constructor threw:", err);
|
|
72
|
+
this.setState("error");
|
|
73
|
+
this.emit("error", `WebSocket constructor failed: ${err}`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
dbg("connect() — WebSocket created, readyState:", this.ws.readyState);
|
|
77
|
+
this.ws.onopen = () => {
|
|
78
|
+
dbg("WS:onopen — connection established! readyState:", this.ws?.readyState);
|
|
79
|
+
this.setState("streaming");
|
|
80
|
+
if (this.autoStart) {
|
|
81
|
+
dbg("WS:onopen — autoStart is true, sending start message");
|
|
82
|
+
this.start(this.defaultOptions);
|
|
83
|
+
} else dbg("WS:onopen — autoStart is false, waiting for manual start()");
|
|
84
|
+
};
|
|
85
|
+
this.ws.onmessage = (event) => {
|
|
86
|
+
this.handleMessage(event.data);
|
|
87
|
+
};
|
|
88
|
+
this.ws.onerror = (evt) => {
|
|
89
|
+
dbgErr("WS:onerror — connection error. Event type:", evt?.type, "| readyState:", this.ws?.readyState);
|
|
90
|
+
this.setState("error");
|
|
91
|
+
this.emit("error", "WebSocket connection failed");
|
|
92
|
+
};
|
|
93
|
+
this.ws.onclose = (evt) => {
|
|
94
|
+
dbg("WS:onclose — code:", evt.code, "| reason:", evt.reason, "| wasClean:", evt.wasClean, "| currentState:", this._state);
|
|
95
|
+
this.ws = null;
|
|
96
|
+
if (this._state !== "error") this.setState("idle");
|
|
97
|
+
if (this.autoReconnect && !this.destroyed) {
|
|
98
|
+
dbg("WS:onclose — scheduling reconnect in", this.reconnectDelay, "ms");
|
|
99
|
+
this.scheduleReconnect();
|
|
100
|
+
} else dbg("WS:onclose — NOT reconnecting. autoReconnect:", this.autoReconnect, "| destroyed:", this.destroyed);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
disconnect() {
|
|
104
|
+
dbg("disconnect() called");
|
|
105
|
+
this.clearReconnectTimer();
|
|
106
|
+
if (this.ws) {
|
|
107
|
+
dbg("disconnect() — closing WebSocket");
|
|
108
|
+
this.ws.close(1e3, "Client disconnect");
|
|
109
|
+
this.ws = null;
|
|
110
|
+
}
|
|
111
|
+
this.setState("idle");
|
|
112
|
+
}
|
|
113
|
+
start(options) {
|
|
114
|
+
dbg("start() — sending start message. options:", options ? JSON.stringify(options) : "none", "| ws.readyState:", this.ws?.readyState);
|
|
115
|
+
this.send({
|
|
116
|
+
type: "start",
|
|
117
|
+
options
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
stop() {
|
|
121
|
+
dbg("stop() — sending stop message");
|
|
122
|
+
this.send({ type: "stop" });
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Send a mouse event. Coordinates are **normalized** (0-1).
|
|
126
|
+
*/
|
|
127
|
+
sendMouse(action, x, y, button) {
|
|
128
|
+
this.send({
|
|
129
|
+
type: "mouse",
|
|
130
|
+
action,
|
|
131
|
+
x,
|
|
132
|
+
y,
|
|
133
|
+
button
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Send a keyboard event.
|
|
138
|
+
* @param modifiers Bitmask: Alt=1, Ctrl=2, Meta=4, Shift=8
|
|
139
|
+
*/
|
|
140
|
+
sendKey(action, key, code, modifiers) {
|
|
141
|
+
dbg("sendKey():", action, key, code, "modifiers:", modifiers);
|
|
142
|
+
this.send({
|
|
143
|
+
type: "key",
|
|
144
|
+
action,
|
|
145
|
+
key,
|
|
146
|
+
code,
|
|
147
|
+
modifiers
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Send a scroll event. Coordinates are **normalized** (0-1).
|
|
152
|
+
*/
|
|
153
|
+
sendScroll(deltaX, deltaY, x, y) {
|
|
154
|
+
this.send({
|
|
155
|
+
type: "scroll",
|
|
156
|
+
deltaX,
|
|
157
|
+
deltaY,
|
|
158
|
+
x,
|
|
159
|
+
y
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
navigate(url) {
|
|
163
|
+
dbg("navigate():", url);
|
|
164
|
+
this.send({
|
|
165
|
+
type: "navigate",
|
|
166
|
+
url
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
goBack() {
|
|
170
|
+
dbg("goBack()");
|
|
171
|
+
this.send({ type: "go-back" });
|
|
172
|
+
}
|
|
173
|
+
goForward() {
|
|
174
|
+
dbg("goForward()");
|
|
175
|
+
this.send({ type: "go-forward" });
|
|
176
|
+
}
|
|
177
|
+
resize(width, height) {
|
|
178
|
+
dbg("resize():", width, "x", height);
|
|
179
|
+
this.send({
|
|
180
|
+
type: "resize",
|
|
181
|
+
width,
|
|
182
|
+
height
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
on(event, cb) {
|
|
186
|
+
if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
187
|
+
this.listeners.get(event).add(cb);
|
|
188
|
+
dbg(`on('${event}') — listener registered, total for event:`, this.listeners.get(event).size);
|
|
189
|
+
return this;
|
|
190
|
+
}
|
|
191
|
+
off(event, cb) {
|
|
192
|
+
this.listeners.get(event)?.delete(cb);
|
|
193
|
+
dbg(`off('${event}') — listener removed`);
|
|
194
|
+
return this;
|
|
195
|
+
}
|
|
196
|
+
destroy() {
|
|
197
|
+
dbg("destroy() called");
|
|
198
|
+
this.destroyed = true;
|
|
199
|
+
this.disconnect();
|
|
200
|
+
this.listeners.clear();
|
|
201
|
+
dbg("destroy() — ✅ complete");
|
|
202
|
+
}
|
|
203
|
+
handleMessage(raw) {
|
|
204
|
+
let msg;
|
|
205
|
+
try {
|
|
206
|
+
msg = JSON.parse(typeof raw === "string" ? raw : String(raw));
|
|
207
|
+
} catch (err) {
|
|
208
|
+
dbgWarn("handleMessage() — failed to parse JSON:", typeof raw === "string" ? raw.slice(0, 100) : typeof raw);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
switch (msg.type) {
|
|
212
|
+
case "frame": {
|
|
213
|
+
_frameCount++;
|
|
214
|
+
const now = Date.now();
|
|
215
|
+
if (_frameCount <= 5 || _frameCount % 30 === 0 || now - _lastFrameLogTime > 5e3) {
|
|
216
|
+
_lastFrameSize = msg.data?.length ?? 0;
|
|
217
|
+
dbg(`📦 FRAME #${_frameCount} | sessionId: ${msg.sessionId} | dataLen: ${_lastFrameSize} | meta: ${msg.metadata?.deviceWidth}x${msg.metadata?.deviceHeight}`);
|
|
218
|
+
_lastFrameLogTime = now;
|
|
219
|
+
}
|
|
220
|
+
const listenerCount = this.listeners.get("frame")?.size ?? 0;
|
|
221
|
+
if (_frameCount <= 3) dbg(` → emitting 'frame' to ${listenerCount} listener(s)`);
|
|
222
|
+
if (listenerCount === 0 && _frameCount <= 3) dbgWarn(" ⚠️ NO frame listeners registered! Frames will be silently dropped.");
|
|
223
|
+
this.emit("frame", msg.data, msg.metadata);
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
case "nav-state":
|
|
227
|
+
dbg("handleMessage(nav-state):", JSON.stringify({
|
|
228
|
+
url: msg.url?.slice(0, 60),
|
|
229
|
+
canGoBack: msg.canGoBack,
|
|
230
|
+
canGoForward: msg.canGoForward
|
|
231
|
+
}));
|
|
232
|
+
this.emit("nav-state", msg);
|
|
233
|
+
break;
|
|
234
|
+
case "error":
|
|
235
|
+
dbgErr("handleMessage(error) — server error:", msg.message);
|
|
236
|
+
this.emit("error", msg.message);
|
|
237
|
+
break;
|
|
238
|
+
case "ready":
|
|
239
|
+
dbg("handleMessage(ready) — bound:", msg.bound);
|
|
240
|
+
this.emit("ready", msg.bound);
|
|
241
|
+
break;
|
|
242
|
+
case "stopped":
|
|
243
|
+
dbg("handleMessage(stopped) — screencast stopped by server");
|
|
244
|
+
break;
|
|
245
|
+
default: dbgWarn("handleMessage() — unknown message type:", msg.type);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
send(msg) {
|
|
249
|
+
const isOpen = this.ws && this.ws.readyState === WebSocket.OPEN;
|
|
250
|
+
if (msg.type !== "mouse" && msg.type !== "ack") dbg(`send(${msg.type}) — ws open: ${isOpen}`);
|
|
251
|
+
if (isOpen) try {
|
|
252
|
+
this.ws.send(JSON.stringify(msg));
|
|
253
|
+
} catch (err) {
|
|
254
|
+
dbgErr(`send(${msg.type}) — failed:`, err);
|
|
255
|
+
}
|
|
256
|
+
else if (msg.type !== "mouse" && msg.type !== "ack") dbgWarn(`send(${msg.type}) — DROPPED, ws not open. readyState: ${this.ws?.readyState ?? "null"}`);
|
|
257
|
+
}
|
|
258
|
+
emit(event, ...args) {
|
|
259
|
+
const set = this.listeners.get(event);
|
|
260
|
+
if (!set) return;
|
|
261
|
+
for (const cb of set) try {
|
|
262
|
+
cb(...args);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
dbgErr(`emit('${event}') — listener threw:`, err);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
scheduleReconnect() {
|
|
268
|
+
this.clearReconnectTimer();
|
|
269
|
+
dbg("scheduleReconnect() — will reconnect in", this.reconnectDelay, "ms");
|
|
270
|
+
this.reconnectTimer = setTimeout(() => {
|
|
271
|
+
if (!this.destroyed) {
|
|
272
|
+
dbg("scheduleReconnect() — timer fired, calling connect()");
|
|
273
|
+
this.connect();
|
|
274
|
+
}
|
|
275
|
+
}, this.reconnectDelay);
|
|
276
|
+
}
|
|
277
|
+
clearReconnectTimer() {
|
|
278
|
+
if (this.reconnectTimer !== null) {
|
|
279
|
+
dbg("clearReconnectTimer() — clearing pending reconnect");
|
|
280
|
+
clearTimeout(this.reconnectTimer);
|
|
281
|
+
this.reconnectTimer = null;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
//#endregion
|
|
286
|
+
export { ScreencastClient };
|
|
287
|
+
|
|
288
|
+
//# sourceMappingURL=client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["// ────────────────────────────────────────────────────────────\n// @open-wa/screencaster/client\n//\n// Framework-agnostic browser-side screencast viewer.\n// Zero Node.js deps — runs in any modern browser.\n//\n// Usage:\n// const client = new ScreencastClient({ url: 'ws://localhost:8080/screencast' });\n// client.on('frame', (data, meta) => drawToCanvas(data, meta));\n// client.connect();\n// ────────────────────────────────────────────────────────────\n\nimport type {\n ScreencastOptions,\n ServerMessage,\n ClientMessage,\n FrameMessage,\n NavStateMessage,\n} from './types';\n\n// Re-export types the consumer will need\nexport type { ScreencastOptions, FrameMessage, NavStateMessage } from './types';\n\n// ────── Debug logger ──────\n\nconst TAG = '[SC:client]';\nlet _frameCount = 0;\nlet _lastFrameLogTime = 0;\nlet _lastFrameSize = 0;\n\nfunction ts(): string {\n return Date.now().toString();\n}\n\n/**\n * Check if debug logging is enabled.\n * Support Node.js process.env and browser localStorage.\n */\nfunction isDebugEnabled(): boolean {\n try {\n // Node.js or bundler-replaced process.env\n if (typeof process !== 'undefined' && process.env?.DEBUG_SCREENCAST) return true;\n // Browser localStorage\n if (typeof localStorage !== 'undefined' && localStorage.getItem('DEBUG_SCREENCAST')) return true;\n } catch {\n // Ignore errors in environments where these aren't accessible\n }\n return false;\n}\n\nconst DEBUG = isDebugEnabled();\n\nfunction dbg(...args: unknown[]): void {\n if (DEBUG) console.log(ts(), TAG, ...args);\n}\n\nfunction dbgWarn(...args: unknown[]): void {\n if (DEBUG) console.warn(ts(), TAG, ...args);\n}\n\nfunction dbgErr(...args: unknown[]): void {\n if (DEBUG) console.error(ts(), TAG, ...args);\n}\n\n// ────── Event types ──────\n\nexport type ScreencastClientState = 'idle' | 'connecting' | 'streaming' | 'error';\n\nexport interface ScreencastClientEvents {\n frame: (data: string, metadata: FrameMessage['metadata']) => void;\n 'nav-state': (state: NavStateMessage) => void;\n error: (message: string) => void;\n 'state-change': (state: ScreencastClientState) => void;\n ready: (bound: boolean) => void;\n}\n\n// ────── ScreencastClient ──────\n\nexport interface ScreencastClientOptions {\n /** Full WebSocket URL, e.g. 'ws://localhost:8080/screencast' */\n url: string;\n /** Auto-send start message on connect? Default: false */\n autoStart?: boolean;\n /** Default screencast options sent with 'start' */\n defaultOptions?: ScreencastOptions;\n /** Auto-reconnect on disconnect? Default: false */\n autoReconnect?: boolean;\n /** Delay between reconnect attempts (ms). Default: 2000 */\n reconnectDelay?: number;\n}\n\ntype EventName = keyof ScreencastClientEvents;\ntype Listener<E extends EventName> = ScreencastClientEvents[E];\n\nexport class ScreencastClient {\n private ws: WebSocket | null = null;\n private _state: ScreencastClientState = 'idle';\n private listeners = new Map<EventName, Set<Listener<EventName>>>();\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n private destroyed = false;\n\n readonly url: string;\n readonly autoStart: boolean;\n readonly defaultOptions: ScreencastOptions | undefined;\n readonly autoReconnect: boolean;\n readonly reconnectDelay: number;\n\n constructor(options: ScreencastClientOptions) {\n this.url = options.url;\n this.autoStart = options.autoStart ?? false;\n this.defaultOptions = options.defaultOptions;\n this.autoReconnect = options.autoReconnect ?? false;\n this.reconnectDelay = options.reconnectDelay ?? 2000;\n dbg('constructor() — url:', this.url, '| autoStart:', this.autoStart, '| autoReconnect:', this.autoReconnect, '| reconnectDelay:', this.reconnectDelay);\n if (this.defaultOptions) {\n dbg('constructor() — defaultOptions:', JSON.stringify(this.defaultOptions));\n }\n }\n\n // ────── State ──────\n\n get state(): ScreencastClientState {\n return this._state;\n }\n\n private setState(s: ScreencastClientState): void {\n if (this._state === s) return;\n const prev = this._state;\n this._state = s;\n dbg(`setState() — ${prev} → ${s}`);\n this.emit('state-change', s);\n }\n\n // ────── Connection ──────\n\n connect(): void {\n dbg('connect() — ws:', !!this.ws, '| destroyed:', this.destroyed);\n if (this.ws || this.destroyed) {\n dbg('connect() — SKIPPING (already connected or destroyed)');\n return;\n }\n\n this.setState('connecting');\n dbg('connect() — creating WebSocket to:', this.url);\n\n try {\n this.ws = new WebSocket(this.url);\n } catch (err) {\n dbgErr('connect() — WebSocket constructor threw:', err);\n this.setState('error');\n this.emit('error', `WebSocket constructor failed: ${err}`);\n return;\n }\n\n dbg('connect() — WebSocket created, readyState:', this.ws.readyState);\n\n this.ws.onopen = () => {\n dbg('WS:onopen — connection established! readyState:', this.ws?.readyState);\n this.setState('streaming');\n if (this.autoStart) {\n dbg('WS:onopen — autoStart is true, sending start message');\n this.start(this.defaultOptions);\n } else {\n dbg('WS:onopen — autoStart is false, waiting for manual start()');\n }\n };\n\n this.ws.onmessage = (event) => {\n this.handleMessage(event.data);\n };\n\n this.ws.onerror = (evt) => {\n dbgErr('WS:onerror — connection error. Event type:', (evt as any)?.type, '| readyState:', this.ws?.readyState);\n this.setState('error');\n this.emit('error', 'WebSocket connection failed');\n };\n\n this.ws.onclose = (evt) => {\n dbg('WS:onclose — code:', evt.code, '| reason:', evt.reason, '| wasClean:', evt.wasClean, '| currentState:', this._state);\n this.ws = null;\n\n if (this._state !== 'error') {\n this.setState('idle');\n }\n\n if (this.autoReconnect && !this.destroyed) {\n dbg('WS:onclose — scheduling reconnect in', this.reconnectDelay, 'ms');\n this.scheduleReconnect();\n } else {\n dbg('WS:onclose — NOT reconnecting. autoReconnect:', this.autoReconnect, '| destroyed:', this.destroyed);\n }\n };\n }\n\n disconnect(): void {\n dbg('disconnect() called');\n this.clearReconnectTimer();\n if (this.ws) {\n dbg('disconnect() — closing WebSocket');\n this.ws.close(1000, 'Client disconnect');\n this.ws = null;\n }\n this.setState('idle');\n }\n\n // ────── Screencast control ──────\n\n start(options?: ScreencastOptions): void {\n dbg('start() — sending start message. options:', options ? JSON.stringify(options) : 'none', '| ws.readyState:', this.ws?.readyState);\n this.send({ type: 'start', options });\n }\n\n stop(): void {\n dbg('stop() — sending stop message');\n this.send({ type: 'stop' });\n }\n\n // ────── Input forwarding ──────\n\n /**\n * Send a mouse event. Coordinates are **normalized** (0-1).\n */\n sendMouse(action: 'move' | 'down' | 'up', x: number, y: number, button?: 'left' | 'right' | 'middle'): void {\n this.send({ type: 'mouse', action, x, y, button });\n }\n\n /**\n * Send a keyboard event.\n * @param modifiers Bitmask: Alt=1, Ctrl=2, Meta=4, Shift=8\n */\n sendKey(action: 'down' | 'up', key: string, code: string, modifiers?: number): void {\n dbg('sendKey():', action, key, code, 'modifiers:', modifiers);\n this.send({ type: 'key', action, key, code, modifiers });\n }\n\n /**\n * Send a scroll event. Coordinates are **normalized** (0-1).\n */\n sendScroll(deltaX: number, deltaY: number, x: number, y: number): void {\n this.send({ type: 'scroll', deltaX, deltaY, x, y });\n }\n\n navigate(url: string): void {\n dbg('navigate():', url);\n this.send({ type: 'navigate', url });\n }\n\n goBack(): void {\n dbg('goBack()');\n this.send({ type: 'go-back' });\n }\n\n goForward(): void {\n dbg('goForward()');\n this.send({ type: 'go-forward' });\n }\n\n resize(width: number, height: number): void {\n dbg('resize():', width, 'x', height);\n this.send({ type: 'resize', width, height });\n }\n\n // ────── Events ──────\n\n on<E extends EventName>(event: E, cb: ScreencastClientEvents[E]): this {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(cb as Listener<EventName>);\n dbg(`on('${event}') — listener registered, total for event:`, this.listeners.get(event)!.size);\n return this;\n }\n\n off<E extends EventName>(event: E, cb: ScreencastClientEvents[E]): this {\n this.listeners.get(event)?.delete(cb as Listener<EventName>);\n dbg(`off('${event}') — listener removed`);\n return this;\n }\n\n // ────── Cleanup ──────\n\n destroy(): void {\n dbg('destroy() called');\n this.destroyed = true;\n this.disconnect();\n this.listeners.clear();\n dbg('destroy() — ✅ complete');\n }\n\n // ────── Internals ──────\n\n private handleMessage(raw: unknown): void {\n let msg: ServerMessage;\n try {\n msg = JSON.parse(typeof raw === 'string' ? raw : String(raw)) as ServerMessage;\n } catch (err) {\n dbgWarn('handleMessage() — failed to parse JSON:', typeof raw === 'string' ? raw.slice(0, 100) : typeof raw);\n return; // Non-JSON data, ignore\n }\n\n switch (msg.type) {\n case 'frame': {\n _frameCount++;\n const now = Date.now();\n\n // Log every frame for the first 5, then every 30th or every 5 seconds\n if (_frameCount <= 5 || _frameCount % 30 === 0 || (now - _lastFrameLogTime) > 5000) {\n _lastFrameSize = msg.data?.length ?? 0;\n dbg(`📦 FRAME #${_frameCount} | sessionId: ${msg.sessionId} | dataLen: ${_lastFrameSize} | meta: ${msg.metadata?.deviceWidth}x${msg.metadata?.deviceHeight}`);\n _lastFrameLogTime = now;\n }\n\n const listenerCount = this.listeners.get('frame')?.size ?? 0;\n if (_frameCount <= 3) {\n dbg(` → emitting 'frame' to ${listenerCount} listener(s)`);\n }\n if (listenerCount === 0 && _frameCount <= 3) {\n dbgWarn(' ⚠️ NO frame listeners registered! Frames will be silently dropped.');\n }\n\n this.emit('frame', msg.data, msg.metadata);\n // ACKs are handled server-side now — no client ack needed\n break;\n }\n\n case 'nav-state':\n dbg('handleMessage(nav-state):', JSON.stringify({ url: msg.url?.slice(0, 60), canGoBack: msg.canGoBack, canGoForward: msg.canGoForward }));\n this.emit('nav-state', msg);\n break;\n\n case 'error':\n dbgErr('handleMessage(error) — server error:', msg.message);\n this.emit('error', msg.message);\n break;\n\n case 'ready':\n dbg('handleMessage(ready) — bound:', msg.bound);\n this.emit('ready', msg.bound);\n break;\n\n case 'stopped':\n dbg('handleMessage(stopped) — screencast stopped by server');\n // screencast was stopped server-side\n break;\n\n default:\n dbgWarn('handleMessage() — unknown message type:', (msg as any).type);\n }\n }\n\n private send(msg: ClientMessage): void {\n const isOpen = this.ws && this.ws.readyState === WebSocket.OPEN;\n\n // Log all sends except high-frequency ones (mouse, ack)\n if (msg.type !== 'mouse' && msg.type !== 'ack') {\n dbg(`send(${msg.type}) — ws open: ${isOpen}`);\n }\n\n if (isOpen) {\n try {\n this.ws!.send(JSON.stringify(msg));\n } catch (err) {\n dbgErr(`send(${msg.type}) — failed:`, err);\n }\n } else {\n if (msg.type !== 'mouse' && msg.type !== 'ack') {\n dbgWarn(`send(${msg.type}) — DROPPED, ws not open. readyState: ${this.ws?.readyState ?? 'null'}`);\n }\n }\n }\n\n private emit<E extends EventName>(event: E, ...args: Parameters<ScreencastClientEvents[E]>): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const cb of set) {\n try {\n (cb as (...a: unknown[]) => void)(...args);\n } catch (err) {\n dbgErr(`emit('${event}') — listener threw:`, err);\n }\n }\n }\n\n private scheduleReconnect(): void {\n this.clearReconnectTimer();\n dbg('scheduleReconnect() — will reconnect in', this.reconnectDelay, 'ms');\n this.reconnectTimer = setTimeout(() => {\n if (!this.destroyed) {\n dbg('scheduleReconnect() — timer fired, calling connect()');\n this.connect();\n }\n }, this.reconnectDelay);\n }\n\n private clearReconnectTimer(): void {\n if (this.reconnectTimer !== null) {\n dbg('clearReconnectTimer() — clearing pending reconnect');\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n }\n}\n"],"mappings":";AAyBA,MAAM,MAAM;AACZ,IAAI,cAAc;AAClB,IAAI,oBAAoB;AACxB,IAAI,iBAAiB;AAErB,SAAS,KAAa;AAClB,QAAO,KAAK,KAAK,CAAC,UAAU;;;;;;AAOhC,SAAS,iBAA0B;AAC/B,KAAI;AAEA,MAAI,OAAO,YAAY,eAAe,QAAQ,KAAK,iBAAkB,QAAO;AAE5E,MAAI,OAAO,iBAAiB,eAAe,aAAa,QAAQ,mBAAmB,CAAE,QAAO;SACxF;AAGR,QAAO;;AAGX,MAAM,QAAQ,gBAAgB;AAE9B,SAAS,IAAI,GAAG,MAAuB;AACnC,KAAI,MAAO,SAAQ,IAAI,IAAI,EAAE,KAAK,GAAG,KAAK;;AAG9C,SAAS,QAAQ,GAAG,MAAuB;AACvC,KAAI,MAAO,SAAQ,KAAK,IAAI,EAAE,KAAK,GAAG,KAAK;;AAG/C,SAAS,OAAO,GAAG,MAAuB;AACtC,KAAI,MAAO,SAAQ,MAAM,IAAI,EAAE,KAAK,GAAG,KAAK;;AAiChD,IA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