@limrun/ui 0.20.5 → 0.20.6

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/dist/lite.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./remote-control-DvQGYstG.js"),e=require("./core-OsPKiOsB.js");exports.RemoteControl=r.RemoteControl;exports.AX_UNAVAILABLE_ERROR=e.AX_UNAVAILABLE_ERROR;exports.axElementAtPoint=e.axElementAtPoint;exports.axElementSelectorExpression=e.axElementSelectorExpression;exports.axElementSummary=e.axElementSummary;exports.axElementsEqual=e.axElementsEqual;exports.axSnapshotsEqual=e.axSnapshotsEqual;exports.clampAxFrameForScreen=e.clampAxFrameForScreen;exports.normalizeAndroidTree=e.normalizeAndroidTree;exports.normalizeIosTree=e.normalizeIosTree;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./remote-control-CTn0dIkj.js"),e=require("./core-Bdivxz74.js");exports.RemoteControl=r.RemoteControl;exports.AX_UNAVAILABLE_ERROR=e.AX_UNAVAILABLE_ERROR;exports.axElementAtPoint=e.axElementAtPoint;exports.axElementSelectorExpression=e.axElementSelectorExpression;exports.axElementSummary=e.axElementSummary;exports.axElementsEqual=e.axElementsEqual;exports.axSnapshotsEqual=e.axSnapshotsEqual;exports.clampAxFrameForScreen=e.clampAxFrameForScreen;exports.normalizeAndroidTree=e.normalizeAndroidTree;exports.normalizeIosTree=e.normalizeIosTree;
package/dist/lite.js CHANGED
@@ -1,5 +1,5 @@
1
- import { R as o } from "./remote-control-CkZWwh1w.mjs";
2
- import { A as s, a as m, b as n, c as t, d as l, e as x, f as E, n as A, g as i } from "./core-DuukW7sF.mjs";
1
+ import { R as o } from "./remote-control-VZ7b8hFe.mjs";
2
+ import { A as s, a as m, b as n, c as t, d as l, e as x, f as E, n as A, g as i } from "./core-BpV73M0K.mjs";
3
3
  export {
4
4
  s as AX_UNAVAILABLE_ERROR,
5
5
  o as RemoteControl,
@@ -0,0 +1 @@
1
+ "use strict";require('./index.css');const h=require("react/jsx-runtime"),r=require("./core-Bdivxz74.js"),d=require("react"),kt=require("react-dom"),Lt=async f=>{if(!f)return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(f),!0}catch{}try{const i=document.createElement("textarea");i.value=f,i.style.position="fixed",i.style.opacity="0",document.body.appendChild(i),i.select();const g=document.execCommand("copy");return document.body.removeChild(i),g}catch{return!1}},Wt=d.memo(function({element:i,screen:g,highlighted:p,selected:O,selectable:H,onClick:R}){const v=r.clampAxFrameForScreen(i.frame,g);if(!v)return null;const W=r.axElementSummary(i);return h.jsx("button",{type:"button",className:i.enabled?"rc-inspect-box":"rc-inspect-box rc-inspect-box-disabled","data-ax-id":i.id,"data-ax-path":i.path,"data-ax-label":i.label||void 0,"data-ax-role":i.role||void 0,"data-highlighted":p?"true":"false","data-selected":O?"true":"false","aria-label":W,onClick:y=>{H&&(y.preventDefault(),y.stopPropagation(),R(i,{x:y.clientX,y:y.clientY}))},style:{left:`${v.x/g.width*100}%`,top:`${v.y/g.height*100}%`,width:`${v.width/g.width*100}%`,height:`${v.height/g.height*100}%`}})},(f,i)=>f.highlighted===i.highlighted&&f.selected===i.selected&&f.selectable===i.selectable&&f.screen.width===i.screen.width&&f.screen.height===i.screen.height&&f.onClick===i.onClick&&r.axElementsEqual(f.element,i.element)),Xt=260,Ht=220,jt=6,Vt=8,Kt=d.memo(function({element:i,platform:g,anchor:p,cursorAnchored:O,showActions:H,onTap:R}){const[v,W]=d.useState(null);d.useEffect(()=>{if(!v)return;const A=window.setTimeout(()=>W(null),1100);return()=>window.clearTimeout(A)},[v]);const y=d.useMemo(()=>{const A=Xt,V=Ht,P=jt,E=Vt,F=typeof window<"u"?window.innerWidth:1024,Te=typeof window<"u"?window.innerHeight:768,K=p.x+P+A<=F-E,G=p.y-P-V>=E;let Z=K?p.x+P:p.x-P,ae=G?p.y-P:p.y+P;const ee=`translate(${K?"0":"-100%"}, ${G?"-100%":"0"})`;return Z=Math.max(E+(K?0:A),Math.min(F-E-(K?A:0),Z)),ae=Math.max(E+(G?V:0),Math.min(Te-E-(G?0:V),ae)),{left:`${Z}px`,top:`${ae}px`,transform:ee}},[p.x,p.y]),M=d.useMemo(()=>r.axElementSelectorExpression(i,g),[i,g]),I=g==="ios"?i.selectors.AXUniqueId:i.selectors.resourceId,x=g==="ios"?"AXUniqueId":"resourceId",$=d.useCallback(async(A,V)=>{if(!A)return;await Lt(A)&&W(V)},[]),q=r.axElementRoleLabel(i),X=i.label||i.value||q,Q=r.axElementSummary(i);return kt.createPortal(h.jsxs("div",{className:"rc-inspect-card","data-cursor-anchored":O?"true":"false",style:y,onClick:A=>A.stopPropagation(),onMouseDown:A=>A.stopPropagation(),onMouseMove:A=>A.stopPropagation(),children:[h.jsxs("div",{className:"rc-inspect-card-header",children:[h.jsx("span",{className:"rc-inspect-card-role",children:q}),!i.enabled&&h.jsx("span",{className:"rc-inspect-card-tag",children:"disabled"}),i.focused&&h.jsx("span",{className:"rc-inspect-card-tag rc-inspect-card-tag-blue",children:"focused"})]}),h.jsx("p",{className:"rc-inspect-card-title",title:Q,children:X}),I&&h.jsxs("div",{className:"rc-inspect-card-row",children:[h.jsxs("span",{className:"rc-inspect-card-row-label",children:[x,":"]}),h.jsx("span",{className:"rc-inspect-card-row-value",children:I})]}),i.value&&i.value!==i.label&&h.jsxs("div",{className:"rc-inspect-card-row",children:[h.jsx("span",{className:"rc-inspect-card-row-label",children:"value:"}),h.jsx("span",{className:"rc-inspect-card-row-value",children:i.value})]}),h.jsxs("div",{className:"rc-inspect-card-row",children:[h.jsx("span",{className:"rc-inspect-card-row-label",children:"frame:"}),h.jsxs("span",{className:"rc-inspect-card-row-value",children:[Math.round(i.frame.width),"×",Math.round(i.frame.height)," @ ",Math.round(i.frame.x),",",Math.round(i.frame.y)]})]}),H&&h.jsxs("div",{className:"rc-inspect-card-actions",children:[h.jsx("button",{type:"button",className:"rc-inspect-card-btn rc-inspect-card-btn-primary",disabled:!R,onClick:()=>R?.(i,p),children:"Tap"}),h.jsx("button",{type:"button",className:v==="selector"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!M,title:M??"No usable selector for this element",onClick:()=>$(M??void 0,"selector"),children:v==="selector"?"Copied!":"Copy selector"}),h.jsx("button",{type:"button",className:v==="id"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!I,title:I??`No ${x}`,onClick:()=>$(I,"id"),children:v==="id"?"Copied!":`Copy ${x}`})]})]}),document.body)}),Ut=d.memo(function({snapshot:i,geometry:g,highlightedId:p,selectedId:O,mode:H,cursorPosition:R,frozenCursorPosition:v,onSelectChange:W,onTapElement:y}){const M=H==="select",I=M?p!==null&&p!==O:p!==null,x=M?p??O:p,$=d.useMemo(()=>{const E=new Map;if(!i)return E;for(const F of i.elements)E.set(F.id,F);return E},[i]),q=d.useMemo(()=>x?$.get(x)??null:null,[x,$]);if(!(!!i&&!!g&&i.screen.width>0&&i.screen.height>0&&i.elements.length>0))return null;const Q=I?R:v??R,A=I,V=M&&!I&&O!==null,P=E=>{M&&E.target===E.currentTarget&&W(null,null)};return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:M?"rc-inspect-overlay rc-inspect-overlay-select":"rc-inspect-overlay",style:{left:`${g.left}px`,top:`${g.top}px`,width:`${g.width}px`,height:`${g.height}px`},onClick:P,children:i.elements.map(E=>h.jsx(Wt,{element:E,screen:i.screen,highlighted:E.id===p,selected:E.id===O,selectable:M,onClick:W},E.id))}),q&&Q&&h.jsx(Kt,{element:q,platform:i.platform,anchor:Q,cursorAnchored:A,showActions:V,onTap:y})]})});function $t(f,i){if(!i.startsWith("lim_st_"))return!1;try{const g=new URL(f).pathname.split("/").map(decodeURIComponent).find(y=>/^(ios|android)_[a-z0-9_]+$/.test(y));if(!g)return!1;const p=g.split("_")[0],O=i.slice(7).split(".");if(O.length!==3||O.some(y=>!y))return!1;const H=atob(O[1].replace(/-/g,"+").replace(/_/g,"/")),R=JSON.parse(new TextDecoder().decode(Uint8Array.from(H,y=>y.charCodeAt(0))));if(!R||typeof R!="object"||!("scopes"in R))return!1;const v=R.scopes;if(!Array.isArray(v)||!v.every(y=>typeof y=="string"))return!1;let W=!1;for(const y of v){const[M,I,x,$]=y.split(":");if(!($!==void 0||M!==p&&M!=="*")&&!(I!==g&&I!=="*")){if(x==="stream"||x==="all")return!1;x==="watch"&&(W=!0)}}return W}catch{return!1}}const Ft=d.lazy(()=>Promise.resolve().then(()=>require("./duo-view-BMPB0h3C.js")).then(f=>f.duoView)),Ce=f=>Object.entries(r.AMOTION_EVENT).find(([g,p])=>g.startsWith("ACTION_")&&p===f)?.[0]??String(f),it=1920,ct=1200,zt=(f,i)=>f===it&&i===ct||f===ct&&i===it,Bt={ios:{videoBorderRadiusMultiplier:.15,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:.9678},landscape:{widthMultiplier:.9678}}},android:{videoBorderRadiusMultiplier:.13,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:.967},landscape:{widthMultiplier:.962}}}},qt={videoBorderRadiusMultiplier:32/1837,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:2560/2798},landscape:{widthMultiplier:2560/2798}}};function Gt(f){const i=f.code,g=r.codeMap[i];if(!g)return r.debugWarn(`Unknown event.code: ${i}, key: ${f.key}`),null;let p=r.ANDROID_KEYS.META_NONE;const O=i>="KeyA"&&i<="KeyZ",H=f.getModifierState("CapsLock"),R=f.shiftKey;let v=R;return O&&(v=R!==H),v&&(p|=r.ANDROID_KEYS.META_SHIFT_ON),f.ctrlKey&&(p|=r.ANDROID_KEYS.META_CTRL_ON),f.altKey&&(p|=r.ANDROID_KEYS.META_ALT_ON),f.metaKey&&(p|=r.ANDROID_KEYS.META_META_ON),{keycode:g,metaState:p}}function Jt(f,i){const g=Object.keys(f);return g.length===Object.keys(i).length&&g.every(p=>f[p]===i[p])}const Qt=d.forwardRef(({className:f,url:i,token:g,sessionId:p,openUrl:O,watchOnly:H=!1,showFrame:R=!0,deviceModel:v,duoModelUrl:W,autoReconnect:y,jitterBufferTargetMs:M,onPlaybackStats:I,onTerminated:x,assets:$,onConnectionStateChange:q,inspectMode:X,onAxSnapshotChange:Q,onInspectSelectionChange:A,onAxStatusChange:V,axPollIntervalMs:P,axMaxBackoffMs:E,androidElementTreeOptions:F,onCameraDemandChange:Te,onCameraStats:K,onTrace:G,microphoneEnabled:Z=!1,onMicrophoneStateChange:ae},Xe)=>{const He=d.useMemo(()=>$t(i,g),[i,g]),ee=H||He,Ne=d.useRef(null),C=d.useRef(null),je=d.useRef(null),[st,at]=d.useState(!1),j=v==="iphone-duo"||st,Ae=d.useRef(null),[Ve,lt]=d.useState(null),[Ke,dt]=d.useState(),[ut,ht]=d.useState(!1),[ft,gt]=d.useState(!1),[pt,mt]=d.useState(!1),[Ue,$e]=d.useState(!1),[Fe,ze]=d.useState(!1),[vt,Be]=d.useState({}),Se=d.useRef(null),S=d.useRef(new Map),te=d.useRef(!1),[yt,Et]=d.useState(!1),b=d.useRef(null),le=d.useRef(null),me=d.useRef({handle:()=>{},end:()=>{}}),[ne,we]=d.useState(null),[qe,De]=d.useState(null),[xe,ve]=d.useState(null),[Ye,Oe]=d.useState(null),[Tt,Ge]=d.useState(null),[Nt,Je]=d.useState(null),Re=d.useRef(null),z=d.useRef(void 0),Qe=e=>{Re.current=e,z.current===void 0&&(z.current=window.requestAnimationFrame(()=>{z.current=void 0,Je(Re.current)}))},[At,de]=d.useState(null),oe=d.useRef(null);oe.current=qe;const ue=d.useRef(A);ue.current=A;const re=X===!0||X==="hover-only",Ze=d.useRef(re);Ze.current=re;const wt=X==="hover-only"?"hover-only":"select",B=d.useMemo(()=>r.detectPlatform(i),[i]),Ot=d.useMemo(()=>p||Array.from(crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(36)).join(""),[p]),he=B==="android"&&Fe?qt:Bt[B],ye=$?.[B],et=B==="android"&&Fe?Ue?ye?.tabletFrameLandscape:ye?.tabletFrame:Ue?ye?.frameLandscape:ye?.frame,tt=ye?.loadingLogo,Ie=!j&&R&&!!et,T=d.useRef(null),U=e=>T.current?.sendControl(e),Pe=(e,t)=>T.current?.sendDuoControl(e,t)??Promise.reject(new Error("Simulator disconnected")),nt=-10,ot=(e,t)=>{const o=Ee();if(!o)return;const n=ge(o,e,t);if(!n)return;const{videoX:s,videoY:l,videoWidth:c,videoHeight:u}=n,a=r.createTouchControlMessage(r.AMOTION_EVENT.ACTION_DOWN,nt,c,u,s,l,1,r.AMOTION_EVENT.BUTTON_PRIMARY,r.AMOTION_EVENT.BUTTON_PRIMARY);a&&U(a),window.setTimeout(()=>{const m=r.createTouchControlMessage(r.AMOTION_EVENT.ACTION_UP,nt,c,u,s,l,0,r.AMOTION_EVENT.BUTTON_PRIMARY,r.AMOTION_EVENT.BUTTON_PRIMARY);m&&U(m)},60)},Rt=(e,t)=>{const o=Ee();if(!o||t.screen.width<=0||t.screen.height<=0)return;const n=e.frame.x+e.frame.width/2,s=e.frame.y+e.frame.height/2,l=n/t.screen.width*o.actualWidth,c=s/t.screen.height*o.actualHeight,u=o.videoRect.left+o.offsetX+l,a=o.videoRect.top+o.offsetY+c;ot(u,a)},be=-1,_e=-2,ie=-3,fe=(e,t,o,n,s,l)=>{const c=r.createTouchControlMessage(e,t,o,n,s,l,1,r.AMOTION_EVENT.BUTTON_PRIMARY,r.AMOTION_EVENT.BUTTON_PRIMARY);c&&(r.debugLog("[rc-touch] sendSingleTouch",{action:e,actionName:Ce(e),pointerId:t,x:s,y:l,video:{width:o,height:n}}),U(c))},ce=(e,t,o)=>{if(!o)return;const{videoX:n,videoY:s,videoWidth:l,videoHeight:c}=o;let u=null,a=null,m=1;const _=r.AMOTION_EVENT.BUTTON_PRIMARY;switch(t){case"down":e!==ie&&me.current.end(),u=S.current.size===0?r.AMOTION_EVENT.ACTION_DOWN:r.AMOTION_EVENT.ACTION_POINTER_DOWN,a={x:n,y:s},S.current.set(e,a),e===-1&&C.current?.focus();break;case"move":S.current.has(e)&&(u=r.AMOTION_EVENT.ACTION_MOVE,a={x:n,y:s},S.current.set(e,a));break;case"up":case"cancel":S.current.has(e)&&(a=S.current.get(e),S.current.delete(e),t==="cancel"?u=r.AMOTION_EVENT.ACTION_CANCEL:u=S.current.size===0?r.AMOTION_EVENT.ACTION_UP:r.AMOTION_EVENT.ACTION_POINTER_UP);break}if(u!==null&&a!==null){r.debugLog("[rc-touch][mouse->touch] sending",{pointerId:e,eventType:t,action:u,actionName:Ce(u),positionToSend:a,video:{width:l,height:c},altHeld:te.current,activePointersAfter:Array.from(S.current.entries()).map(([Y,w])=>({id:Y,x:w.x,y:w.y}))});const N=r.createTouchControlMessage(u,e,l,c,a.x,a.y,m,_,_);N&&(r.debugLog("[rc-touch][mouse->touch] buffer",{pointerId:e,actionName:Ce(u),byteLength:N.byteLength}),U(N))}else(t==="up"||t==="cancel")&&S.current.delete(e)},ke=e=>{if(te.current!==e&&(te.current=e,Et(e),e||we(null),r.debugLog("[rc-touch][alt] updateAltHeld",{nextHeld:e,activePointerIds:Array.from(S.current.keys())}),B==="ios"&&T.current?.getState().controlReady)){const t=e?r.ANDROID_KEYS.ACTION_DOWN:r.ANDROID_KEYS.ACTION_UP,o=r.createInjectKeycodeMessage(t,r.ANDROID_KEYS.KEYCODE_ALT_LEFT,0,r.ANDROID_KEYS.META_NONE);r.debugLog("[rc-touch][alt] sending Indigo modifier keycode",{action:t,keycode:r.ANDROID_KEYS.KEYCODE_ALT_LEFT}),o&&U(o)}},Ee=()=>{const e=C.current,t=Ne.current;if(!e||!t)return null;const o=e.videoWidth,n=e.videoHeight;if(!o||!n)return null;const s=e.getBoundingClientRect(),l=t.getBoundingClientRect(),c=s.width,u=s.height,a=o/n,m=c/u;let _=c,N=u;a>m?N=c/a:_=u*a;const Y=(c-_)/2,w=(u-N)/2;return{videoWidth:o,videoHeight:n,videoRect:s,containerRect:l,actualWidth:_,actualHeight:N,offsetX:Y,offsetY:w}},ge=(e,t,o)=>{const n=t-e.videoRect.left-e.offsetX,s=o-e.videoRect.top-e.offsetY,l=Math.max(0,Math.min(e.actualWidth,n)),c=Math.max(0,Math.min(e.actualHeight,s)),u=Math.max(0,Math.min(e.videoWidth,l/e.actualWidth*e.videoWidth)),a=Math.max(0,Math.min(e.videoHeight,c/e.actualHeight*e.videoHeight));return{videoX:u,videoY:a,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},It=(e,t,o)=>{const n=t-e.videoRect.left-e.offsetX,s=o-e.videoRect.top-e.offsetY,l=Math.max(0,Math.min(e.actualWidth,n)),c=Math.max(0,Math.min(e.actualHeight,s)),u=Math.max(0,Math.min(e.videoWidth,l/e.actualWidth*e.videoWidth)),a=Math.max(0,Math.min(e.videoHeight,c/e.actualHeight*e.videoHeight)),m=e.videoWidth-u,_=e.videoHeight-a,N=e.videoRect.left+e.offsetX,Y=e.videoRect.top+e.offsetY,w=N-e.containerRect.left+l,D=Y-e.containerRect.top+c,se=N-e.containerRect.left+(e.actualWidth-l),L=Y-e.containerRect.top+(e.actualHeight-c);return{containerX:w,containerY:D,mirrorContainerX:se,mirrorContainerY:L,videoX:u,videoY:a,mirrorVideoX:m,mirrorVideoY:_,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},bt=(e,t,o,n,s,l,c)=>{const u=r.createTwoFingerTouchControlMessage(e,t,o,n,s,l,c);r.debugLog("[rc-touch2] sendTwoFingerMessage (iOS)",{actionName:Ce(e),video:{width:t,height:o},p0:{x:n,y:s},p1:{x:l,y:c},byteLength:u.byteLength}),U(u)},pe=(e,t,o,n,s,l,c,u,a)=>{if(r.debugLog("[rc-touch2] applyTwoFingerEvent",{platform:B,eventType:e,video:{width:t,height:o},p0:{x:n,y:s,id:u},p1:{x:l,y:c,id:a}}),e==="down"&&me.current.end(),B==="ios"){const m=e==="down"?r.AMOTION_EVENT.ACTION_DOWN:e==="move"?r.AMOTION_EVENT.ACTION_MOVE:r.AMOTION_EVENT.ACTION_UP;bt(m,t,o,n,s,l,c)}else e==="down"?(fe(r.AMOTION_EVENT.ACTION_DOWN,u,t,o,n,s),fe(r.AMOTION_EVENT.ACTION_POINTER_DOWN,a,t,o,l,c)):e==="move"?(fe(r.AMOTION_EVENT.ACTION_MOVE,u,t,o,n,s),fe(r.AMOTION_EVENT.ACTION_MOVE,a,t,o,l,c)):(fe(r.AMOTION_EVENT.ACTION_POINTER_UP,a,t,o,l,c),fe(r.AMOTION_EVENT.ACTION_UP,u,t,o,n,s))},_t=(e,t,o)=>{if(!te.current){ne!==null&&we(null);return}const n=It(e,t,o);we(n)},Mt=(e,t,o)=>{const n=oe.current;if(!n||n.screen.width<=0||n.screen.height<=0)return null;const s=t-e.videoRect.left-e.offsetX,l=o-e.videoRect.top-e.offsetY;if(s<0||l<0||s>e.actualWidth||l>e.actualHeight)return null;const c=s/e.actualWidth*n.screen.width,u=l/e.actualHeight*n.screen.height;return r.axElementAtPoint(n,c,u)},J=e=>{if(j)return;e.preventDefault(),e.stopPropagation();const t=Ee();if((X===!0||X==="hover-only")&&!("touches"in e))if(e.type==="mousemove"){if(Qe({x:e.clientX,y:e.clientY}),t){const n=Mt(t,e.clientX,e.clientY);ve(n?.id??null)}}else e.type==="mouseleave"&&(Qe(null),ve(null));if(X!==!0&&(!("touches"in e)&&t&&(e.type==="mousemove"?_t(t,e.clientX,e.clientY):e.type==="mouseleave"&&we(null)),!(!T.current?.getState().controlReady||!C.current||!t)))if("touches"in e){const n=e.touches,s=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 c=n[0],u=n[1],a=ge(t,c.clientX,c.clientY),m=ge(t,u.clientX,u.clientY);if(!a||!m)return;b.current?b.current.source==="real-touch"&&(b.current.finger0={x:a.videoX,y:a.videoY},b.current.finger1={x:m.videoX,y:m.videoY},pe("move",a.videoWidth,a.videoHeight,a.videoX,a.videoY,m.videoX,m.videoY,b.current.pointerId0,b.current.pointerId1)):(b.current={finger0:{x:a.videoX,y:a.videoY},finger1:{x:m.videoX,y:m.videoY},videoSize:{width:a.videoWidth,height:a.videoHeight},source:"real-touch",pointerId0:c.identifier,pointerId1:u.identifier},pe("down",a.videoWidth,a.videoHeight,a.videoX,a.videoY,m.videoX,m.videoY,c.identifier,u.identifier))}else if(n.length<2&&b.current?.source==="real-touch"){const c=b.current;pe("up",c.videoSize.width,c.videoSize.height,c.finger0.x,c.finger0.y,c.finger1.x,c.finger1.y,c.pointerId0,c.pointerId1),b.current=null;return}else{if(n.length>2)return;{const c=s[0];if(c){const u=ge(t,c.clientX,c.clientY);ce(c.identifier,l,u)}}}}else{let s=null;const l=b.current?.source==="alt-mouse";switch(e.type){case"mousedown":e.button===0&&(s="down");break;case"mousemove":(l||S.current.has(-1))&&(s="move");break;case"mouseup":e.button===0&&(s="up");break;case"mouseleave":(l||S.current.has(-1))&&(s="up");break}if(s){const c=ge(t,e.clientX,e.clientY);if(!c)return;r.debugLog("[rc-touch][mouse] event",{domType:e.type,eventType:s,button:e.button,buttons:e.buttons,client:{x:e.clientX,y:e.clientY},altHeldRef:te.current,inTwoFingerMode:l,geometry:{videoX:c.videoX,videoY:c.videoY,videoWidth:c.videoWidth,videoHeight:c.videoHeight},activePointerIds:Array.from(S.current.keys())}),te.current||l?Ct(s,c):ce(-1,s,c)}}},Ct=(e,t)=>{const{videoX:o,videoY:n,videoWidth:s,videoHeight:l}=t,c=s-o,u=l-n;if(e==="down"){b.current={finger0:{x:o,y:n},finger1:{x:c,y:u},videoSize:{width:s,height:l},source:"alt-mouse",pointerId0:be,pointerId1:_e},C.current?.focus(),pe("down",s,l,o,n,c,u,be,_e);return}if(e==="move"){b.current?.source==="alt-mouse"&&(b.current.finger0={x:o,y:n},b.current.finger1={x:c,y:u},pe("move",s,l,o,n,c,u,be,_e));return}if(e==="up"||e==="cancel"){const a=b.current;if(a?.source==="alt-mouse"){const{finger0:m,finger1:_,videoSize:N}=a;pe("up",N.width,N.height,m.x,m.y,_.x,_.y,be,_e),b.current=null}return}},St=150,rt=()=>{const e=le.current;e&&(window.clearTimeout(e.endTimer),ce(ie,"up",e.pos),le.current=null)},Dt=e=>{if(!T.current?.getState().controlReady||e.ctrlKey||te.current||b.current)return;const t=S.current.size;if(t>1||t===1&&!S.current.has(ie))return;const o=Ee();if(!o)return;const n=e.clientX-o.videoRect.left-o.offsetX,s=e.clientY-o.videoRect.top-o.offsetY;if(n<0||n>o.actualWidth||s<0||s>o.actualHeight)return;const l=ge(o,e.clientX,e.clientY);if(!l)return;e.preventDefault();const c=(e.deltaMode===1?16:e.deltaMode===2?o.actualWidth:1)*(o.videoWidth/o.actualWidth),u=(e.deltaMode===1?16:e.deltaMode===2?o.actualHeight:1)*(o.videoHeight/o.actualHeight),a=-e.deltaX*c,m=-e.deltaY*u,_=L=>{window.clearTimeout(L.endTimer),L.endTimer=window.setTimeout(rt,St)};if(a===0&&m===0){le.current&&_(le.current);return}const N=()=>({videoWidth:l.videoWidth,videoHeight:l.videoHeight,videoX:Math.abs(a)>Math.abs(m)?Math.min(Math.max(l.videoX,l.videoWidth*.2),l.videoWidth*.8):l.videoX,videoY:Math.abs(m)>=Math.abs(a)?Math.min(Math.max(l.videoY,l.videoHeight*.2),l.videoHeight*.8):l.videoY}),Y=L=>({...L,videoX:Math.min(Math.max(L.videoX+a,0),L.videoWidth),videoY:Math.min(Math.max(L.videoY+m,0),L.videoHeight)});let w=le.current;if(w)window.clearTimeout(w.endTimer);else{const L=N();ce(ie,"down",L),w={pos:L,endTimer:0},le.current=w}let D=w.pos,se=Y(D);se.videoX===D.videoX&&se.videoY===D.videoY&&(ce(ie,"up",D),D=N(),ce(ie,"down",D),se=Y(D)),ce(ie,"move",se),w.pos=se,_(w)};d.useEffect(()=>{me.current={handle:Dt,end:rt}}),d.useEffect(()=>{const e=Ne.current;if(!e)return;const t=o=>me.current.handle(o);return e.addEventListener("wheel",t,{passive:!1}),()=>{me.current.end(),e.removeEventListener("wheel",t)}},[]),d.useEffect(()=>{const e=n=>{n.key==="Alt"&&ke(!0)},t=n=>{n.key==="Alt"&&ke(!1)},o=()=>{ke(!1)};return window.addEventListener("keydown",e,!0),window.addEventListener("keyup",t,!0),window.addEventListener("blur",o),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("keyup",t,!0),window.removeEventListener("blur",o)}},[]);const Me=e=>{e.preventDefault(),e.stopPropagation();const t=document.activeElement===C.current||j&&document.activeElement===e.currentTarget;if(r.debugLog("Keyboard event:",{type:e.type,key:e.key,keyCode:e.keyCode,code:e.code,target:e.target.tagName,focused:t}),!t){r.debugWarn("Simulator input not focused, skipping keyboard event");return}if(!T.current?.getState().controlReady){r.debugWarn("Data channel not ready for keyboard event:",T.current?.getState().connection);return}if(e.type==="keydown"){if(e.key.toLowerCase()==="v"&&(e.metaKey||e.ctrlKey)){r.debugLog("Paste shortcut detected"),navigator.clipboard.readText().then(n=>{if(n){r.debugLog("Pasting text via SET_CLIPBOARD:",n.substring(0,20)+(n.length>20?"...":""));const s=r.createSetClipboardMessage(n,!0);U(s)}}).catch(n=>{console.error("Failed to read clipboard contents: ",n)});return}if(e.key.toLowerCase()==="m"&&(e.metaKey||e.ctrlKey)){r.debugLog("Menu shortcut detected");const n=r.createInjectKeycodeMessage(r.ANDROID_KEYS.ACTION_DOWN,r.ANDROID_KEYS.MENU,0,r.ANDROID_KEYS.META_NONE);U(n);const s=r.createInjectKeycodeMessage(r.ANDROID_KEYS.ACTION_UP,r.ANDROID_KEYS.MENU,0,r.ANDROID_KEYS.META_NONE);U(s);return}}const o=Gt(e);if(o){const{keycode:n,metaState:s}=o,l=e.type==="keydown"?r.ANDROID_KEYS.ACTION_DOWN:r.ANDROID_KEYS.ACTION_UP;r.debugLog(`Sending Keycode: key=${e.key}, code=${n}, action=${l}, meta=${s}`);const c=r.createInjectKeycodeMessage(l,n,0,s);U(c)}else r.debugLog(`Ignoring unhandled key event: type=${e.type}, key=${e.key}`)},xt=e=>{e.stopPropagation(),T.current?.reconnect()},k=d.useRef({onAxSnapshotChange:Q,onAxStatusChange:V,onCameraDemandChange:Te,onCameraStats:K,onMicrophoneStateChange:ae,onTrace:G,onTerminated:x,onConnectionStateChange:q,onPlaybackStats:I});k.current={onAxSnapshotChange:Q,onAxStatusChange:V,onCameraDemandChange:Te,onCameraStats:K,onMicrophoneStateChange:ae,onTrace:G,onTerminated:x,onConnectionStateChange:q,onPlaybackStats:I};const Le=!!G;d.useEffect(()=>{Se.current=null,$e(!1),ze(!1),Be({})},[i,v]),d.useEffect(()=>{let e=!0;oe.current!==null&&(oe.current=null,De(null),r.safeInvoke("onAxSnapshotChange",k.current.onAxSnapshotChange,null));const t=r.createDeviceStream({url:i,token:g,sessionId:Ot,watchOnly:ee,deviceModel:v,autoReconnect:y,jitterBufferTargetMs:M,openUrl:O,inspectMode:X,axPollIntervalMs:P,axMaxBackoffMs:E,androidElementTreeOptions:F,microphoneEnabled:Z,onStateChange:n=>{(n.videoReady||n.connection==="idle"||n.connection==="connecting"||n.connection==="reconnecting")&&ht(n.videoReady),gt(n.connection==="failed"),mt(n.connection==="terminated"),at(n.duo),lt(n.duoState),dt(n.duoError)},onAxSnapshotChange:n=>{e&&(De(s=>r.axSnapshotsEqual(s,n)?s:n),k.current.onAxSnapshotChange?.(n))},onAxStatusChange:(...n)=>k.current.onAxStatusChange?.(...n),onCameraDemandChange:(...n)=>k.current.onCameraDemandChange?.(...n),onCameraStats:K?(...n)=>k.current.onCameraStats?.(...n):void 0,onMicrophoneStateChange:(...n)=>k.current.onMicrophoneStateChange?.(...n),onTrace:Le?(...n)=>k.current.onTrace?.(...n):void 0,onTerminated:()=>k.current.onTerminated?.(),onConnectionStateChange:(...n)=>k.current.onConnectionStateChange?.(...n),onPlaybackStats:I?(...n)=>k.current.onPlaybackStats?.(...n):void 0});T.current=t;const o=C.current?t.attachVideo(C.current):void 0;return t.start(),()=>{e=!1,t.dispose(),o?.(),T.current=null}},[i,p,v,Le,ee]),d.useEffect(()=>{if(j&&Ae.current)return T.current?.attachVideo(Ae.current,"inner")},[j,i,p,v,Le,ee]),d.useEffect(()=>{T.current?.updateOptions({token:g,openUrl:O,axPollIntervalMs:P,axMaxBackoffMs:E,androidElementTreeOptions:F,autoReconnect:y,jitterBufferTargetMs:M,microphoneEnabled:Z,inspectMode:X,onPlaybackStats:I?(...e)=>k.current.onPlaybackStats?.(...e):void 0,onCameraStats:K?(...e)=>k.current.onCameraStats?.(...e):void 0})},[g,y,M,Z,X,!!I,!!K,O,P,E,F]);const We=()=>{if(!Ze.current)return;const e=Ee();if(!e){Ge(null);return}const t={left:e.videoRect.left-e.containerRect.left+e.offsetX,top:e.videoRect.top-e.containerRect.top+e.offsetY,width:e.actualWidth,height:e.actualHeight};Ge(o=>o&&o.left===t.left&&o.top===t.top&&o.width===t.width&&o.height===t.height?o:t)};d.useEffect(()=>{const e=C.current,t=je.current,o=Ne.current;if(!e)return;const n=u=>Be(a=>Jt(a,u)?a:u),s=()=>{const u=e.videoWidth>0&&e.videoHeight>0;u&&(Se.current={width:e.videoWidth,height:e.videoHeight});const a=Se.current,m=a?`${a.width} / ${a.height}`:void 0;if(!Ie||!t){n(!u&&a?{aspectRatio:m,contain:"size",containIntrinsicSize:`${a.width}px ${a.height}px`}:{}),We();return}const _=t.clientWidth,N=t.clientHeight;if(_===0||N===0)return;const Y=a?a.width>a.height:!1;$e(Y),ze(B==="android"&&!!a&&zt(a.width,a.height));const w=Y?he.videoPosition.landscape:he.videoPosition.portrait;let D={aspectRatio:m};w.heightMultiplier?(D.height=`${N*w.heightMultiplier}px`,D.width="auto"):w.widthMultiplier&&(D.width=`${_*w.widthMultiplier}px`,D.height="auto"),D.borderRadius=`${Y?N*he.videoBorderRadiusMultiplier:_*he.videoBorderRadiusMultiplier}px`,n(D),We()},l=new ResizeObserver(()=>{s()});t&&l.observe(t),l.observe(e),o&&l.observe(o),t&&t.addEventListener("load",s),e.addEventListener("loadedmetadata",s),e.addEventListener("resize",s);const c=()=>T.current?.bumpActivity();return e.addEventListener("resize",c),s(),()=>{l.disconnect(),e.removeEventListener("loadedmetadata",s),e.removeEventListener("resize",s),e.removeEventListener("resize",c),t&&t.removeEventListener("load",s)}},[he,Ie,i,v]),d.useEffect(()=>{re?We():(De(null),ve(null),Oe(null),Je(null),de(null),Re.current=null,z.current!==void 0&&(window.cancelAnimationFrame(z.current),z.current=void 0))},[re]),d.useEffect(()=>()=>{z.current!==void 0&&(window.cancelAnimationFrame(z.current),z.current=void 0)},[]),d.useEffect(()=>{if(!re)return;const e=t=>{t.key==="Escape"&&(Ye||xe)&&(Oe(null),ve(null),de(null),r.safeInvoke("onInspectSelectionChange",ue.current,null))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[re,Ye,xe]);const Yt=()=>{C.current&&C.current.focus()};d.useImperativeHandle(Xe,()=>({openUrl:e=>T.current?.openUrl(e),sendKeyEvent:e=>T.current?.sendKeyEvent(e),screenshot:e=>T.current?.screenshot(e)??Promise.reject(new Error("Simulator disconnected")),terminateApp:e=>T.current?.terminateApp(e)??Promise.reject(new Error("Simulator disconnected")),reconnect:()=>T.current?.reconnect(),refreshAxTree:()=>T.current?.refreshAxTree()??Promise.reject(new Error("Simulator disconnected")),getAxSnapshot:()=>T.current?.getAxSnapshot()??null,setInspectHighlight:e=>{ve(e?.id??null)},setInspectSelection:e=>{Oe(e?.id??null),de(e?Re.current:null);const t=oe.current;e&&t?r.safeInvoke("onInspectSelectionChange",ue.current,{element:e,snapshot:t}):r.safeInvoke("onInspectSelectionChange",ue.current,null)},getAxStatus:()=>T.current?.getAxStatus()??"idle"}));const Pt=yt&&ne!==null;return h.jsxs("div",{ref:Ne,className:["rc-container",f].filter(Boolean).join(" "),style:{touchAction:"none"},onMouseDown:J,onMouseMove:J,onMouseUp:J,onMouseLeave:J,onTouchStart:J,onTouchMove:J,onTouchEnd:J,onTouchCancel:J,children:[Pt&&ne&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"rc-touch-indicator",style:{left:`${ne.containerX}px`,top:`${ne.containerY}px`}}),h.jsx("div",{className:"rc-touch-indicator",style:{left:`${ne.mirrorContainerX}px`,top:`${ne.mirrorContainerY}px`}})]}),Ie&&h.jsx("img",{ref:je,src:et,alt:"",className:B==="ios"?"rc-phone-frame rc-phone-frame-ios":"rc-phone-frame",draggable:!1}),h.jsx("video",{ref:C,className:["rc-video",!Ie&&"rc-video-frameless",!ut&&"rc-video-loading"].filter(Boolean).join(" "),style:{...vt,...j?{opacity:0,width:1,height:1,pointerEvents:"none"}:{},...tt?{backgroundImage:`url("${tt}")`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:he.loadingLogoSize}:{}},autoPlay:!0,playsInline:!0,muted:!0,tabIndex:j?-1:0,onKeyDown:Me,onKeyUp:Me,onClick:Yt,onFocus:()=>{C.current&&(C.current.style.outline="none")},onBlur:()=>{C.current&&(C.current.style.outline="none")}}),j&&h.jsx("video",{ref:Ae,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",width:1,height:1,opacity:0,pointerEvents:"none"}}),j&&Ve&&h.jsx(d.Suspense,{fallback:h.jsx("div",{children:"Loading iPhone Duo…"}),children:h.jsx(Ft,{watchOnly:ee,showFrame:R,modelUrl:W,outer:C.current,inner:Ae.current,state:Ve,setAngle:e=>Pe("setHingeAngle",{angleDegrees:e}),setOrientation:e=>Pe("setDuoOrientation",{orientation:e}),button:(e,t)=>Pe("performActions",{actions:[{type:t?"buttonDown":"buttonUp",button:e}]}),touch:(e,t,o,n)=>{T.current?.sendDisplayTouch(e,t,o,n)},onKeyDown:Me,onKeyUp:Me})}),j&&Ke&&h.jsx("div",{role:"alert",className:"rc-duo-error",children:Ke}),!j&&re&&h.jsx(Ut,{snapshot:qe,geometry:Tt,highlightedId:xe,selectedId:Ye,mode:wt,cursorPosition:Nt,frozenCursorPosition:At,onSelectChange:(e,t)=>{Oe(e?.id??null),e&&t?de(t):e||de(null);const o=oe.current;e&&o?r.safeInvoke("onInspectSelectionChange",ue.current,{element:e,snapshot:o}):r.safeInvoke("onInspectSelectionChange",ue.current,null)},onTapElement:ee?void 0:((e,t)=>{if(t){ot(t.x,t.y);return}const o=oe.current;o&&Rt(e,o)})}),pt?h.jsxs("div",{className:"rc-terminated",role:"status",children:[h.jsx("div",{className:"rc-terminated-title",children:"Instance terminated"}),h.jsx("div",{className:"rc-terminated-message",children:"This instance no longer exists and can't be reconnected."})]}):ft&&h.jsx("button",{type:"button",className:"rc-retry-button",onClick:xt,children:"Retry"})]})});exports.RemoteControl=Qt;
@@ -1,5 +1,5 @@
1
1
  import { jsx as m, jsxs as z, Fragment as yt } from "react/jsx-runtime";
2
- import { f as qt, c as wt, d as Gt, b as Jt, h as Qt, i as Zt, s as Te, j as en, e as tn, k as D, l as je, m as nn, o as De, p as M, q as We, a as on, r as rn, t as g, u as cn } from "./core-DuukW7sF.mjs";
2
+ import { f as qt, c as wt, d as Gt, b as Jt, h as Qt, i as Zt, s as Te, j as en, e as tn, k as D, l as je, m as nn, o as De, p as M, q as We, a as on, r as rn, t as g, u as cn } from "./core-BpV73M0K.mjs";
3
3
  import { memo as qe, useState as O, useEffect as F, useMemo as fe, useCallback as sn, lazy as an, forwardRef as ln, useRef as S, useImperativeHandle as dn, Suspense as un } from "react";
4
4
  import { createPortal as hn } from "react-dom";
5
5
  import './index.css';const fn = async (d) => {
@@ -235,7 +235,7 @@ function bn(d, r) {
235
235
  return !1;
236
236
  }
237
237
  }
238
- const Tn = an(() => import("./duo-view-CvOd3jDJ.mjs").then((d) => d.d)), He = (d) => Object.entries(g).find(
238
+ const Tn = an(() => import("./duo-view-DWqQXwdZ.mjs").then((d) => d.d)), He = (d) => Object.entries(g).find(
239
239
  ([u, h]) => u.startsWith("ACTION_") && h === d
240
240
  )?.[0] ?? String(d), gt = 1920, vt = 1200, Cn = (d, r) => d === gt && r === vt || d === vt && r === gt, Rn = {
241
241
  ios: {
@@ -324,7 +324,7 @@ const Pn = ln(
324
324
  dt.current = le;
325
325
  const Xt = $ === "hover-only" ? "hover-only" : "select", Z = fe(() => Zt(r), [r]), Dt = fe(
326
326
  () => h || Array.from(crypto.getRandomValues(new Uint32Array(4)), (e) => e.toString(36)).join(""),
327
- [h, u]
327
+ [h]
328
328
  ), ye = Z === "android" && ot ? Nn : Rn[Z], Ne = G?.[Z], ut = Z === "android" && ot ? tt ? Ne?.tabletFrameLandscape : Ne?.tabletFrame : tt ? Ne?.frameLandscape : Ne?.frame, ht = Ne?.loadingLogo, ke = !K && R && !!ut, w = S(null), q = (e) => w.current?.sendControl(e), ze = (e, t) => w.current?.sendDuoControl(e, t) ?? Promise.reject(new Error("Simulator disconnected")), ft = -10, pt = (e, t) => {
329
329
  const o = Ee();
330
330
  if (!o) return;
@@ -910,11 +910,12 @@ const Pn = ln(
910
910
  return t.start(), () => {
911
911
  e = !1, t.dispose(), o?.(), w.current = null;
912
912
  };
913
- }, [r, u, h, p, Ke, ie]), F(() => {
913
+ }, [r, h, p, Ke, ie]), F(() => {
914
914
  if (K && Me.current)
915
915
  return w.current?.attachVideo(Me.current, "inner");
916
- }, [K, r, u, h, p, Ke, ie]), F(() => {
916
+ }, [K, r, h, p, Ke, ie]), F(() => {
917
917
  w.current?.updateOptions({
918
+ token: u,
918
919
  openUrl: C,
919
920
  axPollIntervalMs: W,
920
921
  axMaxBackoffMs: y,
@@ -927,6 +928,7 @@ const Pn = ln(
927
928
  onCameraStats: j ? (...e) => H.current.onCameraStats?.(...e) : void 0
928
929
  });
929
930
  }, [
931
+ u,
930
932
  v,
931
933
  _,
932
934
  re,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@limrun/ui",
3
- "version": "0.20.5",
3
+ "version": "0.20.6",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1,2 +0,0 @@
1
- "use strict";const Ue={INJECT_KEYCODE:0,INJECT_TEXT:1,INJECT_TOUCH_EVENT:2,INJECT_TWO_FINGER_TOUCH_EVENT:18,INJECT_SCROLL_EVENT:3,BACK_OR_SCREEN_ON:4,EXPAND_NOTIFICATION_PANEL:5,EXPAND_SETTINGS_PANEL:6,COLLAPSE_PANELS:7,GET_CLIPBOARD:8,SET_CLIPBOARD:9,SET_DISPLAY_POWER:10,ROTATE_DEVICE:11},Re={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},i={ACTION_DOWN:0,ACTION_UP:1,META_NONE:0,META_SHIFT_ON:1,META_ALT_ON:2,META_CTRL_ON:4096,META_META_ON:65536,KEYCODE_UNKNOWN:0,KEYCODE_SOFT_LEFT:1,KEYCODE_SOFT_RIGHT:2,KEYCODE_HOME:3,KEYCODE_BACK:4,KEYCODE_CALL:5,KEYCODE_ENDCALL:6,KEYCODE_0:7,KEYCODE_1:8,KEYCODE_2:9,KEYCODE_3:10,KEYCODE_4:11,KEYCODE_5:12,KEYCODE_6:13,KEYCODE_7:14,KEYCODE_8:15,KEYCODE_9:16,KEYCODE_STAR:17,KEYCODE_POUND:18,DPAD_UP:19,DPAD_DOWN:20,DPAD_LEFT:21,DPAD_RIGHT:22,KEYCODE_DPAD_CENTER:23,KEYCODE_VOLUME_UP:24,KEYCODE_VOLUME_DOWN:25,KEYCODE_POWER:26,KEYCODE_CAMERA:27,KEYCODE_CLEAR:28,KEYCODE_A:29,KEYCODE_B:30,KEYCODE_C:31,KEYCODE_D:32,KEYCODE_E:33,KEYCODE_F:34,KEYCODE_G:35,KEYCODE_H:36,KEYCODE_I:37,KEYCODE_J:38,KEYCODE_K:39,KEYCODE_L:40,KEYCODE_M:41,KEYCODE_N:42,KEYCODE_O:43,KEYCODE_P:44,KEYCODE_Q:45,KEYCODE_R:46,KEYCODE_S:47,KEYCODE_T:48,KEYCODE_U:49,KEYCODE_V:50,KEYCODE_W:51,KEYCODE_X:52,KEYCODE_Y:53,KEYCODE_Z:54,KEYCODE_COMMA:55,KEYCODE_PERIOD:56,KEYCODE_ALT_LEFT:57,KEYCODE_ALT_RIGHT:58,KEYCODE_SHIFT_LEFT:59,KEYCODE_SHIFT_RIGHT:60,KEYCODE_TAB:61,KEYCODE_SPACE:62,KEYCODE_SYM:63,KEYCODE_EXPLORER:64,KEYCODE_ENVELOPE:65,ENTER:66,DEL:67,KEYCODE_GRAVE:68,KEYCODE_MINUS:69,KEYCODE_EQUALS:70,KEYCODE_LEFT_BRACKET:71,KEYCODE_RIGHT_BRACKET:72,KEYCODE_BACKSLASH:73,KEYCODE_SEMICOLON:74,KEYCODE_APOSTROPHE:75,KEYCODE_SLASH:76,KEYCODE_AT:77,KEYCODE_NUM:78,KEYCODE_HEADSETHOOK:79,KEYCODE_FOCUS:80,KEYCODE_PLUS:81,MENU:82,KEYCODE_NOTIFICATION:83,KEYCODE_SEARCH:84,KEYCODE_MEDIA_PLAY_PAUSE:85,KEYCODE_MEDIA_STOP:86,KEYCODE_MEDIA_NEXT:87,KEYCODE_MEDIA_PREVIOUS:88,KEYCODE_MEDIA_REWIND:89,KEYCODE_MEDIA_FAST_FORWARD:90,KEYCODE_MUTE:91,KEYCODE_PAGE_UP:92,KEYCODE_PAGE_DOWN:93,KEYCODE_PICTSYMBOLS:94,KEYCODE_SWITCH_CHARSET:95,KEYCODE_BUTTON_A:96,KEYCODE_BUTTON_B:97,KEYCODE_BUTTON_C:98,KEYCODE_BUTTON_X:99,KEYCODE_BUTTON_Y:100,KEYCODE_BUTTON_Z:101,KEYCODE_BUTTON_L1:102,KEYCODE_BUTTON_R1:103,KEYCODE_BUTTON_L2:104,KEYCODE_BUTTON_R2:105,KEYCODE_BUTTON_THUMBL:106,KEYCODE_BUTTON_THUMBR:107,KEYCODE_BUTTON_START:108,KEYCODE_BUTTON_SELECT:109,KEYCODE_BUTTON_MODE:110,KEYCODE_ESCAPE:111,FORWARD_DEL:112,KEYCODE_CTRL_LEFT:113,KEYCODE_CTRL_RIGHT:114,KEYCODE_CAPS_LOCK:115,KEYCODE_SCROLL_LOCK:116,KEYCODE_META_LEFT:117,KEYCODE_META_RIGHT:118,KEYCODE_FUNCTION:119,KEYCODE_SYSRQ:120,KEYCODE_BREAK:121,KEYCODE_MOVE_HOME:122,KEYCODE_MOVE_END:123,KEYCODE_INSERT:124,KEYCODE_FORWARD:125,KEYCODE_MEDIA_PLAY:126,KEYCODE_MEDIA_PAUSE:127,KEYCODE_MEDIA_CLOSE:128,KEYCODE_MEDIA_EJECT:129,KEYCODE_MEDIA_RECORD:130,KEYCODE_F1:131,KEYCODE_F2:132,KEYCODE_F3:133,KEYCODE_F4:134,KEYCODE_F5:135,KEYCODE_F6:136,KEYCODE_F7:137,KEYCODE_F8:138,KEYCODE_F9:139,KEYCODE_F10:140,KEYCODE_F11:141,KEYCODE_F12:142,KEYCODE_NUM_LOCK:143,KEYCODE_NUMPAD_0:144,KEYCODE_NUMPAD_1:145,KEYCODE_NUMPAD_2:146,KEYCODE_NUMPAD_3:147,KEYCODE_NUMPAD_4:148,KEYCODE_NUMPAD_5:149,KEYCODE_NUMPAD_6:150,KEYCODE_NUMPAD_7:151,KEYCODE_NUMPAD_8:152,KEYCODE_NUMPAD_9:153,KEYCODE_NUMPAD_DIVIDE:154,KEYCODE_NUMPAD_MULTIPLY:155,KEYCODE_NUMPAD_SUBTRACT:156,KEYCODE_NUMPAD_ADD:157,KEYCODE_NUMPAD_DOT:158,KEYCODE_NUMPAD_COMMA:159,KEYCODE_NUMPAD_ENTER:160,KEYCODE_NUMPAD_EQUALS:161,KEYCODE_NUMPAD_LEFT_PAREN:162,KEYCODE_NUMPAD_RIGHT_PAREN:163,KEYCODE_VOLUME_MUTE:164,KEYCODE_INFO:165,KEYCODE_CHANNEL_UP:166,KEYCODE_CHANNEL_DOWN:167,KEYCODE_ZOOM_IN:168,KEYCODE_ZOOM_OUT:169,KEYCODE_TV:170,KEYCODE_WINDOW:171,KEYCODE_GUIDE:172,KEYCODE_DVR:173,KEYCODE_BOOKMARK:174,KEYCODE_CAPTIONS:175,KEYCODE_SETTINGS:176,KEYCODE_TV_POWER:177,KEYCODE_TV_INPUT:178,KEYCODE_STB_POWER:179,KEYCODE_STB_INPUT:180,KEYCODE_AVR_POWER:181,KEYCODE_AVR_INPUT:182,KEYCODE_PROG_RED:183,KEYCODE_PROG_GREEN:184,KEYCODE_PROG_YELLOW:185,KEYCODE_PROG_BLUE:186,KEYCODE_APP_SWITCH:187,KEYCODE_LANGUAGE_SWITCH:204,KEYCODE_ASSIST:219,KEYCODE_BRIGHTNESS_DOWN:220,KEYCODE_BRIGHTNESS_UP:221,KEYCODE_SLEEP:223,KEYCODE_WAKEUP:224,KEYCODE_SOFT_SLEEP:276},Kt={KeyA:i.KEYCODE_A,KeyB:i.KEYCODE_B,KeyC:i.KEYCODE_C,KeyD:i.KEYCODE_D,KeyE:i.KEYCODE_E,KeyF:i.KEYCODE_F,KeyG:i.KEYCODE_G,KeyH:i.KEYCODE_H,KeyI:i.KEYCODE_I,KeyJ:i.KEYCODE_J,KeyK:i.KEYCODE_K,KeyL:i.KEYCODE_L,KeyM:i.KEYCODE_M,KeyN:i.KEYCODE_N,KeyO:i.KEYCODE_O,KeyP:i.KEYCODE_P,KeyQ:i.KEYCODE_Q,KeyR:i.KEYCODE_R,KeyS:i.KEYCODE_S,KeyT:i.KEYCODE_T,KeyU:i.KEYCODE_U,KeyV:i.KEYCODE_V,KeyW:i.KEYCODE_W,KeyX:i.KEYCODE_X,KeyY:i.KEYCODE_Y,KeyZ:i.KEYCODE_Z,Digit0:i.KEYCODE_0,Digit1:i.KEYCODE_1,Digit2:i.KEYCODE_2,Digit3:i.KEYCODE_3,Digit4:i.KEYCODE_4,Digit5:i.KEYCODE_5,Digit6:i.KEYCODE_6,Digit7:i.KEYCODE_7,Digit8:i.KEYCODE_8,Digit9:i.KEYCODE_9,Backquote:i.KEYCODE_GRAVE,Minus:i.KEYCODE_MINUS,Equal:i.KEYCODE_EQUALS,BracketLeft:i.KEYCODE_LEFT_BRACKET,BracketRight:i.KEYCODE_RIGHT_BRACKET,Backslash:i.KEYCODE_BACKSLASH,Semicolon:i.KEYCODE_SEMICOLON,Quote:i.KEYCODE_APOSTROPHE,Comma:i.KEYCODE_COMMA,Period:i.KEYCODE_PERIOD,Slash:i.KEYCODE_SLASH,Space:i.KEYCODE_SPACE,Tab:i.KEYCODE_TAB,Escape:i.KEYCODE_ESCAPE,ArrowUp:i.DPAD_UP,ArrowDown:i.DPAD_DOWN,ArrowLeft:i.DPAD_LEFT,ArrowRight:i.DPAD_RIGHT,Enter:i.ENTER,Backspace:i.DEL,Delete:i.FORWARD_DEL,Home:i.KEYCODE_MOVE_HOME,End:i.KEYCODE_MOVE_END,PageUp:i.KEYCODE_PAGE_UP,PageDown:i.KEYCODE_PAGE_DOWN,Insert:i.KEYCODE_INSERT,F1:i.KEYCODE_F1,F2:i.KEYCODE_F2,F3:i.KEYCODE_F3,F4:i.KEYCODE_F4,F5:i.KEYCODE_F5,F6:i.KEYCODE_F6,F7:i.KEYCODE_F7,F8:i.KEYCODE_F8,F9:i.KEYCODE_F9,F10:i.KEYCODE_F10,F11:i.KEYCODE_F11,F12:i.KEYCODE_F12,ShiftLeft:i.KEYCODE_SHIFT_LEFT,ShiftRight:i.KEYCODE_SHIFT_RIGHT,ControlLeft:i.KEYCODE_CTRL_LEFT,ControlRight:i.KEYCODE_CTRL_RIGHT,AltLeft:i.KEYCODE_ALT_LEFT,AltRight:i.KEYCODE_ALT_RIGHT,MetaLeft:i.KEYCODE_META_LEFT,MetaRight:i.KEYCODE_META_RIGHT,ContextMenu:i.MENU,Numpad0:i.KEYCODE_NUMPAD_0,Numpad1:i.KEYCODE_NUMPAD_1,Numpad2:i.KEYCODE_NUMPAD_2,Numpad3:i.KEYCODE_NUMPAD_3,Numpad4:i.KEYCODE_NUMPAD_4,Numpad5:i.KEYCODE_NUMPAD_5,Numpad6:i.KEYCODE_NUMPAD_6,Numpad7:i.KEYCODE_NUMPAD_7,Numpad8:i.KEYCODE_NUMPAD_8,Numpad9:i.KEYCODE_NUMPAD_9,NumpadDivide:i.KEYCODE_NUMPAD_DIVIDE,NumpadMultiply:i.KEYCODE_NUMPAD_MULTIPLY,NumpadSubtract:i.KEYCODE_NUMPAD_SUBTRACT,NumpadAdd:i.KEYCODE_NUMPAD_ADD,NumpadDecimal:i.KEYCODE_NUMPAD_DOT,NumpadComma:i.KEYCODE_NUMPAD_COMMA,NumpadEnter:i.KEYCODE_NUMPAD_ENTER,NumpadEqual:i.KEYCODE_NUMPAD_EQUALS};function Mt(t,e,n,s,E,l,a=1,m=0,O=0){const h=new ArrayBuffer(32),A=new DataView(h);let w=0;A.setUint8(w,Ue.INJECT_TOUCH_EVENT),w+=1;const I=t===Re.ACTION_POINTER_DOWN?Re.ACTION_DOWN:t===Re.ACTION_POINTER_UP?Re.ACTION_UP:t;return A.setUint8(w,I),w+=1,A.setBigInt64(w,BigInt(e),!0),w+=8,A.setInt32(w,Math.round(E),!0),w+=4,A.setInt32(w,Math.round(l),!0),w+=4,A.setUint16(w,n,!0),w+=2,A.setUint16(w,s,!0),w+=2,A.setInt16(w,Math.round(a*65535),!0),w+=2,A.setInt32(w,m,!0),w+=4,A.setInt32(w,O,!0),h}function nn(t,e,n,s,E,l,a){const m=new ArrayBuffer(24),O=new DataView(m);let h=0;return O.setUint8(h,Ue.INJECT_TWO_FINGER_TOUCH_EVENT),h+=1,O.setUint8(h,t),h+=1,O.setInt32(h,Math.round(s),!0),h+=4,O.setInt32(h,Math.round(E),!0),h+=4,O.setInt32(h,Math.round(l),!0),h+=4,O.setInt32(h,Math.round(a),!0),h+=4,O.setUint16(h,e,!0),h+=2,O.setUint16(h,n,!0),h+=2,O.setUint16(h,0,!0),m}function wt(t,e=!0){const s=new TextEncoder().encode(t),E=new ArrayBuffer(14+s.length),l=new DataView(E);let a=0;return l.setUint8(a,Ue.SET_CLIPBOARD),a+=1,l.setBigInt64(a,BigInt(0),!1),a+=8,l.setUint8(a,e?1:0),a+=1,l.setUint32(a,s.length,!1),a+=4,new Uint8Array(E,a).set(s),E}function je(t,e,n=0,s=0){const E=new ArrayBuffer(14),l=new DataView(E);let a=0;return l.setUint8(a,Ue.INJECT_KEYCODE),a+=1,l.setUint8(a,t),a+=1,l.setInt32(a,e,!0),a+=4,l.setInt32(a,n,!0),a+=4,l.setInt32(a,s,!0),E}function rn(t){return t?.displays.find(e=>e.id===(t.angleDegrees<90?"outer":"inner"))}function Yt(t){return t===2?2:t===3?1:t===4?3:0}class on{constructor(e){this.send=e}send;screenId;turns=0;held;get active(){return this.held!==void 0}setDisplay(e,n=Yt(e?.orientation)){(this.screenId!==e?.screenId||this.turns!==n)&&this.release(),this.screenId=e?.screenId,this.turns=n}touch(e,n,s,E=!1){if(this.screenId===void 0)return;const l=bt(n,s,E?0:this.turns);e==="begin"&&(this.release(),this.held={screenId:this.screenId,...l}),this.held&&(Object.assign(this.held,l),e==="end"?this.release():this.send(e==="begin"?0:2,this.held.screenId,l.x,l.y))}release(){if(!this.held)return;const{screenId:e,x:n,y:s}=this.held;this.held=void 0,this.send(1,e,n,s)}}const an={width:164.6,height:117.8,depth:5.2};function bt(t,e,n){return t=Math.max(0,Math.min(1,t)),e=Math.max(0,Math.min(1,e)),n===1?{x:e,y:1-t}:n===2?{x:1-t,y:1-e}:n===3?{x:1-e,y:t}:{x:t,y:e}}function sn(t){return Number.isFinite(t)&&t>=0&&t<=180}function cn(t,e){return{x:Math.max(0,Math.min(1,t)),y:Math.max(0,Math.min(1,1-e))}}function ln(t,e,n){return e&&(t||!n)?"touch":t?"ignore":"orbit"}function Nt(t,e,n,s){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(n)||!Number.isFinite(s)||n<0||n>1||s<0||s>1)throw new RangeError("Invalid display touch coordinates");const E=new ArrayBuffer(12),l=new DataView(E);return l.setUint8(0,19),l.setUint8(1,t),l.setUint8(2,e),l.setFloat32(4,n,!0),l.setFloat32(8,s,!0),E}class dn{constructor(e,n){this.send=e,this.failed=n}send;failed;latest;running=!1;stopped=!1;set(e){this.stopped||!sn(e)||(this.latest=e,this.flush())}stop(){this.stopped=!0,this.latest=void 0}async flush(){if(!(this.running||this.stopped)){this.running=!0;try{for(;this.latest!==void 0&&!this.stopped;){const e=this.latest;this.latest=void 0,await this.send(e)}}catch(e){this.latest=void 0,this.stopped||this.failed(e)}finally{this.running=!1}}}}const un={side:"Sleep/Wake",volumeUp:"Volume Up",volumeDown:"Volume Down"};class En{constructor(e,n){this.send=e,this.failed=n}send;failed;held;tail=Promise.resolve();timeout;press(e){this.held||(this.held=e,this.enqueue(e,!0),this.timeout=setTimeout(()=>this.release(),1e4))}release(){if(!this.held)return;clearTimeout(this.timeout);const e=this.held;this.held=void 0,this.enqueue(e,!1)}enqueue(e,n){this.tail=this.tail.then(()=>this.send(e,n)).catch(this.failed)}}const Xe="Accessibility unavailable on this device.",Qe=500,Rt=(t,e)=>Math.abs(t.x-e.x)<.5&&Math.abs(t.y-e.y)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5,fn=t=>Math.max(0,t.width)*Math.max(0,t.height),hn=t=>{const e=t.find(n=>n.frame&&n.frame.width>0&&n.frame.height>0);return e?.frame?((Math.abs(e.frame.x)>.5||Math.abs(e.frame.y)>.5)&&console.warn(`[ax-tree] iOS root frame is not anchored at (0,0): (${e.frame.x},${e.frame.y}). Element positions may be slightly off from the rendered video.`),{x:0,y:0,width:e.frame.width,height:e.frame.height}):{x:0,y:0,width:1,height:1}},mn=t=>{const e={};return typeof t.AXUniqueId=="string"&&t.AXUniqueId.length>0&&(e.AXUniqueId=t.AXUniqueId),typeof t.AXLabel=="string"&&t.AXLabel.length>0&&(e.AXLabel=t.AXLabel),typeof t.type=="string"&&t.type.length>0&&(e.className=t.type),e},pn=t=>{const e={};for(const[n,s]of Object.entries(t))n!=="children"&&(e[n]=s);return e};function It(t){const e=Array.isArray(t)?t:[t],n=hn(e),s=[],E=(l,a)=>{if(s.length>=Qe)return;const m=l.frame;if(m&&m.width>0&&m.height>0&&!Rt(m,n)){const h=l.role_description||l.role||"",A=(typeof l.AXLabel=="string"?l.AXLabel:"")||(typeof l.title=="string"?l.title:"")||"";s.push({id:typeof l.AXUniqueId=="string"&&l.AXUniqueId.length>0?l.AXUniqueId:a,path:a,label:A,value:typeof l.AXValue=="string"?l.AXValue:"",role:h,type:typeof l.type=="string"?l.type:"",enabled:l.enabled!==!1,focused:l.focused===!0,frame:{x:m.x,y:m.y,width:m.width,height:m.height},selectors:mn(l),raw:pn(l)})}const O=Array.isArray(l.children)?l.children:[];for(let h=0;h<O.length&&s.length<Qe;h++)E(O[h],`${a}.${h}`)};for(let l=0;l<e.length&&s.length<Qe;l++)E(e[l],String(l));return{platform:"ios",screen:{width:n.width,height:n.height},elements:s,capturedAt:Date.now()}}const Cn=t=>{let e={x:0,y:0,width:1,height:1},n=0;for(const s of t){const E=s.parsedBounds;if(!E)continue;const l=E.right-E.left,a=E.bottom-E.top,m=Math.max(0,l)*Math.max(0,a);m>n&&(n=m,e={x:0,y:0,width:l,height:a})}return e},On=t=>{const e={};return typeof t.resourceId=="string"&&t.resourceId.length>0&&(e.resourceId=t.resourceId),typeof t.contentDesc=="string"&&t.contentDesc.length>0&&(e.contentDesc=t.contentDesc),typeof t.text=="string"&&t.text.length>0&&(e.text=t.text),typeof t.className=="string"&&t.className.length>0&&(e.className=t.className),e};function Ut(t){const e=Cn(t),n=[];for(let s=0;s<t.length&&n.length<Qe;s++){const E=t[s],l=E.parsedBounds;if(!l)continue;const a=Math.max(0,l.right-l.left),m=Math.max(0,l.bottom-l.top);if(a<=0||m<=0)continue;const O={x:l.left,y:l.top,width:a,height:m};if(Rt(O,{x:0,y:0,width:e.width,height:e.height}))continue;const h=E.contentDesc||E.text||"",A=E.className||"";n.push({id:E.resourceId&&E.resourceId.length>0?E.resourceId:E.contentDesc&&E.contentDesc.length>0?`cd:${E.contentDesc}`:String(s),path:String(s),label:h,value:typeof E.text=="string"?E.text:"",role:A,type:A,enabled:E.enabled!==!1,focused:E.focused===!0,frame:O,selectors:On(E),raw:{...E}})}return{platform:"android",screen:{width:e.width,height:e.height},elements:n,capturedAt:Date.now()}}function Dn(t,e){const n=Math.max(0,t.x),s=Math.max(0,t.y),E=Math.min(e.width,t.x+t.width),l=Math.min(e.height,t.y+t.height),a=Math.max(0,E-n),m=Math.max(0,l-s);return a>0&&m>0?{x:n,y:s,width:a,height:m}:null}function kt(t,e){if(t===e)return!0;if(t.id!==e.id||t.path!==e.path||t.label!==e.label||t.value!==e.value||t.role!==e.role||t.type!==e.type||t.enabled!==e.enabled||t.focused!==e.focused)return!1;const n=t.frame,s=e.frame;return n.x===s.x&&n.y===s.y&&n.width===s.width&&n.height===s.height}function Pt(t,e){if(t===e)return!0;if(!t||!e||t.platform!==e.platform||t.screen.width!==e.screen.width||t.screen.height!==e.screen.height||t.elements.length!==e.elements.length)return!1;for(let n=0;n<t.elements.length;n++)if(!kt(t.elements[n],e.elements[n]))return!1;return!0}function _n(t,e,n){let s=null,E=1/0;for(const l of t.elements){const a=l.frame;if(e<a.x||n<a.y||e>a.x+a.width||n>a.y+a.height)continue;const m=fn(a);m<E&&(E=m,s=l)}return s}function gn(t,e){if(e==="ios"){if(t.selectors.AXUniqueId)return`client.tapElement({ AXUniqueId: ${JSON.stringify(t.selectors.AXUniqueId)} })`;if(t.selectors.AXLabel){const n=t.selectors.className?`, type: ${JSON.stringify(t.selectors.className)}`:"";return`client.tapElement({ AXLabel: ${JSON.stringify(t.selectors.AXLabel)}${n} })`}return null}return t.selectors.resourceId?`client.tap({ selector: { resourceId: ${JSON.stringify(t.selectors.resourceId)} } })`:t.selectors.contentDesc?`client.tap({ selector: { contentDesc: ${JSON.stringify(t.selectors.contentDesc)} } })`:t.selectors.text?`client.tap({ selector: { text: ${JSON.stringify(t.selectors.text)} } })`:null}function Lt(t){const e=t.role||t.type||"";if(!e)return"element";let n=e.replace(/^AX/,"");return n.includes(".")&&(n=n.split(".").pop()),n==="GenericElement"?"Element":(n=n.replace(/([a-z])([A-Z])/g,"$1 $2"),n)}const gt=80;function Tn(t){const e=Lt(t),n=t.label||t.value||"";if(!n)return e;const s=n.length>gt?n.slice(0,gt).trimEnd()+"…":n;return`${e} · ${s}`}const Sn=500,yn=2e3,Tt=5e3,vn=8e3,An=1200,Kn=250,Mn=()=>`ax-rc-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;class wn{platform;send;onSnapshot;onStatusChange;baseIntervalMs;maxBackoffMs;androidElementTreeOptions;pending=new Map;running=!1;timer;currentInterval;lastSnapshot=null;inflight=!1;lastBumpAtMs=0;boostUntilMs=0;status="idle";constructor(e){this.platform=e.platform,this.send=e.send,this.onSnapshot=e.onSnapshot,this.onStatusChange=e.onStatusChange,this.baseIntervalMs=e.baseIntervalMs??Sn,this.maxBackoffMs=e.maxBackoffMs??yn,this.androidElementTreeOptions=e.androidElementTreeOptions,this.currentInterval=this.baseIntervalMs}start(){this.running||(this.running=!0,this.currentInterval=this.baseIntervalMs,this.boostUntilMs=0,this.setStatus("starting"),this.runOnce())}stop(){this.running&&(this.running=!1,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.failAllPending("Inspector stopped"),this.lastSnapshot=null,this.setStatus("idle"),this.onSnapshot(null))}getStatus(){return this.status}setStatus(e,n){if(this.status!==e&&(this.status=e,!!this.onStatusChange))try{this.onStatusChange(e,n)}catch(s){console.error("[AxFetcher] onStatusChange threw:",s)}}bumpActivity(){if(!this.running)return;const e=Date.now();this.boostUntilMs=e+An;const n=Math.max(150,Math.floor(this.baseIntervalMs/2));if(e-this.lastBumpAtMs<n){this.currentInterval=this.baseIntervalMs;return}this.lastBumpAtMs=e,this.currentInterval=this.baseIntervalMs,this.timer!==void 0&&(window.clearTimeout(this.timer),this.timer=void 0),this.inflight||this.runOnce()}async refresh(){const e=await this.requestOnce();return this.running&&this.deliver(e),e}getLatest(){return this.lastSnapshot}handleMessage(e){if(!e||typeof e.id!="string")return!1;const n=e.id;if(!this.pending.get(n))return!1;if(this.platform==="ios"){if(e.type!=="elementTreeResult")return!1;const m=typeof e.error=="string"?e.error:null;if(m)return this.settleReject(n,new Error(m)),!0;const O=typeof e.json=="string"?e.json:"";try{const h=JSON.parse(O),A=It(h);this.settleResolve(n,A)}catch(h){this.settleReject(n,h instanceof Error?h:new Error(String(h)))}return!0}if(e.type!=="getElementTreeResult")return!1;const E=e.error;if(E&&typeof E=="object"){const m=typeof E.message=="string"?E.message:"getElementTree failed";return this.settleReject(n,new Error(m)),!0}const l=e.payload,a=Array.isArray(l?.nodes)?l.nodes:[];try{const m=Ut(a);this.settleResolve(n,m)}catch(m){this.settleReject(n,m instanceof Error?m:new Error(String(m)))}return!0}buildRequest(e){return this.platform==="ios"?{type:"elementTree",id:e}:{type:"getElementTree",id:e,...this.androidElementTreeOptions}}async requestOnce(){const e=Mn();return new Promise((n,s)=>{const E=window.setTimeout(()=>{this.pending.delete(e),s(new Error("elementTree request timed out"))},vn+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:n,reject:s,timer:E}),this.send(this.buildRequest(e))||(window.clearTimeout(E),this.pending.delete(e),s(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const n=e instanceof Error?e.message:String(e),s=/unavailable|not (yet )?running|failed|timeout/i.test(n);this.currentInterval=s?Tt:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(s?"unavailable":"error",n)}finally{this.inflight=!1,this.scheduleNext()}}}deliver(e){const n=this.lastSnapshot;if(Pt(n,e)){this.currentInterval=Math.min(this.currentInterval*2,this.maxBackoffMs),this.lastSnapshot=e,e.errors?.includes(Xe)||this.setStatus("ready");return}this.lastSnapshot=e,this.currentInterval=this.baseIntervalMs,e.errors?.includes(Xe)?(this.currentInterval=Tt,this.setStatus("unavailable",Xe)):this.setStatus("ready"),this.onSnapshot(e)}scheduleNext(){if(!this.running)return;this.timer!==void 0&&window.clearTimeout(this.timer);const e=Date.now()<this.boostUntilMs?Math.min(Kn,this.currentInterval):this.currentInterval;this.timer=window.setTimeout(()=>{this.timer=void 0,this.runOnce()},e)}settleResolve(e,n){const s=this.pending.get(e);s&&(window.clearTimeout(s.timer),this.pending.delete(e),s.resolve(n))}settleReject(e,n){const s=this.pending.get(e);s&&(window.clearTimeout(s.timer),this.pending.delete(e),s.reject(n))}failAllPending(e){for(const[n,s]of this.pending.entries())window.clearTimeout(s.timer),s.reject(new Error(e)),this.pending.delete(n)}}function St(t,e){if(e!=null&&(!Number.isFinite(e)||e<0||e>4e3)){console.warn("RemoteControl: jitterBufferTargetMs must be a finite number between 0 and 4000.");return}if(!("jitterBufferTarget"in t))return;const n=e??null;try{t.jitterBufferTarget!==n&&(t.jitterBufferTarget=n)}catch(s){console.warn("RemoteControl: could not set the jitter buffer target.",s)}}const Ft=`(function(){"use strict";let e,t;self.onmessage=async({data:s})=>{s.type==="start"?(e=new AbortController,t=s.readable.pipeTo(s.writable,{signal:e.signal}).catch(o=>{e?.signal.aborted||self.postMessage({type:"error",message:String(o)})})):s.type==="stop"&&(e?.abort(),await t,self.postMessage({type:"stopped"}),self.close())}})();
2
- `,yt=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",Ft],{type:"text/javascript;charset=utf-8"});function Yn(t){let e;try{if(e=yt&&(self.URL||self.webkitURL).createObjectURL(yt),!e)throw"";const n=new Worker(e,{name:t?.name});return n.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),n}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Ft),{name:t?.name})}}function bn(t,e,n){const{MediaStreamTrackProcessor:s,MediaStreamTrackGenerator:E}=globalThis,l=e.getVideoTracks()[0];let a,m,O,h,A=!1;const w=()=>{A||(A=!0,a?.stop(),m?.stop(),O&&(O.postMessage({type:"stop"}),h=setTimeout(()=>O?.terminate(),1e3)))},I=D=>{t.srcObject=D,t.play().catch(()=>{})},W=D=>{A||(w(),n(D),I(e))};try{if(l&&s&&E){a=l.clone();const D=new s({track:a,maxBufferSize:1}),$=new E({kind:"video"});m=$,O=new Yn,O.onmessage=({data:P})=>{P.type==="error"?W(new Error(P.message)):P.type==="stopped"&&(clearTimeout(h),O?.terminate())},O.onerror=P=>W(new Error(P.message)),O.postMessage({type:"start",readable:D.readable,writable:$.writable},[D.readable,$.writable]),I(new MediaStream(e.getTracks().map(P=>P===l?$:P)))}else I(e)}catch(D){W(D)}return w}function Ie(t){return typeof t=="number"&&Number.isFinite(t)}function ge(t,e){if(!(!Ie(t)||!Ie(e)||t<e||e<0))return t-e}class Nn{previous=new Map;reset(){this.previous.clear()}read(e,n,s){const E={timestamp:0,video:[],audio:[]};s==null?E.requestedTargetMs=null:Ie(s)&&s>=0&&s<=4e3&&(E.requestedTargetMs=s);const l=new Map;return e.forEach(a=>{if(a.type!=="inbound-rtp"||!Ie(a.timestamp))return;const m=a.kind??a.mediaType;if(m!=="video"&&m!=="audio")return;const O=n.filter(U=>U.kind===m),h=a.trackIdentifier?O.find(U=>U.trackId===a.trackIdentifier):a.mid!=null?O.find(U=>U.mid===a.mid):O.length===1?O[0]:void 0;if(!h)return;const A=this.previous.get(a.id),I=A?.trackId===h.trackId&&A.stats.ssrc===a.ssrc?A.stats:void 0,W=I?a.timestamp-I.timestamp:void 0,D={id:a.id,trackId:h.trackId,timestamp:a.timestamp};if(W!==void 0&&W>0){D.intervalMs=W;const U=ge(a.jitterBufferEmittedCount,I?.jitterBufferEmittedCount),F=ge(a.jitterBufferDelay,I?.jitterBufferDelay);U!==void 0&&U>0&&F!==void 0&&(D.bufferDelayMs=F/U*1e3);const q=ge(a.bytesReceived,I?.bytesReceived);q!==void 0&&(D.bitrateBps=q*8e3/W)}if(m==="video"){const U={...D,display:h.display??"primary"};if(D.intervalMs!==void 0){const F=ge(a.framesDecoded,I?.framesDecoded);F!==void 0&&(U.fps=F*1e3/D.intervalMs),U.droppedFrames=ge(a.framesDropped,I?.framesDropped),U.freezes=ge(a.freezeCount,I?.freezeCount)}E.video.push(U)}else E.audio.push(D);E.timestamp=Math.max(E.timestamp,a.timestamp),l.set(a.id,I&&a.timestamp<=I.timestamp?A:{stats:a,trackId:h.trackId});const $=a.transportId?e.get(a.transportId):void 0,P=$?.selectedCandidatePairId?e.get($.selectedCandidatePairId):void 0;P?.state==="succeeded"&&Ie(P.currentRoundTripTime)&&P.currentRoundTripTime>=0&&(E.rttMs=P.currentRoundTripTime*1e3)}),this.previous=l,E.video.length||E.audio.length?E:null}}const ot=new WeakSet;function Rn(t,e,n){const{peer:s,displays:E}=t,l=new Nn;let a,m=!1,O=!1,h=!1,A=0,w=!1,I=!1;const W=()=>!m&&!document.hidden&&s.connectionState==="connected",D=F=>{if(!(!F&&!w)){w=F!==null;try{e()?.(F)}catch(q){console.error('[RemoteControl] customer callback "onPlaybackStats" threw:',q)}}},$=()=>{O=!1,A++,clearTimeout(a),l.reset(),D(null)},P=async()=>{if(h||!W())return;if(ot.has(s)){a=setTimeout(()=>{P()},2e3);return}h=!0,ot.add(s);const F=A;try{const q=await s.getStats();if(F!==A||!W())return;const ae=s.getTransceivers().filter(Y=>(Y.currentDirection==="recvonly"||Y.currentDirection==="sendrecv")&&Y.receiver.track.readyState!=="ended").map(Y=>({trackId:Y.receiver.track.id,kind:Y.receiver.track.kind,mid:Y.mid,display:E.get(Y.receiver)}));D(l.read(q,ae,n())),I=!1}catch(q){if(F!==A||!W())return;I||console.warn("[RemoteControl] could not read playback stats:",q),I=!0,l.reset(),D(null)}finally{h=!1,ot.delete(s),O&&W()&&(a=setTimeout(()=>{P()},F===A?2e3:0))}},U=()=>{if(!W()){$();return}O||(O=!0,P())};return document.addEventListener("visibilitychange",U),s.addEventListener("connectionstatechange",U),U(),()=>{m=!0,document.removeEventListener("visibilitychange",U),s.removeEventListener("connectionstatechange",U),$()}}function In(t,e){const n=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let s=!1,E=!1,l=0;return n.onmessage=a=>{if(E)return;let m;try{m=JSON.parse(a.data)}catch(O){console.warn("Invalid latency trace message",O);return}m&&typeof m=="object"&&!Array.isArray(m)&&e(m)},n.onclose=()=>{E=!0,s=!1},{accept(a){s=!E&&a===1},wrap(a){if(!s||a.byteLength!==32)return a;const m=new DataView(a);if(m.getUint8(0)!==2||m.getUint8(1)>2)return a;const O=new ArrayBuffer(38),h=new DataView(O);return h.setUint8(0,240),h.setUint8(1,1),h.setUint32(2,++l,!0),new Uint8Array(O,6).set(new Uint8Array(a)),O},close(){E=!0,s=!1,n.onmessage=null,n.onclose=null,n.close()}}}class Un{generation=0;tail=Promise.resolve();get currentGeneration(){return this.generation}enqueue(e){const n=++this.generation;return this.append(n,e)}enqueueCurrent(e){return this.append(this.generation,e)}append(e,n){const s={generation:e,isCurrent:()=>e===this.generation},E=this.tail.then(()=>n(s));return this.tail=E.catch(()=>{}),E}invalidate(){++this.generation}}function kn(t){if(!t||typeof t!="object")return null;const e=t;if(e.type!=="cameraRequest"||typeof e.active!="boolean")return null;const n={active:e.active};return(e.facingMode==="user"||e.facingMode==="environment")&&(n.facingMode=e.facingMode),n}function Pn(t){const e={frameRate:{ideal:30,max:30}};return t?.facingMode&&(e.facingMode={ideal:t.facingMode}),e}function Ln(t,e){return!t||t.facingMode!==e.facingMode}function Fn(t){const e=t.getSettings();return{width:e.width,height:e.height,frameRate:e.frameRate,deviceId:e.deviceId,label:t.label||void 0,facingMode:e.facingMode}}function Bn(t){return{type:"cameraResult",granted:!0,camera:Fn(t)}}const oe=(...t)=>{window.debugRemoteControl&&console.log(...t)},S=(...t)=>{window.debugRemoteControl&&console.warn(...t)},L=(t,e,...n)=>{if(e)try{e(...n)}catch(s){console.error(`[RemoteControl] customer callback "${t}" threw:`,s)}},Bt=t=>t.includes("/android_")?"android":"ios",vt=(t,e)=>{const n=new URL(t);return n.searchParams.set("token",e),n.toString()},at=3,xn=1e3,Wn=15e3,qn=3e3,Vn=4e3;function At(){const t=crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function $n(t){let e={...t};const{url:n,token:s,deviceModel:E}=e,l=e.watchOnly??!1,a=e.sessionId??At(),m=e.platform??Bt(n??"");let O={connection:"idle",videoReady:!1,controlReady:!1,duo:!1,duoState:null};const h=r=>{O={...O,...r},L("onStateChange",e.onStateChange,O)},A=r=>h({videoReady:r}),w=r=>h({duoState:r}),I=r=>h({duoError:r}),W=r=>h({duo:r}),D=r=>oe(r);let $=null,P;const U=()=>{P?.(),P=$&&e.onPlaybackStats?Rn($,()=>e.onPlaybackStats,()=>e.jitterBufferTargetMs):void 0},F=new Map,q=new Set,ae=new Set,Y=new Map;let Te=!1;const ke=new Map,st=(r,u,c)=>{u.stop?.(),u.stop=bn(r,c,d=>S("Video playback fallback:",d))},xt=()=>{ke.clear();for(const[r,u]of F)u.clear?.(),u.stop?.(),u.stop=void 0,r.srcObject=null};let Ee=!1,Se=!1,Pe=0,g=null,b=null,B=null,Le=null,fe,ye,ve,Fe,he,le=0,Be=0,te=!1,de=null,Q=null,ue;const ze=new Un;let Ae=null,xe=null,Ze=!l&&(e.microphoneEnabled??!1),et=!1,Ke=null,ee=null,We=0,ct=Promise.resolve(),me=null,Me=!1,ne=new Map,Z=new Map,se=new Map,re=new Map,V=null,we=null,lt=0;const qe=r=>{if(r===null&&we===null)return;we=r;const u=++lt;queueMicrotask(()=>{u===lt&&L("onAxSnapshotChange",e.onAxSnapshotChange,r)})};let pe=null,Ce=new Map;const Wt=(r,u)=>new Promise((c,d)=>{if(l){d(new Error("Device is watch-only"));return}const y=g;if(!y||y.readyState!==WebSocket.OPEN){d(new Error("Simulator disconnected"));return}const p=At(),C=setTimeout(()=>{Ce.delete(p),d(new Error("Device control timed out"))},5e3);Ce.set(p,{resolve:c,reject:d,timer:C}),y.send(JSON.stringify({type:r,id:p,...u}))}),Oe=r=>{pe!==r&&(pe=r,h({connection:r}),L("onConnectionStateChange",e.onConnectionStateChange,r))},ce=r=>{l||!B||B.readyState!=="open"||(B.send(Le?.wrap(r)??r),V?.bumpActivity())},qt=()=>{g&&g.readyState===WebSocket.OPEN&&g.send(JSON.stringify({type:"keepAlive",sessionId:a}))},dt=()=>{fe&&window.clearInterval(fe),fe=window.setInterval(qt,1e4)},Ye=()=>{fe&&(window.clearInterval(fe),fe=void 0)},Ve=()=>{ye&&(window.clearTimeout(ye),ye=void 0)},$e=()=>{ve&&(window.clearTimeout(ve),ve=void 0)},be=()=>{Fe&&(window.clearInterval(Fe),Fe=void 0)},Ne=()=>{he!==void 0&&(window.clearTimeout(he),he=void 0)},Vt=()=>{Me||(Me=!0,be(),A(!0),Oe("connected"))},H=r=>{for(const u of r.getTracks())try{u.stop()}catch(c){S("track.stop() failed:",c)}},$t=()=>{const r=Q;r&&(Q=null,H(r))},ut=r=>{const u=ct.then(r).catch(c=>{S("microphone operation failed:",c)});return ct=u,u},tt=()=>Ze||et,Et=r=>{const u=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;me=u,r.send(JSON.stringify({type:"microphoneStart",id:u}))},nt=()=>ut(()=>Ht()),Ht=async()=>{const r=We,u=()=>r===We&&tt(),c=f=>{L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:f})};if(!u())return;const d=g,y=Ke;if(!d||d.readyState!==WebSocket.OPEN||!y||ee)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)."),c("Microphone capture requires a secure context (https)");return}let p=null;try{p=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(f){console.warn("[RemoteControl] microphone getUserMedia denied/failed:",f)}if(!u()){p&&H(p);return}if(!p){c("Microphone permission denied or no device available");return}const C=p.getAudioTracks()[0]??null;if(!C){H(p),c("Captured stream has no audio track");return}try{await y.replaceTrack(C)}catch(f){S("replaceTrack(audioTrack) failed:",f),H(p),c("Failed to attach the microphone track to the connection");return}if(!u()){try{await y.replaceTrack(null)}catch(f){S("replaceTrack(null) on stale mic attach failed:",f)}H(p);return}ee=p,C.onended=()=>{ee===p&&He("microphone capture ended by the browser")},Et(d),L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},He=r=>(++We,me=null,ut(async()=>{const u=Ke,c=ee;if(ee=null,u&&c)try{await u.replaceTrack(null)}catch(y){S("replaceTrack(null) on mic detach failed:",y)}c&&H(c);const d=g;if(c&&d&&d.readyState===WebSocket.OPEN){const y=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;d.send(JSON.stringify({type:"microphoneStop",id:y}))}(c||r)&&L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...r!==void 0&&{error:r}})})),ft=(r,u)=>{let c;try{c=Bn(u),console.info(`[RemoteControl] camera capture: ${c.camera?.width}x${c.camera?.height} @ ${c.camera?.frameRate??"?"}fps`+(c.camera?.label?` — ${c.camera.label}`:""))}catch(d){S("getSettings() on outbound camera track failed:",d),c={type:"cameraResult",granted:!0,camera:{label:u.label||void 0}}}r.send(JSON.stringify(c)),L("onCameraDemandChange",e.onCameraDemandChange,!0,!0,c.camera)},Gt=r=>{if(!r)return;const u=r.indexOf("/"),d=(u>=0?r.slice(u+1):r).toUpperCase();return d==="HEVC"?"H265":d},Jt=async()=>{const r=de,u=e.onCameraStats;if(!r||!u)return;let c;try{c=await r.getStats()}catch{return}let d,y,p;if(c.forEach(N=>{N.type==="outbound-rtp"&&N.kind==="video"?d=N:N.type==="remote-inbound-rtp"&&N.kind==="video"&&(p=N)}),d?.codecId){const N=c.get(d.codecId);N&&(y=N.mimeType)}if(!d)return;const C=d.timestamp??Date.now(),f=xe;let J,k,j;if(f&&C>f.timestamp){const N=(C-f.timestamp)/1e3;if(typeof d.framesEncoded=="number"&&typeof f.framesEncoded=="number"&&(J=Math.max(0,(d.framesEncoded-f.framesEncoded)/N)),typeof d.bytesSent=="number"&&typeof f.bytesSent=="number"&&(k=Math.max(0,(d.bytesSent-f.bytesSent)*8/N)),typeof d.packetsSent=="number"&&typeof f.packetsSent=="number"&&p&&typeof p.packetsLost=="number"&&typeof f.packetsLost=="number"){const v=d.packetsSent-f.packetsSent,Je=p.packetsLost-f.packetsLost;v>0&&(j=Math.max(0,Math.min(100,Je/v*100)))}}xe={timestamp:C,framesEncoded:d.framesEncoded,bytesSent:d.bytesSent,packetsSent:d.packetsSent,packetsLost:p?.packetsLost};const M={codec:Gt(y),encoderImplementation:d.encoderImplementation,hardwareAccelerated:typeof d.powerEfficientEncoder=="boolean"?d.powerEfficientEncoder:void 0,framesPerSecond:J,framesEncoded:d.framesEncoded,bitrateBps:k,width:d.frameWidth,height:d.frameHeight,qualityLimitationReason:d.qualityLimitationReason,rttMs:typeof p?.roundTripTime=="number"?p.roundTripTime*1e3:void 0,packetsLostPct:j};L("onCameraStats",e.onCameraStats,M)},ht=()=>{Ae===null&&(xe=null,Ae=setInterval(()=>{Jt()},1e3))},Ge=()=>{Ae!==null&&(clearInterval(Ae),Ae=null),xe=null,L("onCameraStats",e.onCameraStats,null)},jt=(r,u,c,d)=>ze.enqueue(async({isCurrent:y})=>{const p=()=>y()&&d()&&g===u&&de===c;if(!p())return;if(!r.active){const M=Q;try{await c.replaceTrack(null)}catch(N){S("replaceTrack(null) on camera detach failed:",N)}if(Q===M&&(Q=null,ue=void 0,M&&H(M)),Ge(),!p())return;L("onCameraDemandChange",e.onCameraDemandChange,!1);return}L("onCameraDemandChange",e.onCameraDemandChange,!0);const C=Q,f=C?.getVideoTracks()[0],J=ue;if(f?.readyState==="live"&&J&&!Ln(J,r)){ue=r,ft(u,f),ht();return}if(C){try{await c.replaceTrack(null)}catch(M){S("replaceTrack(null) before camera switch failed:",M)}if(Q===C&&(Q=null,ue=void 0,H(C)),Ge(),!p())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."),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}let k=null;try{k=await navigator.mediaDevices.getUserMedia({video:Pn(r),audio:!1})}catch(M){console.warn("[RemoteControl] getUserMedia denied/failed:",M)}if(!p()){k&&H(k);return}if(!k){u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const j=k.getVideoTracks()[0]??null;if(!j){if(H(k),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{j.contentHint="motion"}catch{}try{await c.replaceTrack(j)}catch(M){if(S("replaceTrack(videoTrack) failed:",M),H(k),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!p()){try{await c.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera attach failed:",M)}H(k);return}try{const M=c.getParameters();(!M.encodings||M.encodings.length===0)&&(M.encodings=[{}]),M.encodings[0].maxBitrate=8e6,M.encodings[0].maxFramerate=30,M.degradationPreference="maintain-framerate",await c.setParameters(M)}catch(M){S("setParameters on outbound camera failed:",M)}if(!p()){try{await c.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera finalize failed:",M)}H(k);return}Q=k,ue=r,j.onended=()=>{Q===k&&ze.enqueueCurrent(async({isCurrent:M})=>{if(!(!M()||Q!==k||!d()||g!==u||de!==c)){try{await c.replaceTrack(null)}catch(N){S("replaceTrack(null) after camera ended failed:",N)}!M()||Q!==k||!d()||g!==u||de!==c||(Q=null,ue=void 0,H(k),Ge(),u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1))}}).catch(M=>S("camera ended cleanup failed:",M))},p()&&(ft(u,j),ht())}),De=()=>{for(const r of ae)r();ae.clear();for(const r of Y.values())clearTimeout(r);Y.clear();for(const r of Z.values())r(new Error("Simulator disconnected"));for(const r of re.values())r(new Error("Simulator disconnected"));Z.clear(),ne.clear(),re.clear(),se.clear(),P?.(),P=void 0,xt(),$=null;for(const r of Ce.values())clearTimeout(r.timer),r.reject(new Error("Simulator disconnected"));Ce.clear(),w(null),h({controlReady:!1,videoReady:!1}),$e(),Ne(),be(),V&&(V.stop(),V=null),we!==null&&qe(null),ze.invalidate(),Ge(),$t(),ue=void 0,de=null,++We,et=!1,me=null,ee&&(H(ee),ee=null,L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1})),Ke=null,g&&(g.onopen=null,g.onmessage=null,g.onerror=null,g.onclose=null,g.close(),g=null),Le?.close(),Le=null,b&&(b.onconnectionstatechange=null,b.oniceconnectionstatechange=null,b.ontrack=null,b.onicecandidate=null,b.close(),b=null),B&&(B.onopen=null,B.onclose=null,B.onerror=null,B.close(),B=null)},mt=()=>{document.hidden?Ye():dt()},Xt=async()=>{if(e.transport)return e.transport.isTerminated?.()??!1;if(typeof navigator<"u"&&navigator.onLine===!1)return!1;let r;try{const d=new URL(n);d.protocol=d.protocol==="wss:"?"https:":d.protocol==="ws:"?"http:":d.protocol,r=vt(d.toString(),s)}catch{return!1}const u=new AbortController,c=window.setTimeout(()=>u.abort(),Vn);try{return(await fetch(r,{method:"GET",cache:"no-store",signal:u.signal})).status===404}catch{return!1}finally{window.clearTimeout(c)}},Qt=()=>{Ee||(Ee=!0,le+=1,Ve(),$e(),Ne(),De(),D("Instance terminated"),Ye(),Oe("terminated"),L("onTerminated",e.onTerminated))},zt=()=>{if(Ee||Se)return;Se=!0;const r=Pe;Xt().catch(()=>!1).then(u=>{r===Pe&&(Se=!1,u&&Qt())})},_e=(r,u)=>{if(Ee||u!==le)return;if(zt(),te){if(e.autoReconnect===!1){D(`Connection failed after it was established: ${r}`),Ye(),Oe("failed"),De();return}D(`Reconnecting after established session dropped: ${r}`),te=!1,Be=-1}Ve();const c=Be+1;if(c>=at){D(`Connection failed after ${at} attempts: ${r}`),Ye(),Oe("failed"),De();return}D(`Retrying connection (${c+1}/${at})`),Oe("reconnecting"),De(),ye=window.setTimeout(()=>{ye=void 0,u===le&&pt(c)},xn)},pt=async(r=0)=>{const{openUrl:u,axPollIntervalMs:c,axMaxBackoffMs:d,androidElementTreeOptions:y}=e;if(Ee)return;const p=le+1;le=p,Be=r,te=!1,r===0&&pe!=="reconnecting"&&Oe("connecting"),Ve(),$e(),be(),Me=!1,A(!1),De();const C=()=>p===le;ve=window.setTimeout(()=>{ve=void 0,!(!C()||te)&&_e("Connection did not succeed within 15 seconds",p)},Wn);try{const f=e.transport?await e.transport.connect():new WebSocket(vt(n,s));if(!C()){f.close();return}if(g=f,await new Promise((_,o)=>{let R=!1;const x=()=>K(()=>o(new Error("Connection stopped")));ae.add(x);const T=window.setTimeout(()=>K(()=>o(new Error("WebSocket connection timeout"))),3e4),K=z=>{R||(R=!0,ae.delete(x),window.clearTimeout(T),z())};f.onopen=()=>{!C()||g!==f||K(_)},f.onerror=z=>{!C()||g!==f||(D("WebSocket error: "+z),K(()=>o(new Error("WebSocket connection failed"))))},f.onclose=()=>{!C()||g!==f||(D("WebSocket closed"),K(()=>o(new Error("WebSocket closed before connection was established"))))},f.readyState===WebSocket.OPEN?K(_):f.readyState!==WebSocket.CONNECTING&&K(()=>o(new Error("WebSocket is closed")))}),!C()||g!==f)return;f.onerror=_=>{!C()||g!==f||D("WebSocket error: "+_)},f.onclose=()=>{!C()||g!==f||D("WebSocket closed")};const J=new Promise((_,o)=>{let R=!1;const x=()=>T(()=>o(new Error("Connection stopped")));ae.add(x);const T=G=>{R||(R=!0,ae.delete(x),window.clearTimeout(K),f.removeEventListener("message",z),G())},K=window.setTimeout(()=>T(()=>o(new Error("RTCConfiguration timeout"))),3e4),z=G=>{if(!(!C()||g!==f))try{const X=JSON.parse(G.data);if(X.type==="signalingError"&&X.requestType==="requestRtcConfiguration"&&X.sessionId===a){const tn=typeof X.error=="string"?X.error:"Unable to load streaming configuration";T(()=>o(new Error(tn)))}else X.type==="rtcConfiguration"&&T(()=>_({rtcConfiguration:X.rtcConfiguration,cameraSupported:X.cameraSupported===!0,foldSupported:X.foldSupported===!0}))}catch(X){console.error("Error handling RTC configuration:",X),T(()=>o(X))}};f.addEventListener("message",z),f.send(JSON.stringify({type:"requestRtcConfiguration",sessionId:a}))}),{rtcConfiguration:k,cameraSupported:j,foldSupported:M}=await J;if(!C()||g!==f)return;const N=E==="iphone-duo"||M;W(N);const v=new RTCPeerConnection({...k,iceTransportPolicy:"relay"});b=v;const Je={peer:v,displays:new Map};$=Je,U(),v.addTransceiver("audio",{direction:"recvonly"});const Zt=v.addTransceiver("video",{direction:"recvonly"}),en=N?v.addTransceiver("video",{direction:"recvonly"}):null,_t=!l&&(m==="ios"||j),rt=_t?v.addTransceiver("video",{direction:"sendonly"}):null;if(de=rt?.sender??null,Ke=(_t?v.addTransceiver("audio",{direction:"sendonly"}):null)?.sender??null,RTCRtpReceiver.getCapabilities){const _=RTCRtpReceiver.getCapabilities("video");if(_&&_.codecs){const R=_.codecs.sort((x,T)=>{const K=z=>{const G=z.mimeType.toLowerCase();return G.includes("vp9")?1:G.includes("h265")||G.includes("hevc")?2:G.includes("h264")||G.includes("avc")?3:4};return K(x)-K(T)});Zt.setCodecPreferences(R),en?.setCodecPreferences(R),oe("Set codec preferences:",R.map(x=>x.mimeType).join(", "))}}if(rt&&RTCRtpSender.getCapabilities){const _=RTCRtpSender.getCapabilities("video");if(_&&_.codecs){const o=new Set(["42e01f","42e028","640c1f"]),R=T=>{const K=T.mimeType.toLowerCase(),G=(T.sdpFmtpLine||"").toLowerCase().match(/profile-level-id=([0-9a-f]{6})/),X=G?G[1]:"";return K==="video/h265"||K==="video/hevc"?1:K==="video/h264"&&o.has(X)?2:K==="video/h264"?3:K==="video/vp9"?4:K==="video/vp8"?5:K==="video/rtx"||K==="video/red"||K==="video/ulpfec"?0:6},x=[..._.codecs].sort((T,K)=>R(T)-R(K));try{rt.setCodecPreferences(x),oe("Outbound camera codec preferences:",x.map(T=>`${T.mimeType}${T.sdpFmtpLine?`[${T.sdpFmtpLine}]`:""}`).join(", "))}catch(T){S("Failed to set outbound camera codec preferences:",T)}}}const ie=v.createDataChannel("control",{ordered:!0,negotiated:!0,id:1});B=ie;const it=!l&&!N&&e.onTrace?In(v,_=>{C()&&b===v&&L("onTrace",e.onTrace,_)}):null;if(Le=it,ie.onopen=()=>{if(!C()||B!==ie||g!==f)return;te=!0,h({controlReady:!l}),$e(),D("Control channel opened"),N&&f.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),V||(V=new wn({platform:m,baseIntervalMs:c,maxBackoffMs:d,androidElementTreeOptions:y,send:o=>{if(!g||g.readyState!==WebSocket.OPEN)return!1;try{return g.send(JSON.stringify(o)),!0}catch{return!1}},onSnapshot:qe,onStatusChange:(o,R)=>{L("onAxStatusChange",e.onAxStatusChange,o,R)}}),(e.inspectMode===!0||e.inspectMode==="hover-only")&&V.start());const _=()=>{!C()||Me||B!==ie||g!==f||f.readyState!==WebSocket.OPEN||f.send(JSON.stringify({type:"requestFrame",sessionId:a}))};if(_(),be(),Fe=window.setInterval(()=>{if(!C()||Me||B!==ie||g!==f||f.readyState!==WebSocket.OPEN){be();return}_()},250),!l&&u){try{const o=decodeURIComponent(u);D("Opening URL"),f.send(JSON.stringify({type:"openUrl",url:o,sessionId:a}))}catch(o){console.error({error:o},"Error decoding URL, falling back to the original URL"),f.send(JSON.stringify({type:"openUrl",url:u,sessionId:a}))}V?.bumpActivity()}},ie.onclose=()=>{!C()||B!==ie||(h({controlReady:!1}),D("Control channel closed"))},ie.onerror=_=>{!C()||B!==ie||(console.error("Control channel error:",_),D("Control channel error: "+_))},v.onconnectionstatechange=()=>{!C()||b!==v||(D("Connection state: "+v.connectionState),v.connectionState==="failed"&&te&&_e("WebRTC connection entered failed state",p))},v.oniceconnectionstatechange=()=>{if(!C()||b!==v)return;const _=v.iceConnectionState;if(D("ICE state: "+_),_==="connected"||_==="completed"){Ne(),tt()&&!ee&&nt();return}if(_==="failed"){Ne(),te&&_e("ICE connection entered failed state",p);return}_==="disconnected"&&te&&e.autoReconnect!==!1&&he===void 0&&(he=window.setTimeout(()=>{he=void 0,!(!C()||b!==v)&&v.iceConnectionState==="disconnected"&&_e("ICE stayed disconnected past grace period",p)},qn))},v.ontrack=_=>{if(!C()||b!==v)return;St(_.receiver,e.jitterBufferTargetMs);const o=_.track.id==="duo-inner"||_.streams.some(R=>R.id==="duo-inner");if(_.track.kind==="video"&&Je.displays.set(_.receiver,o?"inner":"primary"),D("Received remote track: "+_.track.kind),_.track.kind==="video"){const R=o?"inner":"primary",x=N?new MediaStream([_.track]):_.streams[0]??new MediaStream([_.track]);ke.set(R,x);for(const[T,K]of F)K.display===R&&st(T,K,x)}},v.onicecandidate=_=>{if(!(!C()||b!==v||g!==f))if(_.candidate&&f.readyState===WebSocket.OPEN){const o={type:"candidate",candidate:_.candidate.candidate,sdpMid:_.candidate.sdpMid,sdpMLineIndex:_.candidate.sdpMLineIndex,sessionId:a};f.send(JSON.stringify(o)),D("Sent ICE candidate")}else D("ICE candidate gathering completed")},f.onmessage=async _=>{if(!C()||g!==f)return;let o;try{o=JSON.parse(_.data)}catch(R){S("Error parsing message:",R);return}if(!V?.handleMessage(o))switch(D("Received: "+o.type),o.type){case"performActionsResult":case"foldStateResult":case"foldStateChanged":{if(!N)break;o.state?(w(o.state),I(void 0)):o.id==="duo-capabilities"&&I(o.error||"This instance does not support native iPhone Duo displays.");const T=Ce.get(o.id);T&&(clearTimeout(T.timer),Ce.delete(o.id),o.error?T.reject(new Error(o.error)):T.resolve());break}case"signalingError":{if(o.requestType!=="offer"||o.sessionId!==a)break;const T=typeof o.error=="string"?o.error:"Unable to establish the streaming connection";D("Error: "+T),_e(T,p);break}case"answer":if(!b||b!==v){D("No peer connection, skipping answer");break}if(it?.accept(o.latencyTraceVersion),await v.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:o.sdp})),!C()||b!==v)return;D("Set remote description");break;case"candidate":if(!b||b!==v){D("No peer connection, skipping candidate");break}if(await v.addIceCandidate(new RTCIceCandidate({candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex})),!C()||b!==v)return;D("Added ICE candidate");break;case"screenshot":case"screenshotResult":{if(typeof o.id!="string"){S("Received invalid screenshot success message:",o);break}const T=Hn(o);if(T){const G=Z.get(o.id);if(typeof G!="function"){S(`Received screenshot error for unknown or handled id: ${o.id}`);break}S(`Received screenshot error for id ${o.id}: ${T}`),G(new Error(T)),ne.delete(o.id),Z.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break}const K=Gn(o);if(!K){S("Received screenshot message without image data:",o);break}const z=ne.get(o.id);if(typeof z!="function"){S(`Received screenshot data for unknown or handled id: ${o.id}`);break}oe(`Received screenshot data for id ${o.id}`),z(K),ne.delete(o.id),Z.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break}case"screenshotError":if(typeof o.id!="string"||typeof o.message!="string"){S("Received invalid screenshot error message:",o);break}const R=Z.get(o.id);if(typeof R!="function"){S(`Received screenshot error for unknown or handled id: ${o.id}`);break}S(`Received screenshot error for id ${o.id}: ${o.message}`),R(new Error(o.message)),ne.delete(o.id),Z.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break;case"cameraRequest":{const T=de;if(!T)break;const K=kn(o);if(!K){S("Received invalid cameraRequest:",o);break}console.info("[RemoteControl] cameraRequest received:",K.active,K.facingMode),await jt(K,f,T,C);break}case"microphoneRequest":{if(!Ke)break;const T=o.active===!0;if(et=T,console.info("[RemoteControl] microphoneRequest received, active=",T),!T){Ze||await He();break}if(ee){Et(f);break}await nt();break}case"microphoneStartResult":{if(me===null||o.id!==me)break;me=null,typeof o.error=="string"&&(console.warn("[RemoteControl] microphoneStart rejected by host:",o.error),He(o.error));break}case"terminateAppResult":if(typeof o.id!="string"){S("Received invalid terminateApp result message:",o);break}if(typeof o.error=="string"){const T=re.get(o.id);if(typeof T!="function"){S(`Received terminateApp error for unknown or handled id: ${o.id}`);break}S(`Received terminateApp error for id ${o.id}: ${o.error}`),T(new Error(o.error)),se.delete(o.id),re.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break}const x=se.get(o.id);if(typeof x!="function"){S(`Received terminateApp result for unknown or handled id: ${o.id}`);break}oe(`Received terminateApp success for id ${o.id}`),x(),se.delete(o.id),re.delete(o.id),clearTimeout(Y.get(o.id)),Y.delete(o.id);break;default:S(`Received unhandled message type: ${o.type}`,o);break}},b===v){const _=await v.createOffer({offerToReceiveVideo:!0,offerToReceiveAudio:!1});if(!C()||b!==v||(await v.setLocalDescription(_),!C()||b!==v))return;C()&&g===f&&f.readyState===WebSocket.OPEN&&f.send(JSON.stringify({type:"offer",...N?{displayStreams:!0}:{},...it?{latencyTraceVersion:1}:{},sdp:_.sdp,sessionId:a})),D("Sent offer")}}catch(f){if(!C()||f instanceof Error&&f.message==="Connection stopped")return;const J=f instanceof Error?f.message:String(f);D("Error: "+J),_e(J,p)}},Ct=()=>{if(Te)throw new Error("Device stream is disposed");Pe++,Se=!1,qe(null),pe!=="reconnecting"&&(pe=null),document.addEventListener("visibilitychange",mt),document.hidden||dt(),Ee=!1,pt(0)},Ot=()=>{Pe++,Se=!1,Ye(),document.removeEventListener("visibilitychange",mt),le+=1,Be=0,te=!1,Ve(),Ne(),De(),pe=null,h({connection:"idle",videoReady:!1,controlReady:!1}),D("Stopped")},Dt=(r,u="primary")=>{if(Te)throw new Error("Device stream is disposed");if(F.has(r))throw new Error("Video element is already attached");const c={display:u};F.set(r,c);const d=()=>{u==="primary"&&ke.has(u)&&Vt()};r.addEventListener("loadeddata",d);const y=ke.get(u);y&&st(r,c,y);let p=!1;const C=()=>{p||(p=!0,q.delete(C),r.removeEventListener("loadeddata",d),c.stop?.(),F.delete(r),r.srcObject=null)};return q.add(C),C};return{start:Ct,stop:Ot,attachVideo:Dt,attachFrameSink:(r,u="primary")=>{const c=document.createElement("video");c.muted=!0,c.playsInline=!0,c.autoplay=!0;const d=Dt(c,u);let y=!1,p=0,C=0;const f=()=>{c.cancelVideoFrameCallback?.(p),cancelAnimationFrame(C)},J=()=>{y||!c.srcObject||(c.readyState>=2&&c.videoWidth>0&&L("present",(...M)=>r.present(...M),c,c.videoWidth,c.videoHeight,u),!(y||!c.srcObject)&&(c.requestVideoFrameCallback?p=c.requestVideoFrameCallback(J):C=requestAnimationFrame(J)))},k=()=>{f(),J()};F.get(c).clear=f,c.addEventListener("loadeddata",k);const j=()=>{y||(y=!0,q.delete(j),f(),c.removeEventListener("loadeddata",k),d(),c.remove())};return q.delete(d),q.add(j),c.readyState>=2&&k(),j},dispose:()=>{if(!Te){Te=!0,Ot();for(const r of q)r();q.clear()}},getState:()=>O,updateOptions:r=>{if(Te)throw new Error("Device stream is disposed");const u=e;if(e={...e,...r},u.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const c of b?.getTransceivers()??[])(c.currentDirection==="recvonly"||c.currentDirection==="sendrecv")&&St(c.receiver,e.jitterBufferTargetMs);!!u.onPlaybackStats!=!!e.onPlaybackStats&&U(),!!u.microphoneEnabled!=!!e.microphoneEnabled&&(Ze=!l&&(e.microphoneEnabled??!1),tt()?nt():He()),!!u.inspectMode!=!!e.inspectMode&&(e.inspectMode?V?.start():(V?.stop(),we!==null&&qe(null)))},sendControl:ce,sendTouch:(r,u,c,d,y,p=0)=>ce(Mt(r==="begin"?0:r==="end"?1:2,p,d,y,u,c,r==="end"?0:1)),sendText:r=>ce(wt(r)),sendDisplayTouch:(r,u,c,d)=>ce(Nt(r,u,c,d)),sendDuoControl:Wt,pressButton:r=>{const u={home:3,back:4,recents:187,power:26}[r];ce(je(0,u,0,0)),ce(je(1,u,0,0))},rotate:()=>ce(new Uint8Array([11]).buffer),bumpActivity:()=>V?.bumpActivity(),getAxStatus:()=>V?.getStatus()??"idle",openUrl:r=>{if(!l){if(!g||g.readyState!==WebSocket.OPEN){S("WebSocket not open, cannot send open_url command.");return}try{const u=decodeURIComponent(r);D("Opening URL"),g.send(JSON.stringify({type:"openUrl",url:u,sessionId:a}))}catch(u){S("Error decoding or sending URL :",{error:u,url:r}),g.send(JSON.stringify({type:"openUrl",url:r,sessionId:a}))}V?.bumpActivity()}},sendKeyEvent:r=>{if(!B||B.readyState!=="open"){S("Data channel not ready for imperative key command:",B?.readyState);return}const u=Kt[r.code];if(!u){S(`Unknown event.code for imperative command: ${r.code}`);return}let c=i.META_NONE;r.shiftKey&&(c|=i.META_SHIFT_ON),r.altKey&&(c|=i.META_ALT_ON),r.ctrlKey&&(c|=i.META_CTRL_ON),r.metaKey&&(c|=i.META_META_ON);const d=r.type==="keydown"?i.ACTION_DOWN:i.ACTION_UP;oe(`Sending Imperative Key Command: code=${r.code}, keycode=${u}, action=${d}, meta=${c}`);const y=je(d,u,0,c);y&&ce(y)},screenshot:r=>new Promise((u,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return S("WebSocket not open, cannot send screenshot command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,y={type:r?"screenshotDisplay":"screenshot",...r?{display:r}:{},id:d};ne.set(d,u),Z.set(d,c),oe("Sending screenshot request:",y);try{g.send(JSON.stringify(y))}catch(p){S("Failed to send screenshot request immediately:",p),ne.delete(d),Z.delete(d),c(p);return}Y.set(d,setTimeout(()=>{Y.delete(d),ne.has(d)&&(S(`Screenshot request timed out for id ${d}`),Z.get(d)?.(new Error("Screenshot request timed out")),ne.delete(d),Z.delete(d))},3e4))}),terminateApp:r=>l?Promise.reject(new Error("Device is watch-only")):new Promise((u,c)=>{if(!g||g.readyState!==WebSocket.OPEN)return S("WebSocket not open, cannot send terminateApp command."),c(new Error("WebSocket is not connected or connection is not open."));const d=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,y={type:"terminateApp",id:d,bundleId:r};se.set(d,u),re.set(d,c),oe("Sending terminateApp request:",y);try{g.send(JSON.stringify(y))}catch(p){S("Failed to send terminateApp request immediately:",p),se.delete(d),re.delete(d),c(p);return}V?.bumpActivity(),Y.set(d,setTimeout(()=>{Y.delete(d),se.has(d)&&(S(`terminateApp request timed out for id ${d}`),re.get(d)?.(new Error("terminateApp request timed out")),se.delete(d),re.delete(d))},3e4))}),reconnect:()=>Ct(),refreshAxTree:async()=>{const r=V;if(!r)throw new Error("Inspect mode is not active");return r.refresh()},getAxSnapshot:()=>we}}const Hn=t=>typeof t.message=="string"?t.message:typeof t.error=="string"?t.error:null,Gn=t=>typeof t.dataUri=="string"?{dataUri:t.dataUri}:typeof t.base64=="string"?t.base64.startsWith("data:")?{dataUri:t.base64}:{dataUri:`data:${t.base64.startsWith("/9j/")?"image/jpeg":"image/png"};base64,${t.base64}`}:null;exports.AMOTION_EVENT=Re;exports.ANDROID_KEYS=i;exports.AX_UNAVAILABLE_ERROR=Xe;exports.CONTROL_MSG_TYPE=Ue;exports.DUO_BUTTONS=un;exports.DUO_DIMENSIONS=an;exports.DuoButtonSender=En;exports.DuoTouchController=on;exports.HingeSender=dn;exports.axElementAtPoint=_n;exports.axElementRoleLabel=Lt;exports.axElementSelectorExpression=gn;exports.axElementSummary=Tn;exports.axElementsEqual=kt;exports.axSnapshotsEqual=Pt;exports.clampAxFrameForScreen=Dn;exports.codeMap=Kt;exports.createDeviceStream=$n;exports.createDisplayTouchMessage=Nt;exports.createInjectKeycodeMessage=je;exports.createSetClipboardMessage=wt;exports.createTouchControlMessage=Mt;exports.createTwoFingerTouchControlMessage=nn;exports.debugLog=oe;exports.debugWarn=S;exports.detectPlatform=Bt;exports.duoDisplayTurns=Yt;exports.duoPointerMode=ln;exports.flatDisplayTouch=bt;exports.getDuoDisplay=rn;exports.normalizeAndroidTree=Ut;exports.normalizeIosTree=It;exports.panelTouch=cn;exports.safeInvoke=L;
@@ -1 +0,0 @@
1
- "use strict";require('./index.css');const h=require("react/jsx-runtime"),r=require("./core-OsPKiOsB.js"),d=require("react"),Lt=require("react-dom"),kt=async f=>{if(!f)return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(f),!0}catch{}try{const i=document.createElement("textarea");i.value=f,i.style.position="fixed",i.style.opacity="0",document.body.appendChild(i),i.select();const g=document.execCommand("copy");return document.body.removeChild(i),g}catch{return!1}},Wt=d.memo(function({element:i,screen:g,highlighted:p,selected:O,selectable:H,onClick:R}){const v=r.clampAxFrameForScreen(i.frame,g);if(!v)return null;const W=r.axElementSummary(i);return h.jsx("button",{type:"button",className:i.enabled?"rc-inspect-box":"rc-inspect-box rc-inspect-box-disabled","data-ax-id":i.id,"data-ax-path":i.path,"data-ax-label":i.label||void 0,"data-ax-role":i.role||void 0,"data-highlighted":p?"true":"false","data-selected":O?"true":"false","aria-label":W,onClick:y=>{H&&(y.preventDefault(),y.stopPropagation(),R(i,{x:y.clientX,y:y.clientY}))},style:{left:`${v.x/g.width*100}%`,top:`${v.y/g.height*100}%`,width:`${v.width/g.width*100}%`,height:`${v.height/g.height*100}%`}})},(f,i)=>f.highlighted===i.highlighted&&f.selected===i.selected&&f.selectable===i.selectable&&f.screen.width===i.screen.width&&f.screen.height===i.screen.height&&f.onClick===i.onClick&&r.axElementsEqual(f.element,i.element)),Xt=260,Ht=220,jt=6,Vt=8,Kt=d.memo(function({element:i,platform:g,anchor:p,cursorAnchored:O,showActions:H,onTap:R}){const[v,W]=d.useState(null);d.useEffect(()=>{if(!v)return;const A=window.setTimeout(()=>W(null),1100);return()=>window.clearTimeout(A)},[v]);const y=d.useMemo(()=>{const A=Xt,V=Ht,P=jt,E=Vt,F=typeof window<"u"?window.innerWidth:1024,Te=typeof window<"u"?window.innerHeight:768,K=p.x+P+A<=F-E,G=p.y-P-V>=E;let Z=K?p.x+P:p.x-P,ae=G?p.y-P:p.y+P;const ee=`translate(${K?"0":"-100%"}, ${G?"-100%":"0"})`;return Z=Math.max(E+(K?0:A),Math.min(F-E-(K?A:0),Z)),ae=Math.max(E+(G?V:0),Math.min(Te-E-(G?0:V),ae)),{left:`${Z}px`,top:`${ae}px`,transform:ee}},[p.x,p.y]),M=d.useMemo(()=>r.axElementSelectorExpression(i,g),[i,g]),I=g==="ios"?i.selectors.AXUniqueId:i.selectors.resourceId,x=g==="ios"?"AXUniqueId":"resourceId",$=d.useCallback(async(A,V)=>{if(!A)return;await kt(A)&&W(V)},[]),q=r.axElementRoleLabel(i),X=i.label||i.value||q,Q=r.axElementSummary(i);return Lt.createPortal(h.jsxs("div",{className:"rc-inspect-card","data-cursor-anchored":O?"true":"false",style:y,onClick:A=>A.stopPropagation(),onMouseDown:A=>A.stopPropagation(),onMouseMove:A=>A.stopPropagation(),children:[h.jsxs("div",{className:"rc-inspect-card-header",children:[h.jsx("span",{className:"rc-inspect-card-role",children:q}),!i.enabled&&h.jsx("span",{className:"rc-inspect-card-tag",children:"disabled"}),i.focused&&h.jsx("span",{className:"rc-inspect-card-tag rc-inspect-card-tag-blue",children:"focused"})]}),h.jsx("p",{className:"rc-inspect-card-title",title:Q,children:X}),I&&h.jsxs("div",{className:"rc-inspect-card-row",children:[h.jsxs("span",{className:"rc-inspect-card-row-label",children:[x,":"]}),h.jsx("span",{className:"rc-inspect-card-row-value",children:I})]}),i.value&&i.value!==i.label&&h.jsxs("div",{className:"rc-inspect-card-row",children:[h.jsx("span",{className:"rc-inspect-card-row-label",children:"value:"}),h.jsx("span",{className:"rc-inspect-card-row-value",children:i.value})]}),h.jsxs("div",{className:"rc-inspect-card-row",children:[h.jsx("span",{className:"rc-inspect-card-row-label",children:"frame:"}),h.jsxs("span",{className:"rc-inspect-card-row-value",children:[Math.round(i.frame.width),"×",Math.round(i.frame.height)," @ ",Math.round(i.frame.x),",",Math.round(i.frame.y)]})]}),H&&h.jsxs("div",{className:"rc-inspect-card-actions",children:[h.jsx("button",{type:"button",className:"rc-inspect-card-btn rc-inspect-card-btn-primary",disabled:!R,onClick:()=>R?.(i,p),children:"Tap"}),h.jsx("button",{type:"button",className:v==="selector"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!M,title:M??"No usable selector for this element",onClick:()=>$(M??void 0,"selector"),children:v==="selector"?"Copied!":"Copy selector"}),h.jsx("button",{type:"button",className:v==="id"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!I,title:I??`No ${x}`,onClick:()=>$(I,"id"),children:v==="id"?"Copied!":`Copy ${x}`})]})]}),document.body)}),Ut=d.memo(function({snapshot:i,geometry:g,highlightedId:p,selectedId:O,mode:H,cursorPosition:R,frozenCursorPosition:v,onSelectChange:W,onTapElement:y}){const M=H==="select",I=M?p!==null&&p!==O:p!==null,x=M?p??O:p,$=d.useMemo(()=>{const E=new Map;if(!i)return E;for(const F of i.elements)E.set(F.id,F);return E},[i]),q=d.useMemo(()=>x?$.get(x)??null:null,[x,$]);if(!(!!i&&!!g&&i.screen.width>0&&i.screen.height>0&&i.elements.length>0))return null;const Q=I?R:v??R,A=I,V=M&&!I&&O!==null,P=E=>{M&&E.target===E.currentTarget&&W(null,null)};return h.jsxs(h.Fragment,{children:[h.jsx("div",{className:M?"rc-inspect-overlay rc-inspect-overlay-select":"rc-inspect-overlay",style:{left:`${g.left}px`,top:`${g.top}px`,width:`${g.width}px`,height:`${g.height}px`},onClick:P,children:i.elements.map(E=>h.jsx(Wt,{element:E,screen:i.screen,highlighted:E.id===p,selected:E.id===O,selectable:M,onClick:W},E.id))}),q&&Q&&h.jsx(Kt,{element:q,platform:i.platform,anchor:Q,cursorAnchored:A,showActions:V,onTap:y})]})});function $t(f,i){if(!i.startsWith("lim_st_"))return!1;try{const g=new URL(f).pathname.split("/").map(decodeURIComponent).find(y=>/^(ios|android)_[a-z0-9_]+$/.test(y));if(!g)return!1;const p=g.split("_")[0],O=i.slice(7).split(".");if(O.length!==3||O.some(y=>!y))return!1;const H=atob(O[1].replace(/-/g,"+").replace(/_/g,"/")),R=JSON.parse(new TextDecoder().decode(Uint8Array.from(H,y=>y.charCodeAt(0))));if(!R||typeof R!="object"||!("scopes"in R))return!1;const v=R.scopes;if(!Array.isArray(v)||!v.every(y=>typeof y=="string"))return!1;let W=!1;for(const y of v){const[M,I,x,$]=y.split(":");if(!($!==void 0||M!==p&&M!=="*")&&!(I!==g&&I!=="*")){if(x==="stream"||x==="all")return!1;x==="watch"&&(W=!0)}}return W}catch{return!1}}const Ft=d.lazy(()=>Promise.resolve().then(()=>require("./duo-view-Cy8dvjCI.js")).then(f=>f.duoView)),Ce=f=>Object.entries(r.AMOTION_EVENT).find(([g,p])=>g.startsWith("ACTION_")&&p===f)?.[0]??String(f),it=1920,ct=1200,zt=(f,i)=>f===it&&i===ct||f===ct&&i===it,Bt={ios:{videoBorderRadiusMultiplier:.15,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:.9678},landscape:{widthMultiplier:.9678}}},android:{videoBorderRadiusMultiplier:.13,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:.967},landscape:{widthMultiplier:.962}}}},qt={videoBorderRadiusMultiplier:32/1837,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:2560/2798},landscape:{widthMultiplier:2560/2798}}};function Gt(f){const i=f.code,g=r.codeMap[i];if(!g)return r.debugWarn(`Unknown event.code: ${i}, key: ${f.key}`),null;let p=r.ANDROID_KEYS.META_NONE;const O=i>="KeyA"&&i<="KeyZ",H=f.getModifierState("CapsLock"),R=f.shiftKey;let v=R;return O&&(v=R!==H),v&&(p|=r.ANDROID_KEYS.META_SHIFT_ON),f.ctrlKey&&(p|=r.ANDROID_KEYS.META_CTRL_ON),f.altKey&&(p|=r.ANDROID_KEYS.META_ALT_ON),f.metaKey&&(p|=r.ANDROID_KEYS.META_META_ON),{keycode:g,metaState:p}}function Jt(f,i){const g=Object.keys(f);return g.length===Object.keys(i).length&&g.every(p=>f[p]===i[p])}const Qt=d.forwardRef(({className:f,url:i,token:g,sessionId:p,openUrl:O,watchOnly:H=!1,showFrame:R=!0,deviceModel:v,duoModelUrl:W,autoReconnect:y,jitterBufferTargetMs:M,onPlaybackStats:I,onTerminated:x,assets:$,onConnectionStateChange:q,inspectMode:X,onAxSnapshotChange:Q,onInspectSelectionChange:A,onAxStatusChange:V,axPollIntervalMs:P,axMaxBackoffMs:E,androidElementTreeOptions:F,onCameraDemandChange:Te,onCameraStats:K,onTrace:G,microphoneEnabled:Z=!1,onMicrophoneStateChange:ae},Xe)=>{const He=d.useMemo(()=>$t(i,g),[i,g]),ee=H||He,Ne=d.useRef(null),C=d.useRef(null),je=d.useRef(null),[st,at]=d.useState(!1),j=v==="iphone-duo"||st,Ae=d.useRef(null),[Ve,lt]=d.useState(null),[Ke,dt]=d.useState(),[ut,ht]=d.useState(!1),[ft,gt]=d.useState(!1),[pt,mt]=d.useState(!1),[Ue,$e]=d.useState(!1),[Fe,ze]=d.useState(!1),[vt,Be]=d.useState({}),Se=d.useRef(null),S=d.useRef(new Map),te=d.useRef(!1),[yt,Et]=d.useState(!1),b=d.useRef(null),le=d.useRef(null),me=d.useRef({handle:()=>{},end:()=>{}}),[ne,we]=d.useState(null),[qe,De]=d.useState(null),[xe,ve]=d.useState(null),[Ye,Oe]=d.useState(null),[Tt,Ge]=d.useState(null),[Nt,Je]=d.useState(null),Re=d.useRef(null),z=d.useRef(void 0),Qe=e=>{Re.current=e,z.current===void 0&&(z.current=window.requestAnimationFrame(()=>{z.current=void 0,Je(Re.current)}))},[At,de]=d.useState(null),oe=d.useRef(null);oe.current=qe;const ue=d.useRef(A);ue.current=A;const re=X===!0||X==="hover-only",Ze=d.useRef(re);Ze.current=re;const wt=X==="hover-only"?"hover-only":"select",B=d.useMemo(()=>r.detectPlatform(i),[i]),Ot=d.useMemo(()=>p||Array.from(crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(36)).join(""),[p,g]),he=B==="android"&&Fe?qt:Bt[B],ye=$?.[B],et=B==="android"&&Fe?Ue?ye?.tabletFrameLandscape:ye?.tabletFrame:Ue?ye?.frameLandscape:ye?.frame,tt=ye?.loadingLogo,Ie=!j&&R&&!!et,T=d.useRef(null),U=e=>T.current?.sendControl(e),Pe=(e,t)=>T.current?.sendDuoControl(e,t)??Promise.reject(new Error("Simulator disconnected")),nt=-10,ot=(e,t)=>{const o=Ee();if(!o)return;const n=ge(o,e,t);if(!n)return;const{videoX:s,videoY:l,videoWidth:c,videoHeight:u}=n,a=r.createTouchControlMessage(r.AMOTION_EVENT.ACTION_DOWN,nt,c,u,s,l,1,r.AMOTION_EVENT.BUTTON_PRIMARY,r.AMOTION_EVENT.BUTTON_PRIMARY);a&&U(a),window.setTimeout(()=>{const m=r.createTouchControlMessage(r.AMOTION_EVENT.ACTION_UP,nt,c,u,s,l,0,r.AMOTION_EVENT.BUTTON_PRIMARY,r.AMOTION_EVENT.BUTTON_PRIMARY);m&&U(m)},60)},Rt=(e,t)=>{const o=Ee();if(!o||t.screen.width<=0||t.screen.height<=0)return;const n=e.frame.x+e.frame.width/2,s=e.frame.y+e.frame.height/2,l=n/t.screen.width*o.actualWidth,c=s/t.screen.height*o.actualHeight,u=o.videoRect.left+o.offsetX+l,a=o.videoRect.top+o.offsetY+c;ot(u,a)},be=-1,_e=-2,ie=-3,fe=(e,t,o,n,s,l)=>{const c=r.createTouchControlMessage(e,t,o,n,s,l,1,r.AMOTION_EVENT.BUTTON_PRIMARY,r.AMOTION_EVENT.BUTTON_PRIMARY);c&&(r.debugLog("[rc-touch] sendSingleTouch",{action:e,actionName:Ce(e),pointerId:t,x:s,y:l,video:{width:o,height:n}}),U(c))},ce=(e,t,o)=>{if(!o)return;const{videoX:n,videoY:s,videoWidth:l,videoHeight:c}=o;let u=null,a=null,m=1;const _=r.AMOTION_EVENT.BUTTON_PRIMARY;switch(t){case"down":e!==ie&&me.current.end(),u=S.current.size===0?r.AMOTION_EVENT.ACTION_DOWN:r.AMOTION_EVENT.ACTION_POINTER_DOWN,a={x:n,y:s},S.current.set(e,a),e===-1&&C.current?.focus();break;case"move":S.current.has(e)&&(u=r.AMOTION_EVENT.ACTION_MOVE,a={x:n,y:s},S.current.set(e,a));break;case"up":case"cancel":S.current.has(e)&&(a=S.current.get(e),S.current.delete(e),t==="cancel"?u=r.AMOTION_EVENT.ACTION_CANCEL:u=S.current.size===0?r.AMOTION_EVENT.ACTION_UP:r.AMOTION_EVENT.ACTION_POINTER_UP);break}if(u!==null&&a!==null){r.debugLog("[rc-touch][mouse->touch] sending",{pointerId:e,eventType:t,action:u,actionName:Ce(u),positionToSend:a,video:{width:l,height:c},altHeld:te.current,activePointersAfter:Array.from(S.current.entries()).map(([Y,w])=>({id:Y,x:w.x,y:w.y}))});const N=r.createTouchControlMessage(u,e,l,c,a.x,a.y,m,_,_);N&&(r.debugLog("[rc-touch][mouse->touch] buffer",{pointerId:e,actionName:Ce(u),byteLength:N.byteLength}),U(N))}else(t==="up"||t==="cancel")&&S.current.delete(e)},Le=e=>{if(te.current!==e&&(te.current=e,Et(e),e||we(null),r.debugLog("[rc-touch][alt] updateAltHeld",{nextHeld:e,activePointerIds:Array.from(S.current.keys())}),B==="ios"&&T.current?.getState().controlReady)){const t=e?r.ANDROID_KEYS.ACTION_DOWN:r.ANDROID_KEYS.ACTION_UP,o=r.createInjectKeycodeMessage(t,r.ANDROID_KEYS.KEYCODE_ALT_LEFT,0,r.ANDROID_KEYS.META_NONE);r.debugLog("[rc-touch][alt] sending Indigo modifier keycode",{action:t,keycode:r.ANDROID_KEYS.KEYCODE_ALT_LEFT}),o&&U(o)}},Ee=()=>{const e=C.current,t=Ne.current;if(!e||!t)return null;const o=e.videoWidth,n=e.videoHeight;if(!o||!n)return null;const s=e.getBoundingClientRect(),l=t.getBoundingClientRect(),c=s.width,u=s.height,a=o/n,m=c/u;let _=c,N=u;a>m?N=c/a:_=u*a;const Y=(c-_)/2,w=(u-N)/2;return{videoWidth:o,videoHeight:n,videoRect:s,containerRect:l,actualWidth:_,actualHeight:N,offsetX:Y,offsetY:w}},ge=(e,t,o)=>{const n=t-e.videoRect.left-e.offsetX,s=o-e.videoRect.top-e.offsetY,l=Math.max(0,Math.min(e.actualWidth,n)),c=Math.max(0,Math.min(e.actualHeight,s)),u=Math.max(0,Math.min(e.videoWidth,l/e.actualWidth*e.videoWidth)),a=Math.max(0,Math.min(e.videoHeight,c/e.actualHeight*e.videoHeight));return{videoX:u,videoY:a,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},It=(e,t,o)=>{const n=t-e.videoRect.left-e.offsetX,s=o-e.videoRect.top-e.offsetY,l=Math.max(0,Math.min(e.actualWidth,n)),c=Math.max(0,Math.min(e.actualHeight,s)),u=Math.max(0,Math.min(e.videoWidth,l/e.actualWidth*e.videoWidth)),a=Math.max(0,Math.min(e.videoHeight,c/e.actualHeight*e.videoHeight)),m=e.videoWidth-u,_=e.videoHeight-a,N=e.videoRect.left+e.offsetX,Y=e.videoRect.top+e.offsetY,w=N-e.containerRect.left+l,D=Y-e.containerRect.top+c,se=N-e.containerRect.left+(e.actualWidth-l),k=Y-e.containerRect.top+(e.actualHeight-c);return{containerX:w,containerY:D,mirrorContainerX:se,mirrorContainerY:k,videoX:u,videoY:a,mirrorVideoX:m,mirrorVideoY:_,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},bt=(e,t,o,n,s,l,c)=>{const u=r.createTwoFingerTouchControlMessage(e,t,o,n,s,l,c);r.debugLog("[rc-touch2] sendTwoFingerMessage (iOS)",{actionName:Ce(e),video:{width:t,height:o},p0:{x:n,y:s},p1:{x:l,y:c},byteLength:u.byteLength}),U(u)},pe=(e,t,o,n,s,l,c,u,a)=>{if(r.debugLog("[rc-touch2] applyTwoFingerEvent",{platform:B,eventType:e,video:{width:t,height:o},p0:{x:n,y:s,id:u},p1:{x:l,y:c,id:a}}),e==="down"&&me.current.end(),B==="ios"){const m=e==="down"?r.AMOTION_EVENT.ACTION_DOWN:e==="move"?r.AMOTION_EVENT.ACTION_MOVE:r.AMOTION_EVENT.ACTION_UP;bt(m,t,o,n,s,l,c)}else e==="down"?(fe(r.AMOTION_EVENT.ACTION_DOWN,u,t,o,n,s),fe(r.AMOTION_EVENT.ACTION_POINTER_DOWN,a,t,o,l,c)):e==="move"?(fe(r.AMOTION_EVENT.ACTION_MOVE,u,t,o,n,s),fe(r.AMOTION_EVENT.ACTION_MOVE,a,t,o,l,c)):(fe(r.AMOTION_EVENT.ACTION_POINTER_UP,a,t,o,l,c),fe(r.AMOTION_EVENT.ACTION_UP,u,t,o,n,s))},_t=(e,t,o)=>{if(!te.current){ne!==null&&we(null);return}const n=It(e,t,o);we(n)},Mt=(e,t,o)=>{const n=oe.current;if(!n||n.screen.width<=0||n.screen.height<=0)return null;const s=t-e.videoRect.left-e.offsetX,l=o-e.videoRect.top-e.offsetY;if(s<0||l<0||s>e.actualWidth||l>e.actualHeight)return null;const c=s/e.actualWidth*n.screen.width,u=l/e.actualHeight*n.screen.height;return r.axElementAtPoint(n,c,u)},J=e=>{if(j)return;e.preventDefault(),e.stopPropagation();const t=Ee();if((X===!0||X==="hover-only")&&!("touches"in e))if(e.type==="mousemove"){if(Qe({x:e.clientX,y:e.clientY}),t){const n=Mt(t,e.clientX,e.clientY);ve(n?.id??null)}}else e.type==="mouseleave"&&(Qe(null),ve(null));if(X!==!0&&(!("touches"in e)&&t&&(e.type==="mousemove"?_t(t,e.clientX,e.clientY):e.type==="mouseleave"&&we(null)),!(!T.current?.getState().controlReady||!C.current||!t)))if("touches"in e){const n=e.touches,s=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 c=n[0],u=n[1],a=ge(t,c.clientX,c.clientY),m=ge(t,u.clientX,u.clientY);if(!a||!m)return;b.current?b.current.source==="real-touch"&&(b.current.finger0={x:a.videoX,y:a.videoY},b.current.finger1={x:m.videoX,y:m.videoY},pe("move",a.videoWidth,a.videoHeight,a.videoX,a.videoY,m.videoX,m.videoY,b.current.pointerId0,b.current.pointerId1)):(b.current={finger0:{x:a.videoX,y:a.videoY},finger1:{x:m.videoX,y:m.videoY},videoSize:{width:a.videoWidth,height:a.videoHeight},source:"real-touch",pointerId0:c.identifier,pointerId1:u.identifier},pe("down",a.videoWidth,a.videoHeight,a.videoX,a.videoY,m.videoX,m.videoY,c.identifier,u.identifier))}else if(n.length<2&&b.current?.source==="real-touch"){const c=b.current;pe("up",c.videoSize.width,c.videoSize.height,c.finger0.x,c.finger0.y,c.finger1.x,c.finger1.y,c.pointerId0,c.pointerId1),b.current=null;return}else{if(n.length>2)return;{const c=s[0];if(c){const u=ge(t,c.clientX,c.clientY);ce(c.identifier,l,u)}}}}else{let s=null;const l=b.current?.source==="alt-mouse";switch(e.type){case"mousedown":e.button===0&&(s="down");break;case"mousemove":(l||S.current.has(-1))&&(s="move");break;case"mouseup":e.button===0&&(s="up");break;case"mouseleave":(l||S.current.has(-1))&&(s="up");break}if(s){const c=ge(t,e.clientX,e.clientY);if(!c)return;r.debugLog("[rc-touch][mouse] event",{domType:e.type,eventType:s,button:e.button,buttons:e.buttons,client:{x:e.clientX,y:e.clientY},altHeldRef:te.current,inTwoFingerMode:l,geometry:{videoX:c.videoX,videoY:c.videoY,videoWidth:c.videoWidth,videoHeight:c.videoHeight},activePointerIds:Array.from(S.current.keys())}),te.current||l?Ct(s,c):ce(-1,s,c)}}},Ct=(e,t)=>{const{videoX:o,videoY:n,videoWidth:s,videoHeight:l}=t,c=s-o,u=l-n;if(e==="down"){b.current={finger0:{x:o,y:n},finger1:{x:c,y:u},videoSize:{width:s,height:l},source:"alt-mouse",pointerId0:be,pointerId1:_e},C.current?.focus(),pe("down",s,l,o,n,c,u,be,_e);return}if(e==="move"){b.current?.source==="alt-mouse"&&(b.current.finger0={x:o,y:n},b.current.finger1={x:c,y:u},pe("move",s,l,o,n,c,u,be,_e));return}if(e==="up"||e==="cancel"){const a=b.current;if(a?.source==="alt-mouse"){const{finger0:m,finger1:_,videoSize:N}=a;pe("up",N.width,N.height,m.x,m.y,_.x,_.y,be,_e),b.current=null}return}},St=150,rt=()=>{const e=le.current;e&&(window.clearTimeout(e.endTimer),ce(ie,"up",e.pos),le.current=null)},Dt=e=>{if(!T.current?.getState().controlReady||e.ctrlKey||te.current||b.current)return;const t=S.current.size;if(t>1||t===1&&!S.current.has(ie))return;const o=Ee();if(!o)return;const n=e.clientX-o.videoRect.left-o.offsetX,s=e.clientY-o.videoRect.top-o.offsetY;if(n<0||n>o.actualWidth||s<0||s>o.actualHeight)return;const l=ge(o,e.clientX,e.clientY);if(!l)return;e.preventDefault();const c=(e.deltaMode===1?16:e.deltaMode===2?o.actualWidth:1)*(o.videoWidth/o.actualWidth),u=(e.deltaMode===1?16:e.deltaMode===2?o.actualHeight:1)*(o.videoHeight/o.actualHeight),a=-e.deltaX*c,m=-e.deltaY*u,_=k=>{window.clearTimeout(k.endTimer),k.endTimer=window.setTimeout(rt,St)};if(a===0&&m===0){le.current&&_(le.current);return}const N=()=>({videoWidth:l.videoWidth,videoHeight:l.videoHeight,videoX:Math.abs(a)>Math.abs(m)?Math.min(Math.max(l.videoX,l.videoWidth*.2),l.videoWidth*.8):l.videoX,videoY:Math.abs(m)>=Math.abs(a)?Math.min(Math.max(l.videoY,l.videoHeight*.2),l.videoHeight*.8):l.videoY}),Y=k=>({...k,videoX:Math.min(Math.max(k.videoX+a,0),k.videoWidth),videoY:Math.min(Math.max(k.videoY+m,0),k.videoHeight)});let w=le.current;if(w)window.clearTimeout(w.endTimer);else{const k=N();ce(ie,"down",k),w={pos:k,endTimer:0},le.current=w}let D=w.pos,se=Y(D);se.videoX===D.videoX&&se.videoY===D.videoY&&(ce(ie,"up",D),D=N(),ce(ie,"down",D),se=Y(D)),ce(ie,"move",se),w.pos=se,_(w)};d.useEffect(()=>{me.current={handle:Dt,end:rt}}),d.useEffect(()=>{const e=Ne.current;if(!e)return;const t=o=>me.current.handle(o);return e.addEventListener("wheel",t,{passive:!1}),()=>{me.current.end(),e.removeEventListener("wheel",t)}},[]),d.useEffect(()=>{const e=n=>{n.key==="Alt"&&Le(!0)},t=n=>{n.key==="Alt"&&Le(!1)},o=()=>{Le(!1)};return window.addEventListener("keydown",e,!0),window.addEventListener("keyup",t,!0),window.addEventListener("blur",o),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("keyup",t,!0),window.removeEventListener("blur",o)}},[]);const Me=e=>{e.preventDefault(),e.stopPropagation();const t=document.activeElement===C.current||j&&document.activeElement===e.currentTarget;if(r.debugLog("Keyboard event:",{type:e.type,key:e.key,keyCode:e.keyCode,code:e.code,target:e.target.tagName,focused:t}),!t){r.debugWarn("Simulator input not focused, skipping keyboard event");return}if(!T.current?.getState().controlReady){r.debugWarn("Data channel not ready for keyboard event:",T.current?.getState().connection);return}if(e.type==="keydown"){if(e.key.toLowerCase()==="v"&&(e.metaKey||e.ctrlKey)){r.debugLog("Paste shortcut detected"),navigator.clipboard.readText().then(n=>{if(n){r.debugLog("Pasting text via SET_CLIPBOARD:",n.substring(0,20)+(n.length>20?"...":""));const s=r.createSetClipboardMessage(n,!0);U(s)}}).catch(n=>{console.error("Failed to read clipboard contents: ",n)});return}if(e.key.toLowerCase()==="m"&&(e.metaKey||e.ctrlKey)){r.debugLog("Menu shortcut detected");const n=r.createInjectKeycodeMessage(r.ANDROID_KEYS.ACTION_DOWN,r.ANDROID_KEYS.MENU,0,r.ANDROID_KEYS.META_NONE);U(n);const s=r.createInjectKeycodeMessage(r.ANDROID_KEYS.ACTION_UP,r.ANDROID_KEYS.MENU,0,r.ANDROID_KEYS.META_NONE);U(s);return}}const o=Gt(e);if(o){const{keycode:n,metaState:s}=o,l=e.type==="keydown"?r.ANDROID_KEYS.ACTION_DOWN:r.ANDROID_KEYS.ACTION_UP;r.debugLog(`Sending Keycode: key=${e.key}, code=${n}, action=${l}, meta=${s}`);const c=r.createInjectKeycodeMessage(l,n,0,s);U(c)}else r.debugLog(`Ignoring unhandled key event: type=${e.type}, key=${e.key}`)},xt=e=>{e.stopPropagation(),T.current?.reconnect()},L=d.useRef({onAxSnapshotChange:Q,onAxStatusChange:V,onCameraDemandChange:Te,onCameraStats:K,onMicrophoneStateChange:ae,onTrace:G,onTerminated:x,onConnectionStateChange:q,onPlaybackStats:I});L.current={onAxSnapshotChange:Q,onAxStatusChange:V,onCameraDemandChange:Te,onCameraStats:K,onMicrophoneStateChange:ae,onTrace:G,onTerminated:x,onConnectionStateChange:q,onPlaybackStats:I};const ke=!!G;d.useEffect(()=>{Se.current=null,$e(!1),ze(!1),Be({})},[i,v]),d.useEffect(()=>{let e=!0;oe.current!==null&&(oe.current=null,De(null),r.safeInvoke("onAxSnapshotChange",L.current.onAxSnapshotChange,null));const t=r.createDeviceStream({url:i,token:g,sessionId:Ot,watchOnly:ee,deviceModel:v,autoReconnect:y,jitterBufferTargetMs:M,openUrl:O,inspectMode:X,axPollIntervalMs:P,axMaxBackoffMs:E,androidElementTreeOptions:F,microphoneEnabled:Z,onStateChange:n=>{(n.videoReady||n.connection==="idle"||n.connection==="connecting"||n.connection==="reconnecting")&&ht(n.videoReady),gt(n.connection==="failed"),mt(n.connection==="terminated"),at(n.duo),lt(n.duoState),dt(n.duoError)},onAxSnapshotChange:n=>{e&&(De(s=>r.axSnapshotsEqual(s,n)?s:n),L.current.onAxSnapshotChange?.(n))},onAxStatusChange:(...n)=>L.current.onAxStatusChange?.(...n),onCameraDemandChange:(...n)=>L.current.onCameraDemandChange?.(...n),onCameraStats:K?(...n)=>L.current.onCameraStats?.(...n):void 0,onMicrophoneStateChange:(...n)=>L.current.onMicrophoneStateChange?.(...n),onTrace:ke?(...n)=>L.current.onTrace?.(...n):void 0,onTerminated:()=>L.current.onTerminated?.(),onConnectionStateChange:(...n)=>L.current.onConnectionStateChange?.(...n),onPlaybackStats:I?(...n)=>L.current.onPlaybackStats?.(...n):void 0});T.current=t;const o=C.current?t.attachVideo(C.current):void 0;return t.start(),()=>{e=!1,t.dispose(),o?.(),T.current=null}},[i,g,p,v,ke,ee]),d.useEffect(()=>{if(j&&Ae.current)return T.current?.attachVideo(Ae.current,"inner")},[j,i,g,p,v,ke,ee]),d.useEffect(()=>{T.current?.updateOptions({openUrl:O,axPollIntervalMs:P,axMaxBackoffMs:E,androidElementTreeOptions:F,autoReconnect:y,jitterBufferTargetMs:M,microphoneEnabled:Z,inspectMode:X,onPlaybackStats:I?(...e)=>L.current.onPlaybackStats?.(...e):void 0,onCameraStats:K?(...e)=>L.current.onCameraStats?.(...e):void 0})},[y,M,Z,X,!!I,!!K,O,P,E,F]);const We=()=>{if(!Ze.current)return;const e=Ee();if(!e){Ge(null);return}const t={left:e.videoRect.left-e.containerRect.left+e.offsetX,top:e.videoRect.top-e.containerRect.top+e.offsetY,width:e.actualWidth,height:e.actualHeight};Ge(o=>o&&o.left===t.left&&o.top===t.top&&o.width===t.width&&o.height===t.height?o:t)};d.useEffect(()=>{const e=C.current,t=je.current,o=Ne.current;if(!e)return;const n=u=>Be(a=>Jt(a,u)?a:u),s=()=>{const u=e.videoWidth>0&&e.videoHeight>0;u&&(Se.current={width:e.videoWidth,height:e.videoHeight});const a=Se.current,m=a?`${a.width} / ${a.height}`:void 0;if(!Ie||!t){n(!u&&a?{aspectRatio:m,contain:"size",containIntrinsicSize:`${a.width}px ${a.height}px`}:{}),We();return}const _=t.clientWidth,N=t.clientHeight;if(_===0||N===0)return;const Y=a?a.width>a.height:!1;$e(Y),ze(B==="android"&&!!a&&zt(a.width,a.height));const w=Y?he.videoPosition.landscape:he.videoPosition.portrait;let D={aspectRatio:m};w.heightMultiplier?(D.height=`${N*w.heightMultiplier}px`,D.width="auto"):w.widthMultiplier&&(D.width=`${_*w.widthMultiplier}px`,D.height="auto"),D.borderRadius=`${Y?N*he.videoBorderRadiusMultiplier:_*he.videoBorderRadiusMultiplier}px`,n(D),We()},l=new ResizeObserver(()=>{s()});t&&l.observe(t),l.observe(e),o&&l.observe(o),t&&t.addEventListener("load",s),e.addEventListener("loadedmetadata",s),e.addEventListener("resize",s);const c=()=>T.current?.bumpActivity();return e.addEventListener("resize",c),s(),()=>{l.disconnect(),e.removeEventListener("loadedmetadata",s),e.removeEventListener("resize",s),e.removeEventListener("resize",c),t&&t.removeEventListener("load",s)}},[he,Ie,i,v]),d.useEffect(()=>{re?We():(De(null),ve(null),Oe(null),Je(null),de(null),Re.current=null,z.current!==void 0&&(window.cancelAnimationFrame(z.current),z.current=void 0))},[re]),d.useEffect(()=>()=>{z.current!==void 0&&(window.cancelAnimationFrame(z.current),z.current=void 0)},[]),d.useEffect(()=>{if(!re)return;const e=t=>{t.key==="Escape"&&(Ye||xe)&&(Oe(null),ve(null),de(null),r.safeInvoke("onInspectSelectionChange",ue.current,null))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[re,Ye,xe]);const Yt=()=>{C.current&&C.current.focus()};d.useImperativeHandle(Xe,()=>({openUrl:e=>T.current?.openUrl(e),sendKeyEvent:e=>T.current?.sendKeyEvent(e),screenshot:e=>T.current?.screenshot(e)??Promise.reject(new Error("Simulator disconnected")),terminateApp:e=>T.current?.terminateApp(e)??Promise.reject(new Error("Simulator disconnected")),reconnect:()=>T.current?.reconnect(),refreshAxTree:()=>T.current?.refreshAxTree()??Promise.reject(new Error("Simulator disconnected")),getAxSnapshot:()=>T.current?.getAxSnapshot()??null,setInspectHighlight:e=>{ve(e?.id??null)},setInspectSelection:e=>{Oe(e?.id??null),de(e?Re.current:null);const t=oe.current;e&&t?r.safeInvoke("onInspectSelectionChange",ue.current,{element:e,snapshot:t}):r.safeInvoke("onInspectSelectionChange",ue.current,null)},getAxStatus:()=>T.current?.getAxStatus()??"idle"}));const Pt=yt&&ne!==null;return h.jsxs("div",{ref:Ne,className:["rc-container",f].filter(Boolean).join(" "),style:{touchAction:"none"},onMouseDown:J,onMouseMove:J,onMouseUp:J,onMouseLeave:J,onTouchStart:J,onTouchMove:J,onTouchEnd:J,onTouchCancel:J,children:[Pt&&ne&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"rc-touch-indicator",style:{left:`${ne.containerX}px`,top:`${ne.containerY}px`}}),h.jsx("div",{className:"rc-touch-indicator",style:{left:`${ne.mirrorContainerX}px`,top:`${ne.mirrorContainerY}px`}})]}),Ie&&h.jsx("img",{ref:je,src:et,alt:"",className:B==="ios"?"rc-phone-frame rc-phone-frame-ios":"rc-phone-frame",draggable:!1}),h.jsx("video",{ref:C,className:["rc-video",!Ie&&"rc-video-frameless",!ut&&"rc-video-loading"].filter(Boolean).join(" "),style:{...vt,...j?{opacity:0,width:1,height:1,pointerEvents:"none"}:{},...tt?{backgroundImage:`url("${tt}")`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:he.loadingLogoSize}:{}},autoPlay:!0,playsInline:!0,muted:!0,tabIndex:j?-1:0,onKeyDown:Me,onKeyUp:Me,onClick:Yt,onFocus:()=>{C.current&&(C.current.style.outline="none")},onBlur:()=>{C.current&&(C.current.style.outline="none")}}),j&&h.jsx("video",{ref:Ae,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",width:1,height:1,opacity:0,pointerEvents:"none"}}),j&&Ve&&h.jsx(d.Suspense,{fallback:h.jsx("div",{children:"Loading iPhone Duo…"}),children:h.jsx(Ft,{watchOnly:ee,showFrame:R,modelUrl:W,outer:C.current,inner:Ae.current,state:Ve,setAngle:e=>Pe("setHingeAngle",{angleDegrees:e}),setOrientation:e=>Pe("setDuoOrientation",{orientation:e}),button:(e,t)=>Pe("performActions",{actions:[{type:t?"buttonDown":"buttonUp",button:e}]}),touch:(e,t,o,n)=>{T.current?.sendDisplayTouch(e,t,o,n)},onKeyDown:Me,onKeyUp:Me})}),j&&Ke&&h.jsx("div",{role:"alert",className:"rc-duo-error",children:Ke}),!j&&re&&h.jsx(Ut,{snapshot:qe,geometry:Tt,highlightedId:xe,selectedId:Ye,mode:wt,cursorPosition:Nt,frozenCursorPosition:At,onSelectChange:(e,t)=>{Oe(e?.id??null),e&&t?de(t):e||de(null);const o=oe.current;e&&o?r.safeInvoke("onInspectSelectionChange",ue.current,{element:e,snapshot:o}):r.safeInvoke("onInspectSelectionChange",ue.current,null)},onTapElement:ee?void 0:((e,t)=>{if(t){ot(t.x,t.y);return}const o=oe.current;o&&Rt(e,o)})}),pt?h.jsxs("div",{className:"rc-terminated",role:"status",children:[h.jsx("div",{className:"rc-terminated-title",children:"Instance terminated"}),h.jsx("div",{className:"rc-terminated-message",children:"This instance no longer exists and can't be reconnected."})]}):ft&&h.jsx("button",{type:"button",className:"rc-retry-button",onClick:xt,children:"Retry"})]})});exports.RemoteControl=Qt;