@limrun/ui 0.20.2 → 0.20.3

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.
@@ -0,0 +1,2155 @@
1
+ const je = {
2
+ INJECT_KEYCODE: 0,
3
+ INJECT_TEXT: 1,
4
+ INJECT_TOUCH_EVENT: 2,
5
+ // iOS-specific: send two touch points in one message (Option/Alt+drag pinch)
6
+ INJECT_TWO_FINGER_TOUCH_EVENT: 18,
7
+ INJECT_SCROLL_EVENT: 3,
8
+ BACK_OR_SCREEN_ON: 4,
9
+ EXPAND_NOTIFICATION_PANEL: 5,
10
+ EXPAND_SETTINGS_PANEL: 6,
11
+ COLLAPSE_PANELS: 7,
12
+ GET_CLIPBOARD: 8,
13
+ SET_CLIPBOARD: 9,
14
+ SET_DISPLAY_POWER: 10,
15
+ ROTATE_DEVICE: 11
16
+ }, Ge = {
17
+ ACTION_DOWN: 0,
18
+ ACTION_UP: 1,
19
+ ACTION_MOVE: 2,
20
+ ACTION_CANCEL: 3,
21
+ ACTION_POINTER_DOWN: 5,
22
+ ACTION_POINTER_UP: 6,
23
+ BUTTON_PRIMARY: 1,
24
+ BUTTON_SECONDARY: 2,
25
+ BUTTON_TERTIARY: 4
26
+ }, i = {
27
+ // Actions
28
+ ACTION_DOWN: 0,
29
+ ACTION_UP: 1,
30
+ // Meta state flags (from android.view.KeyEvent)
31
+ META_NONE: 0,
32
+ META_SHIFT_ON: 1,
33
+ META_ALT_ON: 2,
34
+ META_CTRL_ON: 4096,
35
+ // META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON
36
+ META_META_ON: 65536,
37
+ // META_META_LEFT_ON | META_META_RIGHT_ON
38
+ // Keycodes (from android.view.KeyEvent)
39
+ KEYCODE_UNKNOWN: 0,
40
+ KEYCODE_SOFT_LEFT: 1,
41
+ KEYCODE_SOFT_RIGHT: 2,
42
+ KEYCODE_HOME: 3,
43
+ KEYCODE_BACK: 4,
44
+ KEYCODE_CALL: 5,
45
+ KEYCODE_ENDCALL: 6,
46
+ KEYCODE_0: 7,
47
+ KEYCODE_1: 8,
48
+ KEYCODE_2: 9,
49
+ KEYCODE_3: 10,
50
+ KEYCODE_4: 11,
51
+ KEYCODE_5: 12,
52
+ KEYCODE_6: 13,
53
+ KEYCODE_7: 14,
54
+ KEYCODE_8: 15,
55
+ KEYCODE_9: 16,
56
+ KEYCODE_STAR: 17,
57
+ KEYCODE_POUND: 18,
58
+ DPAD_UP: 19,
59
+ // KEYCODE_DPAD_UP
60
+ DPAD_DOWN: 20,
61
+ // KEYCODE_DPAD_DOWN
62
+ DPAD_LEFT: 21,
63
+ // KEYCODE_DPAD_LEFT
64
+ DPAD_RIGHT: 22,
65
+ // KEYCODE_DPAD_RIGHT
66
+ KEYCODE_DPAD_CENTER: 23,
67
+ KEYCODE_VOLUME_UP: 24,
68
+ KEYCODE_VOLUME_DOWN: 25,
69
+ KEYCODE_POWER: 26,
70
+ KEYCODE_CAMERA: 27,
71
+ KEYCODE_CLEAR: 28,
72
+ KEYCODE_A: 29,
73
+ KEYCODE_B: 30,
74
+ KEYCODE_C: 31,
75
+ KEYCODE_D: 32,
76
+ KEYCODE_E: 33,
77
+ KEYCODE_F: 34,
78
+ KEYCODE_G: 35,
79
+ KEYCODE_H: 36,
80
+ KEYCODE_I: 37,
81
+ KEYCODE_J: 38,
82
+ KEYCODE_K: 39,
83
+ KEYCODE_L: 40,
84
+ KEYCODE_M: 41,
85
+ KEYCODE_N: 42,
86
+ KEYCODE_O: 43,
87
+ KEYCODE_P: 44,
88
+ KEYCODE_Q: 45,
89
+ KEYCODE_R: 46,
90
+ KEYCODE_S: 47,
91
+ KEYCODE_T: 48,
92
+ KEYCODE_U: 49,
93
+ KEYCODE_V: 50,
94
+ KEYCODE_W: 51,
95
+ KEYCODE_X: 52,
96
+ KEYCODE_Y: 53,
97
+ KEYCODE_Z: 54,
98
+ KEYCODE_COMMA: 55,
99
+ KEYCODE_PERIOD: 56,
100
+ KEYCODE_ALT_LEFT: 57,
101
+ KEYCODE_ALT_RIGHT: 58,
102
+ KEYCODE_SHIFT_LEFT: 59,
103
+ KEYCODE_SHIFT_RIGHT: 60,
104
+ KEYCODE_TAB: 61,
105
+ KEYCODE_SPACE: 62,
106
+ KEYCODE_SYM: 63,
107
+ KEYCODE_EXPLORER: 64,
108
+ KEYCODE_ENVELOPE: 65,
109
+ ENTER: 66,
110
+ // KEYCODE_ENTER
111
+ DEL: 67,
112
+ // KEYCODE_DEL (Backspace)
113
+ KEYCODE_GRAVE: 68,
114
+ // `
115
+ KEYCODE_MINUS: 69,
116
+ // -
117
+ KEYCODE_EQUALS: 70,
118
+ // =
119
+ KEYCODE_LEFT_BRACKET: 71,
120
+ // [
121
+ KEYCODE_RIGHT_BRACKET: 72,
122
+ // ]
123
+ KEYCODE_BACKSLASH: 73,
124
+ // \
125
+ KEYCODE_SEMICOLON: 74,
126
+ // ;
127
+ KEYCODE_APOSTROPHE: 75,
128
+ // '
129
+ KEYCODE_SLASH: 76,
130
+ // /
131
+ KEYCODE_AT: 77,
132
+ // @
133
+ KEYCODE_NUM: 78,
134
+ KEYCODE_HEADSETHOOK: 79,
135
+ KEYCODE_FOCUS: 80,
136
+ KEYCODE_PLUS: 81,
137
+ MENU: 82,
138
+ // KEYCODE_MENU
139
+ KEYCODE_NOTIFICATION: 83,
140
+ KEYCODE_SEARCH: 84,
141
+ KEYCODE_MEDIA_PLAY_PAUSE: 85,
142
+ KEYCODE_MEDIA_STOP: 86,
143
+ KEYCODE_MEDIA_NEXT: 87,
144
+ KEYCODE_MEDIA_PREVIOUS: 88,
145
+ KEYCODE_MEDIA_REWIND: 89,
146
+ KEYCODE_MEDIA_FAST_FORWARD: 90,
147
+ KEYCODE_MUTE: 91,
148
+ KEYCODE_PAGE_UP: 92,
149
+ KEYCODE_PAGE_DOWN: 93,
150
+ KEYCODE_PICTSYMBOLS: 94,
151
+ KEYCODE_SWITCH_CHARSET: 95,
152
+ KEYCODE_BUTTON_A: 96,
153
+ KEYCODE_BUTTON_B: 97,
154
+ KEYCODE_BUTTON_C: 98,
155
+ KEYCODE_BUTTON_X: 99,
156
+ KEYCODE_BUTTON_Y: 100,
157
+ KEYCODE_BUTTON_Z: 101,
158
+ KEYCODE_BUTTON_L1: 102,
159
+ KEYCODE_BUTTON_R1: 103,
160
+ KEYCODE_BUTTON_L2: 104,
161
+ KEYCODE_BUTTON_R2: 105,
162
+ KEYCODE_BUTTON_THUMBL: 106,
163
+ KEYCODE_BUTTON_THUMBR: 107,
164
+ KEYCODE_BUTTON_START: 108,
165
+ KEYCODE_BUTTON_SELECT: 109,
166
+ KEYCODE_BUTTON_MODE: 110,
167
+ KEYCODE_ESCAPE: 111,
168
+ FORWARD_DEL: 112,
169
+ // KEYCODE_FORWARD_DEL (Delete key)
170
+ KEYCODE_CTRL_LEFT: 113,
171
+ KEYCODE_CTRL_RIGHT: 114,
172
+ KEYCODE_CAPS_LOCK: 115,
173
+ KEYCODE_SCROLL_LOCK: 116,
174
+ KEYCODE_META_LEFT: 117,
175
+ KEYCODE_META_RIGHT: 118,
176
+ KEYCODE_FUNCTION: 119,
177
+ KEYCODE_SYSRQ: 120,
178
+ KEYCODE_BREAK: 121,
179
+ KEYCODE_MOVE_HOME: 122,
180
+ KEYCODE_MOVE_END: 123,
181
+ KEYCODE_INSERT: 124,
182
+ KEYCODE_FORWARD: 125,
183
+ KEYCODE_MEDIA_PLAY: 126,
184
+ KEYCODE_MEDIA_PAUSE: 127,
185
+ KEYCODE_MEDIA_CLOSE: 128,
186
+ KEYCODE_MEDIA_EJECT: 129,
187
+ KEYCODE_MEDIA_RECORD: 130,
188
+ KEYCODE_F1: 131,
189
+ KEYCODE_F2: 132,
190
+ KEYCODE_F3: 133,
191
+ KEYCODE_F4: 134,
192
+ KEYCODE_F5: 135,
193
+ KEYCODE_F6: 136,
194
+ KEYCODE_F7: 137,
195
+ KEYCODE_F8: 138,
196
+ KEYCODE_F9: 139,
197
+ KEYCODE_F10: 140,
198
+ KEYCODE_F11: 141,
199
+ KEYCODE_F12: 142,
200
+ KEYCODE_NUM_LOCK: 143,
201
+ KEYCODE_NUMPAD_0: 144,
202
+ KEYCODE_NUMPAD_1: 145,
203
+ KEYCODE_NUMPAD_2: 146,
204
+ KEYCODE_NUMPAD_3: 147,
205
+ KEYCODE_NUMPAD_4: 148,
206
+ KEYCODE_NUMPAD_5: 149,
207
+ KEYCODE_NUMPAD_6: 150,
208
+ KEYCODE_NUMPAD_7: 151,
209
+ KEYCODE_NUMPAD_8: 152,
210
+ KEYCODE_NUMPAD_9: 153,
211
+ KEYCODE_NUMPAD_DIVIDE: 154,
212
+ KEYCODE_NUMPAD_MULTIPLY: 155,
213
+ KEYCODE_NUMPAD_SUBTRACT: 156,
214
+ KEYCODE_NUMPAD_ADD: 157,
215
+ KEYCODE_NUMPAD_DOT: 158,
216
+ KEYCODE_NUMPAD_COMMA: 159,
217
+ KEYCODE_NUMPAD_ENTER: 160,
218
+ KEYCODE_NUMPAD_EQUALS: 161,
219
+ KEYCODE_NUMPAD_LEFT_PAREN: 162,
220
+ KEYCODE_NUMPAD_RIGHT_PAREN: 163,
221
+ KEYCODE_VOLUME_MUTE: 164,
222
+ KEYCODE_INFO: 165,
223
+ KEYCODE_CHANNEL_UP: 166,
224
+ KEYCODE_CHANNEL_DOWN: 167,
225
+ KEYCODE_ZOOM_IN: 168,
226
+ KEYCODE_ZOOM_OUT: 169,
227
+ KEYCODE_TV: 170,
228
+ KEYCODE_WINDOW: 171,
229
+ KEYCODE_GUIDE: 172,
230
+ KEYCODE_DVR: 173,
231
+ KEYCODE_BOOKMARK: 174,
232
+ KEYCODE_CAPTIONS: 175,
233
+ KEYCODE_SETTINGS: 176,
234
+ KEYCODE_TV_POWER: 177,
235
+ KEYCODE_TV_INPUT: 178,
236
+ KEYCODE_STB_POWER: 179,
237
+ KEYCODE_STB_INPUT: 180,
238
+ KEYCODE_AVR_POWER: 181,
239
+ KEYCODE_AVR_INPUT: 182,
240
+ KEYCODE_PROG_RED: 183,
241
+ KEYCODE_PROG_GREEN: 184,
242
+ KEYCODE_PROG_YELLOW: 185,
243
+ KEYCODE_PROG_BLUE: 186,
244
+ KEYCODE_APP_SWITCH: 187,
245
+ KEYCODE_LANGUAGE_SWITCH: 204,
246
+ KEYCODE_ASSIST: 219,
247
+ KEYCODE_BRIGHTNESS_DOWN: 220,
248
+ KEYCODE_BRIGHTNESS_UP: 221,
249
+ KEYCODE_SLEEP: 223,
250
+ KEYCODE_WAKEUP: 224,
251
+ KEYCODE_SOFT_SLEEP: 276
252
+ }, $t = {
253
+ KeyA: i.KEYCODE_A,
254
+ KeyB: i.KEYCODE_B,
255
+ KeyC: i.KEYCODE_C,
256
+ KeyD: i.KEYCODE_D,
257
+ KeyE: i.KEYCODE_E,
258
+ KeyF: i.KEYCODE_F,
259
+ KeyG: i.KEYCODE_G,
260
+ KeyH: i.KEYCODE_H,
261
+ KeyI: i.KEYCODE_I,
262
+ KeyJ: i.KEYCODE_J,
263
+ KeyK: i.KEYCODE_K,
264
+ KeyL: i.KEYCODE_L,
265
+ KeyM: i.KEYCODE_M,
266
+ KeyN: i.KEYCODE_N,
267
+ KeyO: i.KEYCODE_O,
268
+ KeyP: i.KEYCODE_P,
269
+ KeyQ: i.KEYCODE_Q,
270
+ KeyR: i.KEYCODE_R,
271
+ KeyS: i.KEYCODE_S,
272
+ KeyT: i.KEYCODE_T,
273
+ KeyU: i.KEYCODE_U,
274
+ KeyV: i.KEYCODE_V,
275
+ KeyW: i.KEYCODE_W,
276
+ KeyX: i.KEYCODE_X,
277
+ KeyY: i.KEYCODE_Y,
278
+ KeyZ: i.KEYCODE_Z,
279
+ Digit0: i.KEYCODE_0,
280
+ Digit1: i.KEYCODE_1,
281
+ Digit2: i.KEYCODE_2,
282
+ Digit3: i.KEYCODE_3,
283
+ Digit4: i.KEYCODE_4,
284
+ Digit5: i.KEYCODE_5,
285
+ Digit6: i.KEYCODE_6,
286
+ Digit7: i.KEYCODE_7,
287
+ Digit8: i.KEYCODE_8,
288
+ Digit9: i.KEYCODE_9,
289
+ Backquote: i.KEYCODE_GRAVE,
290
+ Minus: i.KEYCODE_MINUS,
291
+ Equal: i.KEYCODE_EQUALS,
292
+ BracketLeft: i.KEYCODE_LEFT_BRACKET,
293
+ BracketRight: i.KEYCODE_RIGHT_BRACKET,
294
+ Backslash: i.KEYCODE_BACKSLASH,
295
+ Semicolon: i.KEYCODE_SEMICOLON,
296
+ Quote: i.KEYCODE_APOSTROPHE,
297
+ Comma: i.KEYCODE_COMMA,
298
+ Period: i.KEYCODE_PERIOD,
299
+ Slash: i.KEYCODE_SLASH,
300
+ Space: i.KEYCODE_SPACE,
301
+ Tab: i.KEYCODE_TAB,
302
+ Escape: i.KEYCODE_ESCAPE,
303
+ ArrowUp: i.DPAD_UP,
304
+ ArrowDown: i.DPAD_DOWN,
305
+ ArrowLeft: i.DPAD_LEFT,
306
+ ArrowRight: i.DPAD_RIGHT,
307
+ Enter: i.ENTER,
308
+ Backspace: i.DEL,
309
+ Delete: i.FORWARD_DEL,
310
+ Home: i.KEYCODE_MOVE_HOME,
311
+ End: i.KEYCODE_MOVE_END,
312
+ PageUp: i.KEYCODE_PAGE_UP,
313
+ PageDown: i.KEYCODE_PAGE_DOWN,
314
+ Insert: i.KEYCODE_INSERT,
315
+ F1: i.KEYCODE_F1,
316
+ F2: i.KEYCODE_F2,
317
+ F3: i.KEYCODE_F3,
318
+ F4: i.KEYCODE_F4,
319
+ F5: i.KEYCODE_F5,
320
+ F6: i.KEYCODE_F6,
321
+ F7: i.KEYCODE_F7,
322
+ F8: i.KEYCODE_F8,
323
+ F9: i.KEYCODE_F9,
324
+ F10: i.KEYCODE_F10,
325
+ F11: i.KEYCODE_F11,
326
+ F12: i.KEYCODE_F12,
327
+ ShiftLeft: i.KEYCODE_SHIFT_LEFT,
328
+ ShiftRight: i.KEYCODE_SHIFT_RIGHT,
329
+ ControlLeft: i.KEYCODE_CTRL_LEFT,
330
+ ControlRight: i.KEYCODE_CTRL_RIGHT,
331
+ AltLeft: i.KEYCODE_ALT_LEFT,
332
+ AltRight: i.KEYCODE_ALT_RIGHT,
333
+ MetaLeft: i.KEYCODE_META_LEFT,
334
+ MetaRight: i.KEYCODE_META_RIGHT,
335
+ // Windows/Command key
336
+ ContextMenu: i.MENU,
337
+ // Often the Menu key
338
+ // Numpad mappings
339
+ Numpad0: i.KEYCODE_NUMPAD_0,
340
+ Numpad1: i.KEYCODE_NUMPAD_1,
341
+ Numpad2: i.KEYCODE_NUMPAD_2,
342
+ Numpad3: i.KEYCODE_NUMPAD_3,
343
+ Numpad4: i.KEYCODE_NUMPAD_4,
344
+ Numpad5: i.KEYCODE_NUMPAD_5,
345
+ Numpad6: i.KEYCODE_NUMPAD_6,
346
+ Numpad7: i.KEYCODE_NUMPAD_7,
347
+ Numpad8: i.KEYCODE_NUMPAD_8,
348
+ Numpad9: i.KEYCODE_NUMPAD_9,
349
+ NumpadDivide: i.KEYCODE_NUMPAD_DIVIDE,
350
+ NumpadMultiply: i.KEYCODE_NUMPAD_MULTIPLY,
351
+ NumpadSubtract: i.KEYCODE_NUMPAD_SUBTRACT,
352
+ NumpadAdd: i.KEYCODE_NUMPAD_ADD,
353
+ NumpadDecimal: i.KEYCODE_NUMPAD_DOT,
354
+ NumpadComma: i.KEYCODE_NUMPAD_COMMA,
355
+ // Some numpads have comma
356
+ NumpadEnter: i.KEYCODE_NUMPAD_ENTER,
357
+ NumpadEqual: i.KEYCODE_NUMPAD_EQUALS
358
+ };
359
+ function Vt(t, e, n, s, f, l, a = 1, m = 0, O = 0) {
360
+ const h = new ArrayBuffer(32), K = new DataView(h);
361
+ let w = 0;
362
+ K.setUint8(w, je.INJECT_TOUCH_EVENT), w += 1;
363
+ const I = t === Ge.ACTION_POINTER_DOWN ? Ge.ACTION_DOWN : t === Ge.ACTION_POINTER_UP ? Ge.ACTION_UP : t;
364
+ return K.setUint8(w, I), w += 1, K.setBigInt64(w, BigInt(e), !0), w += 8, K.setInt32(w, Math.round(f), !0), w += 4, K.setInt32(w, Math.round(l), !0), w += 4, K.setUint16(w, n, !0), w += 2, K.setUint16(w, s, !0), w += 2, K.setInt16(w, Math.round(a * 65535), !0), w += 2, K.setInt32(w, m, !0), w += 4, K.setInt32(w, O, !0), h;
365
+ }
366
+ function Un(t, e, n, s, f, l, a) {
367
+ const m = new ArrayBuffer(24), O = new DataView(m);
368
+ let h = 0;
369
+ return O.setUint8(h, je.INJECT_TWO_FINGER_TOUCH_EVENT), h += 1, O.setUint8(h, t), h += 1, O.setInt32(h, Math.round(s), !0), h += 4, O.setInt32(h, Math.round(f), !0), h += 4, O.setInt32(h, Math.round(l), !0), h += 4, O.setInt32(h, Math.round(a), !0), h += 4, O.setUint16(h, e, !0), h += 2, O.setUint16(h, n, !0), h += 2, O.setUint16(h, 0, !0), m;
370
+ }
371
+ function Ht(t, e = !0) {
372
+ const s = new TextEncoder().encode(t), f = new ArrayBuffer(14 + s.length), l = new DataView(f);
373
+ let a = 0;
374
+ return l.setUint8(a, je.SET_CLIPBOARD), a += 1, l.setBigInt64(a, BigInt(0), !1), a += 8, l.setUint8(a, e ? 1 : 0), a += 1, l.setUint32(a, s.length, !1), a += 4, new Uint8Array(f, a).set(s), f;
375
+ }
376
+ function rt(t, e, n = 0, s = 0) {
377
+ const f = new ArrayBuffer(14), l = new DataView(f);
378
+ let a = 0;
379
+ return l.setUint8(a, je.INJECT_KEYCODE), a += 1, l.setUint8(a, t), a += 1, l.setInt32(a, e, !0), a += 4, l.setInt32(a, n, !0), a += 4, l.setInt32(a, s, !0), f;
380
+ }
381
+ function Pn(t) {
382
+ return t?.displays.find((e) => e.id === (t.angleDegrees < 90 ? "outer" : "inner"));
383
+ }
384
+ function Gt(t) {
385
+ return t === 2 ? 2 : t === 3 ? 1 : t === 4 ? 3 : 0;
386
+ }
387
+ class Ln {
388
+ constructor(e) {
389
+ this.send = e;
390
+ }
391
+ send;
392
+ screenId;
393
+ turns = 0;
394
+ held;
395
+ get active() {
396
+ return this.held !== void 0;
397
+ }
398
+ setDisplay(e, n = Gt(e?.orientation)) {
399
+ (this.screenId !== e?.screenId || this.turns !== n) && this.release(), this.screenId = e?.screenId, this.turns = n;
400
+ }
401
+ /** Coordinates are normalized; native input already accounts for the viewer's rotation. */
402
+ touch(e, n, s, f = !1) {
403
+ if (this.screenId === void 0) return;
404
+ const l = Jt(n, s, f ? 0 : this.turns);
405
+ e === "begin" && (this.release(), this.held = { screenId: this.screenId, ...l }), this.held && (Object.assign(this.held, l), e === "end" ? this.release() : this.send(e === "begin" ? 0 : 2, this.held.screenId, l.x, l.y));
406
+ }
407
+ /** Call on pointer cancellation, lost capture, disconnect, and viewer disposal. */
408
+ release() {
409
+ if (!this.held) return;
410
+ const { screenId: e, x: n, y: s } = this.held;
411
+ this.held = void 0, this.send(1, e, n, s);
412
+ }
413
+ }
414
+ const Fn = { width: 164.6, height: 117.8, depth: 5.2 };
415
+ function Jt(t, e, n) {
416
+ return t = Math.max(0, Math.min(1, t)), e = Math.max(0, Math.min(1, e)), n === 1 ? { x: e, y: 1 - t } : n === 2 ? { x: 1 - t, y: 1 - e } : n === 3 ? { x: 1 - e, y: t } : { x: t, y: e };
417
+ }
418
+ function jt(t) {
419
+ return Number.isFinite(t) && t >= 0 && t <= 180;
420
+ }
421
+ function Bn(t, e) {
422
+ return { x: Math.max(0, Math.min(1, t)), y: Math.max(0, Math.min(1, 1 - e)) };
423
+ }
424
+ function xn(t, e, n) {
425
+ return e && (t || !n) ? "touch" : t ? "ignore" : "orbit";
426
+ }
427
+ function Xt(t, e, n, s) {
428
+ if (!Number.isInteger(t) || t < 0 || t > 3 || !Number.isInteger(e) || e < 1 || e > 255 || !Number.isFinite(n) || !Number.isFinite(s) || n < 0 || n > 1 || s < 0 || s > 1)
429
+ throw new RangeError("Invalid display touch coordinates");
430
+ const f = new ArrayBuffer(12), l = new DataView(f);
431
+ return l.setUint8(0, 19), l.setUint8(1, t), l.setUint8(2, e), l.setFloat32(4, n, !0), l.setFloat32(8, s, !0), f;
432
+ }
433
+ class Wn {
434
+ constructor(e, n) {
435
+ this.send = e, this.failed = n;
436
+ }
437
+ send;
438
+ failed;
439
+ latest;
440
+ running = !1;
441
+ stopped = !1;
442
+ set(e) {
443
+ this.stopped || !jt(e) || (this.latest = e, this.flush());
444
+ }
445
+ stop() {
446
+ this.stopped = !0, this.latest = void 0;
447
+ }
448
+ async flush() {
449
+ if (!(this.running || this.stopped)) {
450
+ this.running = !0;
451
+ try {
452
+ for (; this.latest !== void 0 && !this.stopped; ) {
453
+ const e = this.latest;
454
+ this.latest = void 0, await this.send(e);
455
+ }
456
+ } catch (e) {
457
+ this.latest = void 0, this.stopped || this.failed(e);
458
+ } finally {
459
+ this.running = !1;
460
+ }
461
+ }
462
+ }
463
+ }
464
+ const qn = {
465
+ side: "Sleep/Wake",
466
+ volumeUp: "Volume Up",
467
+ volumeDown: "Volume Down"
468
+ };
469
+ class $n {
470
+ constructor(e, n) {
471
+ this.send = e, this.failed = n;
472
+ }
473
+ send;
474
+ failed;
475
+ held;
476
+ tail = Promise.resolve();
477
+ timeout;
478
+ press(e) {
479
+ this.held || (this.held = e, this.enqueue(e, !0), this.timeout = setTimeout(() => this.release(), 1e4));
480
+ }
481
+ release() {
482
+ if (!this.held) return;
483
+ clearTimeout(this.timeout);
484
+ const e = this.held;
485
+ this.held = void 0, this.enqueue(e, !1);
486
+ }
487
+ enqueue(e, n) {
488
+ this.tail = this.tail.then(() => this.send(e, n)).catch(this.failed);
489
+ }
490
+ }
491
+ const it = "Accessibility unavailable on this device.", Je = 500, At = (t, e) => Math.abs(t.x - e.x) < 0.5 && Math.abs(t.y - e.y) < 0.5 && Math.abs(t.width - e.width) < 0.5 && Math.abs(t.height - e.height) < 0.5, Qt = (t) => Math.max(0, t.width) * Math.max(0, t.height), zt = (t) => {
492
+ const e = t.find((n) => n.frame && n.frame.width > 0 && n.frame.height > 0);
493
+ return e?.frame ? ((Math.abs(e.frame.x) > 0.5 || Math.abs(e.frame.y) > 0.5) && console.warn(
494
+ `[ax-tree] iOS root frame is not anchored at (0,0): (${e.frame.x},${e.frame.y}). Element positions may be slightly off from the rendered video.`
495
+ ), { x: 0, y: 0, width: e.frame.width, height: e.frame.height }) : { x: 0, y: 0, width: 1, height: 1 };
496
+ }, Zt = (t) => {
497
+ const e = {};
498
+ return typeof t.AXUniqueId == "string" && t.AXUniqueId.length > 0 && (e.AXUniqueId = t.AXUniqueId), typeof t.AXLabel == "string" && t.AXLabel.length > 0 && (e.AXLabel = t.AXLabel), typeof t.type == "string" && t.type.length > 0 && (e.className = t.type), e;
499
+ }, en = (t) => {
500
+ const e = {};
501
+ for (const [n, s] of Object.entries(t))
502
+ n !== "children" && (e[n] = s);
503
+ return e;
504
+ };
505
+ function tn(t) {
506
+ const e = Array.isArray(t) ? t : [t], n = zt(e), s = [], f = (l, a) => {
507
+ if (s.length >= Je) return;
508
+ const m = l.frame;
509
+ if (m && m.width > 0 && m.height > 0 && !At(m, n)) {
510
+ const h = l.role_description || l.role || "", K = (typeof l.AXLabel == "string" ? l.AXLabel : "") || (typeof l.title == "string" ? l.title : "") || "";
511
+ s.push({
512
+ id: typeof l.AXUniqueId == "string" && l.AXUniqueId.length > 0 ? l.AXUniqueId : a,
513
+ path: a,
514
+ label: K,
515
+ value: typeof l.AXValue == "string" ? l.AXValue : "",
516
+ role: h,
517
+ type: typeof l.type == "string" ? l.type : "",
518
+ enabled: l.enabled !== !1,
519
+ focused: l.focused === !0,
520
+ frame: { x: m.x, y: m.y, width: m.width, height: m.height },
521
+ selectors: Zt(l),
522
+ raw: en(l)
523
+ });
524
+ }
525
+ const O = Array.isArray(l.children) ? l.children : [];
526
+ for (let h = 0; h < O.length && s.length < Je; h++)
527
+ f(O[h], `${a}.${h}`);
528
+ };
529
+ for (let l = 0; l < e.length && s.length < Je; l++)
530
+ f(e[l], String(l));
531
+ return {
532
+ platform: "ios",
533
+ screen: { width: n.width, height: n.height },
534
+ elements: s,
535
+ capturedAt: Date.now()
536
+ };
537
+ }
538
+ const nn = (t) => {
539
+ let e = { x: 0, y: 0, width: 1, height: 1 }, n = 0;
540
+ for (const s of t) {
541
+ const f = s.parsedBounds;
542
+ if (!f) continue;
543
+ const l = f.right - f.left, a = f.bottom - f.top, m = Math.max(0, l) * Math.max(0, a);
544
+ m > n && (n = m, e = { x: 0, y: 0, width: l, height: a });
545
+ }
546
+ return e;
547
+ }, rn = (t) => {
548
+ const e = {};
549
+ return typeof t.resourceId == "string" && t.resourceId.length > 0 && (e.resourceId = t.resourceId), typeof t.contentDesc == "string" && t.contentDesc.length > 0 && (e.contentDesc = t.contentDesc), typeof t.text == "string" && t.text.length > 0 && (e.text = t.text), typeof t.className == "string" && t.className.length > 0 && (e.className = t.className), e;
550
+ };
551
+ function on(t) {
552
+ const e = nn(t), n = [];
553
+ for (let s = 0; s < t.length && n.length < Je; s++) {
554
+ const f = t[s], l = f.parsedBounds;
555
+ if (!l) continue;
556
+ const a = Math.max(0, l.right - l.left), m = Math.max(0, l.bottom - l.top);
557
+ if (a <= 0 || m <= 0) continue;
558
+ const O = { x: l.left, y: l.top, width: a, height: m };
559
+ if (At(O, { x: 0, y: 0, width: e.width, height: e.height })) continue;
560
+ const h = f.contentDesc || f.text || "", K = f.className || "";
561
+ n.push({
562
+ id: f.resourceId && f.resourceId.length > 0 ? f.resourceId : f.contentDesc && f.contentDesc.length > 0 ? `cd:${f.contentDesc}` : String(s),
563
+ path: String(s),
564
+ label: h,
565
+ value: typeof f.text == "string" ? f.text : "",
566
+ role: K,
567
+ type: K,
568
+ enabled: f.enabled !== !1,
569
+ focused: f.focused === !0,
570
+ frame: O,
571
+ selectors: rn(f),
572
+ raw: { ...f }
573
+ });
574
+ }
575
+ return {
576
+ platform: "android",
577
+ screen: { width: e.width, height: e.height },
578
+ elements: n,
579
+ capturedAt: Date.now()
580
+ };
581
+ }
582
+ function Vn(t, e) {
583
+ const n = Math.max(0, t.x), s = Math.max(0, t.y), f = Math.min(e.width, t.x + t.width), l = Math.min(e.height, t.y + t.height), a = Math.max(0, f - n), m = Math.max(0, l - s);
584
+ return a > 0 && m > 0 ? { x: n, y: s, width: a, height: m } : null;
585
+ }
586
+ function an(t, e) {
587
+ if (t === e) return !0;
588
+ if (t.id !== e.id || t.path !== e.path || t.label !== e.label || t.value !== e.value || t.role !== e.role || t.type !== e.type || t.enabled !== e.enabled || t.focused !== e.focused) return !1;
589
+ const n = t.frame, s = e.frame;
590
+ return n.x === s.x && n.y === s.y && n.width === s.width && n.height === s.height;
591
+ }
592
+ function sn(t, e) {
593
+ if (t === e) return !0;
594
+ if (!t || !e || t.platform !== e.platform || t.screen.width !== e.screen.width || t.screen.height !== e.screen.height || t.elements.length !== e.elements.length) return !1;
595
+ for (let n = 0; n < t.elements.length; n++)
596
+ if (!an(t.elements[n], e.elements[n])) return !1;
597
+ return !0;
598
+ }
599
+ function Hn(t, e, n) {
600
+ let s = null, f = 1 / 0;
601
+ for (const l of t.elements) {
602
+ const a = l.frame;
603
+ if (e < a.x || n < a.y || e > a.x + a.width || n > a.y + a.height) continue;
604
+ const m = Qt(a);
605
+ m < f && (f = m, s = l);
606
+ }
607
+ return s;
608
+ }
609
+ function Gn(t, e) {
610
+ if (e === "ios") {
611
+ if (t.selectors.AXUniqueId)
612
+ return `client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;
613
+ if (t.selectors.AXLabel) {
614
+ const n = t.selectors.className ? `, type: ${JSON.stringify(t.selectors.className)}` : "";
615
+ return `client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${n} })`;
616
+ }
617
+ return null;
618
+ }
619
+ return t.selectors.resourceId ? `client.tap({ selector: { resourceId: ${JSON.stringify(t.selectors.resourceId)} } })` : t.selectors.contentDesc ? `client.tap({ selector: { contentDesc: ${JSON.stringify(t.selectors.contentDesc)} } })` : t.selectors.text ? `client.tap({ selector: { text: ${JSON.stringify(t.selectors.text)} } })` : null;
620
+ }
621
+ function cn(t) {
622
+ const e = t.role || t.type || "";
623
+ if (!e) return "element";
624
+ let n = e.replace(/^AX/, "");
625
+ return n.includes(".") && (n = n.split(".").pop()), n === "GenericElement" ? "Element" : (n = n.replace(/([a-z])([A-Z])/g, "$1 $2"), n);
626
+ }
627
+ const gt = 80;
628
+ function Jn(t) {
629
+ const e = cn(t), n = t.label || t.value || "";
630
+ if (!n) return e;
631
+ const s = n.length > gt ? n.slice(0, gt).trimEnd() + "…" : n;
632
+ return `${e} · ${s}`;
633
+ }
634
+ const ln = 500, dn = 2e3, Tt = 5e3, un = 8e3, fn = 1200, En = 250, hn = () => `ax-rc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
635
+ class mn {
636
+ platform;
637
+ send;
638
+ onSnapshot;
639
+ onStatusChange;
640
+ baseIntervalMs;
641
+ maxBackoffMs;
642
+ androidElementTreeOptions;
643
+ pending = /* @__PURE__ */ new Map();
644
+ running = !1;
645
+ timer;
646
+ currentInterval;
647
+ lastSnapshot = null;
648
+ // Single-flight: only one outstanding request at a time. Avoids piling
649
+ // identical requests on a slow server.
650
+ inflight = !1;
651
+ // Rate-limit floor for bumpActivity so high-frequency input (drags,
652
+ // typing) doesn't trigger a request storm.
653
+ lastBumpAtMs = 0;
654
+ // Wall-clock timestamp until which we're in "activity boost" mode and
655
+ // schedule fetches at ACTIVITY_BOOST_INTERVAL_MS instead of the normal
656
+ // backed-off interval. Set by bumpActivity().
657
+ boostUntilMs = 0;
658
+ // Coarse-grained current status; deduplicated before emission so
659
+ // identical-to-current transitions are no-ops.
660
+ status = "idle";
661
+ constructor(e) {
662
+ this.platform = e.platform, this.send = e.send, this.onSnapshot = e.onSnapshot, this.onStatusChange = e.onStatusChange, this.baseIntervalMs = e.baseIntervalMs ?? ln, this.maxBackoffMs = e.maxBackoffMs ?? dn, this.androidElementTreeOptions = e.androidElementTreeOptions, this.currentInterval = this.baseIntervalMs;
663
+ }
664
+ start() {
665
+ this.running || (this.running = !0, this.currentInterval = this.baseIntervalMs, this.boostUntilMs = 0, this.setStatus("starting"), this.runOnce());
666
+ }
667
+ stop() {
668
+ this.running && (this.running = !1, this.timer !== void 0 && (window.clearTimeout(this.timer), this.timer = void 0), this.failAllPending("Inspector stopped"), this.lastSnapshot = null, this.setStatus("idle"), this.onSnapshot(null));
669
+ }
670
+ getStatus() {
671
+ return this.status;
672
+ }
673
+ setStatus(e, n) {
674
+ if (this.status !== e && (this.status = e, !!this.onStatusChange))
675
+ try {
676
+ this.onStatusChange(e, n);
677
+ } catch (s) {
678
+ console.error("[AxFetcher] onStatusChange threw:", s);
679
+ }
680
+ }
681
+ // Called after any user-driven action that's likely to change the UI
682
+ // (taps, scrolls, key events, openUrl, app termination, orientation
683
+ // change, etc.). Has two effects:
684
+ //
685
+ // 1. Resets the polling interval to base and triggers an immediate
686
+ // fetch (rate-limited so drags / rapid typing don't request-storm).
687
+ // 2. Enters a brief "boost" window during which scheduleNext() uses a
688
+ // shorter interval (ACTIVITY_BOOST_INTERVAL_MS), so we capture the
689
+ // mid- and post-animation tree without waiting for the next
690
+ // back-off cycle.
691
+ bumpActivity() {
692
+ if (!this.running) return;
693
+ const e = Date.now();
694
+ this.boostUntilMs = e + fn;
695
+ const n = Math.max(150, Math.floor(this.baseIntervalMs / 2));
696
+ if (e - this.lastBumpAtMs < n) {
697
+ this.currentInterval = this.baseIntervalMs;
698
+ return;
699
+ }
700
+ this.lastBumpAtMs = e, this.currentInterval = this.baseIntervalMs, this.timer !== void 0 && (window.clearTimeout(this.timer), this.timer = void 0), this.inflight || this.runOnce();
701
+ }
702
+ // Fire a one-shot fetch independent of the poll loop. Useful for the
703
+ // imperative refresh() ref method customers may call.
704
+ //
705
+ // Goes through the same change-detect path as the regular poll loop —
706
+ // identical-to-last-snapshot responses do NOT re-emit via onSnapshot, so
707
+ // a customer calling refresh() in a tight loop doesn't see a stream of
708
+ // duplicate snapshots. The returned promise still resolves with the
709
+ // (possibly identical) snapshot for the caller's own use.
710
+ async refresh() {
711
+ const e = await this.requestOnce();
712
+ return this.running && this.deliver(e), e;
713
+ }
714
+ // Returns the latest snapshot delivered to onSnapshot. May be stale.
715
+ getLatest() {
716
+ return this.lastSnapshot;
717
+ }
718
+ // Called by RemoteControl's ws.onmessage when it sees a message type we own.
719
+ // Returns true when the message was a response we were waiting for.
720
+ handleMessage(e) {
721
+ if (!e || typeof e.id != "string") return !1;
722
+ const n = e.id;
723
+ if (!this.pending.get(n)) return !1;
724
+ if (this.platform === "ios") {
725
+ if (e.type !== "elementTreeResult") return !1;
726
+ const m = typeof e.error == "string" ? e.error : null;
727
+ if (m)
728
+ return this.settleReject(n, new Error(m)), !0;
729
+ const O = typeof e.json == "string" ? e.json : "";
730
+ try {
731
+ const h = JSON.parse(O), K = tn(h);
732
+ this.settleResolve(n, K);
733
+ } catch (h) {
734
+ this.settleReject(n, h instanceof Error ? h : new Error(String(h)));
735
+ }
736
+ return !0;
737
+ }
738
+ if (e.type !== "getElementTreeResult") return !1;
739
+ const f = e.error;
740
+ if (f && typeof f == "object") {
741
+ const m = typeof f.message == "string" ? f.message : "getElementTree failed";
742
+ return this.settleReject(n, new Error(m)), !0;
743
+ }
744
+ const l = e.payload, a = Array.isArray(l?.nodes) ? l.nodes : [];
745
+ try {
746
+ const m = on(a);
747
+ this.settleResolve(n, m);
748
+ } catch (m) {
749
+ this.settleReject(n, m instanceof Error ? m : new Error(String(m)));
750
+ }
751
+ return !0;
752
+ }
753
+ buildRequest(e) {
754
+ return this.platform === "ios" ? { type: "elementTree", id: e } : { type: "getElementTree", id: e, ...this.androidElementTreeOptions };
755
+ }
756
+ async requestOnce() {
757
+ const e = hn();
758
+ return new Promise((n, s) => {
759
+ const f = window.setTimeout(
760
+ () => {
761
+ this.pending.delete(e), s(new Error("elementTree request timed out"));
762
+ },
763
+ un + (this.androidElementTreeOptions?.waitForIdleTimeoutMs ?? 0)
764
+ );
765
+ this.pending.set(e, { resolve: n, reject: s, timer: f }), this.send(this.buildRequest(e)) || (window.clearTimeout(f), this.pending.delete(e), s(new Error("elementTree send failed (WebSocket not open)")));
766
+ });
767
+ }
768
+ async runOnce() {
769
+ if (this.running && !this.inflight) {
770
+ this.inflight = !0;
771
+ try {
772
+ const e = await this.requestOnce();
773
+ if (!this.running) return;
774
+ this.deliver(e);
775
+ } catch (e) {
776
+ if (!this.running) return;
777
+ const n = e instanceof Error ? e.message : String(e), s = /unavailable|not (yet )?running|failed|timeout/i.test(n);
778
+ this.currentInterval = s ? Tt : Math.min(this.currentInterval * 2, this.maxBackoffMs), this.setStatus(s ? "unavailable" : "error", n);
779
+ } finally {
780
+ this.inflight = !1, this.scheduleNext();
781
+ }
782
+ }
783
+ }
784
+ deliver(e) {
785
+ const n = this.lastSnapshot;
786
+ if (sn(n, e)) {
787
+ this.currentInterval = Math.min(this.currentInterval * 2, this.maxBackoffMs), this.lastSnapshot = e, e.errors?.includes(it) || this.setStatus("ready");
788
+ return;
789
+ }
790
+ this.lastSnapshot = e, this.currentInterval = this.baseIntervalMs, e.errors?.includes(it) ? (this.currentInterval = Tt, this.setStatus("unavailable", it)) : this.setStatus("ready"), this.onSnapshot(e);
791
+ }
792
+ scheduleNext() {
793
+ if (!this.running) return;
794
+ this.timer !== void 0 && window.clearTimeout(this.timer);
795
+ const e = Date.now() < this.boostUntilMs ? Math.min(En, this.currentInterval) : this.currentInterval;
796
+ this.timer = window.setTimeout(() => {
797
+ this.timer = void 0, this.runOnce();
798
+ }, e);
799
+ }
800
+ settleResolve(e, n) {
801
+ const s = this.pending.get(e);
802
+ s && (window.clearTimeout(s.timer), this.pending.delete(e), s.resolve(n));
803
+ }
804
+ settleReject(e, n) {
805
+ const s = this.pending.get(e);
806
+ s && (window.clearTimeout(s.timer), this.pending.delete(e), s.reject(n));
807
+ }
808
+ failAllPending(e) {
809
+ for (const [n, s] of this.pending.entries())
810
+ window.clearTimeout(s.timer), s.reject(new Error(e)), this.pending.delete(n);
811
+ }
812
+ }
813
+ function yt(t, e) {
814
+ if (e != null && (!Number.isFinite(e) || e < 0 || e > 4e3)) {
815
+ console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");
816
+ return;
817
+ }
818
+ if (!("jitterBufferTarget" in t)) return;
819
+ const n = e ?? null;
820
+ try {
821
+ t.jitterBufferTarget !== n && (t.jitterBufferTarget = n);
822
+ } catch (s) {
823
+ console.warn("RemoteControl: could not set the jitter buffer target.", s);
824
+ }
825
+ }
826
+ const Mt = `(function(){"use strict";let e,t;self.onmessage=async({data:s})=>{s.type==="start"?(e=new AbortController,t=s.readable.pipeTo(s.writable,{signal:e.signal}).catch(o=>{e?.signal.aborted||self.postMessage({type:"error",message:String(o)})})):s.type==="stop"&&(e?.abort(),await t,self.postMessage({type:"stopped"}),self.close())}})();
827
+ `, St = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", Mt], { type: "text/javascript;charset=utf-8" });
828
+ function pn(t) {
829
+ let e;
830
+ try {
831
+ if (e = St && (self.URL || self.webkitURL).createObjectURL(St), !e) throw "";
832
+ const n = new Worker(e, {
833
+ name: t?.name
834
+ });
835
+ return n.addEventListener("error", () => {
836
+ (self.URL || self.webkitURL).revokeObjectURL(e);
837
+ }), n;
838
+ } catch {
839
+ return new Worker(
840
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(Mt),
841
+ {
842
+ name: t?.name
843
+ }
844
+ );
845
+ }
846
+ }
847
+ function Cn(t, e, n) {
848
+ const { MediaStreamTrackProcessor: s, MediaStreamTrackGenerator: f } = globalThis, l = e.getVideoTracks()[0];
849
+ let a, m, O, h, K = !1;
850
+ const w = () => {
851
+ K || (K = !0, a?.stop(), m?.stop(), O && (O.postMessage({ type: "stop" }), h = setTimeout(() => O?.terminate(), 1e3)));
852
+ }, I = (D) => {
853
+ t.srcObject = D, t.play().catch(() => {
854
+ });
855
+ }, W = (D) => {
856
+ K || (w(), n(D), I(e));
857
+ };
858
+ try {
859
+ if (l && s && f) {
860
+ a = l.clone();
861
+ const D = new s({ track: a, maxBufferSize: 1 }), V = new f({ kind: "video" });
862
+ m = V, O = new pn(), O.onmessage = ({ data: P }) => {
863
+ P.type === "error" ? W(new Error(P.message)) : P.type === "stopped" && (clearTimeout(h), O?.terminate());
864
+ }, O.onerror = (P) => W(new Error(P.message)), O.postMessage({ type: "start", readable: D.readable, writable: V.writable }, [
865
+ D.readable,
866
+ V.writable
867
+ ]), I(new MediaStream(e.getTracks().map((P) => P === l ? V : P)));
868
+ } else
869
+ I(e);
870
+ } catch (D) {
871
+ W(D);
872
+ }
873
+ return w;
874
+ }
875
+ function Re(t) {
876
+ return typeof t == "number" && Number.isFinite(t);
877
+ }
878
+ function ge(t, e) {
879
+ if (!(!Re(t) || !Re(e) || t < e || e < 0))
880
+ return t - e;
881
+ }
882
+ class On {
883
+ previous = /* @__PURE__ */ new Map();
884
+ reset() {
885
+ this.previous.clear();
886
+ }
887
+ read(e, n, s) {
888
+ const f = { timestamp: 0, video: [], audio: [] };
889
+ s == null ? f.requestedTargetMs = null : Re(s) && s >= 0 && s <= 4e3 && (f.requestedTargetMs = s);
890
+ const l = /* @__PURE__ */ new Map();
891
+ return e.forEach((a) => {
892
+ if (a.type !== "inbound-rtp" || !Re(a.timestamp)) return;
893
+ const m = a.kind ?? a.mediaType;
894
+ if (m !== "video" && m !== "audio") return;
895
+ const O = n.filter((k) => k.kind === m), h = a.trackIdentifier ? O.find((k) => k.trackId === a.trackIdentifier) : a.mid != null ? O.find((k) => k.mid === a.mid) : O.length === 1 ? O[0] : void 0;
896
+ if (!h) return;
897
+ const K = this.previous.get(a.id), I = K?.trackId === h.trackId && K.stats.ssrc === a.ssrc ? K.stats : void 0, W = I ? a.timestamp - I.timestamp : void 0, D = {
898
+ id: a.id,
899
+ trackId: h.trackId,
900
+ timestamp: a.timestamp
901
+ };
902
+ if (W !== void 0 && W > 0) {
903
+ D.intervalMs = W;
904
+ const k = ge(a.jitterBufferEmittedCount, I?.jitterBufferEmittedCount), F = ge(a.jitterBufferDelay, I?.jitterBufferDelay);
905
+ k !== void 0 && k > 0 && F !== void 0 && (D.bufferDelayMs = F / k * 1e3);
906
+ const q = ge(a.bytesReceived, I?.bytesReceived);
907
+ q !== void 0 && (D.bitrateBps = q * 8e3 / W);
908
+ }
909
+ if (m === "video") {
910
+ const k = { ...D, display: h.display ?? "primary" };
911
+ if (D.intervalMs !== void 0) {
912
+ const F = ge(a.framesDecoded, I?.framesDecoded);
913
+ F !== void 0 && (k.fps = F * 1e3 / D.intervalMs), k.droppedFrames = ge(a.framesDropped, I?.framesDropped), k.freezes = ge(a.freezeCount, I?.freezeCount);
914
+ }
915
+ f.video.push(k);
916
+ } else f.audio.push(D);
917
+ f.timestamp = Math.max(f.timestamp, a.timestamp), l.set(
918
+ a.id,
919
+ I && a.timestamp <= I.timestamp ? K : { stats: a, trackId: h.trackId }
920
+ );
921
+ const V = a.transportId ? e.get(a.transportId) : void 0, P = V?.selectedCandidatePairId ? e.get(V.selectedCandidatePairId) : void 0;
922
+ P?.state === "succeeded" && Re(P.currentRoundTripTime) && P.currentRoundTripTime >= 0 && (f.rttMs = P.currentRoundTripTime * 1e3);
923
+ }), this.previous = l, f.video.length || f.audio.length ? f : null;
924
+ }
925
+ }
926
+ const ot = /* @__PURE__ */ new WeakSet();
927
+ function Dn(t, e, n) {
928
+ const { peer: s, displays: f } = t, l = new On();
929
+ let a, m = !1, O = !1, h = !1, K = 0, w = !1, I = !1;
930
+ const W = () => !m && !document.hidden && s.connectionState === "connected", D = (F) => {
931
+ if (!(!F && !w)) {
932
+ w = F !== null;
933
+ try {
934
+ e()?.(F);
935
+ } catch (q) {
936
+ console.error('[RemoteControl] customer callback "onPlaybackStats" threw:', q);
937
+ }
938
+ }
939
+ }, V = () => {
940
+ O = !1, K++, clearTimeout(a), l.reset(), D(null);
941
+ }, P = async () => {
942
+ if (h || !W()) return;
943
+ if (ot.has(s)) {
944
+ a = setTimeout(() => {
945
+ P();
946
+ }, 2e3);
947
+ return;
948
+ }
949
+ h = !0, ot.add(s);
950
+ const F = K;
951
+ try {
952
+ const q = await s.getStats();
953
+ if (F !== K || !W()) return;
954
+ const oe = s.getTransceivers().filter(
955
+ (Y) => (Y.currentDirection === "recvonly" || Y.currentDirection === "sendrecv") && Y.receiver.track.readyState !== "ended"
956
+ ).map((Y) => ({
957
+ trackId: Y.receiver.track.id,
958
+ kind: Y.receiver.track.kind,
959
+ mid: Y.mid,
960
+ display: f.get(Y.receiver)
961
+ }));
962
+ D(l.read(q, oe, n())), I = !1;
963
+ } catch (q) {
964
+ if (F !== K || !W()) return;
965
+ I || console.warn("[RemoteControl] could not read playback stats:", q), I = !0, l.reset(), D(null);
966
+ } finally {
967
+ h = !1, ot.delete(s), O && W() && (a = setTimeout(
968
+ () => {
969
+ P();
970
+ },
971
+ F === K ? 2e3 : 0
972
+ ));
973
+ }
974
+ }, k = () => {
975
+ if (!W()) {
976
+ V();
977
+ return;
978
+ }
979
+ O || (O = !0, P());
980
+ };
981
+ return document.addEventListener("visibilitychange", k), s.addEventListener("connectionstatechange", k), k(), () => {
982
+ m = !0, document.removeEventListener("visibilitychange", k), s.removeEventListener("connectionstatechange", k), V();
983
+ };
984
+ }
985
+ function _n(t, e) {
986
+ const n = t.createDataChannel("latency-trace-v1", {
987
+ ordered: !0,
988
+ negotiated: !0,
989
+ id: 2
990
+ });
991
+ let s = !1, f = !1, l = 0;
992
+ return n.onmessage = (a) => {
993
+ if (f) return;
994
+ let m;
995
+ try {
996
+ m = JSON.parse(a.data);
997
+ } catch (O) {
998
+ console.warn("Invalid latency trace message", O);
999
+ return;
1000
+ }
1001
+ m && typeof m == "object" && !Array.isArray(m) && e(m);
1002
+ }, n.onclose = () => {
1003
+ f = !0, s = !1;
1004
+ }, {
1005
+ accept(a) {
1006
+ s = !f && a === 1;
1007
+ },
1008
+ wrap(a) {
1009
+ if (!s || a.byteLength !== 32) return a;
1010
+ const m = new DataView(a);
1011
+ if (m.getUint8(0) !== 2 || m.getUint8(1) > 2) return a;
1012
+ const O = new ArrayBuffer(38), h = new DataView(O);
1013
+ return h.setUint8(0, 240), h.setUint8(1, 1), h.setUint32(2, ++l, !0), new Uint8Array(O, 6).set(new Uint8Array(a)), O;
1014
+ },
1015
+ close() {
1016
+ f = !0, s = !1, n.onmessage = null, n.onclose = null, n.close();
1017
+ }
1018
+ };
1019
+ }
1020
+ class gn {
1021
+ generation = 0;
1022
+ tail = Promise.resolve();
1023
+ get currentGeneration() {
1024
+ return this.generation;
1025
+ }
1026
+ enqueue(e) {
1027
+ const n = ++this.generation;
1028
+ return this.append(n, e);
1029
+ }
1030
+ /**
1031
+ * Queues related work without superseding an already queued request.
1032
+ *
1033
+ * The operation retains the generation current at enqueue time and becomes
1034
+ * stale if a later camera request increments it before this work starts.
1035
+ */
1036
+ enqueueCurrent(e) {
1037
+ return this.append(this.generation, e);
1038
+ }
1039
+ append(e, n) {
1040
+ const s = {
1041
+ generation: e,
1042
+ isCurrent: () => e === this.generation
1043
+ }, f = this.tail.then(() => n(s));
1044
+ return this.tail = f.catch(() => {
1045
+ }), f;
1046
+ }
1047
+ invalidate() {
1048
+ ++this.generation;
1049
+ }
1050
+ }
1051
+ function Tn(t) {
1052
+ if (!t || typeof t != "object") return null;
1053
+ const e = t;
1054
+ if (e.type !== "cameraRequest" || typeof e.active != "boolean") return null;
1055
+ const n = { active: e.active };
1056
+ return (e.facingMode === "user" || e.facingMode === "environment") && (n.facingMode = e.facingMode), n;
1057
+ }
1058
+ function yn(t) {
1059
+ const e = {
1060
+ frameRate: { ideal: 30, max: 30 }
1061
+ };
1062
+ return t?.facingMode && (e.facingMode = { ideal: t.facingMode }), e;
1063
+ }
1064
+ function Sn(t, e) {
1065
+ return !t || t.facingMode !== e.facingMode;
1066
+ }
1067
+ function vn(t) {
1068
+ const e = t.getSettings();
1069
+ return {
1070
+ width: e.width,
1071
+ height: e.height,
1072
+ frameRate: e.frameRate,
1073
+ deviceId: e.deviceId,
1074
+ label: t.label || void 0,
1075
+ facingMode: e.facingMode
1076
+ };
1077
+ }
1078
+ function Kn(t) {
1079
+ return {
1080
+ type: "cameraResult",
1081
+ granted: !0,
1082
+ camera: vn(t)
1083
+ };
1084
+ }
1085
+ const ce = (...t) => {
1086
+ window.debugRemoteControl && console.log(...t);
1087
+ }, y = (...t) => {
1088
+ window.debugRemoteControl && console.warn(...t);
1089
+ }, L = (t, e, ...n) => {
1090
+ if (e)
1091
+ try {
1092
+ e(...n);
1093
+ } catch (s) {
1094
+ console.error(`[RemoteControl] customer callback "${t}" threw:`, s);
1095
+ }
1096
+ }, An = (t) => t.includes("/android_") ? "android" : "ios", vt = (t, e) => {
1097
+ const n = new URL(t);
1098
+ return n.searchParams.set("token", e), n.toString();
1099
+ }, at = 3, Mn = 1e3, wn = 15e3, Yn = 3e3, bn = 4e3;
1100
+ function Kt() {
1101
+ const t = crypto.getRandomValues(new Uint8Array(16));
1102
+ t[6] = t[6] & 15 | 64, t[8] = t[8] & 63 | 128;
1103
+ const e = Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("");
1104
+ return `${e.slice(0, 8)}-${e.slice(8, 12)}-${e.slice(12, 16)}-${e.slice(16, 20)}-${e.slice(20)}`;
1105
+ }
1106
+ function jn(t) {
1107
+ let e = { ...t };
1108
+ const { url: n, token: s, deviceModel: f } = e, l = e.watchOnly ?? !1, a = e.sessionId ?? Kt(), m = e.platform ?? An(n ?? "");
1109
+ let O = {
1110
+ connection: "idle",
1111
+ videoReady: !1,
1112
+ controlReady: !1,
1113
+ duo: !1,
1114
+ duoState: null
1115
+ };
1116
+ const h = (r) => {
1117
+ O = { ...O, ...r }, L("onStateChange", e.onStateChange, O);
1118
+ }, K = (r) => h({ videoReady: r }), w = (r) => h({ duoState: r }), I = (r) => h({ duoError: r }), W = (r) => h({ duo: r }), D = (r) => ce(r);
1119
+ let V = null, P;
1120
+ const k = () => {
1121
+ P?.(), P = V && e.onPlaybackStats ? Dn(
1122
+ V,
1123
+ () => e.onPlaybackStats,
1124
+ () => e.jitterBufferTargetMs
1125
+ ) : void 0;
1126
+ }, F = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Set(), oe = /* @__PURE__ */ new Set(), Y = /* @__PURE__ */ new Map();
1127
+ let Te = !1;
1128
+ const Ie = /* @__PURE__ */ new Map(), st = (r, u, c) => {
1129
+ u.stop?.(), u.stop = Cn(r, c, (d) => y("Video playback fallback:", d));
1130
+ }, wt = () => {
1131
+ Ie.clear();
1132
+ for (const [r, u] of F)
1133
+ u.clear?.(), u.stop?.(), u.stop = void 0, r.srcObject = null;
1134
+ };
1135
+ let fe = !1, ye = !1, ke = 0, g = null, b = null, B = null, Ue = null, Ee, Se, ve, Pe, he, le = 0, Le = 0, te = !1, de = null, Q = null, ue;
1136
+ const Xe = new gn();
1137
+ let Ke = null, Fe = null, Qe = !l && (e.microphoneEnabled ?? !1), ze = !1, Ae = null, ee = null, Be = 0, ct = Promise.resolve(), me = null, Me = !1, ne = /* @__PURE__ */ new Map(), Z = /* @__PURE__ */ new Map(), ae = /* @__PURE__ */ new Map(), re = /* @__PURE__ */ new Map(), $ = null, we = null, lt = 0;
1138
+ const xe = (r) => {
1139
+ if (r === null && we === null) return;
1140
+ we = r;
1141
+ const u = ++lt;
1142
+ queueMicrotask(() => {
1143
+ u === lt && L("onAxSnapshotChange", e.onAxSnapshotChange, r);
1144
+ });
1145
+ };
1146
+ let pe = null, Ce = /* @__PURE__ */ new Map();
1147
+ const Yt = (r, u) => new Promise((c, d) => {
1148
+ if (l) {
1149
+ d(new Error("Device is watch-only"));
1150
+ return;
1151
+ }
1152
+ const S = g;
1153
+ if (!S || S.readyState !== WebSocket.OPEN) {
1154
+ d(new Error("Simulator disconnected"));
1155
+ return;
1156
+ }
1157
+ const p = Kt(), C = setTimeout(() => {
1158
+ Ce.delete(p), d(new Error("Device control timed out"));
1159
+ }, 5e3);
1160
+ Ce.set(p, { resolve: c, reject: d, timer: C }), S.send(JSON.stringify({ type: r, id: p, ...u }));
1161
+ }), Oe = (r) => {
1162
+ pe !== r && (pe = r, h({ connection: r }), L("onConnectionStateChange", e.onConnectionStateChange, r));
1163
+ }, se = (r) => {
1164
+ l || !B || B.readyState !== "open" || (B.send(Ue?.wrap(r) ?? r), $?.bumpActivity());
1165
+ }, bt = () => {
1166
+ g && g.readyState === WebSocket.OPEN && g.send(
1167
+ JSON.stringify({
1168
+ type: "keepAlive",
1169
+ sessionId: a
1170
+ })
1171
+ );
1172
+ }, dt = () => {
1173
+ Ee && window.clearInterval(Ee), Ee = window.setInterval(bt, 1e4);
1174
+ }, Ye = () => {
1175
+ Ee && (window.clearInterval(Ee), Ee = void 0);
1176
+ }, We = () => {
1177
+ Se && (window.clearTimeout(Se), Se = void 0);
1178
+ }, qe = () => {
1179
+ ve && (window.clearTimeout(ve), ve = void 0);
1180
+ }, be = () => {
1181
+ Pe && (window.clearInterval(Pe), Pe = void 0);
1182
+ }, Ne = () => {
1183
+ he !== void 0 && (window.clearTimeout(he), he = void 0);
1184
+ }, Nt = () => {
1185
+ Me || (Me = !0, be(), K(!0), Oe("connected"));
1186
+ }, H = (r) => {
1187
+ for (const u of r.getTracks())
1188
+ try {
1189
+ u.stop();
1190
+ } catch (c) {
1191
+ y("track.stop() failed:", c);
1192
+ }
1193
+ }, Rt = () => {
1194
+ const r = Q;
1195
+ r && (Q = null, H(r));
1196
+ }, ut = (r) => {
1197
+ const u = ct.then(r).catch((c) => {
1198
+ y("microphone operation failed:", c);
1199
+ });
1200
+ return ct = u, u;
1201
+ }, Ze = () => Qe || ze, ft = (r) => {
1202
+ const u = `ui-mic-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1203
+ me = u, r.send(JSON.stringify({ type: "microphoneStart", id: u }));
1204
+ }, et = () => ut(() => It()), It = async () => {
1205
+ const r = Be, u = () => r === Be && Ze(), c = (E) => {
1206
+ L("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1207
+ active: !1,
1208
+ error: E
1209
+ });
1210
+ };
1211
+ if (!u()) return;
1212
+ const d = g, S = Ae;
1213
+ if (!d || d.readyState !== WebSocket.OPEN || !S || ee) return;
1214
+ if (!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia != "function") {
1215
+ console.warn(
1216
+ "[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."
1217
+ ), c("Microphone capture requires a secure context (https)");
1218
+ return;
1219
+ }
1220
+ let p = null;
1221
+ try {
1222
+ p = await navigator.mediaDevices.getUserMedia({ audio: !0, video: !1 });
1223
+ } catch (E) {
1224
+ console.warn("[RemoteControl] microphone getUserMedia denied/failed:", E);
1225
+ }
1226
+ if (!u()) {
1227
+ p && H(p);
1228
+ return;
1229
+ }
1230
+ if (!p) {
1231
+ c("Microphone permission denied or no device available");
1232
+ return;
1233
+ }
1234
+ const C = p.getAudioTracks()[0] ?? null;
1235
+ if (!C) {
1236
+ H(p), c("Captured stream has no audio track");
1237
+ return;
1238
+ }
1239
+ try {
1240
+ await S.replaceTrack(C);
1241
+ } catch (E) {
1242
+ y("replaceTrack(audioTrack) failed:", E), H(p), c("Failed to attach the microphone track to the connection");
1243
+ return;
1244
+ }
1245
+ if (!u()) {
1246
+ try {
1247
+ await S.replaceTrack(null);
1248
+ } catch (E) {
1249
+ y("replaceTrack(null) on stale mic attach failed:", E);
1250
+ }
1251
+ H(p);
1252
+ return;
1253
+ }
1254
+ ee = p, C.onended = () => {
1255
+ ee === p && $e("microphone capture ended by the browser");
1256
+ }, ft(d), L("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1257
+ active: !0,
1258
+ label: C.label || void 0
1259
+ });
1260
+ }, $e = (r) => (++Be, me = null, ut(async () => {
1261
+ const u = Ae, c = ee;
1262
+ if (ee = null, u && c)
1263
+ try {
1264
+ await u.replaceTrack(null);
1265
+ } catch (S) {
1266
+ y("replaceTrack(null) on mic detach failed:", S);
1267
+ }
1268
+ c && H(c);
1269
+ const d = g;
1270
+ if (c && d && d.readyState === WebSocket.OPEN) {
1271
+ const S = `ui-mic-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1272
+ d.send(JSON.stringify({ type: "microphoneStop", id: S }));
1273
+ }
1274
+ (c || r) && L("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1275
+ active: !1,
1276
+ ...r !== void 0 && { error: r }
1277
+ });
1278
+ })), Et = (r, u) => {
1279
+ let c;
1280
+ try {
1281
+ c = Kn(u), console.info(
1282
+ `[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate ?? "?"}fps` + (c.camera?.label ? ` — ${c.camera.label}` : "")
1283
+ );
1284
+ } catch (d) {
1285
+ y("getSettings() on outbound camera track failed:", d), c = {
1286
+ type: "cameraResult",
1287
+ granted: !0,
1288
+ camera: {
1289
+ label: u.label || void 0
1290
+ }
1291
+ };
1292
+ }
1293
+ r.send(JSON.stringify(c)), L("onCameraDemandChange", e.onCameraDemandChange, !0, !0, c.camera);
1294
+ }, kt = (r) => {
1295
+ if (!r) return;
1296
+ const u = r.indexOf("/"), d = (u >= 0 ? r.slice(u + 1) : r).toUpperCase();
1297
+ return d === "HEVC" ? "H265" : d;
1298
+ }, Ut = async () => {
1299
+ const r = de, u = e.onCameraStats;
1300
+ if (!r || !u) return;
1301
+ let c;
1302
+ try {
1303
+ c = await r.getStats();
1304
+ } catch {
1305
+ return;
1306
+ }
1307
+ let d, S, p;
1308
+ if (c.forEach((N) => {
1309
+ N.type === "outbound-rtp" && N.kind === "video" ? d = N : N.type === "remote-inbound-rtp" && N.kind === "video" && (p = N);
1310
+ }), d?.codecId) {
1311
+ const N = c.get(d.codecId);
1312
+ N && (S = N.mimeType);
1313
+ }
1314
+ if (!d) return;
1315
+ const C = d.timestamp ?? Date.now(), E = Fe;
1316
+ let J, U, j;
1317
+ if (E && C > E.timestamp) {
1318
+ const N = (C - E.timestamp) / 1e3;
1319
+ if (typeof d.framesEncoded == "number" && typeof E.framesEncoded == "number" && (J = Math.max(0, (d.framesEncoded - E.framesEncoded) / N)), typeof d.bytesSent == "number" && typeof E.bytesSent == "number" && (U = Math.max(0, (d.bytesSent - E.bytesSent) * 8 / N)), typeof d.packetsSent == "number" && typeof E.packetsSent == "number" && p && typeof p.packetsLost == "number" && typeof E.packetsLost == "number") {
1320
+ const v = d.packetsSent - E.packetsSent, He = p.packetsLost - E.packetsLost;
1321
+ v > 0 && (j = Math.max(0, Math.min(100, He / v * 100)));
1322
+ }
1323
+ }
1324
+ Fe = {
1325
+ timestamp: C,
1326
+ framesEncoded: d.framesEncoded,
1327
+ bytesSent: d.bytesSent,
1328
+ packetsSent: d.packetsSent,
1329
+ packetsLost: p?.packetsLost
1330
+ };
1331
+ const M = {
1332
+ codec: kt(S),
1333
+ encoderImplementation: d.encoderImplementation,
1334
+ hardwareAccelerated: typeof d.powerEfficientEncoder == "boolean" ? d.powerEfficientEncoder : void 0,
1335
+ framesPerSecond: J,
1336
+ framesEncoded: d.framesEncoded,
1337
+ bitrateBps: U,
1338
+ width: d.frameWidth,
1339
+ height: d.frameHeight,
1340
+ qualityLimitationReason: d.qualityLimitationReason,
1341
+ rttMs: typeof p?.roundTripTime == "number" ? p.roundTripTime * 1e3 : void 0,
1342
+ packetsLostPct: j
1343
+ };
1344
+ L("onCameraStats", e.onCameraStats, M);
1345
+ }, ht = () => {
1346
+ Ke === null && (Fe = null, Ke = setInterval(() => {
1347
+ Ut();
1348
+ }, 1e3));
1349
+ }, Ve = () => {
1350
+ Ke !== null && (clearInterval(Ke), Ke = null), Fe = null, L("onCameraStats", e.onCameraStats, null);
1351
+ }, Pt = (r, u, c, d) => Xe.enqueue(async ({ isCurrent: S }) => {
1352
+ const p = () => S() && d() && g === u && de === c;
1353
+ if (!p()) return;
1354
+ if (!r.active) {
1355
+ const M = Q;
1356
+ try {
1357
+ await c.replaceTrack(null);
1358
+ } catch (N) {
1359
+ y("replaceTrack(null) on camera detach failed:", N);
1360
+ }
1361
+ if (Q === M && (Q = null, ue = void 0, M && H(M)), Ve(), !p()) return;
1362
+ L("onCameraDemandChange", e.onCameraDemandChange, !1);
1363
+ return;
1364
+ }
1365
+ L("onCameraDemandChange", e.onCameraDemandChange, !0);
1366
+ const C = Q, E = C?.getVideoTracks()[0], J = ue;
1367
+ if (E?.readyState === "live" && J && !Sn(J, r)) {
1368
+ ue = r, Et(u, E), ht();
1369
+ return;
1370
+ }
1371
+ if (C) {
1372
+ try {
1373
+ await c.replaceTrack(null);
1374
+ } catch (M) {
1375
+ y("replaceTrack(null) before camera switch failed:", M);
1376
+ }
1377
+ if (Q === C && (Q = null, ue = void 0, H(C)), Ve(), !p()) return;
1378
+ }
1379
+ if (!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia != "function") {
1380
+ if (console.warn(
1381
+ "[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost). Replying cameraResult granted=false so limulator falls back to black frames."
1382
+ ), !p()) return;
1383
+ u.send(JSON.stringify({ type: "cameraResult", granted: !1 })), L("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1384
+ return;
1385
+ }
1386
+ let U = null;
1387
+ try {
1388
+ U = await navigator.mediaDevices.getUserMedia({
1389
+ video: yn(r),
1390
+ audio: !1
1391
+ });
1392
+ } catch (M) {
1393
+ console.warn("[RemoteControl] getUserMedia denied/failed:", M);
1394
+ }
1395
+ if (!p()) {
1396
+ U && H(U);
1397
+ return;
1398
+ }
1399
+ if (!U) {
1400
+ u.send(JSON.stringify({ type: "cameraResult", granted: !1 })), L("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1401
+ return;
1402
+ }
1403
+ const j = U.getVideoTracks()[0] ?? null;
1404
+ if (!j) {
1405
+ if (H(U), !p()) return;
1406
+ u.send(JSON.stringify({ type: "cameraResult", granted: !1 })), L("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1407
+ return;
1408
+ }
1409
+ try {
1410
+ j.contentHint = "motion";
1411
+ } catch {
1412
+ }
1413
+ try {
1414
+ await c.replaceTrack(j);
1415
+ } catch (M) {
1416
+ if (y("replaceTrack(videoTrack) failed:", M), H(U), !p()) return;
1417
+ u.send(JSON.stringify({ type: "cameraResult", granted: !1 })), L("onCameraDemandChange", e.onCameraDemandChange, !0, !1);
1418
+ return;
1419
+ }
1420
+ if (!p()) {
1421
+ try {
1422
+ await c.replaceTrack(null);
1423
+ } catch (M) {
1424
+ y("replaceTrack(null) for stale camera attach failed:", M);
1425
+ }
1426
+ H(U);
1427
+ return;
1428
+ }
1429
+ try {
1430
+ const M = c.getParameters();
1431
+ (!M.encodings || M.encodings.length === 0) && (M.encodings = [{}]), M.encodings[0].maxBitrate = 8e6, M.encodings[0].maxFramerate = 30, M.degradationPreference = "maintain-framerate", await c.setParameters(M);
1432
+ } catch (M) {
1433
+ y("setParameters on outbound camera failed:", M);
1434
+ }
1435
+ if (!p()) {
1436
+ try {
1437
+ await c.replaceTrack(null);
1438
+ } catch (M) {
1439
+ y("replaceTrack(null) for stale camera finalize failed:", M);
1440
+ }
1441
+ H(U);
1442
+ return;
1443
+ }
1444
+ Q = U, ue = r, j.onended = () => {
1445
+ Q === U && Xe.enqueueCurrent(async ({ isCurrent: M }) => {
1446
+ if (!(!M() || Q !== U || !d() || g !== u || de !== c)) {
1447
+ try {
1448
+ await c.replaceTrack(null);
1449
+ } catch (N) {
1450
+ y("replaceTrack(null) after camera ended failed:", N);
1451
+ }
1452
+ !M() || Q !== U || !d() || g !== u || de !== c || (Q = null, ue = void 0, H(U), Ve(), u.send(JSON.stringify({ type: "cameraResult", granted: !1 })), L("onCameraDemandChange", e.onCameraDemandChange, !0, !1));
1453
+ }
1454
+ }).catch((M) => y("camera ended cleanup failed:", M));
1455
+ }, p() && (Et(u, j), ht());
1456
+ }), De = () => {
1457
+ for (const r of oe) r();
1458
+ oe.clear();
1459
+ for (const r of Y.values()) clearTimeout(r);
1460
+ Y.clear();
1461
+ for (const r of Z.values())
1462
+ r(new Error("Simulator disconnected"));
1463
+ for (const r of re.values())
1464
+ r(new Error("Simulator disconnected"));
1465
+ Z.clear(), ne.clear(), re.clear(), ae.clear(), P?.(), P = void 0, wt(), V = null;
1466
+ for (const r of Ce.values())
1467
+ clearTimeout(r.timer), r.reject(new Error("Simulator disconnected"));
1468
+ Ce.clear(), w(null), h({ controlReady: !1, videoReady: !1 }), qe(), Ne(), be(), $ && ($.stop(), $ = null), we !== null && xe(null), Xe.invalidate(), Ve(), Rt(), ue = void 0, de = null, ++Be, ze = !1, me = null, ee && (H(ee), ee = null, L("onMicrophoneStateChange", e.onMicrophoneStateChange, {
1469
+ active: !1
1470
+ })), Ae = null, g && (g.onopen = null, g.onmessage = null, g.onerror = null, g.onclose = null, g.close(), g = null), Ue?.close(), Ue = null, b && (b.onconnectionstatechange = null, b.oniceconnectionstatechange = null, b.ontrack = null, b.onicecandidate = null, b.close(), b = null), B && (B.onopen = null, B.onclose = null, B.onerror = null, B.close(), B = null);
1471
+ }, mt = () => {
1472
+ document.hidden ? Ye() : dt();
1473
+ }, Lt = async () => {
1474
+ if (e.transport) return e.transport.isTerminated?.() ?? !1;
1475
+ if (typeof navigator < "u" && navigator.onLine === !1)
1476
+ return !1;
1477
+ let r;
1478
+ try {
1479
+ const d = new URL(n);
1480
+ d.protocol = d.protocol === "wss:" ? "https:" : d.protocol === "ws:" ? "http:" : d.protocol, r = vt(d.toString(), s);
1481
+ } catch {
1482
+ return !1;
1483
+ }
1484
+ const u = new AbortController(), c = window.setTimeout(() => u.abort(), bn);
1485
+ try {
1486
+ return (await fetch(r, { method: "GET", cache: "no-store", signal: u.signal })).status === 404;
1487
+ } catch {
1488
+ return !1;
1489
+ } finally {
1490
+ window.clearTimeout(c);
1491
+ }
1492
+ }, Ft = () => {
1493
+ fe || (fe = !0, le += 1, We(), qe(), Ne(), De(), D("Instance terminated"), Ye(), Oe("terminated"), L("onTerminated", e.onTerminated));
1494
+ }, Bt = () => {
1495
+ if (fe || ye) return;
1496
+ ye = !0;
1497
+ const r = ke;
1498
+ Lt().catch(() => !1).then((u) => {
1499
+ r === ke && (ye = !1, u && Ft());
1500
+ });
1501
+ }, _e = (r, u) => {
1502
+ if (fe || u !== le)
1503
+ return;
1504
+ if (Bt(), te) {
1505
+ if (!e.autoReconnect) {
1506
+ D(`Connection failed after it was established: ${r}`), Ye(), Oe("failed"), De();
1507
+ return;
1508
+ }
1509
+ D(`Reconnecting after established session dropped: ${r}`), te = !1, Le = -1;
1510
+ }
1511
+ We();
1512
+ const c = Le + 1;
1513
+ if (c >= at) {
1514
+ D(`Connection failed after ${at} attempts: ${r}`), Ye(), Oe("failed"), De();
1515
+ return;
1516
+ }
1517
+ D(`Retrying connection (${c + 1}/${at})`), Oe("reconnecting"), De(), Se = window.setTimeout(() => {
1518
+ Se = void 0, u === le && pt(c);
1519
+ }, Mn);
1520
+ }, pt = async (r = 0) => {
1521
+ const { openUrl: u, axPollIntervalMs: c, axMaxBackoffMs: d, androidElementTreeOptions: S } = e;
1522
+ if (fe) return;
1523
+ const p = le + 1;
1524
+ le = p, Le = r, te = !1, r === 0 && pe !== "reconnecting" && Oe("connecting"), We(), qe(), be(), Me = !1, K(!1), De();
1525
+ const C = () => p === le;
1526
+ ve = window.setTimeout(() => {
1527
+ ve = void 0, !(!C() || te) && _e("Connection did not succeed within 15 seconds", p);
1528
+ }, wn);
1529
+ try {
1530
+ const E = e.transport ? await e.transport.connect() : new WebSocket(vt(n, s));
1531
+ if (!C()) {
1532
+ E.close();
1533
+ return;
1534
+ }
1535
+ if (g = E, await new Promise((_, o) => {
1536
+ let R = !1;
1537
+ const x = () => A(() => o(new Error("Connection stopped")));
1538
+ oe.add(x);
1539
+ const T = window.setTimeout(
1540
+ () => A(() => o(new Error("WebSocket connection timeout"))),
1541
+ 3e4
1542
+ ), A = (z) => {
1543
+ R || (R = !0, oe.delete(x), window.clearTimeout(T), z());
1544
+ };
1545
+ E.onopen = () => {
1546
+ !C() || g !== E || A(_);
1547
+ }, E.onerror = (z) => {
1548
+ !C() || g !== E || (D("WebSocket error: " + z), A(() => o(new Error("WebSocket connection failed"))));
1549
+ }, E.onclose = () => {
1550
+ !C() || g !== E || (D("WebSocket closed"), A(() => o(new Error("WebSocket closed before connection was established"))));
1551
+ }, E.readyState === WebSocket.OPEN ? A(_) : E.readyState !== WebSocket.CONNECTING && A(() => o(new Error("WebSocket is closed")));
1552
+ }), !C() || g !== E)
1553
+ return;
1554
+ E.onerror = (_) => {
1555
+ !C() || g !== E || D("WebSocket error: " + _);
1556
+ }, E.onclose = () => {
1557
+ !C() || g !== E || D("WebSocket closed");
1558
+ };
1559
+ const J = new Promise((_, o) => {
1560
+ let R = !1;
1561
+ const x = () => T(() => o(new Error("Connection stopped")));
1562
+ oe.add(x);
1563
+ const T = (G) => {
1564
+ R || (R = !0, oe.delete(x), window.clearTimeout(A), E.removeEventListener("message", z), G());
1565
+ }, A = window.setTimeout(
1566
+ () => T(() => o(new Error("RTCConfiguration timeout"))),
1567
+ 3e4
1568
+ ), z = (G) => {
1569
+ if (!(!C() || g !== E))
1570
+ try {
1571
+ const X = JSON.parse(G.data);
1572
+ if (X.type === "signalingError" && X.requestType === "requestRtcConfiguration" && X.sessionId === a) {
1573
+ const qt = typeof X.error == "string" ? X.error : "Unable to load streaming configuration";
1574
+ T(() => o(new Error(qt)));
1575
+ } else X.type === "rtcConfiguration" && T(
1576
+ () => _({
1577
+ rtcConfiguration: X.rtcConfiguration,
1578
+ cameraSupported: X.cameraSupported === !0,
1579
+ foldSupported: X.foldSupported === !0
1580
+ })
1581
+ );
1582
+ } catch (X) {
1583
+ console.error("Error handling RTC configuration:", X), T(() => o(X));
1584
+ }
1585
+ };
1586
+ E.addEventListener("message", z), E.send(
1587
+ JSON.stringify({
1588
+ type: "requestRtcConfiguration",
1589
+ sessionId: a
1590
+ })
1591
+ );
1592
+ }), {
1593
+ rtcConfiguration: U,
1594
+ cameraSupported: j,
1595
+ foldSupported: M
1596
+ } = await J;
1597
+ if (!C() || g !== E)
1598
+ return;
1599
+ const N = f === "iphone-duo" || M;
1600
+ W(N);
1601
+ const v = new RTCPeerConnection({ ...U, iceTransportPolicy: "relay" });
1602
+ b = v;
1603
+ const He = { peer: v, displays: /* @__PURE__ */ new Map() };
1604
+ V = He, k(), v.addTransceiver("audio", { direction: "recvonly" });
1605
+ const xt = v.addTransceiver("video", { direction: "recvonly" }), Wt = N ? v.addTransceiver("video", { direction: "recvonly" }) : null, _t = !l && (m === "ios" || j), tt = _t ? v.addTransceiver("video", {
1606
+ direction: "sendonly"
1607
+ }) : null;
1608
+ if (de = tt?.sender ?? null, Ae = (_t ? v.addTransceiver("audio", {
1609
+ direction: "sendonly"
1610
+ }) : null)?.sender ?? null, RTCRtpReceiver.getCapabilities) {
1611
+ const _ = RTCRtpReceiver.getCapabilities("video");
1612
+ if (_ && _.codecs) {
1613
+ const R = _.codecs.sort((x, T) => {
1614
+ const A = (z) => {
1615
+ const G = z.mimeType.toLowerCase();
1616
+ return G.includes("vp9") ? 1 : G.includes("h265") || G.includes("hevc") ? 2 : G.includes("h264") || G.includes("avc") ? 3 : 4;
1617
+ };
1618
+ return A(x) - A(T);
1619
+ });
1620
+ xt.setCodecPreferences(R), Wt?.setCodecPreferences(R), ce("Set codec preferences:", R.map((x) => x.mimeType).join(", "));
1621
+ }
1622
+ }
1623
+ if (tt && RTCRtpSender.getCapabilities) {
1624
+ const _ = RTCRtpSender.getCapabilities("video");
1625
+ if (_ && _.codecs) {
1626
+ const o = /* @__PURE__ */ new Set(["42e01f", "42e028", "640c1f"]), R = (T) => {
1627
+ const A = T.mimeType.toLowerCase(), G = (T.sdpFmtpLine || "").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/), X = G ? G[1] : "";
1628
+ return A === "video/h265" || A === "video/hevc" ? 1 : A === "video/h264" && o.has(X) ? 2 : A === "video/h264" ? 3 : A === "video/vp9" ? 4 : A === "video/vp8" ? 5 : A === "video/rtx" || A === "video/red" || A === "video/ulpfec" ? 0 : 6;
1629
+ }, x = [..._.codecs].sort((T, A) => R(T) - R(A));
1630
+ try {
1631
+ tt.setCodecPreferences(x), ce(
1632
+ "Outbound camera codec preferences:",
1633
+ x.map((T) => `${T.mimeType}${T.sdpFmtpLine ? `[${T.sdpFmtpLine}]` : ""}`).join(", ")
1634
+ );
1635
+ } catch (T) {
1636
+ y("Failed to set outbound camera codec preferences:", T);
1637
+ }
1638
+ }
1639
+ }
1640
+ const ie = v.createDataChannel("control", {
1641
+ ordered: !0,
1642
+ negotiated: !0,
1643
+ id: 1
1644
+ });
1645
+ B = ie;
1646
+ const nt = !l && !N && e.onTrace ? _n(v, (_) => {
1647
+ C() && b === v && L("onTrace", e.onTrace, _);
1648
+ }) : null;
1649
+ if (Ue = nt, ie.onopen = () => {
1650
+ if (!C() || B !== ie || g !== E)
1651
+ return;
1652
+ te = !0, h({ controlReady: !l }), qe(), D("Control channel opened"), N && E.send(JSON.stringify({ type: "getFoldState", id: "duo-capabilities" })), $ || ($ = new mn({
1653
+ platform: m,
1654
+ baseIntervalMs: c,
1655
+ maxBackoffMs: d,
1656
+ androidElementTreeOptions: S,
1657
+ send: (o) => {
1658
+ if (!g || g.readyState !== WebSocket.OPEN) return !1;
1659
+ try {
1660
+ return g.send(JSON.stringify(o)), !0;
1661
+ } catch {
1662
+ return !1;
1663
+ }
1664
+ },
1665
+ onSnapshot: xe,
1666
+ onStatusChange: (o, R) => {
1667
+ L("onAxStatusChange", e.onAxStatusChange, o, R);
1668
+ }
1669
+ }), (e.inspectMode === !0 || e.inspectMode === "hover-only") && $.start());
1670
+ const _ = () => {
1671
+ !C() || Me || B !== ie || g !== E || E.readyState !== WebSocket.OPEN || E.send(JSON.stringify({ type: "requestFrame", sessionId: a }));
1672
+ };
1673
+ if (_(), be(), Pe = window.setInterval(() => {
1674
+ if (!C() || Me || B !== ie || g !== E || E.readyState !== WebSocket.OPEN) {
1675
+ be();
1676
+ return;
1677
+ }
1678
+ _();
1679
+ }, 250), !l && u) {
1680
+ try {
1681
+ const o = decodeURIComponent(u);
1682
+ D("Opening URL"), E.send(
1683
+ JSON.stringify({
1684
+ type: "openUrl",
1685
+ url: o,
1686
+ sessionId: a
1687
+ })
1688
+ );
1689
+ } catch (o) {
1690
+ console.error({ error: o }, "Error decoding URL, falling back to the original URL"), E.send(
1691
+ JSON.stringify({
1692
+ type: "openUrl",
1693
+ url: u,
1694
+ sessionId: a
1695
+ })
1696
+ );
1697
+ }
1698
+ $?.bumpActivity();
1699
+ }
1700
+ }, ie.onclose = () => {
1701
+ !C() || B !== ie || (h({ controlReady: !1 }), D("Control channel closed"));
1702
+ }, ie.onerror = (_) => {
1703
+ !C() || B !== ie || (console.error("Control channel error:", _), D("Control channel error: " + _));
1704
+ }, v.onconnectionstatechange = () => {
1705
+ !C() || b !== v || (D("Connection state: " + v.connectionState), v.connectionState === "failed" && te && _e("WebRTC connection entered failed state", p));
1706
+ }, v.oniceconnectionstatechange = () => {
1707
+ if (!C() || b !== v)
1708
+ return;
1709
+ const _ = v.iceConnectionState;
1710
+ if (D("ICE state: " + _), _ === "connected" || _ === "completed") {
1711
+ Ne(), Ze() && !ee && et();
1712
+ return;
1713
+ }
1714
+ if (_ === "failed") {
1715
+ Ne(), te && _e("ICE connection entered failed state", p);
1716
+ return;
1717
+ }
1718
+ _ === "disconnected" && te && e.autoReconnect && he === void 0 && (he = window.setTimeout(() => {
1719
+ he = void 0, !(!C() || b !== v) && v.iceConnectionState === "disconnected" && _e("ICE stayed disconnected past grace period", p);
1720
+ }, Yn));
1721
+ }, v.ontrack = (_) => {
1722
+ if (!C() || b !== v)
1723
+ return;
1724
+ yt(_.receiver, e.jitterBufferTargetMs);
1725
+ const o = _.track.id === "duo-inner" || _.streams.some((R) => R.id === "duo-inner");
1726
+ if (_.track.kind === "video" && He.displays.set(_.receiver, o ? "inner" : "primary"), D("Received remote track: " + _.track.kind), _.track.kind === "video") {
1727
+ const R = o ? "inner" : "primary", x = N ? new MediaStream([_.track]) : _.streams[0] ?? new MediaStream([_.track]);
1728
+ Ie.set(R, x);
1729
+ for (const [T, A] of F)
1730
+ A.display === R && st(T, A, x);
1731
+ }
1732
+ }, v.onicecandidate = (_) => {
1733
+ if (!(!C() || b !== v || g !== E))
1734
+ if (_.candidate && E.readyState === WebSocket.OPEN) {
1735
+ const o = {
1736
+ type: "candidate",
1737
+ candidate: _.candidate.candidate,
1738
+ sdpMid: _.candidate.sdpMid,
1739
+ sdpMLineIndex: _.candidate.sdpMLineIndex,
1740
+ sessionId: a
1741
+ };
1742
+ E.send(JSON.stringify(o)), D("Sent ICE candidate");
1743
+ } else
1744
+ D("ICE candidate gathering completed");
1745
+ }, E.onmessage = async (_) => {
1746
+ if (!C() || g !== E)
1747
+ return;
1748
+ let o;
1749
+ try {
1750
+ o = JSON.parse(_.data);
1751
+ } catch (R) {
1752
+ y("Error parsing message:", R);
1753
+ return;
1754
+ }
1755
+ if (!$?.handleMessage(o))
1756
+ switch (D("Received: " + o.type), o.type) {
1757
+ case "performActionsResult":
1758
+ case "foldStateResult":
1759
+ case "foldStateChanged": {
1760
+ if (!N) break;
1761
+ o.state ? (w(o.state), I(void 0)) : o.id === "duo-capabilities" && I(o.error || "This instance does not support native iPhone Duo displays.");
1762
+ const T = Ce.get(o.id);
1763
+ T && (clearTimeout(T.timer), Ce.delete(o.id), o.error ? T.reject(new Error(o.error)) : T.resolve());
1764
+ break;
1765
+ }
1766
+ case "signalingError": {
1767
+ if (o.requestType !== "offer" || o.sessionId !== a)
1768
+ break;
1769
+ const T = typeof o.error == "string" ? o.error : "Unable to establish the streaming connection";
1770
+ D("Error: " + T), _e(T, p);
1771
+ break;
1772
+ }
1773
+ case "answer":
1774
+ if (!b || b !== v) {
1775
+ D("No peer connection, skipping answer");
1776
+ break;
1777
+ }
1778
+ if (nt?.accept(o.latencyTraceVersion), await v.setRemoteDescription(
1779
+ new RTCSessionDescription({
1780
+ type: "answer",
1781
+ sdp: o.sdp
1782
+ })
1783
+ ), !C() || b !== v)
1784
+ return;
1785
+ D("Set remote description");
1786
+ break;
1787
+ case "candidate":
1788
+ if (!b || b !== v) {
1789
+ D("No peer connection, skipping candidate");
1790
+ break;
1791
+ }
1792
+ if (await v.addIceCandidate(
1793
+ new RTCIceCandidate({
1794
+ candidate: o.candidate,
1795
+ sdpMid: o.sdpMid,
1796
+ sdpMLineIndex: o.sdpMLineIndex
1797
+ })
1798
+ ), !C() || b !== v)
1799
+ return;
1800
+ D("Added ICE candidate");
1801
+ break;
1802
+ case "screenshot":
1803
+ case "screenshotResult": {
1804
+ if (typeof o.id != "string") {
1805
+ y("Received invalid screenshot success message:", o);
1806
+ break;
1807
+ }
1808
+ const T = Nn(o);
1809
+ if (T) {
1810
+ const G = Z.get(o.id);
1811
+ if (typeof G != "function") {
1812
+ y(`Received screenshot error for unknown or handled id: ${o.id}`);
1813
+ break;
1814
+ }
1815
+ y(`Received screenshot error for id ${o.id}: ${T}`), G(new Error(T)), ne.delete(o.id), Z.delete(o.id), clearTimeout(Y.get(o.id)), Y.delete(o.id);
1816
+ break;
1817
+ }
1818
+ const A = Rn(o);
1819
+ if (!A) {
1820
+ y("Received screenshot message without image data:", o);
1821
+ break;
1822
+ }
1823
+ const z = ne.get(o.id);
1824
+ if (typeof z != "function") {
1825
+ y(`Received screenshot data for unknown or handled id: ${o.id}`);
1826
+ break;
1827
+ }
1828
+ ce(`Received screenshot data for id ${o.id}`), z(A), ne.delete(o.id), Z.delete(o.id), clearTimeout(Y.get(o.id)), Y.delete(o.id);
1829
+ break;
1830
+ }
1831
+ case "screenshotError":
1832
+ if (typeof o.id != "string" || typeof o.message != "string") {
1833
+ y("Received invalid screenshot error message:", o);
1834
+ break;
1835
+ }
1836
+ const R = Z.get(o.id);
1837
+ if (typeof R != "function") {
1838
+ y(`Received screenshot error for unknown or handled id: ${o.id}`);
1839
+ break;
1840
+ }
1841
+ y(`Received screenshot error for id ${o.id}: ${o.message}`), R(new Error(o.message)), ne.delete(o.id), Z.delete(o.id), clearTimeout(Y.get(o.id)), Y.delete(o.id);
1842
+ break;
1843
+ case "cameraRequest": {
1844
+ const T = de;
1845
+ if (!T)
1846
+ break;
1847
+ const A = Tn(o);
1848
+ if (!A) {
1849
+ y("Received invalid cameraRequest:", o);
1850
+ break;
1851
+ }
1852
+ console.info("[RemoteControl] cameraRequest received:", A.active, A.facingMode), await Pt(A, E, T, C);
1853
+ break;
1854
+ }
1855
+ case "microphoneRequest": {
1856
+ if (!Ae)
1857
+ break;
1858
+ const T = o.active === !0;
1859
+ if (ze = T, console.info("[RemoteControl] microphoneRequest received, active=", T), !T) {
1860
+ Qe || await $e();
1861
+ break;
1862
+ }
1863
+ if (ee) {
1864
+ ft(E);
1865
+ break;
1866
+ }
1867
+ await et();
1868
+ break;
1869
+ }
1870
+ case "microphoneStartResult": {
1871
+ if (me === null || o.id !== me)
1872
+ break;
1873
+ me = null, typeof o.error == "string" && (console.warn("[RemoteControl] microphoneStart rejected by host:", o.error), $e(o.error));
1874
+ break;
1875
+ }
1876
+ case "terminateAppResult":
1877
+ if (typeof o.id != "string") {
1878
+ y("Received invalid terminateApp result message:", o);
1879
+ break;
1880
+ }
1881
+ if (typeof o.error == "string") {
1882
+ const T = re.get(o.id);
1883
+ if (typeof T != "function") {
1884
+ y(`Received terminateApp error for unknown or handled id: ${o.id}`);
1885
+ break;
1886
+ }
1887
+ y(`Received terminateApp error for id ${o.id}: ${o.error}`), T(new Error(o.error)), ae.delete(o.id), re.delete(o.id), clearTimeout(Y.get(o.id)), Y.delete(o.id);
1888
+ break;
1889
+ }
1890
+ const x = ae.get(o.id);
1891
+ if (typeof x != "function") {
1892
+ y(`Received terminateApp result for unknown or handled id: ${o.id}`);
1893
+ break;
1894
+ }
1895
+ ce(`Received terminateApp success for id ${o.id}`), x(), ae.delete(o.id), re.delete(o.id), clearTimeout(Y.get(o.id)), Y.delete(o.id);
1896
+ break;
1897
+ default:
1898
+ y(`Received unhandled message type: ${o.type}`, o);
1899
+ break;
1900
+ }
1901
+ }, b === v) {
1902
+ const _ = await v.createOffer({
1903
+ offerToReceiveVideo: !0,
1904
+ offerToReceiveAudio: !1
1905
+ });
1906
+ if (!C() || b !== v || (await v.setLocalDescription(_), !C() || b !== v))
1907
+ return;
1908
+ C() && g === E && E.readyState === WebSocket.OPEN && E.send(
1909
+ JSON.stringify({
1910
+ type: "offer",
1911
+ ...N ? { displayStreams: !0 } : {},
1912
+ ...nt ? { latencyTraceVersion: 1 } : {},
1913
+ sdp: _.sdp,
1914
+ sessionId: a
1915
+ })
1916
+ ), D("Sent offer");
1917
+ }
1918
+ } catch (E) {
1919
+ if (!C() || E instanceof Error && E.message === "Connection stopped")
1920
+ return;
1921
+ const J = E instanceof Error ? E.message : String(E);
1922
+ D("Error: " + J), _e(J, p);
1923
+ }
1924
+ }, Ct = () => {
1925
+ if (Te) throw new Error("Device stream is disposed");
1926
+ ke++, ye = !1, xe(null), pe !== "reconnecting" && (pe = null), document.addEventListener("visibilitychange", mt), document.hidden || dt(), fe = !1, pt(0);
1927
+ }, Ot = () => {
1928
+ ke++, ye = !1, Ye(), document.removeEventListener("visibilitychange", mt), le += 1, Le = 0, te = !1, We(), Ne(), De(), pe = null, h({ connection: "idle", videoReady: !1, controlReady: !1 }), D("Stopped");
1929
+ }, Dt = (r, u = "primary") => {
1930
+ if (Te) throw new Error("Device stream is disposed");
1931
+ if (F.has(r)) throw new Error("Video element is already attached");
1932
+ const c = { display: u };
1933
+ F.set(r, c);
1934
+ const d = () => {
1935
+ u === "primary" && Ie.has(u) && Nt();
1936
+ };
1937
+ r.addEventListener("loadeddata", d);
1938
+ const S = Ie.get(u);
1939
+ S && st(r, c, S);
1940
+ let p = !1;
1941
+ const C = () => {
1942
+ p || (p = !0, q.delete(C), r.removeEventListener("loadeddata", d), c.stop?.(), F.delete(r), r.srcObject = null);
1943
+ };
1944
+ return q.add(C), C;
1945
+ };
1946
+ return {
1947
+ start: Ct,
1948
+ stop: Ot,
1949
+ attachVideo: Dt,
1950
+ attachFrameSink: (r, u = "primary") => {
1951
+ const c = document.createElement("video");
1952
+ c.muted = !0, c.playsInline = !0, c.autoplay = !0;
1953
+ const d = Dt(c, u);
1954
+ let S = !1, p = 0, C = 0;
1955
+ const E = () => {
1956
+ c.cancelVideoFrameCallback?.(p), cancelAnimationFrame(C);
1957
+ }, J = () => {
1958
+ S || !c.srcObject || (c.readyState >= 2 && c.videoWidth > 0 && L(
1959
+ "present",
1960
+ (...M) => r.present(...M),
1961
+ c,
1962
+ c.videoWidth,
1963
+ c.videoHeight,
1964
+ u
1965
+ ), !(S || !c.srcObject) && (c.requestVideoFrameCallback ? p = c.requestVideoFrameCallback(J) : C = requestAnimationFrame(J)));
1966
+ }, U = () => {
1967
+ E(), J();
1968
+ };
1969
+ F.get(c).clear = E, c.addEventListener("loadeddata", U);
1970
+ const j = () => {
1971
+ S || (S = !0, q.delete(j), E(), c.removeEventListener("loadeddata", U), d(), c.remove());
1972
+ };
1973
+ return q.delete(d), q.add(j), c.readyState >= 2 && U(), j;
1974
+ },
1975
+ dispose: () => {
1976
+ if (!Te) {
1977
+ Te = !0, Ot();
1978
+ for (const r of q) r();
1979
+ q.clear();
1980
+ }
1981
+ },
1982
+ getState: () => O,
1983
+ updateOptions: (r) => {
1984
+ if (Te) throw new Error("Device stream is disposed");
1985
+ const u = e;
1986
+ if (e = { ...e, ...r }, u.jitterBufferTargetMs !== e.jitterBufferTargetMs)
1987
+ for (const c of b?.getTransceivers() ?? [])
1988
+ (c.currentDirection === "recvonly" || c.currentDirection === "sendrecv") && yt(c.receiver, e.jitterBufferTargetMs);
1989
+ !!u.onPlaybackStats != !!e.onPlaybackStats && k(), !!u.microphoneEnabled != !!e.microphoneEnabled && (Qe = !l && (e.microphoneEnabled ?? !1), Ze() ? et() : $e()), !!u.inspectMode != !!e.inspectMode && (e.inspectMode ? $?.start() : ($?.stop(), we !== null && xe(null)));
1990
+ },
1991
+ sendControl: se,
1992
+ sendTouch: (r, u, c, d, S, p = 0) => se(
1993
+ Vt(
1994
+ r === "begin" ? 0 : r === "end" ? 1 : 2,
1995
+ p,
1996
+ d,
1997
+ S,
1998
+ u,
1999
+ c,
2000
+ r === "end" ? 0 : 1
2001
+ )
2002
+ ),
2003
+ sendText: (r) => se(Ht(r)),
2004
+ sendDisplayTouch: (r, u, c, d) => se(Xt(r, u, c, d)),
2005
+ sendDuoControl: Yt,
2006
+ pressButton: (r) => {
2007
+ const u = { home: 3, back: 4, recents: 187, power: 26 }[r];
2008
+ se(rt(0, u, 0, 0)), se(rt(1, u, 0, 0));
2009
+ },
2010
+ rotate: () => se(new Uint8Array([11]).buffer),
2011
+ bumpActivity: () => $?.bumpActivity(),
2012
+ getAxStatus: () => $?.getStatus() ?? "idle",
2013
+ openUrl: (r) => {
2014
+ if (!l) {
2015
+ if (!g || g.readyState !== WebSocket.OPEN) {
2016
+ y("WebSocket not open, cannot send open_url command.");
2017
+ return;
2018
+ }
2019
+ try {
2020
+ const u = decodeURIComponent(r);
2021
+ D("Opening URL"), g.send(
2022
+ JSON.stringify({
2023
+ type: "openUrl",
2024
+ url: u,
2025
+ sessionId: a
2026
+ })
2027
+ );
2028
+ } catch (u) {
2029
+ y("Error decoding or sending URL :", { error: u, url: r }), g.send(
2030
+ JSON.stringify({
2031
+ type: "openUrl",
2032
+ url: r,
2033
+ sessionId: a
2034
+ })
2035
+ );
2036
+ }
2037
+ $?.bumpActivity();
2038
+ }
2039
+ },
2040
+ sendKeyEvent: (r) => {
2041
+ if (!B || B.readyState !== "open") {
2042
+ y("Data channel not ready for imperative key command:", B?.readyState);
2043
+ return;
2044
+ }
2045
+ const u = $t[r.code];
2046
+ if (!u) {
2047
+ y(`Unknown event.code for imperative command: ${r.code}`);
2048
+ return;
2049
+ }
2050
+ let c = i.META_NONE;
2051
+ r.shiftKey && (c |= i.META_SHIFT_ON), r.altKey && (c |= i.META_ALT_ON), r.ctrlKey && (c |= i.META_CTRL_ON), r.metaKey && (c |= i.META_META_ON);
2052
+ const d = r.type === "keydown" ? i.ACTION_DOWN : i.ACTION_UP;
2053
+ ce(
2054
+ `Sending Imperative Key Command: code=${r.code}, keycode=${u}, action=${d}, meta=${c}`
2055
+ );
2056
+ const S = rt(
2057
+ d,
2058
+ u,
2059
+ 0,
2060
+ // repeat count, typically 0 for single presses
2061
+ c
2062
+ );
2063
+ S && se(S);
2064
+ },
2065
+ screenshot: (r) => new Promise((u, c) => {
2066
+ if (!g || g.readyState !== WebSocket.OPEN)
2067
+ return y("WebSocket not open, cannot send screenshot command."), c(new Error("WebSocket is not connected or connection is not open."));
2068
+ const d = `ui-ss-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, S = {
2069
+ type: r ? "screenshotDisplay" : "screenshot",
2070
+ ...r ? { display: r } : {},
2071
+ id: d
2072
+ };
2073
+ ne.set(d, u), Z.set(d, c), ce("Sending screenshot request:", S);
2074
+ try {
2075
+ g.send(JSON.stringify(S));
2076
+ } catch (p) {
2077
+ y("Failed to send screenshot request immediately:", p), ne.delete(d), Z.delete(d), c(p);
2078
+ return;
2079
+ }
2080
+ Y.set(
2081
+ d,
2082
+ setTimeout(() => {
2083
+ Y.delete(d), ne.has(d) && (y(`Screenshot request timed out for id ${d}`), Z.get(d)?.(new Error("Screenshot request timed out")), ne.delete(d), Z.delete(d));
2084
+ }, 3e4)
2085
+ );
2086
+ }),
2087
+ terminateApp: (r) => l ? Promise.reject(new Error("Device is watch-only")) : new Promise((u, c) => {
2088
+ if (!g || g.readyState !== WebSocket.OPEN)
2089
+ return y("WebSocket not open, cannot send terminateApp command."), c(new Error("WebSocket is not connected or connection is not open."));
2090
+ const d = `ui-term-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`, S = {
2091
+ type: "terminateApp",
2092
+ id: d,
2093
+ bundleId: r
2094
+ };
2095
+ ae.set(d, u), re.set(d, c), ce("Sending terminateApp request:", S);
2096
+ try {
2097
+ g.send(JSON.stringify(S));
2098
+ } catch (p) {
2099
+ y("Failed to send terminateApp request immediately:", p), ae.delete(d), re.delete(d), c(p);
2100
+ return;
2101
+ }
2102
+ $?.bumpActivity(), Y.set(
2103
+ d,
2104
+ setTimeout(() => {
2105
+ Y.delete(d), ae.has(d) && (y(`terminateApp request timed out for id ${d}`), re.get(d)?.(new Error("terminateApp request timed out")), ae.delete(d), re.delete(d));
2106
+ }, 3e4)
2107
+ );
2108
+ }),
2109
+ reconnect: () => Ct(),
2110
+ refreshAxTree: async () => {
2111
+ const r = $;
2112
+ if (!r)
2113
+ throw new Error("Inspect mode is not active");
2114
+ return r.refresh();
2115
+ },
2116
+ getAxSnapshot: () => we
2117
+ };
2118
+ }
2119
+ const Nn = (t) => typeof t.message == "string" ? t.message : typeof t.error == "string" ? t.error : null, Rn = (t) => typeof t.dataUri == "string" ? { dataUri: t.dataUri } : typeof t.base64 == "string" ? t.base64.startsWith("data:") ? { dataUri: t.base64 } : { dataUri: `data:${t.base64.startsWith("/9j/") ? "image/jpeg" : "image/png"};base64,${t.base64}` } : null;
2120
+ export {
2121
+ it as A,
2122
+ xn as B,
2123
+ Bn as C,
2124
+ Fn as D,
2125
+ je as E,
2126
+ Xt as F,
2127
+ Jt as G,
2128
+ Wn as H,
2129
+ Hn as a,
2130
+ Gn as b,
2131
+ Jn as c,
2132
+ an as d,
2133
+ sn as e,
2134
+ Vn as f,
2135
+ tn as g,
2136
+ cn as h,
2137
+ An as i,
2138
+ jn as j,
2139
+ ce as k,
2140
+ y as l,
2141
+ Ht as m,
2142
+ on as n,
2143
+ rt as o,
2144
+ i as p,
2145
+ Vt as q,
2146
+ $t as r,
2147
+ L as s,
2148
+ Ge as t,
2149
+ Un as u,
2150
+ Ln as v,
2151
+ Pn as w,
2152
+ Gt as x,
2153
+ $n as y,
2154
+ qn as z
2155
+ };