@limrun/ui 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +0,0 @@
1
- "use strict";require('./index.css');const A=require("react/jsx-runtime"),u=require("react"),Xn=require("react-dom");function Vr(r){var t,o,c="";if(typeof r=="string"||typeof r=="number")c+=r;else if(typeof r=="object")if(Array.isArray(r)){var h=r.length;for(t=0;t<h;t++)r[t]&&(o=Vr(r[t]))&&(c&&(c+=" "),c+=o)}else for(o in r)r[o]&&(c&&(c+=" "),c+=o);return c}function Ye(){for(var r,t,o=0,c="",h=arguments.length;o<h;o++)(r=arguments[o])&&(t=Vr(r))&&(c&&(c+=" "),c+=t);return c}const qn={width:164.6,height:117.8,depth:5.2};function jn(r,t,o){return r=Math.max(0,Math.min(1,r)),t=Math.max(0,Math.min(1,t)),o===1?{x:t,y:1-r}:o===2?{x:1-r,y:1-t}:o===3?{x:1-t,y:r}:{x:r,y:t}}function Vn(r){return Number.isFinite(r)&&r>=0&&r<=180}function Gn(r,t){return{x:Math.max(0,Math.min(1,r)),y:Math.max(0,Math.min(1,1-t))}}function Jn(r,t,o){return t&&(r||!o)?"touch":r?"ignore":"orbit"}function zn(r,t,o,c){if(!Number.isInteger(r)||r<0||r>3||!Number.isInteger(t)||t<1||t>255||!Number.isFinite(o)||!Number.isFinite(c)||o<0||o>1||c<0||c>1)throw new RangeError("Invalid display touch coordinates");const h=new ArrayBuffer(12),p=new DataView(h);return p.setUint8(0,19),p.setUint8(1,r),p.setUint8(2,t),p.setFloat32(4,o,!0),p.setFloat32(8,c,!0),h}class Qn{constructor(t,o){this.send=t,this.failed=o}send;failed;latest;running=!1;stopped=!1;set(t){this.stopped||!Vn(t)||(this.latest=t,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 t=this.latest;this.latest=void 0,await this.send(t)}}catch(t){this.latest=void 0,this.stopped||this.failed(t)}finally{this.running=!1}}}}const Zn={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class ei{constructor(t,o){this.send=t,this.failed=o}send;failed;held;tail=Promise.resolve();timeout;press(t){this.held||(this.held=t,this.enqueue(t,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const t=this.held;this.held=void 0,this.enqueue(t,!1)}enqueue(t,o){this.tail=this.tail.then(()=>this.send(t,o)).catch(this.failed)}}const Ft={INJECT_KEYCODE:0,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,SET_CLIPBOARD:9},L={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},a={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_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,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,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,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,MENU:82,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,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_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},Gr={KeyA:a.KEYCODE_A,KeyB:a.KEYCODE_B,KeyC:a.KEYCODE_C,KeyD:a.KEYCODE_D,KeyE:a.KEYCODE_E,KeyF:a.KEYCODE_F,KeyG:a.KEYCODE_G,KeyH:a.KEYCODE_H,KeyI:a.KEYCODE_I,KeyJ:a.KEYCODE_J,KeyK:a.KEYCODE_K,KeyL:a.KEYCODE_L,KeyM:a.KEYCODE_M,KeyN:a.KEYCODE_N,KeyO:a.KEYCODE_O,KeyP:a.KEYCODE_P,KeyQ:a.KEYCODE_Q,KeyR:a.KEYCODE_R,KeyS:a.KEYCODE_S,KeyT:a.KEYCODE_T,KeyU:a.KEYCODE_U,KeyV:a.KEYCODE_V,KeyW:a.KEYCODE_W,KeyX:a.KEYCODE_X,KeyY:a.KEYCODE_Y,KeyZ:a.KEYCODE_Z,Digit0:a.KEYCODE_0,Digit1:a.KEYCODE_1,Digit2:a.KEYCODE_2,Digit3:a.KEYCODE_3,Digit4:a.KEYCODE_4,Digit5:a.KEYCODE_5,Digit6:a.KEYCODE_6,Digit7:a.KEYCODE_7,Digit8:a.KEYCODE_8,Digit9:a.KEYCODE_9,Backquote:a.KEYCODE_GRAVE,Minus:a.KEYCODE_MINUS,Equal:a.KEYCODE_EQUALS,BracketLeft:a.KEYCODE_LEFT_BRACKET,BracketRight:a.KEYCODE_RIGHT_BRACKET,Backslash:a.KEYCODE_BACKSLASH,Semicolon:a.KEYCODE_SEMICOLON,Quote:a.KEYCODE_APOSTROPHE,Comma:a.KEYCODE_COMMA,Period:a.KEYCODE_PERIOD,Slash:a.KEYCODE_SLASH,Space:a.KEYCODE_SPACE,Tab:a.KEYCODE_TAB,Escape:a.KEYCODE_ESCAPE,ArrowUp:a.DPAD_UP,ArrowDown:a.DPAD_DOWN,ArrowLeft:a.DPAD_LEFT,ArrowRight:a.DPAD_RIGHT,Enter:a.ENTER,Backspace:a.DEL,Delete:a.FORWARD_DEL,Home:a.KEYCODE_MOVE_HOME,End:a.KEYCODE_MOVE_END,PageUp:a.KEYCODE_PAGE_UP,PageDown:a.KEYCODE_PAGE_DOWN,Insert:a.KEYCODE_INSERT,F1:a.KEYCODE_F1,F2:a.KEYCODE_F2,F3:a.KEYCODE_F3,F4:a.KEYCODE_F4,F5:a.KEYCODE_F5,F6:a.KEYCODE_F6,F7:a.KEYCODE_F7,F8:a.KEYCODE_F8,F9:a.KEYCODE_F9,F10:a.KEYCODE_F10,F11:a.KEYCODE_F11,F12:a.KEYCODE_F12,ShiftLeft:a.KEYCODE_SHIFT_LEFT,ShiftRight:a.KEYCODE_SHIFT_RIGHT,ControlLeft:a.KEYCODE_CTRL_LEFT,ControlRight:a.KEYCODE_CTRL_RIGHT,AltLeft:a.KEYCODE_ALT_LEFT,AltRight:a.KEYCODE_ALT_RIGHT,MetaLeft:a.KEYCODE_META_LEFT,MetaRight:a.KEYCODE_META_RIGHT,ContextMenu:a.MENU,Numpad0:a.KEYCODE_NUMPAD_0,Numpad1:a.KEYCODE_NUMPAD_1,Numpad2:a.KEYCODE_NUMPAD_2,Numpad3:a.KEYCODE_NUMPAD_3,Numpad4:a.KEYCODE_NUMPAD_4,Numpad5:a.KEYCODE_NUMPAD_5,Numpad6:a.KEYCODE_NUMPAD_6,Numpad7:a.KEYCODE_NUMPAD_7,Numpad8:a.KEYCODE_NUMPAD_8,Numpad9:a.KEYCODE_NUMPAD_9,NumpadDivide:a.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:a.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:a.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:a.KEYCODE_NUMPAD_ADD,NumpadDecimal:a.KEYCODE_NUMPAD_DOT,NumpadComma:a.KEYCODE_NUMPAD_COMMA,NumpadEnter:a.KEYCODE_NUMPAD_ENTER,NumpadEqual:a.KEYCODE_NUMPAD_EQUALS};function Wr(r,t){if(t!=null&&(!Number.isFinite(t)||t<0||t>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in r))return;const o=t??null;try{r.jitterBufferTarget!==o&&(r.jitterBufferTarget=o)}catch(c){console.warn("RemoteControl: could not set the jitter buffer target.",c)}}function gt(r){return typeof r=="number"&&Number.isFinite(r)}function Ze(r,t){if(!(!gt(r)||!gt(t)||r<t||t<0))return r-t}class ti{previous=new Map;reset(){this.previous.clear()}read(t,o,c){const h={timestamp:0,video:[],audio:[]};c==null?h.requestedTargetMs=null:gt(c)&&c>=0&&c<=4e3&&(h.requestedTargetMs=c);const p=new Map;return t.forEach(d=>{if(d.type!=="inbound-rtp"||!gt(d.timestamp))return;const y=d.kind??d.mediaType;if(y!=="video"&&y!=="audio")return;const T=o.filter(M=>M.kind===y),O=d.trackIdentifier?T.find(M=>M.trackId===d.trackIdentifier):d.mid!=null?T.find(M=>M.mid===d.mid):T.length===1?T[0]:void 0;if(!O)return;const S=this.previous.get(d.id),Y=S?.trackId===O.trackId&&S.stats.ssrc===d.ssrc?S.stats:void 0,j=Y?d.timestamp-Y.timestamp:void 0,I={id:d.id,trackId:O.trackId,timestamp:d.timestamp};if(j!==void 0&&j>0){I.intervalMs=j;const M=Ze(d.jitterBufferEmittedCount,Y?.jitterBufferEmittedCount),G=Ze(d.jitterBufferDelay,Y?.jitterBufferDelay);M!==void 0&&M>0&&G!==void 0&&(I.bufferDelayMs=G/M*1e3);const Z=Ze(d.bytesReceived,Y?.bytesReceived);Z!==void 0&&(I.bitrateBps=Z*8e3/j)}if(y==="video"){const M={...I,display:O.display??"primary"};if(I.intervalMs!==void 0){const G=Ze(d.framesDecoded,Y?.framesDecoded);G!==void 0&&(M.fps=G*1e3/I.intervalMs),M.droppedFrames=Ze(d.framesDropped,Y?.framesDropped),M.freezes=Ze(d.freezeCount,Y?.freezeCount)}h.video.push(M)}else h.audio.push(I);h.timestamp=Math.max(h.timestamp,d.timestamp),p.set(d.id,Y&&d.timestamp<=Y.timestamp?S:{stats:d,trackId:O.trackId});const ee=d.transportId?t.get(d.transportId):void 0,W=ee?.selectedCandidatePairId?t.get(ee.selectedCandidatePairId):void 0;W?.state==="succeeded"&&gt(W.currentRoundTripTime)&&W.currentRoundTripTime>=0&&(h.rttMs=W.currentRoundTripTime*1e3)}),this.previous=p,h.video.length||h.audio.length?h:null}}function ri(r,t,o){const c=u.useRef(t),h=u.useRef(o),p=u.useRef(new Set);c.current=t,h.current=o;const d=!!t;u.useEffect(()=>{if(!r||!d)return;const{peer:y,displays:T}=r,O=new ti;let S,N=!1,Y=!1,j=!1,I=0,ee=!1,W=!1;const M=()=>!N&&!document.hidden&&y.connectionState==="connected",G=de=>{if(!(!de&&!ee)){ee=de!==null;try{c.current?.(de)}catch(ae){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',ae)}}},Z=()=>{Y=!1,I++,clearTimeout(S),O.reset(),G(null)},$=async()=>{if(j||!M())return;if(p.current.has(y)){S=setTimeout(()=>{$()},2e3);return}j=!0,p.current.add(y);const de=I;try{const ae=await y.getStats();if(de!==I||!M())return;const pe=y.getTransceivers().filter(re=>(re.currentDirection==="recvonly"||re.currentDirection==="sendrecv")&&re.receiver.track.readyState!=="ended").map(re=>({trackId:re.receiver.track.id,kind:re.receiver.track.kind,mid:re.mid,display:T.get(re.receiver)}));G(O.read(ae,pe,h.current)),W=!1}catch(ae){if(de!==I||!M())return;W||console.warn("[RemoteControl] could not read playback stats:",ae),W=!0,O.reset(),G(null)}finally{j=!1,p.current.delete(y),Y&&M()&&(S=setTimeout(()=>{$()},de===I?2e3:0))}},ce=()=>{if(!M()){Z();return}Y||(Y=!0,$())};return document.addEventListener("visibilitychange",ce),y.addEventListener("connectionstatechange",ce),ce(),()=>{N=!0,document.removeEventListener("visibilitychange",ce),y.removeEventListener("connectionstatechange",ce),Z()}},[r,d])}const Jr=`(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
- `,Hr=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Jr],{type:"text/javascript;charset=utf-8"});function ni(r){let t;try{if(t=Hr&&(self.URL||self.webkitURL).createObjectURL(Hr),!t)throw"";const o=new Worker(t,{name:r?.name});return o.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),o}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Jr),{name:r?.name})}}function ii(r,t,o){const{MediaStreamTrackProcessor:c,MediaStreamTrackGenerator:h}=globalThis,p=t.getVideoTracks()[0];let d,y,T,O,S=!1;const N=()=>{S||(S=!0,d?.stop(),y?.stop(),T&&(T.postMessage({type:"stop"}),O=setTimeout(()=>T?.terminate(),1e3)))},Y=I=>{r.srcObject=I,r.play().catch(()=>{})},j=I=>{S||(N(),o(I),Y(t))};try{if(p&&c&&h){d=p.clone();const I=new c({track:d,maxBufferSize:1}),ee=new h({kind:"video"});y=ee,T=new ni,T.onmessage=({data:W})=>{W.type==="error"?j(new Error(W.message)):W.type==="stopped"&&(clearTimeout(O),T?.terminate())},T.onerror=W=>j(new Error(W.message)),T.postMessage({type:"start",readable:I.readable,writable:ee.writable},[I.readable,ee.writable]),Y(new MediaStream(t.getTracks().map(W=>W===p?ee:W)))}else Y(t)}catch(I){j(I)}return N}function oi(r,t){const o=r.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let c=!1,h=!1,p=0;return o.onmessage=d=>{if(h)return;let y;try{y=JSON.parse(d.data)}catch(T){console.warn("Invalid latency trace message",T);return}y&&typeof y=="object"&&!Array.isArray(y)&&t(y)},o.onclose=()=>{h=!0,c=!1},{accept(d){c=!h&&d===1},wrap(d){if(!c||d.byteLength!==32)return d;const y=new DataView(d);if(y.getUint8(0)!==2||y.getUint8(1)>2)return d;const T=new ArrayBuffer(38),O=new DataView(T);return O.setUint8(0,240),O.setUint8(1,1),O.setUint32(2,++p,!0),new Uint8Array(T,6).set(new Uint8Array(d)),T},close(){h=!0,c=!1,o.onmessage=null,o.onclose=null,o.close()}}}function Pt(r,t,o,c,h,p,d=1,y=0,T=0){const O=new ArrayBuffer(32),S=new DataView(O);let N=0;S.setUint8(N,Ft.INJECT_TOUCH_EVENT),N+=1;const Y=r===L.ACTION_POINTER_DOWN?L.ACTION_DOWN:r===L.ACTION_POINTER_UP?L.ACTION_UP:r;return S.setUint8(N,Y),N+=1,S.setBigInt64(N,BigInt(t),!0),N+=8,S.setInt32(N,Math.round(h),!0),N+=4,S.setInt32(N,Math.round(p),!0),N+=4,S.setUint16(N,o,!0),N+=2,S.setUint16(N,c,!0),N+=2,S.setInt16(N,Math.round(d*65535),!0),N+=2,S.setInt32(N,y,!0),N+=4,S.setInt32(N,T,!0),O}function si(r,t,o,c,h,p,d){const y=new ArrayBuffer(24),T=new DataView(y);let O=0;return T.setUint8(O,Ft.INJECT_TWO_FINGER_TOUCH_EVENT),O+=1,T.setUint8(O,r),O+=1,T.setInt32(O,Math.round(c),!0),O+=4,T.setInt32(O,Math.round(h),!0),O+=4,T.setInt32(O,Math.round(p),!0),O+=4,T.setInt32(O,Math.round(d),!0),O+=4,T.setUint16(O,t,!0),O+=2,T.setUint16(O,o,!0),O+=2,T.setUint16(O,0,!0),y}function ci(r,t=!0){const c=new TextEncoder().encode(r),h=new ArrayBuffer(14+c.length),p=new DataView(h);let d=0;return p.setUint8(d,Ft.SET_CLIPBOARD),d+=1,p.setBigInt64(d,BigInt(0),!1),d+=8,p.setUint8(d,t?1:0),d+=1,p.setUint32(d,c.length,!1),d+=4,new Uint8Array(h,d).set(c),h}function Et(r,t,o=0,c=0){const h=new ArrayBuffer(14),p=new DataView(h);let d=0;return p.setUint8(d,Ft.INJECT_KEYCODE),d+=1,p.setUint8(d,r),d+=1,p.setInt32(d,t,!0),d+=4,p.setInt32(d,o,!0),d+=4,p.setInt32(d,c,!0),h}const Lt="Accessibility unavailable on this device.",xt=500,zr=(r,t)=>Math.abs(r.x-t.x)<.5&&Math.abs(r.y-t.y)<.5&&Math.abs(r.width-t.width)<.5&&Math.abs(r.height-t.height)<.5,ai=r=>Math.max(0,r.width)*Math.max(0,r.height),ui=r=>{const t=r.find(o=>o.frame&&o.frame.width>0&&o.frame.height>0);return t?.frame?((Math.abs(t.frame.x)>.5||Math.abs(t.frame.y)>.5)&&console.warn(`[ax-tree] iOS root frame is not anchored at (0,0): (${t.frame.x},${t.frame.y}). Element positions may be slightly off from the rendered video.`),{x:0,y:0,width:t.frame.width,height:t.frame.height}):{x:0,y:0,width:1,height:1}},li=r=>{const t={};return typeof r.AXUniqueId=="string"&&r.AXUniqueId.length>0&&(t.AXUniqueId=r.AXUniqueId),typeof r.AXLabel=="string"&&r.AXLabel.length>0&&(t.AXLabel=r.AXLabel),typeof r.type=="string"&&r.type.length>0&&(t.className=r.type),t},di=r=>{const t={};for(const[o,c]of Object.entries(r))o!=="children"&&(t[o]=c);return t};function Qr(r){const t=Array.isArray(r)?r:[r],o=ui(t),c=[],h=(p,d)=>{if(c.length>=xt)return;const y=p.frame;if(y&&y.width>0&&y.height>0&&!zr(y,o)){const O=p.role_description||p.role||"",S=(typeof p.AXLabel=="string"?p.AXLabel:"")||(typeof p.title=="string"?p.title:"")||"";c.push({id:typeof p.AXUniqueId=="string"&&p.AXUniqueId.length>0?p.AXUniqueId:d,path:d,label:S,value:typeof p.AXValue=="string"?p.AXValue:"",role:O,type:typeof p.type=="string"?p.type:"",enabled:p.enabled!==!1,focused:p.focused===!0,frame:{x:y.x,y:y.y,width:y.width,height:y.height},selectors:li(p),raw:di(p)})}const T=Array.isArray(p.children)?p.children:[];for(let O=0;O<T.length&&c.length<xt;O++)h(T[O],`${d}.${O}`)};for(let p=0;p<t.length&&c.length<xt;p++)h(t[p],String(p));return{platform:"ios",screen:{width:o.width,height:o.height},elements:c,capturedAt:Date.now()}}const fi=r=>{let t={x:0,y:0,width:1,height:1},o=0;for(const c of r){const h=c.parsedBounds;if(!h)continue;const p=h.right-h.left,d=h.bottom-h.top,y=Math.max(0,p)*Math.max(0,d);y>o&&(o=y,t={x:0,y:0,width:p,height:d})}return t},hi=r=>{const t={};return typeof r.resourceId=="string"&&r.resourceId.length>0&&(t.resourceId=r.resourceId),typeof r.contentDesc=="string"&&r.contentDesc.length>0&&(t.contentDesc=r.contentDesc),typeof r.text=="string"&&r.text.length>0&&(t.text=r.text),typeof r.className=="string"&&r.className.length>0&&(t.className=r.className),t};function Zr(r){const t=fi(r),o=[];for(let c=0;c<r.length&&o.length<xt;c++){const h=r[c],p=h.parsedBounds;if(!p)continue;const d=Math.max(0,p.right-p.left),y=Math.max(0,p.bottom-p.top);if(d<=0||y<=0)continue;const T={x:p.left,y:p.top,width:d,height:y};if(zr(T,{x:0,y:0,width:t.width,height:t.height}))continue;const O=h.contentDesc||h.text||"",S=h.className||"";o.push({id:h.resourceId&&h.resourceId.length>0?h.resourceId:h.contentDesc&&h.contentDesc.length>0?`cd:${h.contentDesc}`:String(c),path:String(c),label:O,value:typeof h.text=="string"?h.text:"",role:S,type:S,enabled:h.enabled!==!1,focused:h.focused===!0,frame:T,selectors:hi(h),raw:{...h}})}return{platform:"android",screen:{width:t.width,height:t.height},elements:o,capturedAt:Date.now()}}function en(r,t){const o=Math.max(0,r.x),c=Math.max(0,r.y),h=Math.min(t.width,r.x+r.width),p=Math.min(t.height,r.y+r.height),d=Math.max(0,h-o),y=Math.max(0,p-c);return d>0&&y>0?{x:o,y:c,width:d,height:y}:null}function or(r,t){if(r===t)return!0;if(r.id!==t.id||r.path!==t.path||r.label!==t.label||r.value!==t.value||r.role!==t.role||r.type!==t.type||r.enabled!==t.enabled||r.focused!==t.focused)return!1;const o=r.frame,c=t.frame;return o.x===c.x&&o.y===c.y&&o.width===c.width&&o.height===c.height}function sr(r,t){if(r===t)return!0;if(!r||!t||r.platform!==t.platform||r.screen.width!==t.screen.width||r.screen.height!==t.screen.height||r.elements.length!==t.elements.length)return!1;for(let o=0;o<r.elements.length;o++)if(!or(r.elements[o],t.elements[o]))return!1;return!0}function tn(r,t,o){let c=null,h=1/0;for(const p of r.elements){const d=p.frame;if(t<d.x||o<d.y||t>d.x+d.width||o>d.y+d.height)continue;const y=ai(d);y<h&&(h=y,c=p)}return c}function rn(r,t){if(t==="ios"){if(r.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(r.selectors.AXUniqueId)} })`;if(r.selectors.AXLabel){const o=r.selectors.className?`, type: ${JSON.stringify(r.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(r.selectors.AXLabel)}${o} })`}return null}return r.selectors.resourceId?`client.tap({ selector: { resourceId: ${JSON.stringify(r.selectors.resourceId)} } })`:r.selectors.contentDesc?`client.tap({ selector: { contentDesc: ${JSON.stringify(r.selectors.contentDesc)} } })`:r.selectors.text?`client.tap({ selector: { text: ${JSON.stringify(r.selectors.text)} } })`:null}function nn(r){const t=r.role||r.type||"";if(!t)return"element";let o=t.replace(/^AX/,"");return o.includes(".")&&(o=o.split(".").pop()),o==="GenericElement"?"Element":(o=o.replace(/([a-z])([A-Z])/g,"$1 $2"),o)}const $r=80;function cr(r){const t=nn(r),o=r.label||r.value||"";if(!o)return t;const c=o.length>$r?o.slice(0,$r).trimEnd()+"…":o;return`${t} · ${c}`}const mi=500,pi=2e3,Br=5e3,Ei=8e3,gi=1200,yi=250,Ci=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class vi{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(t){this.platform=t.platform,this.send=t.send,this.onSnapshot=t.onSnapshot,this.onStatusChange=t.onStatusChange,this.baseIntervalMs=t.baseIntervalMs??mi,this.maxBackoffMs=t.maxBackoffMs??pi,this.androidElementTreeOptions=t.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(t,o){if(this.status!==t&&(this.status=t,!!this.onStatusChange))try{this.onStatusChange(t,o)}catch(c){console.error("[AxFetcher] onStatusChange threw:",c)}}bumpActivity(){if(!this.running)return;const t=Date.now();this.boostUntilMs=t+gi;const o=Math.max(150,Math.floor(this.baseIntervalMs/2));if(t-this.lastBumpAtMs<o){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=t,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const t=await this.requestOnce();return this.running&&this.deliver(t),t}getLatest(){return this.lastSnapshot}handleMessage(t){if(!t||typeof t.id!="string")return!1;const o=t.id;if(!this.pending.get(o))return!1;if(this.platform==="ios"){if(t.type!=="elementTreeResult")return!1;const y=typeof t.error=="string"?t.error:null;if(y)return this.settleReject(o,new Error(y)),!0;const T=typeof t.json=="string"?t.json:"";try{const O=JSON.parse(T),S=Qr(O);this.settleResolve(o,S)}catch(O){this.settleReject(o,O instanceof Error?O:new Error(String(O)))}return!0}if(t.type!=="getElementTreeResult")return!1;const h=t.error;if(h&&typeof h=="object"){const y=typeof h.message=="string"?h.message:"getElementTree failed";return this.settleReject(o,new Error(y)),!0}const p=t.payload,d=Array.isArray(p?.nodes)?p.nodes:[];try{const y=Zr(d);this.settleResolve(o,y)}catch(y){this.settleReject(o,y instanceof Error?y:new Error(String(y)))}return!0}buildRequest(t){return this.platform==="ios"?{type:"elementTree",id:t}:{type:"getElementTree",id:t,...this.androidElementTreeOptions}}async requestOnce(){const t=Ci();return new Promise((o,c)=>{const h=window.setTimeout(()=>{this.pending.delete(t),c(new Error("elementTree request timed out"))},Ei+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(t,{resolve:o,reject:c,timer:h}),this.send(this.buildRequest(t))||(window.clearTimeout(h),this.pending.delete(t),c(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const t=await this.requestOnce();if(!this.running)return;this.deliver(t)}catch(t){if(!this.running)return;const o=t instanceof Error?t.message:String(t),c=/unavailable|not (yet )?running|failed|timeout/i.test(o);this.currentInterval=c?Br:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(c?"unavailable":"error",o)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(t){const o=this.lastSnapshot;if(sr(o,t)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=t,t.errors?.includes(Lt)||this.setStatus("ready");return}this.lastSnapshot=t,this.currentInterval=this.baseIntervalMs,t.errors?.includes(Lt)?(this.currentInterval=Br,this.setStatus("unavailable",Lt)):this.setStatus("ready"),this.onSnapshot(t)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const t=Date.now()<this.boostUntilMs?Math.min(yi,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},t)}settleResolve(t,o){const c=this.pending.get(t);c&&(window.clearTimeout(c.timer),this.pending.delete(t),c.resolve(o))}settleReject(t,o){const c=this.pending.get(t);c&&(window.clearTimeout(c.timer),this.pending.delete(t),c.reject(o))}failAllPending(t){for(const[o,c]of this.pending.entries())window.clearTimeout(c.timer),c.reject(new Error(t)),this.pending.delete(o)}}class Oi{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(t){const o=++this.generation;return this.append(o,t)}enqueueCurrent(t){return this.append(this.generation,t)}append(t,o){const c={generation:t,isCurrent:()=>t===this.generation},h=this.tail.then(()=>o(c));return this.tail=h.catch(()=>{}),h}invalidate(){++this.generation}}function Ti(r){if(!r||typeof r!="object")return null;const t=r;if(t.type!=="cameraRequest"||typeof t.active!="boolean")return null;const o={active:t.active};return(t.facingMode==="user"||t.facingMode==="environment")&&(o.facingMode=t.facingMode),o}function _i(r){const t={frameRate:{ideal:30,max:30}};return r?.facingMode&&(t.facingMode={ideal:r.facingMode}),t}function wi(r,t){return!r||r.facingMode!==t.facingMode}function Di(r){const t=r.getSettings();return{width:t.width,height:t.height,frameRate:t.frameRate,deviceId:t.deviceId,label:r.label||void 0,facingMode:t.facingMode}}function Ri(r){return{type:"cameraResult",granted:!0,camera:Di(r)}}const Si=async r=>{if(!r)return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(r),!0}catch{}try{const t=document.createElement("textarea");t.value=r,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select();const o=document.execCommand("copy");return document.body.removeChild(t),o}catch{return!1}},bi=u.memo(function({element:t,screen:o,highlighted:c,selected:h,selectable:p,onClick:d}){const y=en(t.frame,o);if(!y)return null;const T=cr(t);return A.jsx("button",{type:"button",className:Ye("rc-inspect-box",!t.enabled&&"rc-inspect-box-disabled"),"data-ax-id":t.id,"data-ax-path":t.path,"data-ax-label":t.label||void 0,"data-ax-role":t.role||void 0,"data-highlighted":c?"true":"false","data-selected":h?"true":"false","aria-label":T,onClick:O=>{p&&(O.preventDefault(),O.stopPropagation(),d(t,{x:O.clientX,y:O.clientY}))},style:{left:`${y.x/o.width*100}%`,top:`${y.y/o.height*100}%`,width:`${y.width/o.width*100}%`,height:`${y.height/o.height*100}%`}})},(r,t)=>r.highlighted===t.highlighted&&r.selected===t.selected&&r.selectable===t.selectable&&r.screen.width===t.screen.width&&r.screen.height===t.screen.height&&r.onClick===t.onClick&&or(r.element,t.element)),Ai=260,Mi=220,Ni=6,Ii=8,ki=u.memo(function({element:t,platform:o,anchor:c,cursorAnchored:h,showActions:p,onTap:d}){const[y,T]=u.useState(null);u.useEffect(()=>{if(!y)return;const M=window.setTimeout(()=>T(null),1100);return()=>window.clearTimeout(M)},[y]);const O=u.useMemo(()=>{const M=Ai,G=Mi,Z=Ni,$=Ii,ce=typeof window<"u"?window.innerWidth:1024,de=typeof window<"u"?window.innerHeight:768,ae=c.x+Z+M<=ce-$,pe=c.y-Z-G>=$;let re=ae?c.x+Z:c.x-Z,et=pe?c.y-Z:c.y+Z;const Ke=`translate(${ae?"0":"-100%"}, ${pe?"-100%":"0"})`;return re=Math.max($+(ae?0:M),Math.min(ce-$-(ae?M:0),re)),et=Math.max($+(pe?G:0),Math.min(de-$-(pe?0:G),et)),{left:`${re}px`,top:`${et}px`,transform:Ke}},[c.x,c.y]),S=u.useMemo(()=>rn(t,o),[t,o]),N=o==="ios"?t.selectors.AXUniqueId:t.selectors.resourceId,Y=o==="ios"?"AXUniqueId":"resourceId",j=u.useCallback(async(M,G)=>{if(!M)return;await Si(M)&&T(G)},[]),I=nn(t),ee=t.label||t.value||I,W=cr(t);return Xn.createPortal(A.jsxs("div",{className:"rc-inspect-card","data-cursor-anchored":h?"true":"false",style:O,onClick:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),onMouseMove:M=>M.stopPropagation(),children:[A.jsxs("div",{className:"rc-inspect-card-header",children:[A.jsx("span",{className:"rc-inspect-card-role",children:I}),!t.enabled&&A.jsx("span",{className:"rc-inspect-card-tag",children:"disabled"}),t.focused&&A.jsx("span",{className:"rc-inspect-card-tag rc-inspect-card-tag-blue",children:"focused"})]}),A.jsx("p",{className:"rc-inspect-card-title",title:W,children:ee}),N&&A.jsxs("div",{className:"rc-inspect-card-row",children:[A.jsxs("span",{className:"rc-inspect-card-row-label",children:[Y,":"]}),A.jsx("span",{className:"rc-inspect-card-row-value",children:N})]}),t.value&&t.value!==t.label&&A.jsxs("div",{className:"rc-inspect-card-row",children:[A.jsx("span",{className:"rc-inspect-card-row-label",children:"value:"}),A.jsx("span",{className:"rc-inspect-card-row-value",children:t.value})]}),A.jsxs("div",{className:"rc-inspect-card-row",children:[A.jsx("span",{className:"rc-inspect-card-row-label",children:"frame:"}),A.jsxs("span",{className:"rc-inspect-card-row-value",children:[Math.round(t.frame.width),"×",Math.round(t.frame.height)," @ ",Math.round(t.frame.x),",",Math.round(t.frame.y)]})]}),p&&A.jsxs("div",{className:"rc-inspect-card-actions",children:[A.jsx("button",{type:"button",className:"rc-inspect-card-btn rc-inspect-card-btn-primary",onClick:()=>d(t,c),children:"Tap"}),A.jsx("button",{type:"button",className:Ye("rc-inspect-card-btn",y==="selector"&&"rc-inspect-card-btn-copied"),disabled:!S,title:S??"No usable selector for this element",onClick:()=>j(S??void 0,"selector"),children:y==="selector"?"Copied!":"Copy selector"}),A.jsx("button",{type:"button",className:Ye("rc-inspect-card-btn",y==="id"&&"rc-inspect-card-btn-copied"),disabled:!N,title:N??`No ${Y}`,onClick:()=>j(N,"id"),children:y==="id"?"Copied!":`Copy ${Y}`})]})]}),document.body)}),Yi=u.memo(function({snapshot:t,geometry:o,highlightedId:c,selectedId:h,mode:p,cursorPosition:d,frozenCursorPosition:y,onSelectChange:T,onTapElement:O}){const S=p==="select",N=S?c!==null&&c!==h:c!==null,Y=S?c??h:c,j=u.useMemo(()=>{const $=new Map;if(!t)return $;for(const ce of t.elements)$.set(ce.id,ce);return $},[t]),I=u.useMemo(()=>Y?j.get(Y)??null:null,[Y,j]);if(!(!!t&&!!o&&t.screen.width>0&&t.screen.height>0&&t.elements.length>0))return null;const W=N?d:y??d,M=N,G=S&&!N&&h!==null,Z=$=>{S&&$.target===$.currentTarget&&T(null,null)};return A.jsxs(A.Fragment,{children:[A.jsx("div",{className:Ye("rc-inspect-overlay",S&&"rc-inspect-overlay-select"),style:{left:`${o.left}px`,top:`${o.top}px`,width:`${o.width}px`,height:`${o.height}px`},onClick:Z,children:t.elements.map($=>A.jsx(bi,{element:$,screen:t.screen,highlighted:$.id===c,selected:$.id===h,selectable:S,onClick:T},$.id))}),I&&W&&A.jsx(ki,{element:I,platform:t.platform,anchor:W,cursorAnchored:M,showActions:G,onTap:O})]})}),Ki=u.lazy(()=>Promise.resolve().then(()=>require("./duo-view-DCJT-n1Z.js")).then(r=>r.duoView)),q=(...r)=>{window.debugRemoteControl&&console.log(...r)},R=(...r)=>{window.debugRemoteControl&&console.warn(...r)},H=(r,t,...o)=>{if(t)try{t(...o)}catch(c){console.error(`[RemoteControl] customer callback "${r}" threw:`,c)}},Ut=r=>Object.entries(L).find(([o,c])=>o.startsWith("ACTION_")&&c===r)?.[0]??String(r),Pi=r=>r.includes("/android_")?"android":"ios",Xr=(r,t)=>{const o=new URL(r);return o.searchParams.set("token",t),o.toString()},qr=1920,jr=1200,ir=3,Ui=1e3,Li=15e3,xi=3e3,Fi=4e3,Wi=(r,t)=>r===qr&&t===jr||r===jr&&t===qr,Hi={ios:{videoBorderRadiusMultiplier:.15,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:.9678},landscape:{widthMultiplier:.9678}}},android:{videoBorderRadiusMultiplier:.13,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:.967},landscape:{widthMultiplier:.962}}}};function $i(r){const t=r.code,o=Gr[t];if(!o)return R(`Unknown event.code: ${t}, key: ${r.key}`),null;let c=a.META_NONE;const h=t>="KeyA"&&t<="KeyZ",p=r.getModifierState("CapsLock"),d=r.shiftKey;let y=d;return h&&(y=d!==p),y&&(c|=a.META_SHIFT_ON),r.ctrlKey&&(c|=a.META_CTRL_ON),r.altKey&&(c|=a.META_ALT_ON),r.metaKey&&(c|=a.META_META_ON),{keycode:o,metaState:c}}const Bi=u.forwardRef(({className:r,url:t,token:o,sessionId:c,openUrl:h,showFrame:p=!0,deviceModel:d,duoModelUrl:y,autoReconnect:T=!1,jitterBufferTargetMs:O,onPlaybackStats:S,onTerminated:N,assets:Y,onConnectionStateChange:j,inspectMode:I,onAxSnapshotChange:ee,onInspectSelectionChange:W,onAxStatusChange:M,axPollIntervalMs:G,axMaxBackoffMs:Z,androidElementTreeOptions:$,onCameraDemandChange:ce,onCameraStats:de,onTrace:ae,microphoneEnabled:pe=!1,onMicrophoneStateChange:re},et)=>{const tt=u.useRef(null),J=u.useRef(null),Ke=u.useRef(new Map),ar=u.useRef(null),[on,sn]=u.useState(!1),ye=d==="iphone-duo"||on,rt=u.useRef(null),[ur,lr]=u.useState(null),[dr,fr]=u.useState(),Pe=u.useRef(new Map),Wt=(e,s)=>new Promise((i,n)=>{const m=D.current;if(!m||m.readyState!==WebSocket.OPEN){n(new Error("Simulator disconnected"));return}const l=crypto.randomUUID(),E=setTimeout(()=>{Pe.current.delete(l),n(new Error("Device control timed out"))},5e3);Pe.current.set(l,{resolve:i,reject:n,timer:E}),m.send(JSON.stringify({type:e,id:l,...s}))}),[cn,Ht]=u.useState(!1),[an,yt]=u.useState(!1),[un,hr]=u.useState(!1),Ue=u.useRef(!1),$t=u.useRef(!1),[mr,ln]=u.useState(!1),[dn,fn]=u.useState(!1),[hn,pr]=u.useState({}),D=u.useRef(null),B=u.useRef(null),[mn,Er]=u.useState(null);ri(mn,S,O);const F=u.useRef(null),Ct=u.useRef(null),Bt=u.useRef(ae);Bt.current=ae;const pn=!!ae,Le=u.useRef(void 0),nt=u.useRef(void 0),it=u.useRef(void 0),vt=u.useRef(void 0),xe=u.useRef(void 0),De=u.useRef(0),Ot=u.useRef(0),Ce=u.useRef(!1),Xt=u.useRef(T);Xt.current=T;const gr=u.useRef(O);u.useEffect(()=>{gr.current=O;for(const e of B.current?.getTransceivers()??[])(e.currentDirection==="recvonly"||e.currentDirection==="sendrecv")&&Wr(e.receiver,O)},[O]);const Re=u.useRef(null),ue=u.useRef(null),Se=u.useRef(void 0),qt=u.useMemo(()=>new Oi,[]),ve=u.useRef(ce);ve.current=ce;const Tt=u.useRef(de);Tt.current=de;const ot=u.useRef(null),_t=u.useRef(null),jt=u.useRef(pe);jt.current=pe;const Vt=u.useRef(!1),st=u.useRef(re);st.current=re;const ct=u.useRef(null),Ee=u.useRef(null),wt=u.useRef(0),yr=u.useRef(Promise.resolve()),Fe=u.useRef(null),at=u.useRef(!1),_e=u.useRef(new Map),Oe=u.useRef(new Map),be=u.useRef(new Map),Ae=u.useRef(new Map),te=u.useRef(new Map),Me=u.useRef(!1),[En,gn]=u.useState(!1),z=u.useRef(null),We=u.useRef(null),ut=u.useRef({handle:()=>{},end:()=>{}}),[Ne,Dt]=u.useState(null),ne=u.useRef(null),[Cr,vr]=u.useState(null),[Gt,lt]=u.useState(null),[Jt,Rt]=u.useState(null),[yn,Or]=u.useState(null),[Cn,Tr]=u.useState(null),St=u.useRef(null),fe=u.useRef(void 0),_r=e=>{St.current=e,fe.current===void 0&&(fe.current=window.requestAnimationFrame(()=>{fe.current=void 0,Tr(St.current)}))},[vn,He]=u.useState(null),$e=u.useRef(I);$e.current=I;const Be=u.useRef(null);Be.current=Cr;const zt=u.useRef(ee);zt.current=ee;const Xe=u.useRef(W);Xe.current=W;const wr=u.useRef(M);wr.current=M;const Dr=u.useRef(N);Dr.current=N;const Rr=u.useRef(j);Rr.current=j;const Qt=u.useRef(null),qe=e=>{Qt.current!==e&&(Qt.current=e,H("onConnectionStateChange",Rr.current,e))},dt=I===!0||I==="hover-only",On=I==="hover-only"?"hover-only":"select",he=u.useMemo(()=>c||Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15),[c]),ge=u.useMemo(()=>Pi(t),[t]),je=Hi[ge],ft=Y?.[ge],Sr=ge==="android"&&dn?mr?ft?.tabletFrameLandscape:ft?.tabletFrame:mr?ft?.frameLandscape:ft?.frame,br=ft?.loadingLogo,bt=!ye&&p&&!!Sr,x=e=>{q(e)},me=e=>{!F.current||F.current.readyState!=="open"||(F.current.send(Ct.current?.wrap(e)??e),ne.current?.bumpActivity())},Ar=-10,Mr=(e,s)=>{const i=ht();if(!i)return;const n=Ge(i,e,s);if(!n)return;const{videoX:m,videoY:l,videoWidth:E,videoHeight:C}=n,v=Pt(L.ACTION_DOWN,Ar,E,C,m,l,1,L.BUTTON_PRIMARY,L.BUTTON_PRIMARY);v&&me(v),window.setTimeout(()=>{const g=Pt(L.ACTION_UP,Ar,E,C,m,l,0,L.BUTTON_PRIMARY,L.BUTTON_PRIMARY);g&&me(g)},60)},Tn=(e,s)=>{const i=ht();if(!i||s.screen.width<=0||s.screen.height<=0)return;const n=e.frame.x+e.frame.width/2,m=e.frame.y+e.frame.height/2,l=n/s.screen.width*i.actualWidth,E=m/s.screen.height*i.actualHeight,C=i.videoRect.left+i.offsetX+l,v=i.videoRect.top+i.offsetY+E;Mr(C,v)},At=-1,Mt=-2,Ie=-3,Ve=(e,s,i,n,m,l)=>{const E=Pt(e,s,i,n,m,l,1,L.BUTTON_PRIMARY,L.BUTTON_PRIMARY);E&&(q("[rc-touch] sendSingleTouch",{action:e,actionName:Ut(e),pointerId:s,x:m,y:l,video:{width:i,height:n}}),me(E))},ke=(e,s,i)=>{if(!i)return;const{videoX:n,videoY:m,videoWidth:l,videoHeight:E}=i;let C=null,v=null,g=1;const k=L.BUTTON_PRIMARY;switch(s){case"down":e!==Ie&&ut.current.end(),C=te.current.size===0?L.ACTION_DOWN:L.ACTION_POINTER_DOWN,v={x:n,y:m},te.current.set(e,v),e===-1&&J.current?.focus();break;case"move":te.current.has(e)&&(C=L.ACTION_MOVE,v={x:n,y:m},te.current.set(e,v));break;case"up":case"cancel":te.current.has(e)&&(v=te.current.get(e),te.current.delete(e),s==="cancel"?C=L.ACTION_CANCEL:C=te.current.size===0?L.ACTION_UP:L.ACTION_POINTER_UP);break}if(C!==null&&v!==null){q("[rc-touch][mouse->touch] sending",{pointerId:e,eventType:s,action:C,actionName:Ut(C),positionToSend:v,video:{width:l,height:E},altHeld:Me.current,activePointersAfter:Array.from(te.current.entries()).map(([U,V])=>({id:U,x:V.x,y:V.y}))});const _=Pt(C,e,l,E,v.x,v.y,g,k,k);_&&(q("[rc-touch][mouse->touch] buffer",{pointerId:e,actionName:Ut(C),byteLength:_.byteLength}),me(_))}else(s==="up"||s==="cancel")&&te.current.delete(e)},Zt=e=>{if(Me.current!==e&&(Me.current=e,gn(e),e||Dt(null),q("[rc-touch][alt] updateAltHeld",{nextHeld:e,activePointerIds:Array.from(te.current.keys())}),ge==="ios"&&F.current&&F.current.readyState==="open")){const s=e?a.ACTION_DOWN:a.ACTION_UP,i=Et(s,a.KEYCODE_ALT_LEFT,0,a.META_NONE);q("[rc-touch][alt] sending Indigo modifier keycode",{action:s,keycode:a.KEYCODE_ALT_LEFT}),i&&me(i)}},ht=()=>{const e=J.current,s=tt.current;if(!e||!s)return null;const i=e.videoWidth,n=e.videoHeight;if(!i||!n)return null;const m=e.getBoundingClientRect(),l=s.getBoundingClientRect(),E=m.width,C=m.height,v=i/n,g=E/C;let k=E,_=C;v>g?_=E/v:k=C*v;const U=(E-k)/2,V=(C-_)/2;return{videoWidth:i,videoHeight:n,videoRect:m,containerRect:l,actualWidth:k,actualHeight:_,offsetX:U,offsetY:V}},Ge=(e,s,i)=>{const n=s-e.videoRect.left-e.offsetX,m=i-e.videoRect.top-e.offsetY,l=Math.max(0,Math.min(e.actualWidth,n)),E=Math.max(0,Math.min(e.actualHeight,m)),C=Math.max(0,Math.min(e.videoWidth,l/e.actualWidth*e.videoWidth)),v=Math.max(0,Math.min(e.videoHeight,E/e.actualHeight*e.videoHeight));return{videoX:C,videoY:v,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},_n=(e,s,i)=>{const n=s-e.videoRect.left-e.offsetX,m=i-e.videoRect.top-e.offsetY,l=Math.max(0,Math.min(e.actualWidth,n)),E=Math.max(0,Math.min(e.actualHeight,m)),C=Math.max(0,Math.min(e.videoWidth,l/e.actualWidth*e.videoWidth)),v=Math.max(0,Math.min(e.videoHeight,E/e.actualHeight*e.videoHeight)),g=e.videoWidth-C,k=e.videoHeight-v,_=e.videoRect.left+e.offsetX,U=e.videoRect.top+e.offsetY,V=_-e.containerRect.left+l,oe=U-e.containerRect.top+E,Te=_-e.containerRect.left+(e.actualWidth-l),X=U-e.containerRect.top+(e.actualHeight-E);return{containerX:V,containerY:oe,mirrorContainerX:Te,mirrorContainerY:X,videoX:C,videoY:v,mirrorVideoX:g,mirrorVideoY:k,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},wn=(e,s,i,n,m,l,E)=>{const C=si(e,s,i,n,m,l,E);q("[rc-touch2] sendTwoFingerMessage (iOS)",{actionName:Ut(e),video:{width:s,height:i},p0:{x:n,y:m},p1:{x:l,y:E},byteLength:C.byteLength}),me(C)},Je=(e,s,i,n,m,l,E,C,v)=>{if(q("[rc-touch2] applyTwoFingerEvent",{platform:ge,eventType:e,video:{width:s,height:i},p0:{x:n,y:m,id:C},p1:{x:l,y:E,id:v}}),e==="down"&&ut.current.end(),ge==="ios"){const g=e==="down"?L.ACTION_DOWN:e==="move"?L.ACTION_MOVE:L.ACTION_UP;wn(g,s,i,n,m,l,E)}else e==="down"?(Ve(L.ACTION_DOWN,C,s,i,n,m),Ve(L.ACTION_POINTER_DOWN,v,s,i,l,E)):e==="move"?(Ve(L.ACTION_MOVE,C,s,i,n,m),Ve(L.ACTION_MOVE,v,s,i,l,E)):(Ve(L.ACTION_POINTER_UP,v,s,i,l,E),Ve(L.ACTION_UP,C,s,i,n,m))},Dn=(e,s,i)=>{if(!Me.current){Ne!==null&&Dt(null);return}const n=_n(e,s,i);Dt(n)},Rn=(e,s,i)=>{const n=Be.current;if(!n||n.screen.width<=0||n.screen.height<=0)return null;const m=s-e.videoRect.left-e.offsetX,l=i-e.videoRect.top-e.offsetY;if(m<0||l<0||m>e.actualWidth||l>e.actualHeight)return null;const E=m/e.actualWidth*n.screen.width,C=l/e.actualHeight*n.screen.height;return tn(n,E,C)},we=e=>{if(ye)return;e.preventDefault(),e.stopPropagation();const s=ht();if(($e.current===!0||$e.current==="hover-only")&&!("touches"in e))if(e.type==="mousemove"){if(_r({x:e.clientX,y:e.clientY}),s){const n=Rn(s,e.clientX,e.clientY);lt(n?.id??null)}}else e.type==="mouseleave"&&(_r(null),lt(null));if($e.current!==!0&&(!("touches"in e)&&s&&(e.type==="mousemove"?Dn(s,e.clientX,e.clientY):e.type==="mouseleave"&&Dt(null)),!(!F.current||F.current.readyState!=="open"||!J.current||!s)))if("touches"in e){const n=e.touches,m=e.changedTouches;let l;switch(e.type){case"touchstart":l="down";break;case"touchmove":l="move";break;case"touchend":l="up";break;case"touchcancel":l="cancel";break;default:return}if(n.length===2){const E=n[0],C=n[1],v=Ge(s,E.clientX,E.clientY),g=Ge(s,C.clientX,C.clientY);if(!v||!g)return;z.current?z.current.source==="real-touch"&&(z.current.finger0={x:v.videoX,y:v.videoY},z.current.finger1={x:g.videoX,y:g.videoY},Je("move",v.videoWidth,v.videoHeight,v.videoX,v.videoY,g.videoX,g.videoY,z.current.pointerId0,z.current.pointerId1)):(z.current={finger0:{x:v.videoX,y:v.videoY},finger1:{x:g.videoX,y:g.videoY},videoSize:{width:v.videoWidth,height:v.videoHeight},source:"real-touch",pointerId0:E.identifier,pointerId1:C.identifier},Je("down",v.videoWidth,v.videoHeight,v.videoX,v.videoY,g.videoX,g.videoY,E.identifier,C.identifier))}else if(n.length<2&&z.current?.source==="real-touch"){const E=z.current;Je("up",E.videoSize.width,E.videoSize.height,E.finger0.x,E.finger0.y,E.finger1.x,E.finger1.y,E.pointerId0,E.pointerId1),z.current=null;return}else{if(n.length>2)return;{const E=m[0];if(E){const C=Ge(s,E.clientX,E.clientY);ke(E.identifier,l,C)}}}}else{let m=null;const l=z.current?.source==="alt-mouse";switch(e.type){case"mousedown":e.button===0&&(m="down");break;case"mousemove":(l||te.current.has(-1))&&(m="move");break;case"mouseup":e.button===0&&(m="up");break;case"mouseleave":(l||te.current.has(-1))&&(m="up");break}if(m){const E=Ge(s,e.clientX,e.clientY);if(!E)return;q("[rc-touch][mouse] event",{domType:e.type,eventType:m,button:e.button,buttons:e.buttons,client:{x:e.clientX,y:e.clientY},altHeldRef:Me.current,inTwoFingerMode:l,geometry:{videoX:E.videoX,videoY:E.videoY,videoWidth:E.videoWidth,videoHeight:E.videoHeight},activePointerIds:Array.from(te.current.keys())}),Me.current||l?Sn(m,E):ke(-1,m,E)}}},Sn=(e,s)=>{const{videoX:i,videoY:n,videoWidth:m,videoHeight:l}=s,E=m-i,C=l-n;if(e==="down"){z.current={finger0:{x:i,y:n},finger1:{x:E,y:C},videoSize:{width:m,height:l},source:"alt-mouse",pointerId0:At,pointerId1:Mt},J.current?.focus(),Je("down",m,l,i,n,E,C,At,Mt);return}if(e==="move"){z.current?.source==="alt-mouse"&&(z.current.finger0={x:i,y:n},z.current.finger1={x:E,y:C},Je("move",m,l,i,n,E,C,At,Mt));return}if(e==="up"||e==="cancel"){const v=z.current;if(v?.source==="alt-mouse"){const{finger0:g,finger1:k,videoSize:_}=v;Je("up",_.width,_.height,g.x,g.y,k.x,k.y,At,Mt),z.current=null}return}},bn=150,Nr=()=>{const e=We.current;e&&(window.clearTimeout(e.endTimer),ke(Ie,"up",e.pos),We.current=null)},An=e=>{if(e.ctrlKey||Me.current||z.current)return;const s=te.current.size;if(s>1||s===1&&!te.current.has(Ie))return;const i=ht();if(!i)return;const n=e.clientX-i.videoRect.left-i.offsetX,m=e.clientY-i.videoRect.top-i.offsetY;if(n<0||n>i.actualWidth||m<0||m>i.actualHeight)return;const l=Ge(i,e.clientX,e.clientY);if(!l)return;e.preventDefault();const E=(e.deltaMode===1?16:e.deltaMode===2?i.actualWidth:1)*(i.videoWidth/i.actualWidth),C=(e.deltaMode===1?16:e.deltaMode===2?i.actualHeight:1)*(i.videoHeight/i.actualHeight),v=-e.deltaX*E,g=-e.deltaY*C,k=X=>{window.clearTimeout(X.endTimer),X.endTimer=window.setTimeout(Nr,bn)};if(v===0&&g===0){We.current&&k(We.current);return}const _=()=>({videoWidth:l.videoWidth,videoHeight:l.videoHeight,videoX:Math.abs(v)>Math.abs(g)?Math.min(Math.max(l.videoX,l.videoWidth*.2),l.videoWidth*.8):l.videoX,videoY:Math.abs(g)>=Math.abs(v)?Math.min(Math.max(l.videoY,l.videoHeight*.2),l.videoHeight*.8):l.videoY}),U=X=>({...X,videoX:Math.min(Math.max(X.videoX+v,0),X.videoWidth),videoY:Math.min(Math.max(X.videoY+g,0),X.videoHeight)});let V=We.current;if(V)window.clearTimeout(V.endTimer);else{const X=_();ke(Ie,"down",X),V={pos:X,endTimer:0},We.current=V}let oe=V.pos,Te=U(oe);Te.videoX===oe.videoX&&Te.videoY===oe.videoY&&(ke(Ie,"up",oe),oe=_(),ke(Ie,"down",oe),Te=U(oe)),ke(Ie,"move",Te),V.pos=Te,k(V)};u.useEffect(()=>{ut.current={handle:An,end:Nr}}),u.useEffect(()=>{const e=tt.current;if(!e)return;const s=i=>ut.current.handle(i);return e.addEventListener("wheel",s,{passive:!1}),()=>{ut.current.end(),e.removeEventListener("wheel",s)}},[]),u.useEffect(()=>{const e=n=>{n.key==="Alt"&&Zt(!0)},s=n=>{n.key==="Alt"&&Zt(!1)},i=()=>{Zt(!1)};return window.addEventListener("keydown",e,!0),window.addEventListener("keyup",s,!0),window.addEventListener("blur",i),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("keyup",s,!0),window.removeEventListener("blur",i)}},[]);const Nt=e=>{e.preventDefault(),e.stopPropagation();const s=document.activeElement===J.current||ye&&document.activeElement===e.currentTarget;if(q("Keyboard event:",{type:e.type,key:e.key,keyCode:e.keyCode,code:e.code,target:e.target.tagName,focused:s}),!s){R("Simulator input not focused, skipping keyboard event");return}if(!F.current||F.current.readyState!=="open"){R("Data channel not ready for keyboard event:",F.current?.readyState);return}if(e.type==="keydown"){if(e.key.toLowerCase()==="v"&&(e.metaKey||e.ctrlKey)){q("Paste shortcut detected"),navigator.clipboard.readText().then(n=>{if(n){q("Pasting text via SET_CLIPBOARD:",n.substring(0,20)+(n.length>20?"...":""));const m=ci(n,!0);me(m)}}).catch(n=>{console.error("Failed to read clipboard contents: ",n)});return}if(e.key.toLowerCase()==="m"&&(e.metaKey||e.ctrlKey)){q("Menu shortcut detected");const n=Et(a.ACTION_DOWN,a.MENU,0,a.META_NONE);me(n);const m=Et(a.ACTION_UP,a.MENU,0,a.META_NONE);me(m);return}}const i=$i(e);if(i){const{keycode:n,metaState:m}=i,l=e.type==="keydown"?a.ACTION_DOWN:a.ACTION_UP;q(`Sending Keycode: key=${e.key}, code=${n}, action=${l}, meta=${m}`);const E=Et(l,n,0,m);me(E)}else q(`Ignoring unhandled key event: type=${e.type}, key=${e.key}`)},Mn=()=>{D.current&&D.current.readyState===WebSocket.OPEN&&D.current.send(JSON.stringify({type:"keepAlive",sessionId:he}))},Ir=()=>{Le.current&&window.clearInterval(Le.current),Le.current=window.setInterval(Mn,1e4)},kr=()=>{Le.current&&(window.clearInterval(Le.current),Le.current=void 0)},It=()=>{nt.current&&(window.clearTimeout(nt.current),nt.current=void 0)},kt=()=>{it.current&&(window.clearTimeout(it.current),it.current=void 0)},mt=()=>{vt.current&&(window.clearInterval(vt.current),vt.current=void 0)},pt=()=>{xe.current!==void 0&&(window.clearTimeout(xe.current),xe.current=void 0)},Nn=()=>{at.current||(at.current=!0,mt(),Ht(!0),qe("connected"))},ie=e=>{for(const s of e.getTracks())try{s.stop()}catch(i){R("track.stop() failed:",i)}},In=()=>{const e=ue.current;e&&(ue.current=null,ie(e))},Yr=e=>{const s=yr.current.then(e).catch(i=>{R("microphone operation failed:",i)});return yr.current=s,s},er=()=>jt.current||Vt.current,Kr=e=>{const s=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;Fe.current=s,e.send(JSON.stringify({type:"microphoneStart",id:s}))},tr=()=>Yr(()=>kn()),kn=async()=>{const e=wt.current,s=()=>e===wt.current&&er(),i=C=>{H("onMicrophoneStateChange",st.current,{active:!1,error:C})};if(!s())return;const n=D.current,m=ct.current;if(!n||n.readyState!==WebSocket.OPEN||!m||Ee.current)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)."),i("Microphone capture requires a secure context (https)");return}let l=null;try{l=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(C){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",C)}if(!s()){l&&ie(l);return}if(!l){i("Microphone permission denied or no device available");return}const E=l.getAudioTracks()[0]??null;if(!E){ie(l),i("Captured stream has no audio track");return}try{await m.replaceTrack(E)}catch(C){R("replaceTrack(audioTrack) failed:",C),ie(l),i("Failed to attach the microphone track to the connection");return}if(!s()){try{await m.replaceTrack(null)}catch(C){R("replaceTrack(null) on stale mic attach failed:",C)}ie(l);return}Ee.current=l,E.onended=()=>{Ee.current===l&&Yt("microphone capture ended by the browser")},Kr(n),H("onMicrophoneStateChange",st.current,{active:!0,label:E.label||void 0})},Yt=e=>(++wt.current,Fe.current=null,Yr(async()=>{const s=ct.current,i=Ee.current;if(Ee.current=null,s&&i)try{await s.replaceTrack(null)}catch(m){R("replaceTrack(null) on mic detach failed:",m)}i&&ie(i);const n=D.current;if(i&&n&&n.readyState===WebSocket.OPEN){const m=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;n.send(JSON.stringify({type:"microphoneStop",id:m}))}(i||e)&&H("onMicrophoneStateChange",st.current,{active:!1,...e!==void 0&&{error:e}})})),Pr=(e,s)=>{let i;try{i=Ri(s),console.info(`[RemoteControl] camera capture: ${i.camera?.width}x${i.camera?.height} @ ${i.camera?.frameRate??"?"}fps`+(i.camera?.label?` — ${i.camera.label}`:""))}catch(n){R("getSettings() on outbound camera track failed:",n),i={type:"cameraResult",granted:!0,camera:{label:s.label||void 0}}}e.send(JSON.stringify(i)),H("onCameraDemandChange",ve.current,!0,!0,i.camera)},Yn=e=>{if(!e)return;const s=e.indexOf("/"),n=(s>=0?e.slice(s+1):e).toUpperCase();return n==="HEVC"?"H265":n},Kn=async()=>{const e=Re.current,s=Tt.current;if(!e||!s)return;let i;try{i=await e.getStats()}catch{return}let n,m,l;if(i.forEach(U=>{U.type==="outbound-rtp"&&U.kind==="video"?n=U:U.type==="remote-inbound-rtp"&&U.kind==="video"&&(l=U)}),n?.codecId){const U=i.get(n.codecId);U&&(m=U.mimeType)}if(!n)return;const E=n.timestamp??Date.now(),C=_t.current;let v,g,k;if(C&&E>C.timestamp){const U=(E-C.timestamp)/1e3;if(typeof n.framesEncoded=="number"&&typeof C.framesEncoded=="number"&&(v=Math.max(0,(n.framesEncoded-C.framesEncoded)/U)),typeof n.bytesSent=="number"&&typeof C.bytesSent=="number"&&(g=Math.max(0,(n.bytesSent-C.bytesSent)*8/U)),typeof n.packetsSent=="number"&&typeof C.packetsSent=="number"&&l&&typeof l.packetsLost=="number"&&typeof C.packetsLost=="number"){const V=n.packetsSent-C.packetsSent,oe=l.packetsLost-C.packetsLost;V>0&&(k=Math.max(0,Math.min(100,oe/V*100)))}}_t.current={timestamp:E,framesEncoded:n.framesEncoded,bytesSent:n.bytesSent,packetsSent:n.packetsSent,packetsLost:l?.packetsLost};const _={codec:Yn(m),encoderImplementation:n.encoderImplementation,hardwareAccelerated:typeof n.powerEfficientEncoder=="boolean"?n.powerEfficientEncoder:void 0,framesPerSecond:v,framesEncoded:n.framesEncoded,bitrateBps:g,width:n.frameWidth,height:n.frameHeight,qualityLimitationReason:n.qualityLimitationReason,rttMs:typeof l?.roundTripTime=="number"?l.roundTripTime*1e3:void 0,packetsLostPct:k};H("onCameraStats",Tt.current,_)},Ur=()=>{ot.current===null&&(_t.current=null,ot.current=setInterval(()=>{Kn()},1e3))},Kt=()=>{ot.current!==null&&(clearInterval(ot.current),ot.current=null),_t.current=null,H("onCameraStats",Tt.current,null)},Pn=(e,s,i,n)=>qt.enqueue(async({isCurrent:m})=>{const l=()=>m()&&n()&&D.current===s&&Re.current===i;if(!l())return;if(!e.active){const _=ue.current;try{await i.replaceTrack(null)}catch(U){R("replaceTrack(null) on camera detach failed:",U)}if(ue.current===_&&(ue.current=null,Se.current=void 0,_&&ie(_)),Kt(),!l())return;H("onCameraDemandChange",ve.current,!1);return}H("onCameraDemandChange",ve.current,!0);const E=ue.current,C=E?.getVideoTracks()[0],v=Se.current;if(C?.readyState==="live"&&v&&!wi(v,e)){Se.current=e,Pr(s,C),Ur();return}if(E){try{await i.replaceTrack(null)}catch(_){R("replaceTrack(null) before camera switch failed:",_)}if(ue.current===E&&(ue.current=null,Se.current=void 0,ie(E)),Kt(),!l())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."),!l())return;s.send(JSON.stringify({type:"cameraResult",granted:!1})),H("onCameraDemandChange",ve.current,!0,!1);return}let g=null;try{g=await navigator.mediaDevices.getUserMedia({video:_i(e),audio:!1})}catch(_){console.warn("[RemoteControl] getUserMedia denied/failed:",_)}if(!l()){g&&ie(g);return}if(!g){s.send(JSON.stringify({type:"cameraResult",granted:!1})),H("onCameraDemandChange",ve.current,!0,!1);return}const k=g.getVideoTracks()[0]??null;if(!k){if(ie(g),!l())return;s.send(JSON.stringify({type:"cameraResult",granted:!1})),H("onCameraDemandChange",ve.current,!0,!1);return}try{k.contentHint="motion"}catch{}try{await i.replaceTrack(k)}catch(_){if(R("replaceTrack(videoTrack) failed:",_),ie(g),!l())return;s.send(JSON.stringify({type:"cameraResult",granted:!1})),H("onCameraDemandChange",ve.current,!0,!1);return}if(!l()){try{await i.replaceTrack(null)}catch(_){R("replaceTrack(null) for stale camera attach failed:",_)}ie(g);return}try{const _=i.getParameters();(!_.encodings||_.encodings.length===0)&&(_.encodings=[{}]),_.encodings[0].maxBitrate=8e6,_.encodings[0].maxFramerate=30,_.degradationPreference="maintain-framerate",await i.setParameters(_)}catch(_){R("setParameters on outbound camera failed:",_)}if(!l()){try{await i.replaceTrack(null)}catch(_){R("replaceTrack(null) for stale camera finalize failed:",_)}ie(g);return}ue.current=g,Se.current=e,k.onended=()=>{ue.current===g&&qt.enqueueCurrent(async({isCurrent:_})=>{if(!(!_()||ue.current!==g||!n()||D.current!==s||Re.current!==i)){try{await i.replaceTrack(null)}catch(U){R("replaceTrack(null) after camera ended failed:",U)}!_()||ue.current!==g||!n()||D.current!==s||Re.current!==i||(ue.current=null,Se.current=void 0,ie(g),Kt(),s.send(JSON.stringify({type:"cameraResult",granted:!1})),H("onCameraDemandChange",ve.current,!0,!1))}}).catch(_=>R("camera ended cleanup failed:",_))},l()&&(Pr(s,k),Ur())}),ze=()=>{Er(null);for(const e of Ke.current.values())e();Ke.current.clear();for(const e of Pe.current.values())clearTimeout(e.timer),e.reject(new Error("Simulator disconnected"));Pe.current.clear(),lr(null),rt.current&&(rt.current.srcObject=null),kt(),pt(),mt(),ne.current&&(ne.current.stop(),ne.current=null),qt.invalidate(),Kt(),In(),Se.current=void 0,Re.current=null,++wt.current,Vt.current=!1,Fe.current=null,Ee.current&&(ie(Ee.current),Ee.current=null,H("onMicrophoneStateChange",st.current,{active:!1})),ct.current=null,fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0),D.current&&(D.current.onopen=null,D.current.onmessage=null,D.current.onerror=null,D.current.onclose=null,D.current.close(),D.current=null),Ct.current?.close(),Ct.current=null,B.current&&(B.current.onconnectionstatechange=null,B.current.oniceconnectionstatechange=null,B.current.ontrack=null,B.current.onicecandidate=null,B.current.close(),B.current=null),J.current&&(J.current.srcObject=null),F.current&&(F.current.onopen=null,F.current.onclose=null,F.current.onerror=null,F.current.close(),F.current=null)},Lr=()=>{document.hidden?kr():Ir()},Un=async()=>{if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let e;try{const n=new URL(t);n.protocol=n.protocol==="wss:"?"https:":n.protocol==="ws:"?"http:":n.protocol,e=Xr(n.toString(),o)}catch{return!1}const s=new AbortController,i=window.setTimeout(()=>s.abort(),Fi);try{return(await fetch(e,{method:"GET",cache:"no-store",signal:s.signal})).status===404}catch{return!1}finally{window.clearTimeout(i)}},Ln=()=>{Ue.current||(Ue.current=!0,hr(!0),yt(!1),De.current+=1,It(),kt(),pt(),ze(),x("Instance terminated"),qe("terminated"),H("onTerminated",Dr.current))},xn=()=>{Ue.current||$t.current||($t.current=!0,Un().then(e=>{$t.current=!1,e&&Ln()}))},Qe=(e,s)=>{if(Ue.current||s!==De.current)return;if(xn(),Ce.current){if(!Xt.current){x(`Connection failed after it was established: ${e}`),yt(!0),qe("failed"),ze();return}x(`Reconnecting after established session dropped: ${e}`),Ce.current=!1,Ot.current=-1}It();const i=Ot.current+1;if(i>=ir){x(`Connection failed after ${ir} attempts: ${e}`),yt(!0),qe("failed"),ze();return}x(`Retrying connection (${i+1}/${ir})`),qe("reconnecting"),ze(),nt.current=window.setTimeout(()=>{nt.current=void 0,s===De.current&&xr(i)},Ui)},xr=async(e=0)=>{if(Ue.current)return;const s=De.current+1;De.current=s,Ot.current=e,Ce.current=!1,yt(!1),e===0&&Qt.current!=="reconnecting"&&qe("connecting"),It(),kt(),mt(),at.current=!1,Ht(!1),ze();const i=()=>s===De.current;it.current=window.setTimeout(()=>{it.current=void 0,!(!i()||Ce.current)&&Qe("Connection did not succeed within 15 seconds",s)},Li);try{const n=new WebSocket(Xr(t,o));if(D.current=n,await new Promise((w,f)=>{let K=!1;const se=window.setTimeout(()=>f(new Error("WebSocket connection timeout")),3e4),b=P=>{K||(K=!0,window.clearTimeout(se),P())};n.onopen=()=>{!i()||D.current!==n||b(w)},n.onerror=P=>{!i()||D.current!==n||(x("WebSocket error: "+P),b(()=>f(new Error("WebSocket connection failed"))))},n.onclose=()=>{!i()||D.current!==n||(x("WebSocket closed"),b(()=>f(new Error("WebSocket closed before connection was established"))))}}),!i()||D.current!==n)return;n.onerror=w=>{!i()||D.current!==n||x("WebSocket error: "+w)},n.onclose=()=>{!i()||D.current!==n||x("WebSocket closed")};const m=new Promise((w,f)=>{const K=P=>{window.clearTimeout(se),n.removeEventListener("message",b),P()},se=window.setTimeout(()=>K(()=>f(new Error("RTCConfiguration timeout"))),3e4),b=P=>{if(!(!i()||D.current!==n))try{const Q=JSON.parse(P.data);if(Q.type==="signalingError"&&Q.requestType==="requestRtcConfiguration"&&Q.sessionId===he){const le=typeof Q.error=="string"?Q.error:"Unable to load streaming configuration";K(()=>f(new Error(le)))}else Q.type==="rtcConfiguration"&&K(()=>w({rtcConfiguration:Q.rtcConfiguration,cameraSupported:Q.cameraSupported===!0,foldSupported:Q.foldSupported===!0}))}catch(Q){console.error("Error handling RTC configuration:",Q),K(()=>f(Q))}};n.addEventListener("message",b),n.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:he}))}),{rtcConfiguration:l,cameraSupported:E,foldSupported:C}=await m;if(!i()||D.current!==n)return;const v=d==="iphone-duo"||C;sn(v);const g=new RTCPeerConnection({...l,iceTransportPolicy:"relay"});B.current=g;const k={peer:g,displays:new Map};Er(k),g.addTransceiver("audio",{direction:"recvonly"});const _=g.addTransceiver("video",{direction:"recvonly"}),U=v?g.addTransceiver("video",{direction:"recvonly"}):null,V=ge==="ios"||E,oe=V?g.addTransceiver("video",{direction:"sendonly"}):null;Re.current=oe?.sender??null;const Te=V?g.addTransceiver("audio",{direction:"sendonly"}):null;if(ct.current=Te?.sender??null,RTCRtpReceiver.getCapabilities){const w=RTCRtpReceiver.getCapabilities("video");if(w&&w.codecs){const K=w.codecs.sort((se,b)=>{const P=Q=>{const le=Q.mimeType.toLowerCase();return le.includes("vp9")?1:le.includes("h265")||le.includes("hevc")?2:le.includes("h264")||le.includes("avc")?3:4};return P(se)-P(b)});_.setCodecPreferences(K),U?.setCodecPreferences(K),q("Set codec preferences:",K.map(se=>se.mimeType).join(", "))}}if(oe&&RTCRtpSender.getCapabilities){const w=RTCRtpSender.getCapabilities("video");if(w&&w.codecs){const f=new Set(["42e01f","42e028","640c1f"]),K=b=>{const P=b.mimeType.toLowerCase(),le=(b.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),Bn=le?le[1]:"";return P==="video/h265"||P==="video/hevc"?1:P==="video/h264"&&f.has(Bn)?2:P==="video/h264"?3:P==="video/vp9"?4:P==="video/vp8"?5:P==="video/rtx"||P==="video/red"||P==="video/ulpfec"?0:6},se=[...w.codecs].sort((b,P)=>K(b)-K(P));try{oe.setCodecPreferences(se),q("Outbound camera codec preferences:",se.map(b=>`${b.mimeType}${b.sdpFmtpLine?`[${b.sdpFmtpLine}]`:""}`).join(", "))}catch(b){R("Failed to set outbound camera codec preferences:",b)}}}const X=g.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});F.current=X;const nr=!v&&Bt.current?oi(g,w=>{i()&&B.current===g&&H("onTrace",Bt.current,w)}):null;if(Ct.current=nr,X.onopen=()=>{if(!i()||F.current!==X||D.current!==n)return;Ce.current=!0,kt(),x("Control channel opened"),v&&n.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),ne.current||(ne.current=new vi({platform:ge,baseIntervalMs:G,maxBackoffMs:Z,androidElementTreeOptions:$,send:f=>{if(!D.current||D.current.readyState!==WebSocket.OPEN)return!1;try{return D.current.send(JSON.stringify(f)),!0}catch{return!1}},onSnapshot:f=>{vr(K=>sr(K,f)?K:f),queueMicrotask(()=>{H("onAxSnapshotChange",zt.current,f)})},onStatusChange:(f,K)=>{H("onAxStatusChange",wr.current,f,K)}}),($e.current===!0||$e.current==="hover-only")&&ne.current.start());const w=()=>{!i()||at.current||F.current!==X||D.current!==n||n.readyState!==WebSocket.OPEN||n.send(JSON.stringify({type:"requestFrame",sessionId:he}))};if(w(),mt(),vt.current=window.setInterval(()=>{if(!i()||at.current||F.current!==X||D.current!==n||n.readyState!==WebSocket.OPEN){mt();return}w()},250),h){try{const f=decodeURIComponent(h);x("Opening URL"),n.send(JSON.stringify({type:"openUrl",url:f,sessionId:he}))}catch(f){console.error({error:f},"Error decoding URL, falling back to the original URL"),n.send(JSON.stringify({type:"openUrl",url:h,sessionId:he}))}ne.current?.bumpActivity()}},X.onclose=()=>{!i()||F.current!==X||x("Control channel closed")},X.onerror=w=>{!i()||F.current!==X||(console.error("Control channel error:",w),x("Control channel error: "+w))},g.onconnectionstatechange=()=>{!i()||B.current!==g||(x("Connection state: "+g.connectionState),g.connectionState==="failed"&&Ce.current&&Qe("WebRTC connection entered failed state",s))},g.oniceconnectionstatechange=()=>{if(!i()||B.current!==g)return;const w=g.iceConnectionState;if(x("ICE state: "+w),w==="connected"||w==="completed"){pt(),er()&&!Ee.current&&tr();return}if(w==="failed"){pt(),Ce.current&&Qe("ICE connection entered failed state",s);return}w==="disconnected"&&Ce.current&&Xt.current&&xe.current===void 0&&(xe.current=window.setTimeout(()=>{xe.current=void 0,!(!i()||B.current!==g)&&g.iceConnectionState==="disconnected"&&Qe("ICE stayed disconnected past grace period",s)},xi))},g.ontrack=w=>{if(!i()||B.current!==g)return;Wr(w.receiver,gr.current);const f=w.track.id==="duo-inner"||w.streams.some(K=>K.id==="duo-inner");if(w.track.kind==="video"&&k.displays.set(w.receiver,f?"inner":"primary"),x("Received remote track: "+w.track.kind),w.track.kind==="video"&&J.current){q(`[${new Date().toISOString()}] Video track received:`,w.track);const K=f?rt.current:J.current;if(K){const se=v?new MediaStream([w.track]):w.streams[0]??new MediaStream([w.track]);Ke.current.get(K)?.(),Ke.current.set(K,ii(K,se,b=>R("Video playback fallback:",b)))}}},g.onicecandidate=w=>{if(!(!i()||B.current!==g||D.current!==n))if(w.candidate&&n.readyState===WebSocket.OPEN){const f={type:"candidate",candidate:w.candidate.candidate,sdpMid:w.candidate.sdpMid,sdpMLineIndex:w.candidate.sdpMLineIndex,sessionId:he};n.send(JSON.stringify(f)),x("Sent ICE candidate")}else x("ICE candidate gathering completed")},n.onmessage=async w=>{if(!i()||D.current!==n)return;let f;try{f=JSON.parse(w.data)}catch(K){R("Error parsing message:",K);return}if(!ne.current?.handleMessage(f))switch(x("Received: "+f.type),f.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!v)break;f.state?(lr(f.state),fr(void 0)):f.id==="duo-capabilities"&&fr(f.error||"This instance does not support native iPhone Duo displays.");const b=Pe.current.get(f.id);b&&(clearTimeout(b.timer),Pe.current.delete(f.id),f.error?b.reject(new Error(f.error)):b.resolve());break}case"signalingError":{if(f.requestType!=="offer"||f.sessionId!==he)break;const b=typeof f.error=="string"?f.error:"Unable to establish the streaming connection";x("Error: "+b),Qe(b,s);break}case"answer":if(!B.current||B.current!==g){x("No peer connection, skipping answer");break}if(nr?.accept(f.latencyTraceVersion),await g.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:f.sdp})),!i()||B.current!==g)return;x("Set remote description");break;case"candidate":if(!B.current||B.current!==g){x("No peer connection, skipping candidate");break}if(await g.addIceCandidate(new RTCIceCandidate({candidate:f.candidate,sdpMid:f.sdpMid,sdpMLineIndex:f.sdpMLineIndex})),!i()||B.current!==g)return;x("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof f.id!="string"){R("Received invalid screenshot success message:",f);break}const b=Xi(f);if(b){const le=Oe.current.get(f.id);if(!le){R(`Received screenshot error for unknown or handled id: ${f.id}`);break}R(`Received screenshot error for id ${f.id}: ${b}`),le(new Error(b)),_e.current.delete(f.id),Oe.current.delete(f.id);break}const P=qi(f);if(!P){R("Received screenshot message without image data:",f);break}const Q=_e.current.get(f.id);if(!Q){R(`Received screenshot data for unknown or handled id: ${f.id}`);break}q(`Received screenshot data for id ${f.id}`),Q(P),_e.current.delete(f.id),Oe.current.delete(f.id);break}case"screenshotError":if(typeof f.id!="string"||typeof f.message!="string"){R("Received invalid screenshot error message:",f);break}const K=Oe.current.get(f.id);if(!K){R(`Received screenshot error for unknown or handled id: ${f.id}`);break}R(`Received screenshot error for id ${f.id}: ${f.message}`),K(new Error(f.message)),_e.current.delete(f.id),Oe.current.delete(f.id);break;case"cameraRequest":{const b=Re.current;if(!b)break;const P=Ti(f);if(!P){R("Received invalid cameraRequest:",f);break}console.info("[RemoteControl] cameraRequest received:",P.active,P.facingMode),await Pn(P,n,b,i);break}case"microphoneRequest":{if(!ct.current)break;const b=f.active===!0;if(Vt.current=b,console.info("[RemoteControl] microphoneRequest received, active=",b),!b){jt.current||await Yt();break}if(Ee.current){Kr(n);break}await tr();break}case"microphoneStartResult":{if(Fe.current===null||f.id!==Fe.current)break;Fe.current=null,typeof f.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",f.error),Yt(f.error));break}case"terminateAppResult":if(typeof f.id!="string"){R("Received invalid terminateApp result message:",f);break}if(typeof f.error=="string"){const b=Ae.current.get(f.id);if(!b){R(`Received terminateApp error for unknown or handled id: ${f.id}`);break}R(`Received terminateApp error for id ${f.id}: ${f.error}`),b(new Error(f.error)),be.current.delete(f.id),Ae.current.delete(f.id);break}const se=be.current.get(f.id);if(!se){R(`Received terminateApp result for unknown or handled id: ${f.id}`);break}q(`Received terminateApp success for id ${f.id}`),se(),be.current.delete(f.id),Ae.current.delete(f.id);break;default:R(`Received unhandled message type: ${f.type}`,f);break}},B.current===g){const w=await g.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!i()||B.current!==g||(await g.setLocalDescription(w),!i()||B.current!==g))return;i()&&D.current===n&&n.readyState===WebSocket.OPEN&&n.send(JSON.stringify({type:"offer",...v?{displayStreams:!0}:{},...nr?{latencyTraceVersion:1}:{},sdp:w.sdp,sessionId:he})),x("Sent offer")}}catch(n){if(!i())return;const m=n instanceof Error?n.message:String(n);x("Error: "+m),Qe(m,s)}},rr=()=>{Ue.current=!1,hr(!1),xr(0)},Fn=()=>{De.current+=1,Ot.current=0,Ce.current=!1,It(),pt(),ze(),x("Stopped")},Wn=e=>{e.stopPropagation(),rr()};u.useEffect(()=>{er()?tr():Yt()},[pe]),u.useEffect(()=>(Ht(!1),rr(),document.hidden||Ir(),document.addEventListener("visibilitychange",Lr),()=>{kr(),Fn(),document.removeEventListener("visibilitychange",Lr)}),[t,o,c,d,pn]);const Fr=()=>{const e=ht();if(!e){Or(null);return}const s={left:e.videoRect.left-e.containerRect.left+e.offsetX,top:e.videoRect.top-e.containerRect.top+e.offsetY,width:e.actualWidth,height:e.actualHeight};Or(i=>i&&i.left===s.left&&i.top===s.top&&i.width===s.width&&i.height===s.height?i:s)};u.useEffect(()=>{const e=J.current,s=ar.current,i=tt.current;if(!e)return;const n=()=>{if(!bt||!s){pr({}),Fr();return}const E=s.clientWidth,C=s.clientHeight;if(E===0||C===0)return;const v=e.videoWidth>e.videoHeight;ln(v),fn(ge==="android"&&Wi(e.videoWidth,e.videoHeight));const g=v?je.videoPosition.landscape:je.videoPosition.portrait;let k={};g.heightMultiplier?(k.height=`${C*g.heightMultiplier}px`,k.width="auto"):g.widthMultiplier&&(k.width=`${E*g.widthMultiplier}px`,k.height="auto"),k.borderRadius=`${v?C*je.videoBorderRadiusMultiplier:E*je.videoBorderRadiusMultiplier}px`,pr(k),Fr()},m=new ResizeObserver(()=>{n()});s&&m.observe(s),m.observe(e),i&&m.observe(i),s&&s.addEventListener("load",n),e.addEventListener("loadedmetadata",n),e.addEventListener("resize",n);const l=()=>ne.current?.bumpActivity();return e.addEventListener("resize",l),n(),()=>{m.disconnect(),e.removeEventListener("loadedmetadata",n),e.removeEventListener("resize",n),e.removeEventListener("resize",l),s&&s.removeEventListener("load",n)}},[je,bt]),u.useEffect(()=>{const e=ne.current;dt?e?.start():(e?.stop(),vr(null),lt(null),Rt(null),Tr(null),He(null),St.current=null,fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0),H("onAxSnapshotChange",zt.current,null))},[dt]),u.useEffect(()=>()=>{fe.current!==void 0&&(window.cancelAnimationFrame(fe.current),fe.current=void 0)},[]),u.useEffect(()=>{if(!dt)return;const e=s=>{s.key==="Escape"&&(Jt||Gt)&&(Rt(null),lt(null),He(null),H("onInspectSelectionChange",Xe.current,null))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[dt,Jt,Gt]);const Hn=()=>{J.current&&J.current.focus()};u.useImperativeHandle(et,()=>({openUrl:e=>{if(!D.current||D.current.readyState!==WebSocket.OPEN){R("WebSocket not open, cannot send open_url command via ref.");return}try{const s=decodeURIComponent(e);x("Opening URL"),D.current.send(JSON.stringify({type:"openUrl",url:s,sessionId:he}))}catch(s){R("Error decoding or sending URL via ref:",{error:s,url:e}),D.current.send(JSON.stringify({type:"openUrl",url:e,sessionId:he}))}ne.current?.bumpActivity()},sendKeyEvent:e=>{if(!F.current||F.current.readyState!=="open"){R("Data channel not ready for imperative key command:",F.current?.readyState);return}const s=Gr[e.code];if(!s){R(`Unknown event.code for imperative command: ${e.code}`);return}let i=a.META_NONE;e.shiftKey&&(i|=a.META_SHIFT_ON),e.altKey&&(i|=a.META_ALT_ON),e.ctrlKey&&(i|=a.META_CTRL_ON),e.metaKey&&(i|=a.META_META_ON);const n=e.type==="keydown"?a.ACTION_DOWN:a.ACTION_UP;q(`Sending Imperative Key Command: code=${e.code}, keycode=${s}, action=${n}, meta=${i}`);const m=Et(n,s,0,i);m&&me(m)},screenshot:e=>new Promise((s,i)=>{if(!D.current||D.current.readyState!==WebSocket.OPEN)return R("WebSocket not open, cannot send screenshot command."),i(new Error("WebSocket is not connected or connection is not open."));const n=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,m={type:e?"screenshotDisplay":"screenshot",...e?{display:e}:{},id:n};_e.current.set(n,s),Oe.current.set(n,i),q("Sending screenshot request:",m);try{D.current.send(JSON.stringify(m))}catch(l){R("Failed to send screenshot request immediately:",l),_e.current.delete(n),Oe.current.delete(n),i(l);return}setTimeout(()=>{_e.current.has(n)&&(R(`Screenshot request timed out for id ${n}`),Oe.current.get(n)?.(new Error("Screenshot request timed out")),_e.current.delete(n),Oe.current.delete(n))},3e4)}),terminateApp:e=>new Promise((s,i)=>{if(!D.current||D.current.readyState!==WebSocket.OPEN)return R("WebSocket not open, cannot send terminateApp command."),i(new Error("WebSocket is not connected or connection is not open."));const n=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,m={type:"terminateApp",id:n,bundleId:e};be.current.set(n,s),Ae.current.set(n,i),q("Sending terminateApp request:",m);try{D.current.send(JSON.stringify(m))}catch(l){R("Failed to send terminateApp request immediately:",l),be.current.delete(n),Ae.current.delete(n),i(l);return}ne.current?.bumpActivity(),setTimeout(()=>{be.current.has(n)&&(R(`terminateApp request timed out for id ${n}`),Ae.current.get(n)?.(new Error("terminateApp request timed out")),be.current.delete(n),Ae.current.delete(n))},3e4)}),reconnect:()=>rr(),refreshAxTree:async()=>{const e=ne.current;if(!e)throw new Error("Inspect mode is not active");return e.refresh()},getAxSnapshot:()=>Be.current,setInspectHighlight:e=>{lt(e?.id??null)},setInspectSelection:e=>{Rt(e?.id??null),He(e?St.current:null);const s=Be.current;e&&s?H("onInspectSelectionChange",Xe.current,{element:e,snapshot:s}):H("onInspectSelectionChange",Xe.current,null)},getAxStatus:()=>ne.current?.getStatus()??"idle"}));const $n=En&&Ne!==null;return A.jsxs("div",{ref:tt,className:Ye("rc-container",r),style:{touchAction:"none"},onMouseDown:we,onMouseMove:we,onMouseUp:we,onMouseLeave:we,onTouchStart:we,onTouchMove:we,onTouchEnd:we,onTouchCancel:we,children:[$n&&Ne&&A.jsxs(A.Fragment,{children:[A.jsx("div",{className:"rc-touch-indicator",style:{left:`${Ne.containerX}px`,top:`${Ne.containerY}px`}}),A.jsx("div",{className:"rc-touch-indicator",style:{left:`${Ne.mirrorContainerX}px`,top:`${Ne.mirrorContainerY}px`}})]}),bt&&A.jsx("img",{ref:ar,src:Sr,alt:"",className:ge==="ios"?Ye("rc-phone-frame","rc-phone-frame-ios"):"rc-phone-frame",draggable:!1}),A.jsx("video",{ref:J,className:Ye("rc-video",!bt&&"rc-video-frameless",!cn&&"rc-video-loading"),style:{...hn,...ye?{opacity:0,width:1,height:1,pointerEvents:"none"}:{},...br?{backgroundImage:`url("${br}")`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:je.loadingLogoSize}:{}},autoPlay:!0,playsInline:!0,muted:!0,tabIndex:ye?-1:0,onKeyDown:Nt,onKeyUp:Nt,onClick:Hn,onLoadedData:Nn,onFocus:()=>{J.current&&(J.current.style.outline="none")},onBlur:()=>{J.current&&(J.current.style.outline="none")}}),ye&&A.jsx("video",{ref:rt,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",width:1,height:1,opacity:0,pointerEvents:"none"}}),ye&&ur&&A.jsx(u.Suspense,{fallback:A.jsx("div",{children:"Loading iPhone Duo…"}),children:A.jsx(Ki,{showFrame:p,modelUrl:y,outer:J.current,inner:rt.current,state:ur,setAngle:e=>Wt("setHingeAngle",{angleDegrees:e}),setOrientation:e=>Wt("setDuoOrientation",{orientation:e}),button:(e,s)=>Wt("performActions",{actions:[{type:s?"buttonDown":"buttonUp",button:e}]}),touch:(e,s,i,n)=>{const m=F.current;m?.readyState==="open"&&m.send(zn(e,s,i,n))},onKeyDown:Nt,onKeyUp:Nt})}),ye&&dr&&A.jsx("div",{role:"alert",className:"rc-duo-error",children:dr}),!ye&&dt&&A.jsx(Yi,{snapshot:Cr,geometry:yn,highlightedId:Gt,selectedId:Jt,mode:On,cursorPosition:Cn,frozenCursorPosition:vn,onSelectChange:(e,s)=>{Rt(e?.id??null),e&&s?He(s):e||He(null);const i=Be.current;e&&i?H("onInspectSelectionChange",Xe.current,{element:e,snapshot:i}):H("onInspectSelectionChange",Xe.current,null)},onTapElement:(e,s)=>{if(s){Mr(s.x,s.y);return}const i=Be.current;i&&Tn(e,i)}}),un?A.jsxs("div",{className:"rc-terminated",role:"status",children:[A.jsx("div",{className:"rc-terminated-title",children:"Instance terminated"}),A.jsx("div",{className:"rc-terminated-message",children:"This instance no longer exists and can't be reconnected."})]}):an&&A.jsx("button",{type:"button",className:"rc-retry-button",onClick:Wn,children:"Retry"})]})}),Xi=r=>typeof r.message=="string"?r.message:typeof r.error=="string"?r.error:null,qi=r=>typeof r.dataUri=="string"?{dataUri:r.dataUri}:typeof r.base64=="string"?r.base64.startsWith("data:")?{dataUri:r.base64}:{dataUri:`data:${r.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${r.base64}`}:null;exports.AX_UNAVAILABLE_ERROR=Lt;exports.DUO_BUTTONS=Zn;exports.DUO_DIMENSIONS=qn;exports.DuoButtonSender=ei;exports.HingeSender=Qn;exports.RemoteControl=Bi;exports.axElementAtPoint=tn;exports.axElementSelectorExpression=rn;exports.axElementSummary=cr;exports.axElementsEqual=or;exports.axSnapshotsEqual=sr;exports.clampAxFrameForScreen=en;exports.duoPointerMode=Jn;exports.flatDisplayTouch=jn;exports.normalizeAndroidTree=Zr;exports.normalizeIosTree=Qr;exports.panelTouch=Gn;