@limrun/ui 0.19.0 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -0
- package/dist/{GLTFLoader-BEplsEG3.mjs → GLTFLoader-CEdCEYr6.mjs} +1 -1
- package/dist/{GLTFLoader-CC3leQFv.js → GLTFLoader-yqDaHF46.js} +1 -1
- package/dist/components/remote-control.d.ts +4 -68
- package/dist/core/device-stream.d.ts +30 -0
- package/dist/core/playback-subscription.d.ts +7 -0
- package/dist/core/stream-options.d.ts +62 -0
- package/dist/core/stream-types.d.ts +66 -0
- package/dist/core/stream-utils.d.ts +6 -0
- package/dist/core/use-playback-stats.d.ts +3 -6
- package/dist/core-BqXmROsc.mjs +2162 -0
- package/dist/core-D7ODbXln.js +2 -0
- package/dist/core.cjs +1 -0
- package/dist/core.d.ts +12 -0
- package/dist/core.js +21 -0
- package/dist/{duo-frame-BZ-XDtxc.js → duo-frame-BMVxq-Qi.js} +2 -2
- package/dist/{duo-frame-CB8dL8T-.mjs → duo-frame-DCl_2GS3.mjs} +3 -3
- package/dist/{duo-view-BEWqEQI2.mjs → duo-view-DhzmW9X6.mjs} +64 -64
- package/dist/duo-view-UZazbOh-.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/lite.cjs +1 -1
- package/dist/lite.js +7 -6
- package/dist/remote-control-Cl8nEKUE.js +1 -0
- package/dist/remote-control-aGoEKYFB.mjs +1128 -0
- package/package.json +15 -7
- package/dist/duo-view-DCJT-n1Z.js +0 -1
- package/dist/remote-control-CdnZRsWd.mjs +0 -2920
- package/dist/remote-control-DUG1S1Jq.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const Pe={INJECT_KEYCODE:0,INJECT_TEXT:1,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,INJECT_SCROLL_EVENT:3,BACK_OR_SCREEN_ON:4,EXPAND_NOTIFICATION_PANEL:5,EXPAND_SETTINGS_PANEL:6,COLLAPSE_PANELS:7,GET_CLIPBOARD:8,SET_CLIPBOARD:9,SET_DISPLAY_POWER:10,ROTATE_DEVICE:11},ke={ACTION_DOWN:0,ACTION_UP:1,ACTION_MOVE:2,ACTION_CANCEL:3,ACTION_POINTER_DOWN:5,ACTION_POINTER_UP:6,BUTTON_PRIMARY:1,BUTTON_SECONDARY:2,BUTTON_TERTIARY:4},o={ACTION_DOWN:0,ACTION_UP:1,META_NONE:0,META_SHIFT_ON:1,META_ALT_ON:2,META_CTRL_ON:4096,META_META_ON:65536,KEYCODE_UNKNOWN:0,KEYCODE_SOFT_LEFT:1,KEYCODE_SOFT_RIGHT:2,KEYCODE_HOME:3,KEYCODE_BACK:4,KEYCODE_CALL:5,KEYCODE_ENDCALL:6,KEYCODE_0:7,KEYCODE_1:8,KEYCODE_2:9,KEYCODE_3:10,KEYCODE_4:11,KEYCODE_5:12,KEYCODE_6:13,KEYCODE_7:14,KEYCODE_8:15,KEYCODE_9:16,KEYCODE_STAR:17,KEYCODE_POUND:18,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,KEYCODE_DPAD_CENTER:23,KEYCODE_VOLUME_UP:24,KEYCODE_VOLUME_DOWN:25,KEYCODE_POWER:26,KEYCODE_CAMERA:27,KEYCODE_CLEAR:28,KEYCODE_A:29,KEYCODE_B:30,KEYCODE_C:31,KEYCODE_D:32,KEYCODE_E:33,KEYCODE_F:34,KEYCODE_G:35,KEYCODE_H:36,KEYCODE_I:37,KEYCODE_J:38,KEYCODE_K:39,KEYCODE_L:40,KEYCODE_M:41,KEYCODE_N:42,KEYCODE_O:43,KEYCODE_P:44,KEYCODE_Q:45,KEYCODE_R:46,KEYCODE_S:47,KEYCODE_T:48,KEYCODE_U:49,KEYCODE_V:50,KEYCODE_W:51,KEYCODE_X:52,KEYCODE_Y:53,KEYCODE_Z:54,KEYCODE_COMMA:55,KEYCODE_PERIOD:56,KEYCODE_ALT_LEFT:57,KEYCODE_ALT_RIGHT:58,KEYCODE_SHIFT_LEFT:59,KEYCODE_SHIFT_RIGHT:60,KEYCODE_TAB:61,KEYCODE_SPACE:62,KEYCODE_SYM:63,KEYCODE_EXPLORER:64,KEYCODE_ENVELOPE:65,ENTER:66,DEL:67,KEYCODE_GRAVE:68,KEYCODE_MINUS:69,KEYCODE_EQUALS:70,KEYCODE_LEFT_BRACKET:71,KEYCODE_RIGHT_BRACKET:72,KEYCODE_BACKSLASH:73,KEYCODE_SEMICOLON:74,KEYCODE_APOSTROPHE:75,KEYCODE_SLASH:76,KEYCODE_AT:77,KEYCODE_NUM:78,KEYCODE_HEADSETHOOK:79,KEYCODE_FOCUS:80,KEYCODE_PLUS:81,MENU:82,KEYCODE_NOTIFICATION:83,KEYCODE_SEARCH:84,KEYCODE_MEDIA_PLAY_PAUSE:85,KEYCODE_MEDIA_STOP:86,KEYCODE_MEDIA_NEXT:87,KEYCODE_MEDIA_PREVIOUS:88,KEYCODE_MEDIA_REWIND:89,KEYCODE_MEDIA_FAST_FORWARD:90,KEYCODE_MUTE:91,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_PICTSYMBOLS:94,KEYCODE_SWITCH_CHARSET:95,KEYCODE_BUTTON_A:96,KEYCODE_BUTTON_B:97,KEYCODE_BUTTON_C:98,KEYCODE_BUTTON_X:99,KEYCODE_BUTTON_Y:100,KEYCODE_BUTTON_Z:101,KEYCODE_BUTTON_L1:102,KEYCODE_BUTTON_R1:103,KEYCODE_BUTTON_L2:104,KEYCODE_BUTTON_R2:105,KEYCODE_BUTTON_THUMBL:106,KEYCODE_BUTTON_THUMBR:107,KEYCODE_BUTTON_START:108,KEYCODE_BUTTON_SELECT:109,KEYCODE_BUTTON_MODE:110,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_CAPS_LOCK:115,KEYCODE_SCROLL_LOCK:116,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_FUNCTION:119,KEYCODE_SYSRQ:120,KEYCODE_BREAK:121,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,KEYCODE_FORWARD:125,KEYCODE_MEDIA_PLAY:126,KEYCODE_MEDIA_PAUSE:127,KEYCODE_MEDIA_CLOSE:128,KEYCODE_MEDIA_EJECT:129,KEYCODE_MEDIA_RECORD:130,KEYCODE_F1:131,KEYCODE_F2:132,KEYCODE_F3:133,KEYCODE_F4:134,KEYCODE_F5:135,KEYCODE_F6:136,KEYCODE_F7:137,KEYCODE_F8:138,KEYCODE_F9:139,KEYCODE_F10:140,KEYCODE_F11:141,KEYCODE_F12:142,KEYCODE_NUM_LOCK:143,KEYCODE_NUMPAD_0:144,KEYCODE_NUMPAD_1:145,KEYCODE_NUMPAD_2:146,KEYCODE_NUMPAD_3:147,KEYCODE_NUMPAD_4:148,KEYCODE_NUMPAD_5:149,KEYCODE_NUMPAD_6:150,KEYCODE_NUMPAD_7:151,KEYCODE_NUMPAD_8:152,KEYCODE_NUMPAD_9:153,KEYCODE_NUMPAD_DIVIDE:154,KEYCODE_NUMPAD_MULTIPLY:155,KEYCODE_NUMPAD_SUBTRACT:156,KEYCODE_NUMPAD_ADD:157,KEYCODE_NUMPAD_DOT:158,KEYCODE_NUMPAD_COMMA:159,KEYCODE_NUMPAD_ENTER:160,KEYCODE_NUMPAD_EQUALS:161,KEYCODE_NUMPAD_LEFT_PAREN:162,KEYCODE_NUMPAD_RIGHT_PAREN:163,KEYCODE_VOLUME_MUTE:164,KEYCODE_INFO:165,KEYCODE_CHANNEL_UP:166,KEYCODE_CHANNEL_DOWN:167,KEYCODE_ZOOM_IN:168,KEYCODE_ZOOM_OUT:169,KEYCODE_TV:170,KEYCODE_WINDOW:171,KEYCODE_GUIDE:172,KEYCODE_DVR:173,KEYCODE_BOOKMARK:174,KEYCODE_CAPTIONS:175,KEYCODE_SETTINGS:176,KEYCODE_TV_POWER:177,KEYCODE_TV_INPUT:178,KEYCODE_STB_POWER:179,KEYCODE_STB_INPUT:180,KEYCODE_AVR_POWER:181,KEYCODE_AVR_INPUT:182,KEYCODE_PROG_RED:183,KEYCODE_PROG_GREEN:184,KEYCODE_PROG_YELLOW:185,KEYCODE_PROG_BLUE:186,KEYCODE_APP_SWITCH:187,KEYCODE_LANGUAGE_SWITCH:204,KEYCODE_ASSIST:219,KEYCODE_BRIGHTNESS_DOWN:220,KEYCODE_BRIGHTNESS_UP:221,KEYCODE_SLEEP:223,KEYCODE_WAKEUP:224,KEYCODE_SOFT_SLEEP:276},wt={KeyA:o.KEYCODE_A,KeyB:o.KEYCODE_B,KeyC:o.KEYCODE_C,KeyD:o.KEYCODE_D,KeyE:o.KEYCODE_E,KeyF:o.KEYCODE_F,KeyG:o.KEYCODE_G,KeyH:o.KEYCODE_H,KeyI:o.KEYCODE_I,KeyJ:o.KEYCODE_J,KeyK:o.KEYCODE_K,KeyL:o.KEYCODE_L,KeyM:o.KEYCODE_M,KeyN:o.KEYCODE_N,KeyO:o.KEYCODE_O,KeyP:o.KEYCODE_P,KeyQ:o.KEYCODE_Q,KeyR:o.KEYCODE_R,KeyS:o.KEYCODE_S,KeyT:o.KEYCODE_T,KeyU:o.KEYCODE_U,KeyV:o.KEYCODE_V,KeyW:o.KEYCODE_W,KeyX:o.KEYCODE_X,KeyY:o.KEYCODE_Y,KeyZ:o.KEYCODE_Z,Digit0:o.KEYCODE_0,Digit1:o.KEYCODE_1,Digit2:o.KEYCODE_2,Digit3:o.KEYCODE_3,Digit4:o.KEYCODE_4,Digit5:o.KEYCODE_5,Digit6:o.KEYCODE_6,Digit7:o.KEYCODE_7,Digit8:o.KEYCODE_8,Digit9:o.KEYCODE_9,Backquote:o.KEYCODE_GRAVE,Minus:o.KEYCODE_MINUS,Equal:o.KEYCODE_EQUALS,BracketLeft:o.KEYCODE_LEFT_BRACKET,BracketRight:o.KEYCODE_RIGHT_BRACKET,Backslash:o.KEYCODE_BACKSLASH,Semicolon:o.KEYCODE_SEMICOLON,Quote:o.KEYCODE_APOSTROPHE,Comma:o.KEYCODE_COMMA,Period:o.KEYCODE_PERIOD,Slash:o.KEYCODE_SLASH,Space:o.KEYCODE_SPACE,Tab:o.KEYCODE_TAB,Escape:o.KEYCODE_ESCAPE,ArrowUp:o.DPAD_UP,ArrowDown:o.DPAD_DOWN,ArrowLeft:o.DPAD_LEFT,ArrowRight:o.DPAD_RIGHT,Enter:o.ENTER,Backspace:o.DEL,Delete:o.FORWARD_DEL,Home:o.KEYCODE_MOVE_HOME,End:o.KEYCODE_MOVE_END,PageUp:o.KEYCODE_PAGE_UP,PageDown:o.KEYCODE_PAGE_DOWN,Insert:o.KEYCODE_INSERT,F1:o.KEYCODE_F1,F2:o.KEYCODE_F2,F3:o.KEYCODE_F3,F4:o.KEYCODE_F4,F5:o.KEYCODE_F5,F6:o.KEYCODE_F6,F7:o.KEYCODE_F7,F8:o.KEYCODE_F8,F9:o.KEYCODE_F9,F10:o.KEYCODE_F10,F11:o.KEYCODE_F11,F12:o.KEYCODE_F12,ShiftLeft:o.KEYCODE_SHIFT_LEFT,ShiftRight:o.KEYCODE_SHIFT_RIGHT,ControlLeft:o.KEYCODE_CTRL_LEFT,ControlRight:o.KEYCODE_CTRL_RIGHT,AltLeft:o.KEYCODE_ALT_LEFT,AltRight:o.KEYCODE_ALT_RIGHT,MetaLeft:o.KEYCODE_META_LEFT,MetaRight:o.KEYCODE_META_RIGHT,ContextMenu:o.MENU,Numpad0:o.KEYCODE_NUMPAD_0,Numpad1:o.KEYCODE_NUMPAD_1,Numpad2:o.KEYCODE_NUMPAD_2,Numpad3:o.KEYCODE_NUMPAD_3,Numpad4:o.KEYCODE_NUMPAD_4,Numpad5:o.KEYCODE_NUMPAD_5,Numpad6:o.KEYCODE_NUMPAD_6,Numpad7:o.KEYCODE_NUMPAD_7,Numpad8:o.KEYCODE_NUMPAD_8,Numpad9:o.KEYCODE_NUMPAD_9,NumpadDivide:o.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:o.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:o.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:o.KEYCODE_NUMPAD_ADD,NumpadDecimal:o.KEYCODE_NUMPAD_DOT,NumpadComma:o.KEYCODE_NUMPAD_COMMA,NumpadEnter:o.KEYCODE_NUMPAD_ENTER,NumpadEqual:o.KEYCODE_NUMPAD_EQUALS};function Yt(t,e,r,c,f,d,l=1,h=0,O=0){const C=new ArrayBuffer(32),A=new DataView(C);let w=0;A.setUint8(w,Pe.INJECT_TOUCH_EVENT),w+=1;const U=t===ke.ACTION_POINTER_DOWN?ke.ACTION_DOWN:t===ke.ACTION_POINTER_UP?ke.ACTION_UP:t;return A.setUint8(w,U),w+=1,A.setBigInt64(w,BigInt(e),!0),w+=8,A.setInt32(w,Math.round(f),!0),w+=4,A.setInt32(w,Math.round(d),!0),w+=4,A.setUint16(w,r,!0),w+=2,A.setUint16(w,c,!0),w+=2,A.setInt16(w,Math.round(l*65535),!0),w+=2,A.setInt32(w,h,!0),w+=4,A.setInt32(w,O,!0),C}function tn(t,e,r,c,f,d,l){const h=new ArrayBuffer(24),O=new DataView(h);let C=0;return O.setUint8(C,Pe.INJECT_TWO_FINGER_TOUCH_EVENT),C+=1,O.setUint8(C,t),C+=1,O.setInt32(C,Math.round(c),!0),C+=4,O.setInt32(C,Math.round(f),!0),C+=4,O.setInt32(C,Math.round(d),!0),C+=4,O.setInt32(C,Math.round(l),!0),C+=4,O.setUint16(C,e,!0),C+=2,O.setUint16(C,r,!0),C+=2,O.setUint16(C,0,!0),h}function bt(t,e=!0){const c=new TextEncoder().encode(t),f=new ArrayBuffer(14+c.length),d=new DataView(f);let l=0;return d.setUint8(l,Pe.SET_CLIPBOARD),l+=1,d.setBigInt64(l,BigInt(0),!1),l+=8,d.setUint8(l,e?1:0),l+=1,d.setUint32(l,c.length,!1),l+=4,new Uint8Array(f,l).set(c),f}function Xe(t,e,r=0,c=0){const f=new ArrayBuffer(14),d=new DataView(f);let l=0;return d.setUint8(l,Pe.INJECT_KEYCODE),l+=1,d.setUint8(l,t),l+=1,d.setInt32(l,e,!0),l+=4,d.setInt32(l,r,!0),l+=4,d.setInt32(l,c,!0),f}const nn={width:164.6,height:117.8,depth:5.2};function rn(t,e,r){return t=Math.max(0,Math.min(1,t)),e=Math.max(0,Math.min(1,e)),r===1?{x:e,y:1-t}:r===2?{x:1-t,y:1-e}:r===3?{x:1-e,y:t}:{x:t,y:e}}function on(t){return Number.isFinite(t)&&t>=0&&t<=180}function an(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function sn(t,e,r){return e&&(t||!r)?"touch":t?"ignore":"orbit"}function Nt(t,e,r,c){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(r)||!Number.isFinite(c)||r<0||r>1||c<0||c>1)throw new RangeError("Invalid display touch coordinates");const f=new ArrayBuffer(12),d=new DataView(f);return d.setUint8(0,19),d.setUint8(1,t),d.setUint8(2,e),d.setFloat32(4,r,!0),d.setFloat32(8,c,!0),f}class cn{constructor(e,r){this.send=e,this.failed=r}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!on(e)||(this.latest=e,this.flush())}stop(){this.stopped=!0,this.latest=void 0}async flush(){if(!(this.running||this.stopped)){this.running=!0;try{for(;this.latest!==void 0&&!this.stopped;){const e=this.latest;this.latest=void 0,await this.send(e)}}catch(e){this.latest=void 0,this.stopped||this.failed(e)}finally{this.running=!1}}}}const ln={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class dn{constructor(e,r){this.send=e,this.failed=r}send;failed;held;tail=Promise.resolve();timeout;press(e){this.held||(this.held=e,this.enqueue(e,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const e=this.held;this.held=void 0,this.enqueue(e,!1)}enqueue(e,r){this.tail=this.tail.then(()=>this.send(e,r)).catch(this.failed)}}const ze="Accessibility unavailable on this device.",Qe=500,Rt=(t,e)=>Math.abs(t.x-e.x)<.5&&Math.abs(t.y-e.y)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5,un=t=>Math.max(0,t.width)*Math.max(0,t.height),En=t=>{const e=t.find(r=>r.frame&&r.frame.width>0&&r.frame.height>0);return e?.frame?((Math.abs(e.frame.x)>.5||Math.abs(e.frame.y)>.5)&&console.warn(`[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.`),{x:0,y:0,width:e.frame.width,height:e.frame.height}):{x:0,y:0,width:1,height:1}},fn=t=>{const e={};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},hn=t=>{const e={};for(const[r,c]of Object.entries(t))r!=="children"&&(e[r]=c);return e};function It(t){const e=Array.isArray(t)?t:[t],r=En(e),c=[],f=(d,l)=>{if(c.length>=Qe)return;const h=d.frame;if(h&&h.width>0&&h.height>0&&!Rt(h,r)){const C=d.role_description||d.role||"",A=(typeof d.AXLabel=="string"?d.AXLabel:"")||(typeof d.title=="string"?d.title:"")||"";c.push({id:typeof d.AXUniqueId=="string"&&d.AXUniqueId.length>0?d.AXUniqueId:l,path:l,label:A,value:typeof d.AXValue=="string"?d.AXValue:"",role:C,type:typeof d.type=="string"?d.type:"",enabled:d.enabled!==!1,focused:d.focused===!0,frame:{x:h.x,y:h.y,width:h.width,height:h.height},selectors:fn(d),raw:hn(d)})}const O=Array.isArray(d.children)?d.children:[];for(let C=0;C<O.length&&c.length<Qe;C++)f(O[C],`${l}.${C}`)};for(let d=0;d<e.length&&c.length<Qe;d++)f(e[d],String(d));return{platform:"ios",screen:{width:r.width,height:r.height},elements:c,capturedAt:Date.now()}}const mn=t=>{let e={x:0,y:0,width:1,height:1},r=0;for(const c of t){const f=c.parsedBounds;if(!f)continue;const d=f.right-f.left,l=f.bottom-f.top,h=Math.max(0,d)*Math.max(0,l);h>r&&(r=h,e={x:0,y:0,width:d,height:l})}return e},pn=t=>{const e={};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};function kt(t){const e=mn(t),r=[];for(let c=0;c<t.length&&r.length<Qe;c++){const f=t[c],d=f.parsedBounds;if(!d)continue;const l=Math.max(0,d.right-d.left),h=Math.max(0,d.bottom-d.top);if(l<=0||h<=0)continue;const O={x:d.left,y:d.top,width:l,height:h};if(Rt(O,{x:0,y:0,width:e.width,height:e.height}))continue;const C=f.contentDesc||f.text||"",A=f.className||"";r.push({id:f.resourceId&&f.resourceId.length>0?f.resourceId:f.contentDesc&&f.contentDesc.length>0?`cd:${f.contentDesc}`:String(c),path:String(c),label:C,value:typeof f.text=="string"?f.text:"",role:A,type:A,enabled:f.enabled!==!1,focused:f.focused===!0,frame:O,selectors:pn(f),raw:{...f}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:r,capturedAt:Date.now()}}function Cn(t,e){const r=Math.max(0,t.x),c=Math.max(0,t.y),f=Math.min(e.width,t.x+t.width),d=Math.min(e.height,t.y+t.height),l=Math.max(0,f-r),h=Math.max(0,d-c);return l>0&&h>0?{x:r,y:c,width:l,height:h}:null}function Ut(t,e){if(t===e)return!0;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;const r=t.frame,c=e.frame;return r.x===c.x&&r.y===c.y&&r.width===c.width&&r.height===c.height}function Pt(t,e){if(t===e)return!0;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;for(let r=0;r<t.elements.length;r++)if(!Ut(t.elements[r],e.elements[r]))return!1;return!0}function On(t,e,r){let c=null,f=1/0;for(const d of t.elements){const l=d.frame;if(e<l.x||r<l.y||e>l.x+l.width||r>l.y+l.height)continue;const h=un(l);h<f&&(f=h,c=d)}return c}function Dn(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const r=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${r} })`}return null}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}function Lt(t){const e=t.role||t.type||"";if(!e)return"element";let r=e.replace(/^AX/,"");return r.includes(".")&&(r=r.split(".").pop()),r==="GenericElement"?"Element":(r=r.replace(/([a-z])([A-Z])/g,"$1 $2"),r)}const St=80;function _n(t){const e=Lt(t),r=t.label||t.value||"";if(!r)return e;const c=r.length>St?r.slice(0,St).trimEnd()+"…":r;return`${e} · ${c}`}const gn=500,Tn=2e3,yt=5e3,Sn=8e3,yn=1200,vn=250,An=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class Kn{platform;send;onSnapshot;onStatusChange;baseIntervalMs;maxBackoffMs;androidElementTreeOptions;pending=new Map;running=!1;timer;currentInterval;lastSnapshot=null;inflight=!1;lastBumpAtMs=0;boostUntilMs=0;status="idle";constructor(e){this.platform=e.platform,this.send=e.send,this.onSnapshot=e.onSnapshot,this.onStatusChange=e.onStatusChange,this.baseIntervalMs=e.baseIntervalMs??gn,this.maxBackoffMs=e.maxBackoffMs??Tn,this.androidElementTreeOptions=e.androidElementTreeOptions,this.currentInterval=this.baseIntervalMs}start(){this.running||(this.running=!0,this.currentInterval=this.baseIntervalMs,this.boostUntilMs=0,this.setStatus("starting"),this.runOnce())}stop(){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))}getStatus(){return this.status}setStatus(e,r){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,r)}catch(c){console.error("[AxFetcher] onStatusChange threw:",c)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+yn;const r=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<r){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=e,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const e=await this.requestOnce();return this.running&&this.deliver(e),e}getLatest(){return this.lastSnapshot}handleMessage(e){if(!e||typeof e.id!="string")return!1;const r=e.id;if(!this.pending.get(r))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const h=typeof e.error=="string"?e.error:null;if(h)return this.settleReject(r,new Error(h)),!0;const O=typeof e.json=="string"?e.json:"";try{const C=JSON.parse(O),A=It(C);this.settleResolve(r,A)}catch(C){this.settleReject(r,C instanceof Error?C:new Error(String(C)))}return!0}if(e.type!=="getElementTreeResult")return!1;const f=e.error;if(f&&typeof f=="object"){const h=typeof f.message=="string"?f.message:"getElementTree failed";return this.settleReject(r,new Error(h)),!0}const d=e.payload,l=Array.isArray(d?.nodes)?d.nodes:[];try{const h=kt(l);this.settleResolve(r,h)}catch(h){this.settleReject(r,h instanceof Error?h:new Error(String(h)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=An();return new Promise((r,c)=>{const f=window.setTimeout(()=>{this.pending.delete(e),c(new Error("elementTree request timed out"))},Sn+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:r,reject:c,timer:f}),this.send(this.buildRequest(e))||(window.clearTimeout(f),this.pending.delete(e),c(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const r=e instanceof Error?e.message:String(e),c=/unavailable|not (yet )?running|failed|timeout/i.test(r);this.currentInterval=c?yt:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(c?"unavailable":"error",r)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const r=this.lastSnapshot;if(Pt(r,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(ze)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(ze)?(this.currentInterval=yt,this.setStatus("unavailable",ze)):this.setStatus("ready"),this.onSnapshot(e)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const e=Date.now()<this.boostUntilMs?Math.min(vn,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,r){const c=this.pending.get(e);c&&(window.clearTimeout(c.timer),this.pending.delete(e),c.resolve(r))}settleReject(e,r){const c=this.pending.get(e);c&&(window.clearTimeout(c.timer),this.pending.delete(e),c.reject(r))}failAllPending(e){for(const[r,c]of this.pending.entries())window.clearTimeout(c.timer),c.reject(new Error(e)),this.pending.delete(r)}}function vt(t,e){if(e!=null&&(!Number.isFinite(e)||e<0||e>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in t))return;const r=e??null;try{t.jitterBufferTarget!==r&&(t.jitterBufferTarget=r)}catch(c){console.warn("RemoteControl: could not set the jitter buffer target.",c)}}const Ft=`(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())}})();
|
|
2
|
+
`,At=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Ft],{type:"text/javascript;charset=utf-8"});function Mn(t){let e;try{if(e=At&&(self.URL||self.webkitURL).createObjectURL(At),!e)throw"";const r=new Worker(e,{name:t?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ft),{name:t?.name})}}function wn(t,e,r){const{MediaStreamTrackProcessor:c,MediaStreamTrackGenerator:f}=globalThis,d=e.getVideoTracks()[0];let l,h,O,C,A=!1;const w=()=>{A||(A=!0,l?.stop(),h?.stop(),O&&(O.postMessage({type:"stop"}),C=setTimeout(()=>O?.terminate(),1e3)))},U=b=>{t.srcObject=b,t.play().catch(()=>{})},T=b=>{A||(w(),r(b),U(e))};try{if(d&&c&&f){l=d.clone();const b=new c({track:l,maxBufferSize:1}),$=new f({kind:"video"});h=$,O=new Mn,O.onmessage=({data:F})=>{F.type==="error"?T(new Error(F.message)):F.type==="stopped"&&(clearTimeout(C),O?.terminate())},O.onerror=F=>T(new Error(F.message)),O.postMessage({type:"start",readable:b.readable,writable:$.writable},[b.readable,$.writable]),U(new MediaStream(e.getTracks().map(F=>F===d?$:F)))}else U(e)}catch(b){T(b)}return w}function Ue(t){return typeof t=="number"&&Number.isFinite(t)}function Te(t,e){if(!(!Ue(t)||!Ue(e)||t<e||e<0))return t-e}class Yn{previous=new Map;reset(){this.previous.clear()}read(e,r,c){const f={timestamp:0,video:[],audio:[]};c==null?f.requestedTargetMs=null:Ue(c)&&c>=0&&c<=4e3&&(f.requestedTargetMs=c);const d=new Map;return e.forEach(l=>{if(l.type!=="inbound-rtp"||!Ue(l.timestamp))return;const h=l.kind??l.mediaType;if(h!=="video"&&h!=="audio")return;const O=r.filter(Y=>Y.kind===h),C=l.trackIdentifier?O.find(Y=>Y.trackId===l.trackIdentifier):l.mid!=null?O.find(Y=>Y.mid===l.mid):O.length===1?O[0]:void 0;if(!C)return;const A=this.previous.get(l.id),U=A?.trackId===C.trackId&&A.stats.ssrc===l.ssrc?A.stats:void 0,T=U?l.timestamp-U.timestamp:void 0,b={id:l.id,trackId:C.trackId,timestamp:l.timestamp};if(T!==void 0&&T>0){b.intervalMs=T;const Y=Te(l.jitterBufferEmittedCount,U?.jitterBufferEmittedCount),L=Te(l.jitterBufferDelay,U?.jitterBufferDelay);Y!==void 0&&Y>0&&L!==void 0&&(b.bufferDelayMs=L/Y*1e3);const H=Te(l.bytesReceived,U?.bytesReceived);H!==void 0&&(b.bitrateBps=H*8e3/T)}if(h==="video"){const Y={...b,display:C.display??"primary"};if(b.intervalMs!==void 0){const L=Te(l.framesDecoded,U?.framesDecoded);L!==void 0&&(Y.fps=L*1e3/b.intervalMs),Y.droppedFrames=Te(l.framesDropped,U?.framesDropped),Y.freezes=Te(l.freezeCount,U?.freezeCount)}f.video.push(Y)}else f.audio.push(b);f.timestamp=Math.max(f.timestamp,l.timestamp),d.set(l.id,U&&l.timestamp<=U.timestamp?A:{stats:l,trackId:C.trackId});const $=l.transportId?e.get(l.transportId):void 0,F=$?.selectedCandidatePairId?e.get($.selectedCandidatePairId):void 0;F?.state==="succeeded"&&Ue(F.currentRoundTripTime)&&F.currentRoundTripTime>=0&&(f.rttMs=F.currentRoundTripTime*1e3)}),this.previous=d,f.video.length||f.audio.length?f:null}}const at=new WeakSet;function bn(t,e,r){const{peer:c,displays:f}=t,d=new Yn;let l,h=!1,O=!1,C=!1,A=0,w=!1,U=!1;const T=()=>!h&&!document.hidden&&c.connectionState==="connected",b=L=>{if(!(!L&&!w)){w=L!==null;try{e()?.(L)}catch(H){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',H)}}},$=()=>{O=!1,A++,clearTimeout(l),d.reset(),b(null)},F=async()=>{if(C||!T())return;if(at.has(c)){l=setTimeout(()=>{F()},2e3);return}C=!0,at.add(c);const L=A;try{const H=await c.getStats();if(L!==A||!T())return;const B=c.getTransceivers().filter(j=>(j.currentDirection==="recvonly"||j.currentDirection==="sendrecv")&&j.receiver.track.readyState!=="ended").map(j=>({trackId:j.receiver.track.id,kind:j.receiver.track.kind,mid:j.mid,display:f.get(j.receiver)}));b(d.read(H,B,r())),U=!1}catch(H){if(L!==A||!T())return;U||console.warn("[RemoteControl] could not read playback stats:",H),U=!0,d.reset(),b(null)}finally{C=!1,at.delete(c),O&&T()&&(l=setTimeout(()=>{F()},L===A?2e3:0))}},Y=()=>{if(!T()){$();return}O||(O=!0,F())};return document.addEventListener("visibilitychange",Y),c.addEventListener("connectionstatechange",Y),Y(),()=>{h=!0,document.removeEventListener("visibilitychange",Y),c.removeEventListener("connectionstatechange",Y),$()}}function Nn(t,e){const r=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let c=!1,f=!1,d=0;return r.onmessage=l=>{if(f)return;let h;try{h=JSON.parse(l.data)}catch(O){console.warn("Invalid latency trace message",O);return}h&&typeof h=="object"&&!Array.isArray(h)&&e(h)},r.onclose=()=>{f=!0,c=!1},{accept(l){c=!f&&l===1},wrap(l){if(!c||l.byteLength!==32)return l;const h=new DataView(l);if(h.getUint8(0)!==2||h.getUint8(1)>2)return l;const O=new ArrayBuffer(38),C=new DataView(O);return C.setUint8(0,240),C.setUint8(1,1),C.setUint32(2,++d,!0),new Uint8Array(O,6).set(new Uint8Array(l)),O},close(){f=!0,c=!1,r.onmessage=null,r.onclose=null,r.close()}}}class Rn{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const r=++this.generation;return this.append(r,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,r){const c={generation:e,isCurrent:()=>e===this.generation},f=this.tail.then(()=>r(c));return this.tail=f.catch(()=>{}),f}invalidate(){++this.generation}}function In(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const r={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(r.facingMode=e.facingMode),r}function kn(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function Un(t,e){return!t||t.facingMode!==e.facingMode}function Pn(t){const e=t.getSettings();return{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,label:t.label||void 0,facingMode:e.facingMode}}function Ln(t){return{type:"cameraResult",granted:!0,camera:Pn(t)}}const ae=(...t)=>{window.debugRemoteControl&&console.log(...t)},S=(...t)=>{window.debugRemoteControl&&console.warn(...t)},P=(t,e,...r)=>{if(e)try{e(...r)}catch(c){console.error(`[RemoteControl] customer callback "${t}" threw:`,c)}},Bt=t=>t.includes("/android_")?"android":"ios",Kt=(t,e)=>{const r=new URL(t);return r.searchParams.set("token",e),r.toString()},st=3,Fn=1e3,Bn=15e3,xn=3e3,Wn=4e3;function Mt(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function qn(t){let e={...t};const{url:r,token:c,deviceModel:f}=e,d=e.sessionId??Mt(),l=e.platform??Bt(r??"");let h={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const O=n=>{h={...h,...n},P("onStateChange",e.onStateChange,h)},C=n=>O({videoReady:n}),A=n=>O({duoState:n}),w=n=>O({duoError:n}),U=n=>O({duo:n}),T=n=>ae(n);let b=null,$;const F=()=>{$?.(),$=b&&e.onPlaybackStats?bn(b,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},Y=new Map,L=new Set,H=new Set,B=new Map;let j=!1;const Se=new Map,ct=(n,u,a)=>{u.stop?.(),u.stop=wn(n,a,s=>S("Video playback fallback:",s))},xt=()=>{Se.clear();for(const[n,u]of Y)u.clear?.(),u.stop?.(),u.stop=void 0,n.srcObject=null};let fe=!1,ye=!1,Le=0,_=null,N=null,x=null,Fe=null,he,ve,Ae,Be,me,le=0,xe=0,ne=!1,de=null,Q=null,ue;const Ze=new Rn;let Ke=null,We=null,et=e.microphoneEnabled??!1,tt=!1,Me=null,te=null,qe=0,lt=Promise.resolve(),pe=null,we=!1,re=new Map,ee=new Map,se=new Map,ie=new Map,q=null,Ye=null,dt=0;const Ve=n=>{if(n===null&&Ye===null)return;Ye=n;const u=++dt;queueMicrotask(()=>{u===dt&&P("onAxSnapshotChange",e.onAxSnapshotChange,n)})};let Ce=null,Ee=new Map;const be=(n,u)=>new Promise((a,s)=>{const y=_;if(!y||y.readyState!==WebSocket.OPEN){s(new Error("Simulator disconnected"));return}const m=Mt(),p=setTimeout(()=>{Ee.delete(m),s(new Error("Device control timed out"))},5e3);Ee.set(m,{resolve:a,reject:s,timer:p});try{y.send(JSON.stringify({type:n,id:m,...u})),q?.bumpActivity()}catch(E){clearTimeout(p),Ee.delete(m),s(E)}});let Oe;const ut=()=>{if(Oe)return Oe;const n=be("getFoldState",{}).then(()=>{if(!h.duoState)throw new Error("This instance does not support native iPhone Duo displays.")}).finally(()=>{Oe===n&&(Oe=void 0)});return Oe=n,n},De=n=>{Ce!==n&&(Ce=n,O({connection:n}),P("onConnectionStateChange",e.onConnectionStateChange,n))},ce=n=>{!x||x.readyState!=="open"||(x.send(Fe?.wrap(n)??n),q?.bumpActivity())},Wt=()=>{_&&_.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"keepAlive",sessionId:d}))},Et=()=>{he&&window.clearInterval(he),he=window.setInterval(Wt,1e4)},Ne=()=>{he&&(window.clearInterval(he),he=void 0)},$e=()=>{ve&&(window.clearTimeout(ve),ve=void 0)},He=()=>{Ae&&(window.clearTimeout(Ae),Ae=void 0)},Re=()=>{Be&&(window.clearInterval(Be),Be=void 0)},Ie=()=>{me!==void 0&&(window.clearTimeout(me),me=void 0)},qt=()=>{we||(we=!0,Re(),C(!0),De("connected"))},G=n=>{for(const u of n.getTracks())try{u.stop()}catch(a){S("track.stop() failed:",a)}},Vt=()=>{const n=Q;n&&(Q=null,G(n))},ft=n=>{const u=lt.then(n).catch(a=>{S("microphone operation failed:",a)});return lt=u,u},nt=()=>et||tt,ht=n=>{const u=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;pe=u,n.send(JSON.stringify({type:"microphoneStart",id:u}))},rt=()=>ft(()=>$t()),$t=async()=>{const n=qe,u=()=>n===qe&&nt(),a=E=>{P("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:E})};if(!u())return;const s=_,y=Me;if(!s||s.readyState!==WebSocket.OPEN||!y||te)return;if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){console.warn("[RemoteControl] navigator.mediaDevices.getUserMedia unavailable. getUserMedia requires a secure context (https or http://localhost)."),a("Microphone capture requires a secure context (https)");return}let m=null;try{m=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(E){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",E)}if(!u()){m&&G(m);return}if(!m){a("Microphone permission denied or no device available");return}const p=m.getAudioTracks()[0]??null;if(!p){G(m),a("Captured stream has no audio track");return}try{await y.replaceTrack(p)}catch(E){S("replaceTrack(audioTrack) failed:",E),G(m),a("Failed to attach the microphone track to the connection");return}if(!u()){try{await y.replaceTrack(null)}catch(E){S("replaceTrack(null) on stale mic attach failed:",E)}G(m);return}te=m,p.onended=()=>{te===m&&Ge("microphone capture ended by the browser")},ht(s),P("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:p.label||void 0})},Ge=n=>(++qe,pe=null,ft(async()=>{const u=Me,a=te;if(te=null,u&&a)try{await u.replaceTrack(null)}catch(y){S("replaceTrack(null) on mic detach failed:",y)}a&&G(a);const s=_;if(a&&s&&s.readyState===WebSocket.OPEN){const y=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;s.send(JSON.stringify({type:"microphoneStop",id:y}))}(a||n)&&P("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...n!==void 0&&{error:n}})})),mt=(n,u)=>{let a;try{a=Ln(u),console.info(`[RemoteControl] camera capture: ${a.camera?.width}x${a.camera?.height} @ ${a.camera?.frameRate??"?"}fps`+(a.camera?.label?` — ${a.camera.label}`:""))}catch(s){S("getSettings() on outbound camera track failed:",s),a={type:"cameraResult",granted:!0,camera:{label:u.label||void 0}}}n.send(JSON.stringify(a)),P("onCameraDemandChange",e.onCameraDemandChange,!0,!0,a.camera)},Ht=n=>{if(!n)return;const u=n.indexOf("/"),s=(u>=0?n.slice(u+1):n).toUpperCase();return s==="HEVC"?"H265":s},Gt=async()=>{const n=de,u=e.onCameraStats;if(!n||!u)return;let a;try{a=await n.getStats()}catch{return}let s,y,m;if(a.forEach(R=>{R.type==="outbound-rtp"&&R.kind==="video"?s=R:R.type==="remote-inbound-rtp"&&R.kind==="video"&&(m=R)}),s?.codecId){const R=a.get(s.codecId);R&&(y=R.mimeType)}if(!s)return;const p=s.timestamp??Date.now(),E=We;let V,k,X;if(E&&p>E.timestamp){const R=(p-E.timestamp)/1e3;if(typeof s.framesEncoded=="number"&&typeof E.framesEncoded=="number"&&(V=Math.max(0,(s.framesEncoded-E.framesEncoded)/R)),typeof s.bytesSent=="number"&&typeof E.bytesSent=="number"&&(k=Math.max(0,(s.bytesSent-E.bytesSent)*8/R)),typeof s.packetsSent=="number"&&typeof E.packetsSent=="number"&&m&&typeof m.packetsLost=="number"&&typeof E.packetsLost=="number"){const v=s.packetsSent-E.packetsSent,je=m.packetsLost-E.packetsLost;v>0&&(X=Math.max(0,Math.min(100,je/v*100)))}}We={timestamp:p,framesEncoded:s.framesEncoded,bytesSent:s.bytesSent,packetsSent:s.packetsSent,packetsLost:m?.packetsLost};const M={codec:Ht(y),encoderImplementation:s.encoderImplementation,hardwareAccelerated:typeof s.powerEfficientEncoder=="boolean"?s.powerEfficientEncoder:void 0,framesPerSecond:V,framesEncoded:s.framesEncoded,bitrateBps:k,width:s.frameWidth,height:s.frameHeight,qualityLimitationReason:s.qualityLimitationReason,rttMs:typeof m?.roundTripTime=="number"?m.roundTripTime*1e3:void 0,packetsLostPct:X};P("onCameraStats",e.onCameraStats,M)},pt=()=>{Ke===null&&(We=null,Ke=setInterval(()=>{Gt()},1e3))},Je=()=>{Ke!==null&&(clearInterval(Ke),Ke=null),We=null,P("onCameraStats",e.onCameraStats,null)},Jt=(n,u,a,s)=>Ze.enqueue(async({isCurrent:y})=>{const m=()=>y()&&s()&&_===u&&de===a;if(!m())return;if(!n.active){const M=Q;try{await a.replaceTrack(null)}catch(R){S("replaceTrack(null) on camera detach failed:",R)}if(Q===M&&(Q=null,ue=void 0,M&&G(M)),Je(),!m())return;P("onCameraDemandChange",e.onCameraDemandChange,!1);return}P("onCameraDemandChange",e.onCameraDemandChange,!0);const p=Q,E=p?.getVideoTracks()[0],V=ue;if(E?.readyState==="live"&&V&&!Un(V,n)){ue=n,mt(u,E),pt();return}if(p){try{await a.replaceTrack(null)}catch(M){S("replaceTrack(null) before camera switch failed:",M)}if(Q===p&&(Q=null,ue=void 0,G(p)),Je(),!m())return}if(!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!="function"){if(console.warn("[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."),!m())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),P("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let k=null;try{k=await navigator.mediaDevices.getUserMedia({video:kn(n),audio:!1})}catch(M){console.warn("[RemoteControl] getUserMedia denied/failed:",M)}if(!m()){k&&G(k);return}if(!k){u.send(JSON.stringify({type:"cameraResult",granted:!1})),P("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const X=k.getVideoTracks()[0]??null;if(!X){if(G(k),!m())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),P("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{X.contentHint="motion"}catch{}try{await a.replaceTrack(X)}catch(M){if(S("replaceTrack(videoTrack) failed:",M),G(k),!m())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),P("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!m()){try{await a.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera attach failed:",M)}G(k);return}try{const M=a.getParameters();(!M.encodings||M.encodings.length===0)&&(M.encodings=[{}]),M.encodings[0].maxBitrate=8e6,M.encodings[0].maxFramerate=30,M.degradationPreference="maintain-framerate",await a.setParameters(M)}catch(M){S("setParameters on outbound camera failed:",M)}if(!m()){try{await a.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera finalize failed:",M)}G(k);return}Q=k,ue=n,X.onended=()=>{Q===k&&Ze.enqueueCurrent(async({isCurrent:M})=>{if(!(!M()||Q!==k||!s()||_!==u||de!==a)){try{await a.replaceTrack(null)}catch(R){S("replaceTrack(null) after camera ended failed:",R)}!M()||Q!==k||!s()||_!==u||de!==a||(Q=null,ue=void 0,G(k),Je(),u.send(JSON.stringify({type:"cameraResult",granted:!1})),P("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(M=>S("camera ended cleanup failed:",M))},m()&&(mt(u,X),pt())}),_e=()=>{for(const n of H)n();H.clear();for(const n of B.values())clearTimeout(n);B.clear();for(const n of ee.values())n(new Error("Simulator disconnected"));for(const n of ie.values())n(new Error("Simulator disconnected"));ee.clear(),re.clear(),ie.clear(),se.clear(),$?.(),$=void 0,xt(),b=null;for(const n of Ee.values())clearTimeout(n.timer),n.reject(new Error("Simulator disconnected"));Ee.clear(),Oe=void 0,A(null),O({controlReady:!1,videoReady:!1}),He(),Ie(),Re(),q&&(q.stop(),q=null),Ye!==null&&Ve(null),Ze.invalidate(),Je(),Vt(),ue=void 0,de=null,++qe,tt=!1,pe=null,te&&(G(te),te=null,P("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),Me=null,_&&(_.onopen=null,_.onmessage=null,_.onerror=null,_.onclose=null,_.close(),_=null),Fe?.close(),Fe=null,N&&(N.onconnectionstatechange=null,N.oniceconnectionstatechange=null,N.ontrack=null,N.onicecandidate=null,N.close(),N=null),x&&(x.onopen=null,x.onclose=null,x.onerror=null,x.close(),x=null)},Ct=()=>{document.hidden?Ne():Et()},jt=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let n;try{const s=new URL(r);s.protocol=s.protocol==="wss:"?"https:":s.protocol==="ws:"?"http:":s.protocol,n=Kt(s.toString(),c)}catch{return!1}const u=new AbortController,a=window.setTimeout(()=>u.abort(),Wn);try{return(await fetch(n,{method:"GET",cache:"no-store",signal:u.signal})).status===404}catch{return!1}finally{window.clearTimeout(a)}},Xt=()=>{fe||(fe=!0,le+=1,$e(),He(),Ie(),_e(),T("Instance terminated"),Ne(),De("terminated"),P("onTerminated",e.onTerminated))},zt=()=>{if(fe||ye)return;ye=!0;const n=Le;jt().catch(()=>!1).then(u=>{n===Le&&(ye=!1,u&&Xt())})},ge=(n,u)=>{if(fe||u!==le)return;if(zt(),ne){if(!e.autoReconnect){T(`Connection failed after it was established: ${n}`),Ne(),De("failed"),_e();return}T(`Reconnecting after established session dropped: ${n}`),ne=!1,xe=-1}$e();const a=xe+1;if(a>=st){T(`Connection failed after ${st} attempts: ${n}`),Ne(),De("failed"),_e();return}T(`Retrying connection (${a+1}/${st})`),De("reconnecting"),_e(),ve=window.setTimeout(()=>{ve=void 0,u===le&&Ot(a)},Fn)},Ot=async(n=0)=>{const{openUrl:u,axPollIntervalMs:a,axMaxBackoffMs:s,androidElementTreeOptions:y}=e;if(fe)return;const m=le+1;le=m,xe=n,ne=!1,n===0&&Ce!=="reconnecting"&&De("connecting"),$e(),He(),Re(),we=!1,C(!1),_e();const p=()=>m===le;Ae=window.setTimeout(()=>{Ae=void 0,!(!p()||ne)&&ge("Connection did not succeed within 15 seconds",m)},Bn);try{const E=e.transport?await e.transport.connect():new WebSocket(Kt(r,c));if(!p()){E.close();return}if(_=E,await new Promise((D,i)=>{let I=!1;const W=()=>K(()=>i(new Error("Connection stopped")));H.add(W);const g=window.setTimeout(()=>K(()=>i(new Error("WebSocket connection timeout"))),3e4),K=Z=>{I||(I=!0,H.delete(W),window.clearTimeout(g),Z())};E.onopen=()=>{!p()||_!==E||K(D)},E.onerror=Z=>{!p()||_!==E||(T("WebSocket error: "+Z),K(()=>i(new Error("WebSocket connection failed"))))},E.onclose=()=>{!p()||_!==E||(T("WebSocket closed"),K(()=>i(new Error("WebSocket closed before connection was established"))))},E.readyState===WebSocket.OPEN?K(D):E.readyState!==WebSocket.CONNECTING&&K(()=>i(new Error("WebSocket is closed")))}),!p()||_!==E)return;E.onerror=D=>{!p()||_!==E||T("WebSocket error: "+D)},E.onclose=()=>{!p()||_!==E||T("WebSocket closed")};const V=new Promise((D,i)=>{let I=!1;const W=()=>g(()=>i(new Error("Connection stopped")));H.add(W);const g=J=>{I||(I=!0,H.delete(W),window.clearTimeout(K),E.removeEventListener("message",Z),J())},K=window.setTimeout(()=>g(()=>i(new Error("RTCConfiguration timeout"))),3e4),Z=J=>{if(!(!p()||_!==E))try{const z=JSON.parse(J.data);if(z.type==="signalingError"&&z.requestType==="requestRtcConfiguration"&&z.sessionId===d){const en=typeof z.error=="string"?z.error:"Unable to load streaming configuration";g(()=>i(new Error(en)))}else z.type==="rtcConfiguration"&&g(()=>D({rtcConfiguration:z.rtcConfiguration,cameraSupported:z.cameraSupported===!0,foldSupported:z.foldSupported===!0}))}catch(z){console.error("Error handling RTC configuration:",z),g(()=>i(z))}};E.addEventListener("message",Z),E.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:d}))}),{rtcConfiguration:k,cameraSupported:X,foldSupported:M}=await V;if(!p()||_!==E)return;const R=f==="iphone-duo"||M;U(R);const v=new RTCPeerConnection({...k,iceTransportPolicy:"relay"});N=v;const je={peer:v,displays:new Map};b=je,F(),v.addTransceiver("audio",{direction:"recvonly"});const Qt=v.addTransceiver("video",{direction:"recvonly"}),Zt=R?v.addTransceiver("video",{direction:"recvonly"}):null,Tt=l==="ios"||X,it=Tt?v.addTransceiver("video",{direction:"sendonly"}):null;if(de=it?.sender??null,Me=(Tt?v.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const D=RTCRtpReceiver.getCapabilities("video");if(D&&D.codecs){const I=D.codecs.sort((W,g)=>{const K=Z=>{const J=Z.mimeType.toLowerCase();return J.includes("vp9")?1:J.includes("h265")||J.includes("hevc")?2:J.includes("h264")||J.includes("avc")?3:4};return K(W)-K(g)});Qt.setCodecPreferences(I),Zt?.setCodecPreferences(I),ae("Set codec preferences:",I.map(W=>W.mimeType).join(", "))}}if(it&&RTCRtpSender.getCapabilities){const D=RTCRtpSender.getCapabilities("video");if(D&&D.codecs){const i=new Set(["42e01f","42e028","640c1f"]),I=g=>{const K=g.mimeType.toLowerCase(),J=(g.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),z=J?J[1]:"";return K==="video/h265"||K==="video/hevc"?1:K==="video/h264"&&i.has(z)?2:K==="video/h264"?3:K==="video/vp9"?4:K==="video/vp8"?5:K==="video/rtx"||K==="video/red"||K==="video/ulpfec"?0:6},W=[...D.codecs].sort((g,K)=>I(g)-I(K));try{it.setCodecPreferences(W),ae("Outbound camera codec preferences:",W.map(g=>`${g.mimeType}${g.sdpFmtpLine?`[${g.sdpFmtpLine}]`:""}`).join(", "))}catch(g){S("Failed to set outbound camera codec preferences:",g)}}}const oe=v.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});x=oe;const ot=!R&&e.onTrace?Nn(v,D=>{p()&&N===v&&P("onTrace",e.onTrace,D)}):null;if(Fe=ot,oe.onopen=()=>{if(!p()||x!==oe||_!==E)return;ne=!0,R&&ut().catch(i=>{p()&&_===E&&E.readyState===WebSocket.OPEN&&w(i instanceof Error?i.message:String(i))}),O({controlReady:!0}),He(),T("Control channel opened"),q||(q=new Kn({platform:l,baseIntervalMs:a,maxBackoffMs:s,androidElementTreeOptions:y,send:i=>{if(!_||_.readyState!==WebSocket.OPEN)return!1;try{return _.send(JSON.stringify(i)),!0}catch{return!1}},onSnapshot:Ve,onStatusChange:(i,I)=>{P("onAxStatusChange",e.onAxStatusChange,i,I)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&q.start());const D=()=>{!p()||we||x!==oe||_!==E||E.readyState!==WebSocket.OPEN||E.send(JSON.stringify({type:"requestFrame",sessionId:d}))};if(D(),Re(),Be=window.setInterval(()=>{if(!p()||we||x!==oe||_!==E||E.readyState!==WebSocket.OPEN){Re();return}D()},250),u){try{const i=decodeURIComponent(u);T("Opening URL"),E.send(JSON.stringify({type:"openUrl",url:i,sessionId:d}))}catch(i){console.error({error:i},"Error decoding URL, falling back to the original URL"),E.send(JSON.stringify({type:"openUrl",url:u,sessionId:d}))}q?.bumpActivity()}},oe.onclose=()=>{!p()||x!==oe||(O({controlReady:!1}),T("Control channel closed"))},oe.onerror=D=>{!p()||x!==oe||(console.error("Control channel error:",D),T("Control channel error: "+D))},v.onconnectionstatechange=()=>{!p()||N!==v||(T("Connection state: "+v.connectionState),v.connectionState==="failed"&&ne&&ge("WebRTC connection entered failed state",m))},v.oniceconnectionstatechange=()=>{if(!p()||N!==v)return;const D=v.iceConnectionState;if(T("ICE state: "+D),D==="connected"||D==="completed"){Ie(),nt()&&!te&&rt();return}if(D==="failed"){Ie(),ne&&ge("ICE connection entered failed state",m);return}D==="disconnected"&&ne&&e.autoReconnect&&me===void 0&&(me=window.setTimeout(()=>{me=void 0,!(!p()||N!==v)&&v.iceConnectionState==="disconnected"&&ge("ICE stayed disconnected past grace period",m)},xn))},v.ontrack=D=>{if(!p()||N!==v)return;vt(D.receiver,e.jitterBufferTargetMs);const i=D.track.id==="duo-inner"||D.streams.some(I=>I.id==="duo-inner");if(D.track.kind==="video"&&je.displays.set(D.receiver,i?"inner":"primary"),T("Received remote track: "+D.track.kind),D.track.kind==="video"){const I=i?"inner":"primary",W=R?new MediaStream([D.track]):D.streams[0]??new MediaStream([D.track]);Se.set(I,W);for(const[g,K]of Y)K.display===I&&ct(g,K,W)}},v.onicecandidate=D=>{if(!(!p()||N!==v||_!==E))if(D.candidate&&E.readyState===WebSocket.OPEN){const i={type:"candidate",candidate:D.candidate.candidate,sdpMid:D.candidate.sdpMid,sdpMLineIndex:D.candidate.sdpMLineIndex,sessionId:d};E.send(JSON.stringify(i)),T("Sent ICE candidate")}else T("ICE candidate gathering completed")},E.onmessage=async D=>{if(!p()||_!==E)return;let i;try{i=JSON.parse(D.data)}catch(I){S("Error parsing message:",I);return}if(!q?.handleMessage(i))switch(T("Received: "+i.type),i.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{R&&i.state&&(A(i.state),w(void 0));const g=Ee.get(i.id);g&&(clearTimeout(g.timer),Ee.delete(i.id),i.error?g.reject(new Error(i.error)):g.resolve());break}case"signalingError":{if(i.requestType!=="offer"||i.sessionId!==d)break;const g=typeof i.error=="string"?i.error:"Unable to establish the streaming connection";T("Error: "+g),ge(g,m);break}case"answer":if(!N||N!==v){T("No peer connection, skipping answer");break}if(ot?.accept(i.latencyTraceVersion),await v.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:i.sdp})),!p()||N!==v)return;T("Set remote description");break;case"candidate":if(!N||N!==v){T("No peer connection, skipping candidate");break}if(await v.addIceCandidate(new RTCIceCandidate({candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex})),!p()||N!==v)return;T("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof i.id!="string"){S("Received invalid screenshot success message:",i);break}const g=Vn(i);if(g){const J=ee.get(i.id);if(typeof J!="function"){S(`Received screenshot error for unknown or handled id: ${i.id}`);break}S(`Received screenshot error for id ${i.id}: ${g}`),J(new Error(g)),re.delete(i.id),ee.delete(i.id),clearTimeout(B.get(i.id)),B.delete(i.id);break}const K=$n(i);if(!K){S("Received screenshot message without image data:",i);break}const Z=re.get(i.id);if(typeof Z!="function"){S(`Received screenshot data for unknown or handled id: ${i.id}`);break}ae(`Received screenshot data for id ${i.id}`),Z(K),re.delete(i.id),ee.delete(i.id),clearTimeout(B.get(i.id)),B.delete(i.id);break}case"screenshotError":if(typeof i.id!="string"||typeof i.message!="string"){S("Received invalid screenshot error message:",i);break}const I=ee.get(i.id);if(typeof I!="function"){S(`Received screenshot error for unknown or handled id: ${i.id}`);break}S(`Received screenshot error for id ${i.id}: ${i.message}`),I(new Error(i.message)),re.delete(i.id),ee.delete(i.id),clearTimeout(B.get(i.id)),B.delete(i.id);break;case"cameraRequest":{const g=de;if(!g)break;const K=In(i);if(!K){S("Received invalid cameraRequest:",i);break}console.info("[RemoteControl] cameraRequest received:",K.active,K.facingMode),await Jt(K,E,g,p);break}case"microphoneRequest":{if(!Me)break;const g=i.active===!0;if(tt=g,console.info("[RemoteControl] microphoneRequest received, active=",g),!g){et||await Ge();break}if(te){ht(E);break}await rt();break}case"microphoneStartResult":{if(pe===null||i.id!==pe)break;pe=null,typeof i.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",i.error),Ge(i.error));break}case"terminateAppResult":if(typeof i.id!="string"){S("Received invalid terminateApp result message:",i);break}if(typeof i.error=="string"){const g=ie.get(i.id);if(typeof g!="function"){S(`Received terminateApp error for unknown or handled id: ${i.id}`);break}S(`Received terminateApp error for id ${i.id}: ${i.error}`),g(new Error(i.error)),se.delete(i.id),ie.delete(i.id),clearTimeout(B.get(i.id)),B.delete(i.id);break}const W=se.get(i.id);if(typeof W!="function"){S(`Received terminateApp result for unknown or handled id: ${i.id}`);break}ae(`Received terminateApp success for id ${i.id}`),W(),se.delete(i.id),ie.delete(i.id),clearTimeout(B.get(i.id)),B.delete(i.id);break;default:S(`Received unhandled message type: ${i.type}`,i);break}},N===v){const D=await v.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!p()||N!==v||(await v.setLocalDescription(D),!p()||N!==v))return;p()&&_===E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"offer",...R?{displayStreams:!0}:{},...ot?{latencyTraceVersion:1}:{},sdp:D.sdp,sessionId:d})),T("Sent offer")}}catch(E){if(!p()||E instanceof Error&&E.message==="Connection stopped")return;const V=E instanceof Error?E.message:String(E);T("Error: "+V),ge(V,m)}},Dt=()=>{if(j)throw new Error("Device stream is disposed");Le++,ye=!1,Ve(null),Ce!=="reconnecting"&&(Ce=null),document.addEventListener("visibilitychange",Ct),document.hidden||Et(),fe=!1,Ot(0)},_t=()=>{Le++,ye=!1,Ne(),document.removeEventListener("visibilitychange",Ct),le+=1,xe=0,ne=!1,$e(),Ie(),_e(),Ce=null,O({connection:"idle",videoReady:!1,controlReady:!1}),T("Stopped")},gt=(n,u="primary")=>{if(j)throw new Error("Device stream is disposed");if(Y.has(n))throw new Error("Video element is already attached");const a={display:u};Y.set(n,a);const s=()=>{u==="primary"&&Se.has(u)&&qt()};n.addEventListener("loadeddata",s);const y=Se.get(u);y&&ct(n,a,y);let m=!1;const p=()=>{m||(m=!0,L.delete(p),n.removeEventListener("loadeddata",s),a.stop?.(),Y.delete(n),n.srcObject=null)};return L.add(p),p};return{start:Dt,stop:_t,attachVideo:gt,attachFrameSink:(n,u="primary")=>{const a=document.createElement("video");a.muted=!0,a.playsInline=!0,a.autoplay=!0;const s=gt(a,u);let y=!1,m=0,p=0;const E=()=>{a.cancelVideoFrameCallback?.(m),cancelAnimationFrame(p)},V=()=>{y||!a.srcObject||(a.readyState>=2&&a.videoWidth>0&&P("present",(...M)=>n.present(...M),a,a.videoWidth,a.videoHeight,u),!(y||!a.srcObject)&&(a.requestVideoFrameCallback?m=a.requestVideoFrameCallback(V):p=requestAnimationFrame(V)))},k=()=>{E(),V()};Y.get(a).clear=E,a.addEventListener("loadeddata",k);const X=()=>{y||(y=!0,L.delete(X),E(),a.removeEventListener("loadeddata",k),s(),a.remove())};return L.delete(s),L.add(X),a.readyState>=2&&k(),X},dispose:()=>{if(!j){j=!0,_t();for(const n of L)n();L.clear()}},getState:()=>h,updateOptions:n=>{if(j)throw new Error("Device stream is disposed");const u=e;if(e={...e,...n},u.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const a of N?.getTransceivers()??[])(a.currentDirection==="recvonly"||a.currentDirection==="sendrecv")&&vt(a.receiver,e.jitterBufferTargetMs);!!u.onPlaybackStats!=!!e.onPlaybackStats&&F(),!!u.microphoneEnabled!=!!e.microphoneEnabled&&(et=e.microphoneEnabled??!1,nt()?rt():Ge()),!!u.inspectMode!=!!e.inspectMode&&(e.inspectMode?q?.start():(q?.stop(),Ye!==null&&Ve(null)))},sendControl:ce,sendTouch:(n,u,a,s,y,m=0)=>ce(Yt(n==="begin"?0:n==="end"?1:2,m,s,y,u,a,n==="end"?0:1)),sendText:n=>ce(bt(n)),sendDisplayTouch:(n,u,a,s)=>ce(Nt(n,u,a,s)),sendDuoControl:be,pressButton:n=>{if(l==="ios"){if(!h.controlReady||n==="back")return;const a=n==="power"?"lock":"home",s=[{type:"buttonDown",button:a},{type:"buttonUp",button:a}],y=n==="recents"?[...s,{type:"wait",durationMs:100},...s]:s;be("performActions",{actions:y}).catch(m=>console.warn("[DeviceStream] Button command failed:",m));return}const u={home:3,back:4,recents:187,power:26}[n];ce(Xe(0,u,0,0)),ce(Xe(1,u,0,0))},rotate:()=>{if(l==="android"){ce(new Uint8Array([11]).buffer);return}if(!h.controlReady)return;if(h.duo){(async()=>{h.duoState||await ut();const p=h.duoState?.orientation;if(!p)throw new Error("Duo orientation unavailable");const E=["portrait","landscape-left","pud","landscape-right"],V=E.indexOf(p);await be("setDuoOrientation",{orientation:E[(V+1)%E.length]})})().catch(p=>console.warn("[DeviceStream] Rotation command failed:",p));return}const n=[...Y].find(([m,p])=>p.display==="primary"&&m.videoWidth>0)?.[0],u=Se.get("primary")?.getVideoTracks()[0]?.getSettings(),a=n?.videoWidth??u?.width??0,s=n?.videoHeight??u?.height??0,y=a>s?"Portrait":"Landscape";be("performActions",{actions:[{type:"setOrientation",orientation:y}]}).catch(m=>console.warn("[DeviceStream] Rotation command failed:",m))},bumpActivity:()=>q?.bumpActivity(),getAxStatus:()=>q?.getStatus()??"idle",openUrl:n=>{if(!_||_.readyState!==WebSocket.OPEN){S("WebSocket not open, cannot send open_url command.");return}try{const u=decodeURIComponent(n);T("Opening URL"),_.send(JSON.stringify({type:"openUrl",url:u,sessionId:d}))}catch(u){S("Error decoding or sending URL :",{error:u,url:n}),_.send(JSON.stringify({type:"openUrl",url:n,sessionId:d}))}q?.bumpActivity()},sendKeyEvent:n=>{if(!x||x.readyState!=="open"){S("Data channel not ready for imperative key command:",x?.readyState);return}const u=wt[n.code];if(!u){S(`Unknown event.code for imperative command: ${n.code}`);return}let a=o.META_NONE;n.shiftKey&&(a|=o.META_SHIFT_ON),n.altKey&&(a|=o.META_ALT_ON),n.ctrlKey&&(a|=o.META_CTRL_ON),n.metaKey&&(a|=o.META_META_ON);const s=n.type==="keydown"?o.ACTION_DOWN:o.ACTION_UP;ae(`Sending Imperative Key Command: code=${n.code}, keycode=${u}, action=${s}, meta=${a}`);const y=Xe(s,u,0,a);y&&ce(y)},screenshot:n=>new Promise((u,a)=>{if(!_||_.readyState!==WebSocket.OPEN)return S("WebSocket not open, cannot send screenshot command."),a(new Error("WebSocket is not connected or connection is not open."));const s=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,y={type:n?"screenshotDisplay":"screenshot",...n?{display:n}:{},id:s};re.set(s,u),ee.set(s,a),ae("Sending screenshot request:",y);try{_.send(JSON.stringify(y))}catch(m){S("Failed to send screenshot request immediately:",m),re.delete(s),ee.delete(s),a(m);return}B.set(s,setTimeout(()=>{B.delete(s),re.has(s)&&(S(`Screenshot request timed out for id ${s}`),ee.get(s)?.(new Error("Screenshot request timed out")),re.delete(s),ee.delete(s))},3e4))}),terminateApp:n=>new Promise((u,a)=>{if(!_||_.readyState!==WebSocket.OPEN)return S("WebSocket not open, cannot send terminateApp command."),a(new Error("WebSocket is not connected or connection is not open."));const s=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,y={type:"terminateApp",id:s,bundleId:n};se.set(s,u),ie.set(s,a),ae("Sending terminateApp request:",y);try{_.send(JSON.stringify(y))}catch(m){S("Failed to send terminateApp request immediately:",m),se.delete(s),ie.delete(s),a(m);return}q?.bumpActivity(),B.set(s,setTimeout(()=>{B.delete(s),se.has(s)&&(S(`terminateApp request timed out for id ${s}`),ie.get(s)?.(new Error("terminateApp request timed out")),se.delete(s),ie.delete(s))},3e4))}),reconnect:()=>Dt(),refreshAxTree:async()=>{const n=q;if(!n)throw new Error("Inspect mode is not active");return n.refresh()},getAxSnapshot:()=>Ye}}const Vn=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,$n=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;exports.AMOTION_EVENT=ke;exports.ANDROID_KEYS=o;exports.AX_UNAVAILABLE_ERROR=ze;exports.CONTROL_MSG_TYPE=Pe;exports.DUO_BUTTONS=ln;exports.DUO_DIMENSIONS=nn;exports.DuoButtonSender=dn;exports.HingeSender=cn;exports.axElementAtPoint=On;exports.axElementRoleLabel=Lt;exports.axElementSelectorExpression=Dn;exports.axElementSummary=_n;exports.axElementsEqual=Ut;exports.axSnapshotsEqual=Pt;exports.clampAxFrameForScreen=Cn;exports.codeMap=wt;exports.createDeviceStream=qn;exports.createDisplayTouchMessage=Nt;exports.createInjectKeycodeMessage=Xe;exports.createSetClipboardMessage=bt;exports.createTouchControlMessage=Yt;exports.createTwoFingerTouchControlMessage=tn;exports.debugLog=ae;exports.debugWarn=S;exports.detectPlatform=Bt;exports.duoPointerMode=sn;exports.flatDisplayTouch=rn;exports.normalizeAndroidTree=kt;exports.normalizeIosTree=It;exports.panelTouch=an;exports.safeInvoke=P;
|
package/dist/core.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./core-D7ODbXln.js");exports.AMOTION_EVENT=e.AMOTION_EVENT;exports.ANDROID_KEYS=e.ANDROID_KEYS;exports.AX_UNAVAILABLE_ERROR=e.AX_UNAVAILABLE_ERROR;exports.CONTROL_MSG_TYPE=e.CONTROL_MSG_TYPE;exports.axElementAtPoint=e.axElementAtPoint;exports.axElementSelectorExpression=e.axElementSelectorExpression;exports.axElementSummary=e.axElementSummary;exports.axElementsEqual=e.axElementsEqual;exports.axSnapshotsEqual=e.axSnapshotsEqual;exports.clampAxFrameForScreen=e.clampAxFrameForScreen;exports.createDeviceStream=e.createDeviceStream;exports.createDisplayTouchMessage=e.createDisplayTouchMessage;exports.createInjectKeycodeMessage=e.createInjectKeycodeMessage;exports.createSetClipboardMessage=e.createSetClipboardMessage;exports.createTouchControlMessage=e.createTouchControlMessage;exports.createTwoFingerTouchControlMessage=e.createTwoFingerTouchControlMessage;exports.normalizeAndroidTree=e.normalizeAndroidTree;exports.normalizeIosTree=e.normalizeIosTree;
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { createDeviceStream, type DeviceStream } from './core/device-stream';
|
|
2
|
+
export type { DeviceStreamOptions, DeviceStreamLiveOptions, DeviceStreamState, DeviceStreamTransport, DeviceFrameSink, StreamDisplay, } from './core/stream-options';
|
|
3
|
+
export type { RemoteControlConnectionState, ImperativeKeyboardEvent, ScreenshotData, MicrophoneState, CameraStreamStats, } from './core/stream-types';
|
|
4
|
+
export type { PlaybackStats, PlaybackVideoStats, PlaybackAudioStats, PlaybackTrackStats, } from './core/playback-stats';
|
|
5
|
+
export type { CameraCaptureInfo, CameraFacingMode, CameraRequest, CameraResult } from './core/camera';
|
|
6
|
+
export type { AxSnapshot, AxElement, AxRect, AxSelectors, AxPlatform } from './core/ax-tree';
|
|
7
|
+
export { axElementAtPoint, axElementSelectorExpression, axElementSummary, axElementsEqual, axSnapshotsEqual, clampAxFrameForScreen, normalizeAndroidTree, normalizeIosTree, AX_UNAVAILABLE_ERROR, } from './core/ax-tree';
|
|
8
|
+
export type { AndroidElementTreeOptions, AxStatus } from './core/ax-fetcher';
|
|
9
|
+
export type { DuoState, DuoOrientation } from './core/duo';
|
|
10
|
+
export { createTouchControlMessage, createTwoFingerTouchControlMessage, createInjectKeycodeMessage, createSetClipboardMessage, } from './core/webrtc-messages';
|
|
11
|
+
export { createDisplayTouchMessage } from './core/duo';
|
|
12
|
+
export { ANDROID_KEYS, AMOTION_EVENT, CONTROL_MSG_TYPE } from './core/constants';
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { t as s, p as r, A as o, C as t, a as c, b as n, c as l, d as m, e as E, f as A, j as T, B as i, o as x, m as S, q as g, u as p, n as u, g as M } from "./core-BqXmROsc.mjs";
|
|
2
|
+
export {
|
|
3
|
+
s as AMOTION_EVENT,
|
|
4
|
+
r as ANDROID_KEYS,
|
|
5
|
+
o as AX_UNAVAILABLE_ERROR,
|
|
6
|
+
t as CONTROL_MSG_TYPE,
|
|
7
|
+
c as axElementAtPoint,
|
|
8
|
+
n as axElementSelectorExpression,
|
|
9
|
+
l as axElementSummary,
|
|
10
|
+
m as axElementsEqual,
|
|
11
|
+
E as axSnapshotsEqual,
|
|
12
|
+
A as clampAxFrameForScreen,
|
|
13
|
+
T as createDeviceStream,
|
|
14
|
+
i as createDisplayTouchMessage,
|
|
15
|
+
x as createInjectKeycodeMessage,
|
|
16
|
+
S as createSetClipboardMessage,
|
|
17
|
+
g as createTouchControlMessage,
|
|
18
|
+
p as createTwoFingerTouchControlMessage,
|
|
19
|
+
u as normalizeAndroidTree,
|
|
20
|
+
M as normalizeIosTree
|
|
21
|
+
};
|