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