@limrun/ui 0.18.0 → 0.18.2

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