@limrun/ui 0.20.8 → 0.21.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";require('./index.css');const f=require("react/jsx-runtime"),n=require("./core-C5BY3i_b.js"),l=require("react"),Bt=require("react-dom"),qt=async p=>{if(!p)return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(p),!0}catch{}try{const i=document.createElement("textarea");i.value=p,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}},Gt=l.memo(function({element:i,screen:g,highlighted:m,selected:I,selectable:K,onClick:M}){const y=n.clampAxFrameForScreen(i.frame,g);if(!y)return null;const j=n.axElementSummary(i);return f.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":m?"true":"false","data-selected":I?"true":"false","aria-label":j,onClick:E=>{K&&(E.preventDefault(),E.stopPropagation(),M(i,{x:E.clientX,y:E.clientY}))},style:{left:`${y.x/g.width*100}%`,top:`${y.y/g.height*100}%`,width:`${y.width/g.width*100}%`,height:`${y.height/g.height*100}%`}})},(p,i)=>p.highlighted===i.highlighted&&p.selected===i.selected&&p.selectable===i.selectable&&p.screen.width===i.screen.width&&p.screen.height===i.screen.height&&p.onClick===i.onClick&&n.axElementsEqual(p.element,i.element)),Jt=260,Qt=220,Zt=6,eo=8,to=l.memo(function({element:i,platform:g,anchor:m,cursorAnchored:I,showActions:K,onTap:M}){const[y,j]=l.useState(null);l.useEffect(()=>{if(!y)return;const O=window.setTimeout(()=>j(null),1100);return()=>window.clearTimeout(O)},[y]);const E=l.useMemo(()=>{const O=Jt,$=Qt,W=Zt,N=eo,B=typeof window<"u"?window.innerWidth:1024,Ie=typeof window<"u"?window.innerHeight:768,F=m.x+W+O<=B-N,J=m.y-W-$>=N;let oe=F?m.x+W:m.x-W,de=J?m.y-W:m.y+W;const Q=`translate(${F?"0":"-100%"}, ${J?"-100%":"0"})`;return oe=Math.max(N+(F?0:O),Math.min(B-N-(F?O:0),oe)),de=Math.max(N+(J?$:0),Math.min(Ie-N-(J?0:$),de)),{left:`${oe}px`,top:`${de}px`,transform:Q}},[m.x,m.y]),_=l.useMemo(()=>n.axElementSelectorExpression(i,g),[i,g]),R=g==="ios"?i.selectors.AXUniqueId:i.selectors.resourceId,Y=g==="ios"?"AXUniqueId":"resourceId",z=l.useCallback(async(O,$)=>{if(!O)return;await qt(O)&&j($)},[]),G=n.axElementRoleLabel(i),V=i.label||i.value||G,te=n.axElementSummary(i);return Bt.createPortal(f.jsxs("div",{className:"rc-inspect-card","data-cursor-anchored":I?"true":"false",style:E,onClick:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),onMouseMove:O=>O.stopPropagation(),children:[f.jsxs("div",{className:"rc-inspect-card-header",children:[f.jsx("span",{className:"rc-inspect-card-role",children:G}),!i.enabled&&f.jsx("span",{className:"rc-inspect-card-tag",children:"disabled"}),i.focused&&f.jsx("span",{className:"rc-inspect-card-tag rc-inspect-card-tag-blue",children:"focused"})]}),f.jsx("p",{className:"rc-inspect-card-title",title:te,children:V}),R&&f.jsxs("div",{className:"rc-inspect-card-row",children:[f.jsxs("span",{className:"rc-inspect-card-row-label",children:[Y,":"]}),f.jsx("span",{className:"rc-inspect-card-row-value",children:R})]}),i.value&&i.value!==i.label&&f.jsxs("div",{className:"rc-inspect-card-row",children:[f.jsx("span",{className:"rc-inspect-card-row-label",children:"value:"}),f.jsx("span",{className:"rc-inspect-card-row-value",children:i.value})]}),f.jsxs("div",{className:"rc-inspect-card-row",children:[f.jsx("span",{className:"rc-inspect-card-row-label",children:"frame:"}),f.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)]})]}),K&&f.jsxs("div",{className:"rc-inspect-card-actions",children:[f.jsx("button",{type:"button",className:"rc-inspect-card-btn rc-inspect-card-btn-primary",disabled:!M,onClick:()=>M?.(i,m),children:"Tap"}),f.jsx("button",{type:"button",className:y==="selector"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!_,title:_??"No usable selector for this element",onClick:()=>z(_??void 0,"selector"),children:y==="selector"?"Copied!":"Copy selector"}),f.jsx("button",{type:"button",className:y==="id"?"rc-inspect-card-btn rc-inspect-card-btn-copied":"rc-inspect-card-btn",disabled:!R,title:R??`No ${Y}`,onClick:()=>z(R,"id"),children:y==="id"?"Copied!":`Copy ${Y}`})]})]}),document.body)}),oo=l.memo(function({snapshot:i,geometry:g,highlightedId:m,selectedId:I,mode:K,cursorPosition:M,frozenCursorPosition:y,onSelectChange:j,onTapElement:E}){const _=K==="select",R=_?m!==null&&m!==I:m!==null,Y=_?m??I:m,z=l.useMemo(()=>{const N=new Map;if(!i)return N;for(const B of i.elements)N.set(B.id,B);return N},[i]),G=l.useMemo(()=>Y?z.get(Y)??null:null,[Y,z]);if(!(!!i&&!!g&&i.screen.width>0&&i.screen.height>0&&i.elements.length>0))return null;const te=R?M:y??M,O=R,$=_&&!R&&I!==null,W=N=>{_&&N.target===N.currentTarget&&j(null,null)};return f.jsxs(f.Fragment,{children:[f.jsx("div",{className:_?"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:W,children:i.elements.map(N=>f.jsx(Gt,{element:N,screen:i.screen,highlighted:N.id===m,selected:N.id===I,selectable:_,onClick:j},N.id))}),G&&te&&f.jsx(to,{element:G,platform:i.platform,anchor:te,cursorAnchored:O,showActions:$,onTap:E})]})});function no(p,i){if(!i.startsWith("lim_st_"))return!1;try{const g=new URL(p).pathname.split("/").map(decodeURIComponent).find(E=>/^(ios|android)_[a-z0-9_]+$/.test(E));if(!g)return!1;const m=g.split("_")[0],I=i.slice(7).split(".");if(I.length!==3||I.some(E=>!E))return!1;const K=atob(I[1].replace(/-/g,"+").replace(/_/g,"/")),M=JSON.parse(new TextDecoder().decode(Uint8Array.from(K,E=>E.charCodeAt(0))));if(!M||typeof M!="object"||!("scopes"in M))return!1;const y=M.scopes;if(!Array.isArray(y)||!y.every(E=>typeof E=="string"))return!1;let j=!1;for(const E of y){const[_,R,Y,z]=E.split(":");if(!(z!==void 0||_!==m&&_!=="*")&&!(R!==g&&R!=="*")){if(Y==="stream"||Y==="all")return!1;Y==="watch"&&(j=!0)}}return j}catch{return!1}}const ro=l.lazy(()=>Promise.resolve().then(()=>require("./duo-view-BJaUyddX.js")).then(p=>p.duoView)),ke=p=>Object.entries(n.AMOTION_EVENT).find(([g,m])=>g.startsWith("ACTION_")&&m===p)?.[0]??String(p),mt=1920,yt=1200,io=(p,i)=>p===mt&&i===yt||p===yt&&i===mt,co={ios:{videoBorderRadiusMultiplier:.15,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:.9678},landscape:{widthMultiplier:.9678}}},android:{videoBorderRadiusMultiplier:.13,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:.967},landscape:{widthMultiplier:.962}}},macos:{videoBorderRadiusMultiplier:0,loadingLogoSize:"10%",videoPosition:{portrait:{heightMultiplier:1},landscape:{widthMultiplier:1}}}},so={"iphone-se":{videoBorderRadiusMultiplier:0,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:667/889},landscape:{widthMultiplier:667/889}},homeButton:{offset:389/889,diameter:64/889}},"iphone-17e":{videoBorderRadiusMultiplier:47.33/452,loadingLogoSize:"20%",videoPosition:{portrait:{heightMultiplier:844/888},landscape:{widthMultiplier:844/888}}}},ao={videoBorderRadiusMultiplier:32/1837,loadingLogoSize:"40%",videoPosition:{portrait:{heightMultiplier:2560/2798},landscape:{widthMultiplier:2560/2798}}};function lo(p){const i=p.code,g=n.codeMap[i];if(!g)return n.debugWarn(`Unknown event.code: ${i}, key: ${p.key}`),null;let m=n.ANDROID_KEYS.META_NONE;const I=i>="KeyA"&&i<="KeyZ",K=p.getModifierState("CapsLock"),M=p.shiftKey;let y=M;return I&&(y=M!==K),y&&(m|=n.ANDROID_KEYS.META_SHIFT_ON),p.ctrlKey&&(m|=n.ANDROID_KEYS.META_CTRL_ON),p.altKey&&(m|=n.ANDROID_KEYS.META_ALT_ON),p.metaKey&&(m|=n.ANDROID_KEYS.META_META_ON),{keycode:g,metaState:m}}function vt(p,i){const g=Object.keys(p);return g.length===Object.keys(i).length&&g.every(m=>p[m]===i[m])}const uo=l.forwardRef(({className:p,url:i,token:g,sessionId:m,openUrl:I,watchOnly:K=!1,showFrame:M=!0,deviceModel:y,duoModelUrl:j,autoReconnect:E,jitterBufferTargetMs:_,onPlaybackStats:R,onTerminated:Y,assets:z,onConnectionStateChange:G,inspectMode:V,onAxSnapshotChange:te,onInspectSelectionChange:O,onAxStatusChange:$,axPollIntervalMs:W,axMaxBackoffMs:N,androidElementTreeOptions:B,onCameraDemandChange:Ie,onCameraStats:F,onTrace:J,microphoneEnabled:oe=!1,onMicrophoneStateChange:de},ze)=>{const Be=l.useMemo(()=>no(i,g),[i,g]),Q=K||Be,Me=l.useRef(null),C=l.useRef(null),qe=l.useRef(null),[Tt,Et]=l.useState(!1),U=y==="iphone-duo"||Tt,Re=y==="iphone-duo"?y:void 0,be=l.useRef(null),[Ge,Nt]=l.useState(null),[Je,At]=l.useState(),[wt,Ot]=l.useState(!1),[It,Mt]=l.useState(!1),[Rt,bt]=l.useState(!1),[We,Qe]=l.useState(!1),[Ze,et]=l.useState(!1),[_t,tt]=l.useState({}),[ot,nt]=l.useState(null),Xe=l.useRef(null),D=l.useRef(new Map),ne=l.useRef(!1),[Ct,St]=l.useState(!1),b=l.useRef(null),ue=l.useRef(null),Te=l.useRef({handle:()=>{},end:()=>{}}),[re,_e]=l.useState(null),[rt,He]=l.useState(null),[je,Ee]=l.useState(null),[Ve,Ce]=l.useState(null),[Dt,it]=l.useState(null),[xt,ct]=l.useState(null),Se=l.useRef(null),q=l.useRef(void 0),st=e=>{Se.current=e,q.current===void 0&&(q.current=window.requestAnimationFrame(()=>{q.current=void 0,ct(Se.current)}))},[Pt,he]=l.useState(null),ie=l.useRef(null);ie.current=rt;const fe=l.useRef(O);fe.current=O;const ce=V===!0||V==="hover-only",at=l.useRef(ce);at.current=ce;const Yt=V==="hover-only"?"hover-only":"select",x=l.useMemo(()=>n.detectPlatform(i),[i]),Lt=l.useMemo(()=>m||Array.from(crypto.getRandomValues(new Uint32Array(4)),e=>e.toString(36)).join(""),[m]),Ne=x==="ios"&&y&&y!=="iphone-duo"?y:void 0,se=x==="android"&&Ze?ao:Ne?so[Ne]:co[x],pe=z?.[x],lt=Ne&&pe?.modelFrames?.[Ne],dt=x==="android"&&Ze?We?pe?.tabletFrameLandscape:pe?.tabletFrame:Ne?We?lt?.frameLandscape:lt?.frame:We?pe?.frameLandscape:pe?.frame,ut=pe?.loadingLogo,Ae=!U&&M&&!!dt,T=l.useRef(null),X=e=>T.current?.sendControl(e),De=l.useRef(new Set),xe=l.useCallback(()=>{for(const e of De.current)T.current?.sendControl(n.createMacKeyMessage(n.MAC_INPUT_ACTION.UP,e));De.current.clear()},[]),Ke=(e,o)=>T.current?.sendDuoControl(e,o)??Promise.reject(new Error("Simulator disconnected")),ht=-10,ft=(e,o)=>{const r=me();if(!r)return;const t=Z(r,e,o);if(!t)return;const{videoX:a,videoY:c,videoWidth:s,videoHeight:u}=t,d=n.createTouchControlMessage(n.AMOTION_EVENT.ACTION_DOWN,ht,s,u,a,c,1,n.AMOTION_EVENT.BUTTON_PRIMARY,n.AMOTION_EVENT.BUTTON_PRIMARY);d&&X(d),window.setTimeout(()=>{const h=n.createTouchControlMessage(n.AMOTION_EVENT.ACTION_UP,ht,s,u,a,c,0,n.AMOTION_EVENT.BUTTON_PRIMARY,n.AMOTION_EVENT.BUTTON_PRIMARY);h&&X(h)},60)},kt=(e,o)=>{const r=me();if(!r||o.screen.width<=0||o.screen.height<=0)return;const t=e.frame.x+e.frame.width/2,a=e.frame.y+e.frame.height/2,c=t/o.screen.width*r.actualWidth,s=a/o.screen.height*r.actualHeight,u=r.videoRect.left+r.offsetX+c,d=r.videoRect.top+r.offsetY+s;ft(u,d)},Pe=-1,Ye=-2,ae=-3,ge=(e,o,r,t,a,c)=>{const s=n.createTouchControlMessage(e,o,r,t,a,c,1,n.AMOTION_EVENT.BUTTON_PRIMARY,n.AMOTION_EVENT.BUTTON_PRIMARY);s&&(n.debugLog("[rc-touch] sendSingleTouch",{action:e,actionName:ke(e),pointerId:o,x:a,y:c,video:{width:r,height:t}}),X(s))},le=(e,o,r)=>{if(!r)return;const{videoX:t,videoY:a,videoWidth:c,videoHeight:s}=r;let u=null,d=null,h=1;const S=n.AMOTION_EVENT.BUTTON_PRIMARY;switch(o){case"down":e!==ae&&Te.current.end(),u=D.current.size===0?n.AMOTION_EVENT.ACTION_DOWN:n.AMOTION_EVENT.ACTION_POINTER_DOWN,d={x:t,y:a},D.current.set(e,d),e===-1&&C.current?.focus();break;case"move":D.current.has(e)&&(u=n.AMOTION_EVENT.ACTION_MOVE,d={x:t,y:a},D.current.set(e,d));break;case"up":case"cancel":D.current.has(e)&&(d=D.current.get(e),D.current.delete(e),o==="cancel"?u=n.AMOTION_EVENT.ACTION_CANCEL:u=D.current.size===0?n.AMOTION_EVENT.ACTION_UP:n.AMOTION_EVENT.ACTION_POINTER_UP);break}if(u!==null&&d!==null){n.debugLog("[rc-touch][mouse->touch] sending",{pointerId:e,eventType:o,action:u,actionName:ke(u),positionToSend:d,video:{width:c,height:s},altHeld:ne.current,activePointersAfter:Array.from(D.current.entries()).map(([P,w])=>({id:P,x:w.x,y:w.y}))});const A=n.createTouchControlMessage(u,e,c,s,d.x,d.y,h,S,S);A&&(n.debugLog("[rc-touch][mouse->touch] buffer",{pointerId:e,actionName:ke(u),byteLength:A.byteLength}),X(A))}else(o==="up"||o==="cancel")&&D.current.delete(e)},Ue=e=>{if(ne.current!==e&&(ne.current=e,St(e),e||_e(null),n.debugLog("[rc-touch][alt] updateAltHeld",{nextHeld:e,activePointerIds:Array.from(D.current.keys())}),x==="ios"&&T.current?.getState().controlReady)){const o=e?n.ANDROID_KEYS.ACTION_DOWN:n.ANDROID_KEYS.ACTION_UP,r=n.createInjectKeycodeMessage(o,n.ANDROID_KEYS.KEYCODE_ALT_LEFT,0,n.ANDROID_KEYS.META_NONE);n.debugLog("[rc-touch][alt] sending Indigo modifier keycode",{action:o,keycode:n.ANDROID_KEYS.KEYCODE_ALT_LEFT}),r&&X(r)}},me=()=>{const e=C.current,o=Me.current;if(!e||!o)return null;const r=e.videoWidth,t=e.videoHeight;if(!r||!t)return null;const a=e.getBoundingClientRect(),c=o.getBoundingClientRect(),s=a.width,u=a.height,d=r/t,h=s/u;let S=s,A=u;d>h?A=s/d:S=u*d;const P=(s-S)/2,w=(u-A)/2;return{videoWidth:r,videoHeight:t,videoRect:a,containerRect:c,actualWidth:S,actualHeight:A,offsetX:P,offsetY:w}},Z=(e,o,r)=>{const t=o-e.videoRect.left-e.offsetX,a=r-e.videoRect.top-e.offsetY,c=Math.max(0,Math.min(e.actualWidth,t)),s=Math.max(0,Math.min(e.actualHeight,a)),u=Math.max(0,Math.min(e.videoWidth,c/e.actualWidth*e.videoWidth)),d=Math.max(0,Math.min(e.videoHeight,s/e.actualHeight*e.videoHeight));return{videoX:u,videoY:d,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},Wt=(e,o,r)=>{const t=o-e.videoRect.left-e.offsetX,a=r-e.videoRect.top-e.offsetY,c=Math.max(0,Math.min(e.actualWidth,t)),s=Math.max(0,Math.min(e.actualHeight,a)),u=Math.max(0,Math.min(e.videoWidth,c/e.actualWidth*e.videoWidth)),d=Math.max(0,Math.min(e.videoHeight,s/e.actualHeight*e.videoHeight)),h=e.videoWidth-u,S=e.videoHeight-d,A=e.videoRect.left+e.offsetX,P=e.videoRect.top+e.offsetY,w=A-e.containerRect.left+c,L=P-e.containerRect.top+s,k=A-e.containerRect.left+(e.actualWidth-c),v=P-e.containerRect.top+(e.actualHeight-s);return{containerX:w,containerY:L,mirrorContainerX:k,mirrorContainerY:v,videoX:u,videoY:d,mirrorVideoX:h,mirrorVideoY:S,videoWidth:e.videoWidth,videoHeight:e.videoHeight}},Xt=(e,o,r,t,a,c,s)=>{const u=n.createTwoFingerTouchControlMessage(e,o,r,t,a,c,s);n.debugLog("[rc-touch2] sendTwoFingerMessage (iOS)",{actionName:ke(e),video:{width:o,height:r},p0:{x:t,y:a},p1:{x:c,y:s},byteLength:u.byteLength}),X(u)},ye=(e,o,r,t,a,c,s,u,d)=>{if(n.debugLog("[rc-touch2] applyTwoFingerEvent",{platform:x,eventType:e,video:{width:o,height:r},p0:{x:t,y:a,id:u},p1:{x:c,y:s,id:d}}),e==="down"&&Te.current.end(),x==="ios"){const h=e==="down"?n.AMOTION_EVENT.ACTION_DOWN:e==="move"?n.AMOTION_EVENT.ACTION_MOVE:n.AMOTION_EVENT.ACTION_UP;Xt(h,o,r,t,a,c,s)}else e==="down"?(ge(n.AMOTION_EVENT.ACTION_DOWN,u,o,r,t,a),ge(n.AMOTION_EVENT.ACTION_POINTER_DOWN,d,o,r,c,s)):e==="move"?(ge(n.AMOTION_EVENT.ACTION_MOVE,u,o,r,t,a),ge(n.AMOTION_EVENT.ACTION_MOVE,d,o,r,c,s)):(ge(n.AMOTION_EVENT.ACTION_POINTER_UP,d,o,r,c,s),ge(n.AMOTION_EVENT.ACTION_UP,u,o,r,t,a))},Ht=(e,o,r)=>{if(!ne.current){re!==null&&_e(null);return}const t=Wt(e,o,r);_e(t)},jt=(e,o,r)=>{const t=ie.current;if(!t||t.screen.width<=0||t.screen.height<=0)return null;const a=o-e.videoRect.left-e.offsetX,c=r-e.videoRect.top-e.offsetY;if(a<0||c<0||a>e.actualWidth||c>e.actualHeight)return null;const s=a/e.actualWidth*t.screen.width,u=c/e.actualHeight*t.screen.height;return n.axElementAtPoint(t,s,u)},ee=e=>{if(U)return;e.preventDefault(),e.stopPropagation();const o=me();if((V===!0||V==="hover-only")&&!("touches"in e))if(e.type==="mousemove"){if(st({x:e.clientX,y:e.clientY}),o){const t=jt(o,e.clientX,e.clientY);Ee(t?.id??null)}}else e.type==="mouseleave"&&(st(null),Ee(null));if(V!==!0){if(x==="macos"){if("touches"in e||!o||!T.current?.getState().controlReady)return;const t=Z(o,e.clientX,e.clientY);if(!t)return;const a=e.type==="mousedown"?n.MAC_INPUT_ACTION.DOWN:e.type==="mouseup"?n.MAC_INPUT_ACTION.UP:n.MAC_INPUT_ACTION.MOVE,c=e.type==="mouseleave"?0:e.buttons;e.type==="mousedown"&&C.current?.focus(),X(n.createMouseControlMessage(a,t.videoWidth,t.videoHeight,t.videoX,t.videoY,c));return}if(!("touches"in e)&&o&&(e.type==="mousemove"?Ht(o,e.clientX,e.clientY):e.type==="mouseleave"&&_e(null)),!(!T.current?.getState().controlReady||!C.current||!o))if("touches"in e){const t=e.touches,a=e.changedTouches;let c;switch(e.type){case"touchstart":c="down";break;case"touchmove":c="move";break;case"touchend":c="up";break;case"touchcancel":c="cancel";break;default:return}if(t.length===2){const s=t[0],u=t[1],d=Z(o,s.clientX,s.clientY),h=Z(o,u.clientX,u.clientY);if(!d||!h)return;b.current?b.current.source==="real-touch"&&(b.current.finger0={x:d.videoX,y:d.videoY},b.current.finger1={x:h.videoX,y:h.videoY},ye("move",d.videoWidth,d.videoHeight,d.videoX,d.videoY,h.videoX,h.videoY,b.current.pointerId0,b.current.pointerId1)):(b.current={finger0:{x:d.videoX,y:d.videoY},finger1:{x:h.videoX,y:h.videoY},videoSize:{width:d.videoWidth,height:d.videoHeight},source:"real-touch",pointerId0:s.identifier,pointerId1:u.identifier},ye("down",d.videoWidth,d.videoHeight,d.videoX,d.videoY,h.videoX,h.videoY,s.identifier,u.identifier))}else if(t.length<2&&b.current?.source==="real-touch"){const s=b.current;ye("up",s.videoSize.width,s.videoSize.height,s.finger0.x,s.finger0.y,s.finger1.x,s.finger1.y,s.pointerId0,s.pointerId1),b.current=null;return}else{if(t.length>2)return;{const s=a[0];if(s){const u=Z(o,s.clientX,s.clientY);le(s.identifier,c,u)}}}}else{let a=null;const c=b.current?.source==="alt-mouse";switch(e.type){case"mousedown":e.button===0&&(a="down");break;case"mousemove":(c||D.current.has(-1))&&(a="move");break;case"mouseup":e.button===0&&(a="up");break;case"mouseleave":(c||D.current.has(-1))&&(a="up");break}if(a){const s=Z(o,e.clientX,e.clientY);if(!s)return;n.debugLog("[rc-touch][mouse] event",{domType:e.type,eventType:a,button:e.button,buttons:e.buttons,client:{x:e.clientX,y:e.clientY},altHeldRef:ne.current,inTwoFingerMode:c,geometry:{videoX:s.videoX,videoY:s.videoY,videoWidth:s.videoWidth,videoHeight:s.videoHeight},activePointerIds:Array.from(D.current.keys())}),ne.current||c?Vt(a,s):le(-1,a,s)}}}},Vt=(e,o)=>{const{videoX:r,videoY:t,videoWidth:a,videoHeight:c}=o,s=a-r,u=c-t;if(e==="down"){b.current={finger0:{x:r,y:t},finger1:{x:s,y:u},videoSize:{width:a,height:c},source:"alt-mouse",pointerId0:Pe,pointerId1:Ye},C.current?.focus(),ye("down",a,c,r,t,s,u,Pe,Ye);return}if(e==="move"){b.current?.source==="alt-mouse"&&(b.current.finger0={x:r,y:t},b.current.finger1={x:s,y:u},ye("move",a,c,r,t,s,u,Pe,Ye));return}if(e==="up"||e==="cancel"){const d=b.current;if(d?.source==="alt-mouse"){const{finger0:h,finger1:S,videoSize:A}=d;ye("up",A.width,A.height,h.x,h.y,S.x,S.y,Pe,Ye),b.current=null}return}},Kt=150,pt=()=>{const e=ue.current;e&&(window.clearTimeout(e.endTimer),le(ae,"up",e.pos),ue.current=null)},Ut=e=>{if(!T.current?.getState().controlReady||e.ctrlKey)return;if(x==="macos"){const v=me();if(!v)return;const ve=e.clientX-v.videoRect.left-v.offsetX,we=e.clientY-v.videoRect.top-v.offsetY;if(ve<0||ve>v.actualWidth||we<0||we>v.actualHeight)return;const Oe=Z(v,e.clientX,e.clientY);if(!Oe)return;e.preventDefault();const gt=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:e.deltaMode===WheelEvent.DOM_DELTA_PAGE?v.actualHeight:1;X(n.createMacScrollMessage(Oe.videoWidth,Oe.videoHeight,Oe.videoX,Oe.videoY,e.deltaX*gt,e.deltaY*gt));return}if(ne.current||b.current)return;const o=D.current.size;if(o>1||o===1&&!D.current.has(ae))return;const r=me();if(!r)return;const t=e.clientX-r.videoRect.left-r.offsetX,a=e.clientY-r.videoRect.top-r.offsetY;if(t<0||t>r.actualWidth||a<0||a>r.actualHeight)return;const c=Z(r,e.clientX,e.clientY);if(!c)return;e.preventDefault();const s=(e.deltaMode===1?16:e.deltaMode===2?r.actualWidth:1)*(r.videoWidth/r.actualWidth),u=(e.deltaMode===1?16:e.deltaMode===2?r.actualHeight:1)*(r.videoHeight/r.actualHeight),d=-e.deltaX*s,h=-e.deltaY*u,S=v=>{window.clearTimeout(v.endTimer),v.endTimer=window.setTimeout(pt,Kt)};if(d===0&&h===0){ue.current&&S(ue.current);return}const A=()=>({videoWidth:c.videoWidth,videoHeight:c.videoHeight,videoX:Math.abs(d)>Math.abs(h)?Math.min(Math.max(c.videoX,c.videoWidth*.2),c.videoWidth*.8):c.videoX,videoY:Math.abs(h)>=Math.abs(d)?Math.min(Math.max(c.videoY,c.videoHeight*.2),c.videoHeight*.8):c.videoY}),P=v=>({...v,videoX:Math.min(Math.max(v.videoX+d,0),v.videoWidth),videoY:Math.min(Math.max(v.videoY+h,0),v.videoHeight)});let w=ue.current;if(w)window.clearTimeout(w.endTimer);else{const v=A();le(ae,"down",v),w={pos:v,endTimer:0},ue.current=w}let L=w.pos,k=P(L);k.videoX===L.videoX&&k.videoY===L.videoY&&(le(ae,"up",L),L=A(),le(ae,"down",L),k=P(L)),le(ae,"move",k),w.pos=k,S(w)};l.useEffect(()=>{Te.current={handle:Ut,end:pt}}),l.useEffect(()=>{const e=Me.current;if(!e)return;const o=r=>Te.current.handle(r);return e.addEventListener("wheel",o,{passive:!1}),()=>{Te.current.end(),e.removeEventListener("wheel",o)}},[]),l.useEffect(()=>{const e=a=>{a.key==="Alt"&&Ue(!0)},o=a=>{a.key==="Alt"&&Ue(!1)},r=()=>{Ue(!1),xe()},t=()=>{document.hidden&&xe()};return window.addEventListener("keydown",e,!0),window.addEventListener("keyup",o,!0),window.addEventListener("blur",r),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("keyup",o,!0),window.removeEventListener("blur",r),document.removeEventListener("visibilitychange",t)}},[xe]);const Le=e=>{e.preventDefault(),e.stopPropagation();const o=document.activeElement===C.current||U&&document.activeElement===e.currentTarget;if(n.debugLog("Keyboard event:",{type:e.type,key:e.key,keyCode:e.keyCode,code:e.code,target:e.target.tagName,focused:o}),!o){n.debugWarn("Simulator input not focused, skipping keyboard event");return}if(!T.current?.getState().controlReady){n.debugWarn("Data channel not ready for keyboard event:",T.current?.getState().connection);return}if(x==="macos"){if(e.type==="keydown"&&e.repeat)return;const t=n.macKeyCodeFor(e.code);if(t===void 0){n.debugLog(`Ignoring unmapped key for macOS: code=${e.code}`);return}e.type==="keydown"?De.current.add(t):De.current.delete(t),X(n.createMacKeyMessage(e.type==="keydown"?n.MAC_INPUT_ACTION.DOWN:n.MAC_INPUT_ACTION.UP,t));return}if(e.type==="keydown"){if(e.key.toLowerCase()==="v"&&(e.metaKey||e.ctrlKey)){n.debugLog("Paste shortcut detected"),navigator.clipboard.readText().then(t=>{if(t){n.debugLog("Pasting text via SET_CLIPBOARD:",t.substring(0,20)+(t.length>20?"...":""));const a=n.createSetClipboardMessage(t,!0);X(a)}}).catch(t=>{console.error("Failed to read clipboard contents: ",t)});return}if(e.key.toLowerCase()==="m"&&(e.metaKey||e.ctrlKey)){n.debugLog("Menu shortcut detected");const t=n.createInjectKeycodeMessage(n.ANDROID_KEYS.ACTION_DOWN,n.ANDROID_KEYS.MENU,0,n.ANDROID_KEYS.META_NONE);X(t);const a=n.createInjectKeycodeMessage(n.ANDROID_KEYS.ACTION_UP,n.ANDROID_KEYS.MENU,0,n.ANDROID_KEYS.META_NONE);X(a);return}}const r=lo(e);if(r){const{keycode:t,metaState:a}=r,c=e.type==="keydown"?n.ANDROID_KEYS.ACTION_DOWN:n.ANDROID_KEYS.ACTION_UP;n.debugLog(`Sending Keycode: key=${e.key}, code=${t}, action=${c}, meta=${a}`);const s=n.createInjectKeycodeMessage(c,t,0,a);X(s)}else n.debugLog(`Ignoring unhandled key event: type=${e.type}, key=${e.key}`)},$t=e=>{e.stopPropagation(),T.current?.reconnect()},H=l.useRef({onAxSnapshotChange:te,onAxStatusChange:$,onCameraDemandChange:Ie,onCameraStats:F,onMicrophoneStateChange:de,onTrace:J,onTerminated:Y,onConnectionStateChange:G,onPlaybackStats:R});H.current={onAxSnapshotChange:te,onAxStatusChange:$,onCameraDemandChange:Ie,onCameraStats:F,onMicrophoneStateChange:de,onTrace:J,onTerminated:Y,onConnectionStateChange:G,onPlaybackStats:R};const $e=!!J;l.useEffect(()=>{Xe.current=null,Qe(!1),et(!1),tt({}),nt(null)},[i,Re]),l.useEffect(()=>{let e=!0;ie.current!==null&&(ie.current=null,He(null),n.safeInvoke("onAxSnapshotChange",H.current.onAxSnapshotChange,null));const o=n.createDeviceStream({url:i,token:g,sessionId:Lt,watchOnly:Q,deviceModel:Re,autoReconnect:E,jitterBufferTargetMs:_,openUrl:I,inspectMode:V,axPollIntervalMs:W,axMaxBackoffMs:N,androidElementTreeOptions:B,microphoneEnabled:oe,onStateChange:t=>{(t.videoReady||t.connection==="idle"||t.connection==="connecting"||t.connection==="reconnecting")&&Ot(t.videoReady),Mt(t.connection==="failed"),bt(t.connection==="terminated"),Et(t.duo),Nt(t.duoState),At(t.duoError)},onAxSnapshotChange:t=>{e&&(He(a=>n.axSnapshotsEqual(a,t)?a:t),H.current.onAxSnapshotChange?.(t))},onAxStatusChange:(...t)=>H.current.onAxStatusChange?.(...t),onCameraDemandChange:(...t)=>H.current.onCameraDemandChange?.(...t),onCameraStats:F?(...t)=>H.current.onCameraStats?.(...t):void 0,onMicrophoneStateChange:(...t)=>H.current.onMicrophoneStateChange?.(...t),onTrace:$e?(...t)=>H.current.onTrace?.(...t):void 0,onTerminated:()=>H.current.onTerminated?.(),onConnectionStateChange:(...t)=>H.current.onConnectionStateChange?.(...t),onPlaybackStats:R?(...t)=>H.current.onPlaybackStats?.(...t):void 0});T.current=o;const r=C.current?o.attachVideo(C.current):void 0;return o.start(),()=>{e=!1,o.dispose(),r?.(),T.current=null}},[i,m,Re,$e,Q]),l.useEffect(()=>{if(U&&be.current)return T.current?.attachVideo(be.current,"inner")},[U,i,m,Re,$e,Q]),l.useEffect(()=>{T.current?.updateOptions({token:g,openUrl:I,axPollIntervalMs:W,axMaxBackoffMs:N,androidElementTreeOptions:B,autoReconnect:E,jitterBufferTargetMs:_,microphoneEnabled:oe,inspectMode:V,onPlaybackStats:R?(...e)=>H.current.onPlaybackStats?.(...e):void 0,onCameraStats:F?(...e)=>H.current.onCameraStats?.(...e):void 0})},[g,E,_,oe,V,!!R,!!F,I,W,N,B]);const Fe=()=>{if(!at.current)return;const e=me();if(!e){it(null);return}const o={left:e.videoRect.left-e.containerRect.left+e.offsetX,top:e.videoRect.top-e.containerRect.top+e.offsetY,width:e.actualWidth,height:e.actualHeight};it(r=>r&&r.left===o.left&&r.top===o.top&&r.width===o.width&&r.height===o.height?r:o)};l.useEffect(()=>{const e=C.current,o=qe.current,r=Me.current;if(!e)return;const t=d=>tt(h=>vt(h,d)?h:d),a=d=>nt(h=>h&&d&&vt(h,d)?h:d),c=()=>{const d=e.videoWidth>0&&e.videoHeight>0;d&&(Xe.current={width:e.videoWidth,height:e.videoHeight});const h=Xe.current,S=h?`${h.width} / ${h.height}`:void 0;if(!Ae||!o){t(!d&&h?{aspectRatio:S,contain:"size",containIntrinsicSize:`${h.width}px ${h.height}px`}:{}),a(null),Fe();return}const A=o.clientWidth,P=o.clientHeight;if(A===0||P===0)return;const w=h?h.width>h.height:!1;Qe(w),et(x==="android"&&!!h&&io(h.width,h.height));const L=w?se.videoPosition.landscape:se.videoPosition.portrait;let k={aspectRatio:S};L.heightMultiplier?(k.height=`${P*L.heightMultiplier}px`,k.width="auto"):L.widthMultiplier&&(k.width=`${A*L.widthMultiplier}px`,k.height="auto"),k.borderRadius=`${w?P*se.videoBorderRadiusMultiplier:A*se.videoBorderRadiusMultiplier}px`,t(k);const v=se.homeButton,ve=w?A:P,we=`calc(50% + ${ve*(v?.offset??0)}px)`;a(v?{width:`${ve*v.diameter}px`,height:`${ve*v.diameter}px`,left:w?we:"50%",top:w?"50%":we}:null),Fe()},s=new ResizeObserver(()=>{c()});o&&s.observe(o),s.observe(e),r&&s.observe(r),o&&o.addEventListener("load",c),e.addEventListener("loadedmetadata",c),e.addEventListener("resize",c);const u=()=>T.current?.bumpActivity();return e.addEventListener("resize",u),c(),()=>{s.disconnect(),e.removeEventListener("loadedmetadata",c),e.removeEventListener("resize",c),e.removeEventListener("resize",u),o&&o.removeEventListener("load",c)}},[se,Ae,i,y]),l.useEffect(()=>{ce?Fe():(He(null),Ee(null),Ce(null),ct(null),he(null),Se.current=null,q.current!==void 0&&(window.cancelAnimationFrame(q.current),q.current=void 0))},[ce]),l.useEffect(()=>()=>{q.current!==void 0&&(window.cancelAnimationFrame(q.current),q.current=void 0)},[]),l.useEffect(()=>{if(!ce)return;const e=o=>{o.key==="Escape"&&(Ve||je)&&(Ce(null),Ee(null),he(null),n.safeInvoke("onInspectSelectionChange",fe.current,null))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ce,Ve,je]);const Ft=()=>{C.current&&C.current.focus()};l.useImperativeHandle(ze,()=>({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=>{Ee(e?.id??null)},setInspectSelection:e=>{Ce(e?.id??null),he(e?Se.current:null);const o=ie.current;e&&o?n.safeInvoke("onInspectSelectionChange",fe.current,{element:e,snapshot:o}):n.safeInvoke("onInspectSelectionChange",fe.current,null)},getAxStatus:()=>T.current?.getAxStatus()??"idle"}));const zt=Ct&&re!==null;return f.jsxs("div",{ref:Me,className:["rc-container",p].filter(Boolean).join(" "),style:{touchAction:"none"},onMouseDown:ee,onMouseMove:ee,onMouseUp:ee,onMouseLeave:ee,onTouchStart:ee,onTouchMove:ee,onTouchEnd:ee,onTouchCancel:ee,onContextMenu:x==="macos"?e=>e.preventDefault():void 0,children:[zt&&re&&f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"rc-touch-indicator",style:{left:`${re.containerX}px`,top:`${re.containerY}px`}}),f.jsx("div",{className:"rc-touch-indicator",style:{left:`${re.mirrorContainerX}px`,top:`${re.mirrorContainerY}px`}})]}),Ae&&f.jsx("img",{ref:qe,src:dt,alt:"",className:x==="ios"?"rc-phone-frame rc-phone-frame-ios":"rc-phone-frame",draggable:!1}),Ae&&ot&&!Q&&f.jsx("button",{type:"button",className:"rc-home-button","aria-label":"Home",title:"Home",style:ot,onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),onTouchEnd:e=>{e.stopPropagation(),e.preventDefault(),T.current?.pressButton("home")},onClick:e=>{e.stopPropagation(),T.current?.pressButton("home")}}),f.jsx("video",{ref:C,className:["rc-video",!Ae&&"rc-video-frameless",!wt&&(x==="macos"?"rc-video-loading-desktop":"rc-video-loading")].filter(Boolean).join(" "),style:{..._t,...U?{opacity:0,width:1,height:1,pointerEvents:"none"}:{},...ut?{backgroundImage:`url("${ut}")`,backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:se.loadingLogoSize}:{}},autoPlay:!0,playsInline:!0,muted:!0,tabIndex:U?-1:0,onKeyDown:Le,onKeyUp:Le,onClick:Ft,onFocus:()=>{C.current&&(C.current.style.outline="none")},onBlur:()=>{C.current&&(C.current.style.outline="none"),xe()}}),U&&f.jsx("video",{ref:be,autoPlay:!0,playsInline:!0,muted:!0,style:{position:"absolute",width:1,height:1,opacity:0,pointerEvents:"none"}}),U&&Ge&&f.jsx(l.Suspense,{fallback:f.jsx("div",{children:"Loading iPhone Duo…"}),children:f.jsx(ro,{watchOnly:Q,showFrame:M,modelUrl:j,outer:C.current,inner:be.current,state:Ge,setAngle:e=>Ke("setHingeAngle",{angleDegrees:e}),setOrientation:e=>Ke("setDuoOrientation",{orientation:e}),button:(e,o)=>Ke("performActions",{actions:[{type:o?"buttonDown":"buttonUp",button:e}]}),touch:(e,o,r,t)=>{T.current?.sendDisplayTouch(e,o,r,t)},onKeyDown:Le,onKeyUp:Le})}),U&&Je&&f.jsx("div",{role:"alert",className:"rc-duo-error",children:Je}),!U&&ce&&f.jsx(oo,{snapshot:rt,geometry:Dt,highlightedId:je,selectedId:Ve,mode:Yt,cursorPosition:xt,frozenCursorPosition:Pt,onSelectChange:(e,o)=>{Ce(e?.id??null),e&&o?he(o):e||he(null);const r=ie.current;e&&r?n.safeInvoke("onInspectSelectionChange",fe.current,{element:e,snapshot:r}):n.safeInvoke("onInspectSelectionChange",fe.current,null)},onTapElement:Q?void 0:((e,o)=>{if(o){ft(o.x,o.y);return}const r=ie.current;r&&kt(e,r)})}),Rt?f.jsxs("div",{className:"rc-terminated",role:"status",children:[f.jsx("div",{className:"rc-terminated-title",children:"Instance terminated"}),f.jsx("div",{className:"rc-terminated-message",children:"This instance no longer exists and can't be reconnected."})]}):It&&f.jsx("button",{type:"button",className:"rc-retry-button",onClick:$t,children:"Retry"})]})});exports.RemoteControl=uo;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@limrun/ui",
3
- "version": "0.20.8",
3
+ "version": "0.21.0-rc.1",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1,2 +0,0 @@
1
- "use strict";const ke={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,c,E,d,a=1,m=0,O=0){const h=new ArrayBuffer(32),A=new DataView(h);let w=0;A.setUint8(w,ke.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(d),!0),w+=4,A.setUint16(w,n,!0),w+=2,A.setUint16(w,c,!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,c,E,d,a){const m=new ArrayBuffer(24),O=new DataView(m);let h=0;return O.setUint8(h,ke.INJECT_TWO_FINGER_TOUCH_EVENT),h+=1,O.setUint8(h,t),h+=1,O.setInt32(h,Math.round(c),!0),h+=4,O.setInt32(h,Math.round(E),!0),h+=4,O.setInt32(h,Math.round(d),!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 c=new TextEncoder().encode(t),E=new ArrayBuffer(14+c.length),d=new DataView(E);let a=0;return d.setUint8(a,ke.SET_CLIPBOARD),a+=1,d.setBigInt64(a,BigInt(0),!1),a+=8,d.setUint8(a,e?1:0),a+=1,d.setUint32(a,c.length,!1),a+=4,new Uint8Array(E,a).set(c),E}function je(t,e,n=0,c=0){const E=new ArrayBuffer(14),d=new DataView(E);let a=0;return d.setUint8(a,ke.INJECT_KEYCODE),a+=1,d.setUint8(a,t),a+=1,d.setInt32(a,e,!0),a+=4,d.setInt32(a,n,!0),a+=4,d.setInt32(a,c,!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,c,E=!1){if(this.screenId===void 0)return;const d=bt(n,c,E?0:this.turns);e==="begin"&&(this.release(),this.held={screenId:this.screenId,...d}),this.held&&(Object.assign(this.held,d),e==="end"?this.release():this.send(e==="begin"?0:2,this.held.screenId,d.x,d.y))}release(){if(!this.held)return;const{screenId:e,x:n,y:c}=this.held;this.held=void 0,this.send(1,e,n,c)}}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,c){if(!Number.isInteger(t)||t<0||t>3||!Number.isInteger(e)||e<1||e>255||!Number.isFinite(n)||!Number.isFinite(c)||n<0||n>1||c<0||c>1)throw new RangeError("Invalid display touch coordinates");const E=new ArrayBuffer(12),d=new DataView(E);return d.setUint8(0,19),d.setUint8(1,t),d.setUint8(2,e),d.setFloat32(4,n,!0),d.setFloat32(8,c,!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,c]of Object.entries(t))n!=="children"&&(e[n]=c);return e};function It(t){const e=Array.isArray(t)?t:[t],n=hn(e),c=[],E=(d,a)=>{if(c.length>=Qe)return;const m=d.frame;if(m&&m.width>0&&m.height>0&&!Rt(m,n)){const h=d.role_description||d.role||"",A=(typeof d.AXLabel=="string"?d.AXLabel:"")||(typeof d.title=="string"?d.title:"")||"";c.push({id:typeof d.AXUniqueId=="string"&&d.AXUniqueId.length>0?d.AXUniqueId:a,path:a,label:A,value:typeof d.AXValue=="string"?d.AXValue:"",role:h,type:typeof d.type=="string"?d.type:"",enabled:d.enabled!==!1,focused:d.focused===!0,frame:{x:m.x,y:m.y,width:m.width,height:m.height},selectors:mn(d),raw:pn(d)})}const O=Array.isArray(d.children)?d.children:[];for(let h=0;h<O.length&&c.length<Qe;h++)E(O[h],`${a}.${h}`)};for(let d=0;d<e.length&&c.length<Qe;d++)E(e[d],String(d));return{platform:"ios",screen:{width:n.width,height:n.height},elements:c,capturedAt:Date.now()}}const Cn=t=>{let e={x:0,y:0,width:1,height:1},n=0;for(const c of t){const E=c.parsedBounds;if(!E)continue;const d=E.right-E.left,a=E.bottom-E.top,m=Math.max(0,d)*Math.max(0,a);m>n&&(n=m,e={x:0,y:0,width:d,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 kt(t){const e=Cn(t),n=[];for(let c=0;c<t.length&&n.length<Qe;c++){const E=t[c],d=E.parsedBounds;if(!d)continue;const a=Math.max(0,d.right-d.left),m=Math.max(0,d.bottom-d.top);if(a<=0||m<=0)continue;const O={x:d.left,y:d.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(c),path:String(c),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),c=Math.max(0,t.y),E=Math.min(e.width,t.x+t.width),d=Math.min(e.height,t.y+t.height),a=Math.max(0,E-n),m=Math.max(0,d-c);return a>0&&m>0?{x:n,y:c,width:a,height:m}:null}function Ut(t,e){if(t===e)return!0;if(t.id!==e.id||t.path!==e.path||t.label!==e.label||t.value!==e.value||t.role!==e.role||t.type!==e.type||t.enabled!==e.enabled||t.focused!==e.focused)return!1;const n=t.frame,c=e.frame;return n.x===c.x&&n.y===c.y&&n.width===c.width&&n.height===c.height}function Pt(t,e){if(t===e)return!0;if(!t||!e||t.platform!==e.platform||t.screen.width!==e.screen.width||t.screen.height!==e.screen.height||t.elements.length!==e.elements.length)return!1;for(let n=0;n<t.elements.length;n++)if(!Ut(t.elements[n],e.elements[n]))return!1;return!0}function _n(t,e,n){let c=null,E=1/0;for(const d of t.elements){const a=d.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,c=d)}return c}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 c=n.length>gt?n.slice(0,gt).trimEnd()+"…":n;return`${e} · ${c}`}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(c){console.error("[AxFetcher] onStatusChange threw:",c)}}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 d=e.payload,a=Array.isArray(d?.nodes)?d.nodes:[];try{const m=kt(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,c)=>{const E=window.setTimeout(()=>{this.pending.delete(e),c(new Error("elementTree request timed out"))},vn+(this.androidElementTreeOptions?.waitForIdleTimeoutMs??0));this.pending.set(e,{resolve:n,reject:c,timer:E}),this.send(this.buildRequest(e))||(window.clearTimeout(E),this.pending.delete(e),c(new Error("elementTree send failed (WebSocket not open)")))})}async runOnce(){if(this.running&&!this.inflight){this.inflight=!0;try{const e=await this.requestOnce();if(!this.running)return;this.deliver(e)}catch(e){if(!this.running)return;const n=e instanceof Error?e.message:String(e),c=/unavailable|not (yet )?running|failed|timeout/i.test(n);this.currentInterval=c?Tt:Math.min(this.currentInterval*2,this.maxBackoffMs),this.setStatus(c?"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 c=this.pending.get(e);c&&(window.clearTimeout(c.timer),this.pending.delete(e),c.resolve(n))}settleReject(e,n){const c=this.pending.get(e);c&&(window.clearTimeout(c.timer),this.pending.delete(e),c.reject(n))}failAllPending(e){for(const[n,c]of this.pending.entries())window.clearTimeout(c.timer),c.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(c){console.warn("RemoteControl: could not set the jitter buffer target.",c)}}const Ft=`(function(){"use strict";let e,t;self.onmessage=async({data:s})=>{s.type==="start"?(e=new AbortController,t=s.readable.pipeTo(s.writable,{signal:e.signal}).catch(o=>{e?.signal.aborted||self.postMessage({type:"error",message:String(o)})})):s.type==="stop"&&(e?.abort(),await t,self.postMessage({type:"stopped"}),self.close())}})();
2
- `,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:c,MediaStreamTrackGenerator:E}=globalThis,d=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(d&&c&&E){a=d.clone();const D=new c({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===d?$: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,c){const E={timestamp:0,video:[],audio:[]};c==null?E.requestedTargetMs=null:Ie(c)&&c>=0&&c<=4e3&&(E.requestedTargetMs=c);const d=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(k=>k.kind===m),h=a.trackIdentifier?O.find(k=>k.trackId===a.trackIdentifier):a.mid!=null?O.find(k=>k.mid===a.mid):O.length===1?O[0]:void 0;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 k=ge(a.jitterBufferEmittedCount,I?.jitterBufferEmittedCount),F=ge(a.jitterBufferDelay,I?.jitterBufferDelay);k!==void 0&&k>0&&F!==void 0&&(D.bufferDelayMs=F/k*1e3);const q=ge(a.bytesReceived,I?.bytesReceived);q!==void 0&&(D.bitrateBps=q*8e3/W)}if(m==="video"){const k={...D,display:h.display??"primary"};if(D.intervalMs!==void 0){const F=ge(a.framesDecoded,I?.framesDecoded);F!==void 0&&(k.fps=F*1e3/D.intervalMs),k.droppedFrames=ge(a.framesDropped,I?.framesDropped),k.freezes=ge(a.freezeCount,I?.freezeCount)}E.video.push(k)}else E.audio.push(D);E.timestamp=Math.max(E.timestamp,a.timestamp),d.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=d,E.video.length||E.audio.length?E:null}}const ot=new WeakSet;function Rn(t,e,n){const{peer:c,displays:E}=t,d=new Nn;let a,m=!1,O=!1,h=!1,A=0,w=!1,I=!1;const W=()=>!m&&!document.hidden&&c.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),d.reset(),D(null)},P=async()=>{if(h||!W())return;if(ot.has(c)){a=setTimeout(()=>{P()},2e3);return}h=!0,ot.add(c);const F=A;try{const q=await c.getStats();if(F!==A||!W())return;const ae=c.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(d.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,d.reset(),D(null)}finally{h=!1,ot.delete(c),O&&W()&&(a=setTimeout(()=>{P()},F===A?2e3:0))}},k=()=>{if(!W()){$();return}O||(O=!0,P())};return document.addEventListener("visibilitychange",k),c.addEventListener("connectionstatechange",k),k(),()=>{m=!0,document.removeEventListener("visibilitychange",k),c.removeEventListener("connectionstatechange",k),$()}}function In(t,e){const n=t.createDataChannel("latency-trace-v1",{ordered:!0,negotiated:!0,id:2});let c=!1,E=!1,d=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,c=!1},{accept(a){c=!E&&a===1},wrap(a){if(!c||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,++d,!0),new Uint8Array(O,6).set(new Uint8Array(a)),O},close(){E=!0,c=!1,n.onmessage=null,n.onclose=null,n.close()}}}class kn{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 c={generation:e,isCurrent:()=>e===this.generation},E=this.tail.then(()=>n(c));return this.tail=E.catch(()=>{}),E}invalidate(){++this.generation}}function Un(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(c){console.error(`[RemoteControl] customer callback "${t}" threw:`,c)}},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,deviceModel:c}=e;let E=e.token;const d=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 k=()=>{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 Ue=new Map,st=(r,u,s)=>{u.stop?.(),u.stop=bn(r,s,l=>S("Video playback fallback:",l))},xt=()=>{Ue.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 kn;let Ae=null,xe=null,Ze=!d&&(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((s,l)=>{if(d){l(new Error("Device is watch-only"));return}const y=g;if(!y||y.readyState!==WebSocket.OPEN){l(new Error("Simulator disconnected"));return}const p=At(),C=setTimeout(()=>{Ce.delete(p),l(new Error("Device control timed out"))},5e3);Ce.set(p,{resolve:s,reject:l,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=>{d||!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(s){S("track.stop() failed:",s)}},$t=()=>{const r=Q;r&&(Q=null,H(r))},ut=r=>{const u=ct.then(r).catch(s=>{S("microphone operation failed:",s)});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(),s=f=>{L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,error:f})};if(!u())return;const l=g,y=Ke;if(!l||l.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)."),s("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){s("Microphone permission denied or no device available");return}const C=p.getAudioTracks()[0]??null;if(!C){H(p),s("Captured stream has no audio track");return}try{await y.replaceTrack(C)}catch(f){S("replaceTrack(audioTrack) failed:",f),H(p),s("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(l),L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!0,label:C.label||void 0})},He=r=>(++We,me=null,ut(async()=>{const u=Ke,s=ee;if(ee=null,u&&s)try{await u.replaceTrack(null)}catch(y){S("replaceTrack(null) on mic detach failed:",y)}s&&H(s);const l=g;if(s&&l&&l.readyState===WebSocket.OPEN){const y=`ui-mic-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;l.send(JSON.stringify({type:"microphoneStop",id:y}))}(s||r)&&L("onMicrophoneStateChange",e.onMicrophoneStateChange,{active:!1,...r!==void 0&&{error:r}})})),ft=(r,u)=>{let s;try{s=Bn(u),console.info(`[RemoteControl] camera capture: ${s.camera?.width}x${s.camera?.height} @ ${s.camera?.frameRate??"?"}fps`+(s.camera?.label?` — ${s.camera.label}`:""))}catch(l){S("getSettings() on outbound camera track failed:",l),s={type:"cameraResult",granted:!0,camera:{label:u.label||void 0}}}r.send(JSON.stringify(s)),L("onCameraDemandChange",e.onCameraDemandChange,!0,!0,s.camera)},Gt=r=>{if(!r)return;const u=r.indexOf("/"),l=(u>=0?r.slice(u+1):r).toUpperCase();return l==="HEVC"?"H265":l},Jt=async()=>{const r=de,u=e.onCameraStats;if(!r||!u)return;let s;try{s=await r.getStats()}catch{return}let l,y,p;if(s.forEach(N=>{N.type==="outbound-rtp"&&N.kind==="video"?l=N:N.type==="remote-inbound-rtp"&&N.kind==="video"&&(p=N)}),l?.codecId){const N=s.get(l.codecId);N&&(y=N.mimeType)}if(!l)return;const C=l.timestamp??Date.now(),f=xe;let J,U,j;if(f&&C>f.timestamp){const N=(C-f.timestamp)/1e3;if(typeof l.framesEncoded=="number"&&typeof f.framesEncoded=="number"&&(J=Math.max(0,(l.framesEncoded-f.framesEncoded)/N)),typeof l.bytesSent=="number"&&typeof f.bytesSent=="number"&&(U=Math.max(0,(l.bytesSent-f.bytesSent)*8/N)),typeof l.packetsSent=="number"&&typeof f.packetsSent=="number"&&p&&typeof p.packetsLost=="number"&&typeof f.packetsLost=="number"){const v=l.packetsSent-f.packetsSent,Je=p.packetsLost-f.packetsLost;v>0&&(j=Math.max(0,Math.min(100,Je/v*100)))}}xe={timestamp:C,framesEncoded:l.framesEncoded,bytesSent:l.bytesSent,packetsSent:l.packetsSent,packetsLost:p?.packetsLost};const M={codec:Gt(y),encoderImplementation:l.encoderImplementation,hardwareAccelerated:typeof l.powerEfficientEncoder=="boolean"?l.powerEfficientEncoder:void 0,framesPerSecond:J,framesEncoded:l.framesEncoded,bitrateBps:U,width:l.frameWidth,height:l.frameHeight,qualityLimitationReason:l.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,s,l)=>ze.enqueue(async({isCurrent:y})=>{const p=()=>y()&&l()&&g===u&&de===s;if(!p())return;if(!r.active){const M=Q;try{await s.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 s.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 U=null;try{U=await navigator.mediaDevices.getUserMedia({video:Pn(r),audio:!1})}catch(M){console.warn("[RemoteControl] getUserMedia denied/failed:",M)}if(!p()){U&&H(U);return}if(!U){u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}const j=U.getVideoTracks()[0]??null;if(!j){if(H(U),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}try{j.contentHint="motion"}catch{}try{await s.replaceTrack(j)}catch(M){if(S("replaceTrack(videoTrack) failed:",M),H(U),!p())return;u.send(JSON.stringify({type:"cameraResult",granted:!1})),L("onCameraDemandChange",e.onCameraDemandChange,!0,!1);return}if(!p()){try{await s.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera attach failed:",M)}H(U);return}try{const M=s.getParameters();(!M.encodings||M.encodings.length===0)&&(M.encodings=[{}]),M.encodings[0].maxBitrate=8e6,M.encodings[0].maxFramerate=30,M.degradationPreference="maintain-framerate",await s.setParameters(M)}catch(M){S("setParameters on outbound camera failed:",M)}if(!p()){try{await s.replaceTrack(null)}catch(M){S("replaceTrack(null) for stale camera finalize failed:",M)}H(U);return}Q=U,ue=r,j.onended=()=>{Q===U&&ze.enqueueCurrent(async({isCurrent:M})=>{if(!(!M()||Q!==U||!l()||g!==u||de!==s)){try{await s.replaceTrack(null)}catch(N){S("replaceTrack(null) after camera ended failed:",N)}!M()||Q!==U||!l()||g!==u||de!==s||(Q=null,ue=void 0,H(U),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 l=new URL(n);l.protocol=l.protocol==="wss:"?"https:":l.protocol==="ws:"?"http:":l.protocol,r=vt(l.toString(),E)}catch{return!1}const u=new AbortController,s=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(s)}},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 s=Be+1;if(s>=at){D(`Connection failed after ${at} attempts: ${r}`),Ye(),Oe("failed"),De();return}D(`Retrying connection (${s+1}/${at})`),Oe("reconnecting"),De(),ye=window.setTimeout(()=>{ye=void 0,u===le&&pt(s)},xn)},pt=async(r=0)=>{const{openUrl:u,axPollIntervalMs:s,axMaxBackoffMs:l,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,E));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:U,cameraSupported:j,foldSupported:M}=await J;if(!C()||g!==f)return;const N=c==="iphone-duo"||M;W(N);const v=new RTCPeerConnection({...U,iceTransportPolicy:"relay"});b=v;const Je={peer:v,displays:new Map};$=Je,k(),v.addTransceiver("audio",{direction:"recvonly"});const Zt=v.addTransceiver("video",{direction:"recvonly"}),en=N?v.addTransceiver("video",{direction:"recvonly"}):null,_t=!d&&(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=!d&&!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:!d}),$e(),D("Control channel opened"),N&&f.send(JSON.stringify({type:"getFoldState",id:"duo-capabilities"})),V||(V=new wn({platform:m,baseIntervalMs:s,maxBackoffMs:l,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),!d&&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]);Ue.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=Un(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 s={display:u};F.set(r,s);const l=()=>{u==="primary"&&Ue.has(u)&&Vt()};r.addEventListener("loadeddata",l);const y=Ue.get(u);y&&st(r,s,y);let p=!1;const C=()=>{p||(p=!0,q.delete(C),r.removeEventListener("loadeddata",l),s.stop?.(),F.delete(r),r.srcObject=null)};return q.add(C),C};return{start:Ct,stop:Ot,attachVideo:Dt,attachFrameSink:(r,u="primary")=>{const s=document.createElement("video");s.muted=!0,s.playsInline=!0,s.autoplay=!0;const l=Dt(s,u);let y=!1,p=0,C=0;const f=()=>{s.cancelVideoFrameCallback?.(p),cancelAnimationFrame(C)},J=()=>{y||!s.srcObject||(s.readyState>=2&&s.videoWidth>0&&L("present",(...M)=>r.present(...M),s,s.videoWidth,s.videoHeight,u),!(y||!s.srcObject)&&(s.requestVideoFrameCallback?p=s.requestVideoFrameCallback(J):C=requestAnimationFrame(J)))},U=()=>{f(),J()};F.get(s).clear=f,s.addEventListener("loadeddata",U);const j=()=>{y||(y=!0,q.delete(j),f(),s.removeEventListener("loadeddata",U),l(),s.remove())};return q.delete(l),q.add(j),s.readyState>=2&&U(),j},dispose:()=>{if(!Te){Te=!0,Ot();for(const r of q)r();q.clear()}},getState:()=>O,updateOptions:({token:r,...u})=>{if(Te)throw new Error("Device stream is disposed");r!==void 0&&!e.transport&&(E=r);const s=e;if(e={...e,...u},s.jitterBufferTargetMs!==e.jitterBufferTargetMs)for(const l of b?.getTransceivers()??[])(l.currentDirection==="recvonly"||l.currentDirection==="sendrecv")&&St(l.receiver,e.jitterBufferTargetMs);!!s.onPlaybackStats!=!!e.onPlaybackStats&&k(),!!s.microphoneEnabled!=!!e.microphoneEnabled&&(Ze=!d&&(e.microphoneEnabled??!1),tt()?nt():He()),!!s.inspectMode!=!!e.inspectMode&&(e.inspectMode?V?.start():(V?.stop(),we!==null&&qe(null)))},sendControl:ce,sendTouch:(r,u,s,l,y,p=0)=>ce(Mt(r==="begin"?0:r==="end"?1:2,p,l,y,u,s,r==="end"?0:1)),sendText:r=>ce(wt(r)),sendDisplayTouch:(r,u,s,l)=>ce(Nt(r,u,s,l)),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(!d){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 s=i.META_NONE;r.shiftKey&&(s|=i.META_SHIFT_ON),r.altKey&&(s|=i.META_ALT_ON),r.ctrlKey&&(s|=i.META_CTRL_ON),r.metaKey&&(s|=i.META_META_ON);const l=r.type==="keydown"?i.ACTION_DOWN:i.ACTION_UP;oe(`Sending Imperative Key Command: code=${r.code}, keycode=${u}, action=${l}, meta=${s}`);const y=je(l,u,0,s);y&&ce(y)},screenshot:r=>new Promise((u,s)=>{if(!g||g.readyState!==WebSocket.OPEN)return S("WebSocket not open, cannot send screenshot command."),s(new Error("WebSocket is not connected or connection is not open."));const l=`ui-ss-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,y={type:r?"screenshotDisplay":"screenshot",...r?{display:r}:{},id:l};ne.set(l,u),Z.set(l,s),oe("Sending screenshot request:",y);try{g.send(JSON.stringify(y))}catch(p){S("Failed to send screenshot request immediately:",p),ne.delete(l),Z.delete(l),s(p);return}Y.set(l,setTimeout(()=>{Y.delete(l),ne.has(l)&&(S(`Screenshot request timed out for id ${l}`),Z.get(l)?.(new Error("Screenshot request timed out")),ne.delete(l),Z.delete(l))},3e4))}),terminateApp:r=>d?Promise.reject(new Error("Device is watch-only")):new Promise((u,s)=>{if(!g||g.readyState!==WebSocket.OPEN)return S("WebSocket not open, cannot send terminateApp command."),s(new Error("WebSocket is not connected or connection is not open."));const l=`ui-term-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,y={type:"terminateApp",id:l,bundleId:r};se.set(l,u),re.set(l,s),oe("Sending terminateApp request:",y);try{g.send(JSON.stringify(y))}catch(p){S("Failed to send terminateApp request immediately:",p),se.delete(l),re.delete(l),s(p);return}V?.bumpActivity(),Y.set(l,setTimeout(()=>{Y.delete(l),se.has(l)&&(S(`terminateApp request timed out for id ${l}`),re.get(l)?.(new Error("terminateApp request timed out")),se.delete(l),re.delete(l))},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=ke;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=Ut;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=kt;exports.normalizeIosTree=It;exports.panelTouch=cn;exports.safeInvoke=L;