@ledgerhq/device-management-kit-devtools-rozenite 0.0.0-develop-20261109000905 → 0.0.0-develop-20261110000801

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/index.js CHANGED
@@ -24,7 +24,7 @@ Error generating stack: `+b.message+`
24
24
  ${a.right}px ${a.bottom}px,
25
25
  ${a.right}px ${a.top}px,
26
26
  ${a.left}px ${a.top}px
27
- )`}return v.jsx("div",{ref:t,role:"presentation","data-base-ui-inert":"",...n,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})});function iR(e){return e==="starting"?Lj:Rr}const t2=x.createContext(void 0);function r2(e){return x.useContext(t2)}const n2="ArrowUp",i2="ArrowDown",o2="ArrowLeft",s2="ArrowRight",a2="Home",l2=new Set([n2,i2,o2,s2,a2,"End"]);function c2(e,t={}){const r="rootStore"in e?e.rootStore:e,n=r.useState("open"),o=r.useState("floatingElement"),a=r.useState("domReferenceElement"),{dataRef:l}=r.context,{enabled:u=!0,closeDelay:d=0}=t,p=Pk(r),h=ta(),m=Vo(),y=et(()=>Dk(l.current.openEvent?.type,p.interactedInside)),w=et(()=>{const $=l.current.openEvent?.type;return $?.includes("mouse")&&$!=="mousedown"}),E=et($=>Ck($,r.context.triggerElements)),S=x.useCallback($=>{const A=Fu(d,"close",p.pointerType),D=()=>{r.setOpen(!1,zt(Cr,$)),h?.events.emit("floating.closed",$)};A?p.openChangeTimeout.start(A,D):(p.openChangeTimeout.clear(),D())},[d,r,p,h]),C=et(()=>{uv(p)}),R=et($=>{const A=gn($);if(!$M(A)){p.interactedInside=!1;return}p.interactedInside=A?.closest("[aria-haspopup]")!=null});at(()=>{n||(p.pointerType=void 0,p.restTimeoutPending=!1,p.interactedInside=!1,C())},[n,p,C]),x.useEffect(()=>C,[C]),at(()=>{if(u&&n&&p.handleCloseOptions?.blockPointerEvents&&w()&&gt(a)&&o){const $=a,A=o,D=_t(o),N=h?.nodesRef.current.find(I=>I.id===m)?.context?.elements.floating;N&&(N.style.pointerEvents="");const P=p.handleCloseOptions?.getScope?.()??p.pointerEventsScopeElement??N??$.closest("[data-rootownerid]")??D.body;return TM(p,{scopeElement:P,referenceElement:$,floatingElement:A}),()=>{C()}}},[u,n,a,o,p,w,h,m,C]);const k=Vs();x.useEffect(()=>{if(!u)return;function $(){p.openChangeTimeout.clear(),k.clear(),h?.events.off("floating.closed",D),C()}function A(P){if(h&&m&&oi(h.nodesRef.current,m).length>0){h.events.on("floating.closed",D);return}if(!E(P.relatedTarget)){if(p.handler){p.handler(P);return}C(),y()||S(P)}}function D(P){!h||!m||oi(h.nodesRef.current,m).length>0||k.start(0,()=>{h.events.off("floating.closed",D),r.setOpen(!1,zt(Cr,P)),h.events.emit("floating.closed",P)})}const N=o;return N&&(N.addEventListener("mouseenter",$),N.addEventListener("mouseleave",A),N.addEventListener("pointerdown",R,!0)),()=>{N&&(N.removeEventListener("mouseenter",$),N.removeEventListener("mouseleave",A),N.removeEventListener("pointerdown",R,!0)),h?.events.off("floating.closed",D)}},[u,o,r,l,y,E,S,C,R,p,h,m,k])}const uh={inert:new WeakMap,"aria-hidden":new WeakMap},ow="data-base-ui-inert",vg={inert:new WeakSet,"aria-hidden":new WeakSet};let Ja=new WeakMap,dh=0;function u2(e){return vg[e]}function oR(e){return e?bl(e)?e.host:oR(e.parentNode):null}const fh=(e,t)=>t.map(r=>{if(e.contains(r))return r;const n=oR(r);return e.contains(n)?n:null}).filter(r=>r!=null),sw=e=>{const t=new Set;return e.forEach(r=>{let n=r;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},aw=(e,t,r)=>{const n=[],o=a=>{!a||r.has(a)||Array.from(a.children).forEach(l=>{Qi(l)!=="script"&&(t.has(l)?o(l):n.push(l))})};return o(e),n};function d2(e,t,r,n,{mark:o=!0,markerIgnoreElements:a=[]}){const l=n?"inert":r?"aria-hidden":null;let u=null,d=null;const p=fh(t,e),h=o?fh(t,a):[],m=new Set(h),y=o?aw(t,sw(p),new Set(p)).filter(S=>!m.has(S)):[],w=[],E=[];if(l){const S=uh[l],C=u2(l);d=C,u=S;const R=fh(t,Array.from(t.querySelectorAll("[aria-live]"))),k=p.concat(R);aw(t,sw(k),new Set(k)).forEach($=>{const A=$.getAttribute(l),D=A!==null&&A!=="false",N=(S.get($)||0)+1;S.set($,N),w.push($),N===1&&D&&C.add($),D||$.setAttribute(l,l==="inert"?"":"true")})}return o&&y.forEach(S=>{const C=(Ja.get(S)||0)+1;Ja.set(S,C),E.push(S),C===1&&S.setAttribute(ow,"")}),dh+=1,()=>{u&&w.forEach(S=>{const C=(u.get(S)||0)-1;u.set(S,C),C||(!d?.has(S)&&l&&S.removeAttribute(l),d?.delete(S))}),o&&E.forEach(S=>{const C=(Ja.get(S)||0)-1;Ja.set(S,C),C||S.removeAttribute(ow)}),dh-=1,dh||(uh.inert=new WeakMap,uh["aria-hidden"]=new WeakMap,vg.inert=new WeakSet,vg["aria-hidden"]=new WeakSet,Ja=new WeakMap)}}function lw(e,t={}){const{ariaHidden:r=!1,inert:n=!1,mark:o=!0,markerIgnoreElements:a=[]}=t,l=_t(e[0]).body;return d2(e,l,r,n,{mark:o,markerIgnoreElements:a})}function f2(e,t){const r=tr(e.target);return e instanceof r.KeyboardEvent?"keyboard":e instanceof r.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof r.MouseEvent?t||(e.detail===0?"keyboard":"mouse"):""}const cw=20;let Fi=[];function pv(){Fi=Fi.filter(e=>e.deref()?.isConnected)}function p2(e){pv(),e&&Qi(e)!=="body"&&(Fi.push(new WeakRef(e)),Fi.length>cw&&(Fi=Fi.slice(-cw)))}function ph(){return pv(),Fi[Fi.length-1]?.deref()}function h2(e){if(!e)return null;const t=ra();return Vk(e,t)?e:Tl(e,t)[0]||e}function m2(e){return!e||!e.isConnected?!1:typeof e.checkVisibility=="function"?e.checkVisibility():K6(e)}function uw(e,t){if(!t.current.includes("floating")&&!e.getAttribute("role")?.includes("dialog"))return;const r=ra(),n=JM(e,r).filter(a=>{const l=a.getAttribute("data-tabindex")||"";return Vk(a,r)||a.hasAttribute("data-tabindex")&&!l.startsWith("-")}),o=e.getAttribute("tabindex");t.current.includes("floating")||n.length===0?o!=="0"&&e.setAttribute("tabindex","0"):(o!=="-1"||e.hasAttribute("data-tabindex")&&e.getAttribute("data-tabindex")!=="-1")&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function g2(e){const{context:t,children:r,disabled:n=!1,initialFocus:o=!0,returnFocus:a=!0,restoreFocus:l=!1,modal:u=!0,closeOnFocusOut:d=!0,openInteractionType:p="",nextFocusableElement:h,previousFocusableElement:m,beforeContentFocusGuardRef:y,externalTree:w,getInsideElements:E}=e,S="rootStore"in t?t.rootStore:t,C=S.useState("open"),R=S.useState("domReferenceElement"),k=S.useState("floatingElement"),{events:$,dataRef:A}=S.context,D=et(()=>A.current.floatingContext?.nodeId),N=o===!1,P=Mx(R)&&N,I=x.useRef(["content"]),re=Nn(o),Z=Nn(a),ee=Nn(p),ne=ta(w),X=Xk(),F=x.useRef(!1),V=x.useRef(!1),H=x.useRef(!1),O=x.useRef(-1),L=x.useRef(""),U=x.useRef(""),z=x.useRef(null),T=x.useRef(null),M=ud(z,y,X?.beforeInsideRef),te=ud(T,X?.afterInsideRef),le=Vs(),G=Vs(),fe=ev(),be=X!=null,pe=lg(k),ue=et((we=pe)=>we?Tl(we,ra()):[]),ge=et(()=>E?.().filter(we=>we!=null)??[]),qe=et(we=>{const ze=ue(we);return I.current.map(()=>ze).filter(Boolean).flat()});x.useEffect(()=>{if(n||!u)return;function we(We){We.key==="Tab"&&st(pe,$o(_t(pe)))&&ue().length===0&&!P&&p6(We)}const ze=_t(pe);return ze.addEventListener("keydown",we),()=>{ze.removeEventListener("keydown",we)}},[n,R,pe,u,I,P,ue,qe]),x.useEffect(()=>{if(n||!C)return;const we=_t(pe);function ze(){H.current=!1}function We(De){const Fe=gn(De),lt=ge(),Ne=st(k,Fe)||st(R,Fe)||st(X?.portalNode,Fe)||lt.some(oe=>oe===Fe||st(oe,Fe));H.current=!Ne,U.current=De.pointerType||"keyboard",Fe?.closest(`[${lk}]`)&&(V.current=!0)}function tt(){U.current="keyboard"}return we.addEventListener("pointerdown",We,!0),we.addEventListener("pointerup",ze,!0),we.addEventListener("pointercancel",ze,!0),we.addEventListener("keydown",tt,!0),()=>{we.removeEventListener("pointerdown",We,!0),we.removeEventListener("pointerup",ze,!0),we.removeEventListener("pointercancel",ze,!0),we.removeEventListener("keydown",tt,!0)}},[n,k,R,pe,C,X,ge]),x.useEffect(()=>{if(n||!d)return;const we=_t(pe);function ze(){V.current=!0,G.start(0,()=>{V.current=!1})}function We(Ne){const oe=gn(Ne),Se=ue().indexOf(oe);Se!==-1&&(O.current=Se)}function tt(Ne){const oe=Ne.relatedTarget,Se=Ne.currentTarget,Je=gn(Ne);queueMicrotask(()=>{const ht=D(),Bt=S.context.triggerElements,Ut=ge(),jt=oe?.hasAttribute(sd("focus-guard"))&&[z.current,T.current,X?.beforeInsideRef.current,X?.afterInsideRef.current,X?.beforeOutsideRef.current,X?.afterOutsideRef.current,Zn(m),Zn(h)].includes(oe),Vt=!(st(R,oe)||st(k,oe)||st(oe,k)||st(X?.portalNode,oe)||Ut.some(bt=>bt===oe||st(bt,oe))||oe!=null&&Bt.hasElement(oe)||Bt.hasMatchingElement(bt=>st(bt,oe))||jt||ne&&(oi(ne.nodesRef.current,ht).find(bt=>st(bt.context?.elements.floating,oe)||st(bt.context?.elements.domReference,oe))||zx(ne.nodesRef.current,ht).find(bt=>[bt.context?.elements.floating,lg(bt.context?.elements.floating)].includes(oe)||bt.context?.elements.domReference===oe)));if(Se===R&&pe&&uw(pe,I),l&&Se!==R&&!m2(Je)&&$o(we)===we.body){if(Kt(pe)&&(pe.focus(),l==="popup")){fe.request(()=>{pe.focus()});return}const bt=O.current,rt=ue(),q=rt[bt]||rt[rt.length-1]||pe;Kt(q)&&q.focus()}if(A.current.insideReactTree){A.current.insideReactTree=!1;return}(P||!u)&&oe&&Vt&&!V.current&&(P||oe!==ph())&&(F.current=!0,S.setOpen(!1,zt(El,Ne)))})}function De(){H.current||(A.current.insideReactTree=!0,le.start(0,()=>{A.current.insideReactTree=!1}))}const Fe=Kt(R)?R:null,lt=[];if(!(!k&&!Fe))return Fe&&(Fe.addEventListener("focusout",tt),Fe.addEventListener("pointerdown",ze),lt.push(()=>{Fe.removeEventListener("focusout",tt),Fe.removeEventListener("pointerdown",ze)})),k&&(k.addEventListener("focusin",We),k.addEventListener("focusout",tt),X&&(k.addEventListener("focusout",De,!0),lt.push(()=>{k.removeEventListener("focusout",De,!0)})),lt.push(()=>{k.removeEventListener("focusin",We),k.removeEventListener("focusout",tt)})),()=>{lt.forEach(Ne=>{Ne()})}},[n,R,k,pe,u,ne,X,S,d,l,ue,P,D,I,A,le,G,fe,h,m,ge]),x.useEffect(()=>{if(n||!k||!C)return;const we=Array.from(X?.portalNode?.querySelectorAll(`[${sd("portal")}]`)||[]),ze=(ne?zx(ne.nodesRef.current,D()):[]).find(lt=>Mx(lt.context?.elements.domReference||null))?.context?.elements.domReference,We=[k,...we,z.current,T.current,X?.beforeOutsideRef.current,X?.afterOutsideRef.current,...ge(),ze,Zn(m),Zn(h),P?R:null].filter(lt=>lt!=null),tt=lw(We,{ariaHidden:u||P,mark:!1}),De=[k,...we].filter(lt=>lt!=null),Fe=lw(De);return()=>{Fe(),tt()}},[C,n,R,k,u,I,X,P,ne,D,h,m,ge]),at(()=>{if(!C||n||!Kt(pe))return;const we=_t(pe),ze=$o(we);queueMicrotask(()=>{const We=qe(pe),tt=re.current,De=typeof tt=="function"?tt(ee.current||""):tt;if(De===void 0||De===!1)return;let Fe;De===!0||De===null?Fe=We[0]||pe:Fe=Zn(De),Fe=Fe||We[0]||pe,!st(pe,ze)&&sh(Fe,{preventScroll:Fe===pe})})},[n,C,pe,N,qe,re,ee]),at(()=>{if(n||!pe)return;const we=_t(pe),ze=$o(we);p2(ze);function We(De){if(De.open||(L.current=f2(De.nativeEvent,U.current)),De.reason===Cr&&De.nativeEvent.type==="mouseleave"&&(F.current=!0),De.reason===kk)if(De.nested)F.current=!1;else if(m6(De.nativeEvent)||g6(De.nativeEvent))F.current=!1;else{let Fe=!1;document.createElement("div").focus({get preventScroll(){return Fe=!0,!1}}),Fe?F.current=!1:F.current=!0}}$.on("openchange",We);function tt(){const De=Z.current;let Fe=typeof De=="function"?De(L.current):De;if(Fe===void 0||Fe===!1)return null;if(Fe===null&&(Fe=!0),typeof Fe=="boolean"){const Ne=R||ph();return Ne&&Ne.isConnected?Ne:null}const lt=R||ph();return Zn(Fe)||lt||null}return()=>{$.off("openchange",We);const De=$o(we),Fe=ge(),lt=st(k,De)||Fe.some(oe=>oe===De||st(oe,De))||ne&&oi(ne.nodesRef.current,D(),!1).some(oe=>st(oe.context?.elements.floating,De)),Ne=tt();queueMicrotask(()=>{const oe=h2(Ne),Se=typeof Z.current!="boolean";Z.current&&!F.current&&Kt(oe)&&(!(!Se&&oe!==De&&De!==we.body)||lt)&&oe.focus({preventScroll:!0}),F.current=!1})}},[n,k,pe,Z,A,$,ne,R,D,ge]),at(()=>{if(!ik||C||!k)return;const we=$o(_t(k));!Kt(we)||!iv(we)||st(k,we)&&we.blur()},[C,k]),at(()=>{if(!(n||!X))return X.setFocusManagerState({modal:u,closeOnFocusOut:d,open:C,onOpenChange:S.setOpen,domReference:R}),()=>{X.setFocusManagerState(null)}},[n,X,u,C,S,d,R]),at(()=>{if(!(n||!pe))return uw(pe,I),()=>{queueMicrotask(pv)}},[n,pe,I]);const Xe=!n&&(u?!P:!0)&&(be||u);return v.jsxs(x.Fragment,{children:[Xe&&v.jsx(qs,{"data-type":"inside",ref:M,onFocus:we=>{if(u){const ze=qe();sh(ze[ze.length-1])}else X?.portalNode&&(F.current=!1,Ps(we,X.portalNode)?dv(R)?.focus():Zn(m??X.beforeOutsideRef)?.focus())}}),r,Xe&&v.jsx(qs,{"data-type":"inside",ref:te,onFocus:we=>{u?sh(qe()[0]):X?.portalNode&&(d&&(F.current=!0),Ps(we,X.portalNode)?Hk(R)?.focus():Zn(h??X.afterOutsideRef)?.focus())}})]})}function v2(){return{...b6(),disabled:!1,modal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,nested:!1,openOnHover:!1,closeDelay:0,hasViewport:!1}}const y2={...x6,disabled:ct(e=>e.disabled),instantType:ct(e=>e.instantType),openMethod:ct(e=>e.openMethod),openChangeReason:ct(e=>e.openChangeReason),modal:ct(e=>e.modal),stickIfOpen:ct(e=>e.stickIfOpen),titleElementId:ct(e=>e.titleElementId),descriptionElementId:ct(e=>e.descriptionElementId),openOnHover:ct(e=>e.openOnHover),closeDelay:ct(e=>e.closeDelay),hasViewport:ct(e=>e.hasViewport)};let b2=class sR extends fk{constructor(t){const r={...v2(),...t};r.open&&t?.mounted===void 0&&(r.mounted=!0),super(r,{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),stickIfOpenTimeout:new li,triggerElements:new nv},y2)}setOpen=(t,r)=>{const n=r.reason===Cr,o=r.reason===Ws&&r.event.detail===0,a=!t&&(r.reason===Rk||r.reason==null);if(r.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},this.context.onOpenChange?.(t,r),r.isCanceled)return;const l={open:t,nativeEvent:r.event,reason:r.reason,nested:this.state.nested,triggerElement:r.trigger};this.state.floatingRootContext.context.events?.emit("openchange",l);const u=()=>{const d={open:t,openChangeReason:r.reason},p=r.trigger?.id??null;(p||t)&&(d.activeTriggerId=p,d.activeTriggerElement=r.trigger??null),this.update(d)};n?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(Tj,()=>{this.set("stickIfOpen",!1)}),Lr.flushSync(u)):u(),o||a?this.set("instantType",o?"click":"dismiss"):r.reason===El?this.set("instantType","focus"):this.set("instantType",void 0)};static useStore(t,r){const n=yn(()=>new sR(r)).current,o=t??n;return Dd(n.disposeEffect),o}disposeEffect=()=>this.context.stickIfOpenTimeout.disposeEffect()};const aR=x.createContext(void 0);function na(e){const t=x.useContext(aR);if(t===void 0&&!e)throw new Error(Uo(47));return t}function dw({props:e}){const{children:t,open:r,defaultOpen:n=!1,onOpenChange:o,onOpenChangeComplete:a,modal:l=!1,handle:u,triggerId:d,defaultTriggerId:p=null}=e,h=b2.useStore(u?.store,{modal:l,open:n,openProp:r,activeTriggerId:p,triggerIdProp:d});dj(()=>{r===void 0&&h.state.open===!1&&n===!0&&h.update({open:!0,activeTriggerId:p})}),h.useControlledProp("openProp",r),h.useControlledProp("triggerIdProp",d);const m=h.useState("open"),y=h.useState("positionerElement"),w=h.useState("payload"),E=h.useState("openChangeReason");h.useContextCallback("onOpenChange",o),h.useContextCallback("onOpenChangeComplete",a);const{openMethod:S,triggerProps:C}=Mj(m);A6(h);const{forceUnmount:R}=T6(m,h,()=>{h.update({stickIfOpen:!0,openChangeReason:null})});$j(m&&l===!0&&E!==Cr&&S!=="touch",y),x.useEffect(()=>{m||h.context.stickIfOpenTimeout.clear()},[h,m]);const k=x.useCallback(F=>{const V=zt(F);return V.preventUnmountOnClose=()=>{h.set("preventUnmountingOnClose",!0)},V},[h]),$=x.useCallback(()=>{h.setOpen(!1,k(O6))},[h,k]);x.useImperativeHandle(e.actionsRef,()=>({unmount:R,close:$}),[R,$]);const A=L6({popupStore:h,onOpenChange:h.setOpen}),D=j6(A,{outsidePressEvent:{mouse:l==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),N=z6(A),{getReferenceProps:P,getFloatingProps:I,getTriggerProps:re}=$k([D,N]),Z=x.useMemo(()=>P(C),[P,C]),ee=x.useMemo(()=>re(C),[re,C]),ne=x.useMemo(()=>I(),[I]);h.useSyncedValues({modal:l,openMethod:S,activeTriggerProps:Z,inactiveTriggerProps:ee,popupProps:ne,floatingRootContext:A,nested:Vo()!=null});const X=x.useMemo(()=>({store:h}),[h]);return v.jsx(aR.Provider,{value:X,children:typeof t=="function"?t({payload:w}):t})}function x2(e){return na(!0)?v.jsx(dw,{props:e}):v.jsx(E6,{children:v.jsx(dw,{props:e})})}const w2=300,S2=x.forwardRef(function(e,t){const{render:r,className:n,disabled:o=!1,nativeButton:a=!0,handle:l,payload:u,openOnHover:d=!1,delay:p=w2,closeDelay:h=0,id:m,...y}=e,w=na(!0),E=l?.store??w?.store;if(!E)throw new Error(Uo(74));const S=CM(m),C=E.useState("isTriggerActive",S),R=E.useState("floatingRootContext"),k=E.useState("isOpenedByTrigger",S),$=x.useRef(null),{registerTrigger:A,isMountedByThisTrigger:D}=$6(S,$,E,{payload:u,disabled:o,openOnHover:d,closeDelay:h}),N=E.useState("openChangeReason"),P=E.useState("stickIfOpen"),I=E.useState("openMethod"),re=OM(R,{enabled:R!=null&&d&&(I!=="touch"||N!==Ws),mouseOnly:!0,move:!1,handleClose:DM(),restMs:p,delay:{close:h},triggerElementRef:$,isActiveTrigger:C}),Z=jM(R,{enabled:R!=null,stickIfOpen:P}),ee=$k([Z]),ne=E.useState("triggerProps",D),X={disabled:o,open:k},{getButtonProps:F,buttonRef:V}=SM({disabled:o,native:a}),H=x.useMemo(()=>({open(T){return T&&N===Ws?lM.open(T):aM.open(T)}}),[N]),O=Al("button",e,{state:X,ref:[V,t,A,$],props:[ee.getReferenceProps(),re,ne,{[lk]:"",id:S},y,F],stateAttributesMapping:H}),L=x.useRef(null),U=et(T=>{Lr.flushSync(()=>{E.setOpen(!1,zt(El,T.nativeEvent,T.currentTarget))}),e4(L.current)?.focus()}),z=et(T=>{const M=E.select("positionerElement");if(M&&Ps(T,M))E.context.beforeContentFocusGuardRef.current?.focus();else{Lr.flushSync(()=>{E.setOpen(!1,zt(El,T.nativeEvent,T.currentTarget))});let te=ZM(E.context.triggerFocusTargetRef.current||$.current);for(;te!==null&&st(M,te);){const le=te;if(te=dv(te),te===le)break}te?.focus()}});return C?v.jsxs(x.Fragment,{children:[v.jsx(qs,{ref:L,onFocus:U}),v.jsx(x.Fragment,{children:O},S),v.jsx(qs,{ref:E.context.triggerFocusTargetRef,onFocus:z})]}):v.jsx(x.Fragment,{children:O},S)}),lR=x.createContext(void 0);function E2(){const e=x.useContext(lR);if(e===void 0)throw new Error(Uo(45));return e}const C2=x.forwardRef(function(e,t){const{keepMounted:r=!1,...n}=e,{store:o}=na();return o.useState("mounted")||r?v.jsx(lR.Provider,{value:r,children:v.jsx(i4,{ref:t,...n})}):null}),k2={...cv,...yk},R2=x.forwardRef(function(e,t){const{className:r,render:n,...o}=e,{store:a}=na(),l=a.useState("open"),u=a.useState("mounted"),d=a.useState("transitionStatus"),p=a.useState("openChangeReason");return Al("div",e,{state:{open:l,transitionStatus:d},ref:[a.context.backdropRef,t],props:[{role:"presentation",hidden:!u,style:{pointerEvents:p===Cr?"none":void 0,userSelect:"none",WebkitUserSelect:"none"}},o],stateAttributesMapping:k2})}),cR=x.createContext(void 0);function _2(){const e=x.useContext(cR);if(!e)throw new Error(Uo(46));return e}const $2=x.forwardRef(function(e,t){const{render:r,className:n,anchor:o,positionMethod:a="absolute",side:l="bottom",align:u="center",sideOffset:d=0,alignOffset:p=0,collisionBoundary:h="clipping-ancestors",collisionPadding:m=5,arrowPadding:y=5,sticky:w=!1,disableAnchorTracking:E=!1,collisionAvoidance:S=Ij,...C}=e,{store:R}=na(),k=E2(),$=w6(),A=R.useState("floatingRootContext"),D=R.useState("mounted"),N=R.useState("open"),P=R.useState("openChangeReason"),I=R.useState("activeTriggerElement"),re=R.useState("modal"),Z=R.useState("positionerElement"),ee=R.useState("instantType"),ne=R.useState("transitionStatus"),X=R.useState("hasViewport"),F=x.useRef(null),V=bk(Z,!1,!1),H=Z4({anchor:o,floatingRootContext:A,positionMethod:a,mounted:D,side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:y,collisionBoundary:h,collisionPadding:m,sticky:w,disableAnchorTracking:E,keepMounted:k,nodeId:$,collisionAvoidance:S,adaptiveOrigin:X?K4:void 0}),O=x.useMemo(()=>{const te={};return N||(te.pointerEvents="none"),{role:"presentation",hidden:!D,style:{...H.positionerStyles,...te}}},[N,D,H.positionerStyles]),L=x.useMemo(()=>({props:O,...H}),[O,H]),U=A.useState("domReferenceElement");at(()=>{const te=U,le=F.current;if(te&&(F.current=te),le&&te&&te!==le){R.set("instantType",void 0);const G=new AbortController;return V(()=>{R.set("instantType","trigger-change")},G.signal),()=>{G.abort()}}},[U,V,R]);const z={open:N,side:L.side,align:L.align,anchorHidden:L.anchorHidden,instant:ee},T=x.useCallback(te=>{R.set("positionerElement",te)},[R]),M=Al("div",e,{state:z,props:[L.props,iR(ne),C],ref:[t,T],stateAttributesMapping:cv});return v.jsxs(cR.Provider,{value:L,children:[D&&re===!0&&P!==Cr&&v.jsx(e2,{ref:R.context.internalBackdropRef,inert:o4(!N),cutout:I}),v.jsx(S6,{id:$,children:M})]})}),A2=x.createContext(void 0);function T2(){const[e,t]=x.useState(0),r=et(()=>(t(n=>n+1),()=>{t(n=>Math.max(0,n-1))}));return{context:x.useMemo(()=>({register:r}),[r]),hasClosePart:e>0}}function L2(e){const{value:t,children:r}=e;return v.jsx(A2.Provider,{value:t,children:r})}const I2={...cv,...yk},O2=x.forwardRef(function(e,t){const{className:r,render:n,initialFocus:o,finalFocus:a,...l}=e,{store:u}=na(),d=_2(),p=r2()!=null,{context:h,hasClosePart:m}=T2(),y=u.useState("open"),w=u.useState("openMethod"),E=u.useState("instantType"),S=u.useState("transitionStatus"),C=u.useState("popupProps"),R=u.useState("titleElementId"),k=u.useState("descriptionElementId"),$=u.useState("modal"),A=u.useState("mounted"),D=u.useState("openChangeReason"),N=u.useState("activeTriggerElement"),P=u.useState("floatingRootContext");xk({open:y,ref:u.context.popupRef,onComplete(){y&&u.context.onOpenChangeComplete?.(!0)}});const I=u.useState("disabled"),re=u.useState("openOnHover"),Z=u.useState("closeDelay");c2(P,{enabled:re&&!I,closeDelay:Z});function ee(O){return O==="touch"?u.context.popupRef.current:!0}const ne=o===void 0?ee:o,X={open:y,side:d.side,align:d.align,instant:E,transitionStatus:S},F=$!==!1&&m,V=x.useCallback(O=>{u.set("popupElement",O)},[u]),H=Al("div",e,{state:X,ref:[t,u.context.popupRef,V],props:[C,{"aria-labelledby":R,"aria-describedby":k,onKeyDown(O){p&&l2.has(O.key)&&O.stopPropagation()}},iR(S),l],stateAttributesMapping:I2});return v.jsx(g2,{context:P,openInteractionType:w,modal:F,disabled:!A||D===Cr,initialFocus:ne,returnFocus:a,restoreFocus:"popup",previousFocusableElement:Kt(N)?N:void 0,nextFocusableElement:u.context.triggerFocusTargetRef,beforeContentFocusGuardRef:u.context.beforeContentFocusGuardRef,children:v.jsx(L2,{value:h,children:H})})}),[N2,P2]=Cd("Popover"),D2=kr(["overflow-hidden rounded-md bg-canvas-sheet p-16 outline-none","shadow-xl","data-open:data-[side=top]:animate-slide-in-from-bottom","data-closed:data-[side=top]:animate-slide-out-to-bottom","data-open:data-[side=bottom]:animate-slide-in-from-top","data-closed:data-[side=bottom]:animate-slide-out-to-top","data-open:data-[side=left]:animate-slide-in-from-right","data-closed:data-[side=left]:animate-slide-out-to-right","data-open:data-[side=right]:animate-slide-in-from-left","data-closed:data-[side=right]:animate-slide-out-to-left"],{variants:{width:{fit:"",fixed:"w-400"}},defaultVariants:{width:"fit"}}),j2=Qt("fixed inset-0 z-dialog-overlay bg-canvas-overlay-subtle","data-open:animate-fade-in","data-closed:animate-fade-out"),M2=({open:e,defaultOpen:t,onOpenChange:r,overlay:n=!1,handle:o,children:a})=>v.jsx(N2,{value:{overlay:n},children:v.jsx(x2,{open:e,defaultOpen:t,onOpenChange:r,modal:n,handle:o,children:a})}),z2=({handle:e,payload:t,render:r,className:n,...o})=>v.jsx(S2,{"data-slot":"popover-trigger",handle:e,payload:t,render:r,className:Qt("data-popup-open:z-menu",n),...o}),F2=({side:e="bottom",sideOffset:t=8,align:r="start",width:n="fit",initialFocus:o=!1,className:a,children:l})=>{const{overlay:u}=P2({consumerName:"PopoverContent",contextRequired:!0});return v.jsxs(C2,{children:[u&&v.jsx(R2,{"data-slot":"popover-overlay",className:j2}),v.jsx($2,{"data-slot":"popover-positioner",className:"z-menu",side:e,sideOffset:t,align:r,children:v.jsx(O2,{"data-slot":"popover-content",initialFocus:o,className:Qt(D2({width:n}),a),children:l})})]})},B2=pt("ChevronLeft",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M9.333 5.333 6.667 8l2.666 2.667"})})),[U2,V2]=Cd("SegmentedControl"),W2=()=>V2({consumerName:"SegmentedControlButton",contextRequired:!0});function H2({ref:e,selectedIndex:t,children:r}){const[n,o]=x.useState({width:0,height:0,x:0}),[a,l]=x.useState(!1);return x.useLayoutEffect(()=>{const u=e.current;if(!u)return;const d=()=>{const h=Array.from(u.children).slice(0,-1),m=t>=0?h[t]:void 0;o({width:m?.offsetWidth??0,height:u.offsetHeight,x:m?.offsetLeft??0})};if(d(),typeof ResizeObserver>"u")return;const p=new ResizeObserver(d);return p.observe(u),()=>p.disconnect()},[r,t,e]),x.useEffect(()=>{const u=requestAnimationFrame(()=>{l(!0)});return()=>cancelAnimationFrame(u)},[]),{pill:n,isReady:a}}function q2(e,t){return x.useMemo(()=>x.Children.toArray(t).findIndex(r=>x.isValidElement(r)&&r.props.value===e),[e,t])}function G2(e){const{canScrollLeft:t,canScrollRight:r}=qD(e),n=x.useCallback(o=>{const a=e.current;if(!a)return;const l=a.clientWidth/2;a.scrollBy({left:o==="left"?-l:l,behavior:"smooth"})},[e]);return{canScrollLeft:t,canScrollRight:r,scrollBy:n}}function X2(e,t){x.useLayoutEffect(()=>{if(t<0)return;const r=e.current;if(!r)return;const n=r.querySelectorAll('button[role="radio"]')[t];if(n){const{offsetLeft:o,offsetWidth:a}=n,{clientWidth:l}=r;r.scrollLeft=o-(l-a)/2}},[])}const Ll={root:kr("relative flex-row items-center rounded-sm",{variants:{tabLayout:{fit:"inline-flex",fixed:"flex w-full"}}}),pill:kr("pointer-events-none absolute top-0 left-0 z-0 rounded-sm",{variants:{disabled:{true:"bg-base-transparent-pressed",false:"bg-muted-transparent"},isReady:{true:"transition-[transform,width] duration-250 ease-in-out",false:"transition-none"}}}),item:kr("z-10 flex cursor-pointer flex-row items-center justify-center rounded-sm px-16 py-8 select-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed",{variants:{selected:{true:"body-2-semi-bold",false:"body-2"},disabled:{true:"text-muted",false:""}},compoundVariants:[{selected:!0,disabled:!1,className:"text-base"},{selected:!1,disabled:!1,className:"text-muted hover:text-muted-hover"}]}),scrollArea:kr("relative rounded-sm",{variants:{appearance:{background:"bg-surface","no-background":"bg-transparent"},tabLayout:{fit:"",fixed:"w-full"}}}),arrow:kr("absolute inset-y-0 z-20 flex cursor-pointer items-center justify-center rounded-sm py-8 text-muted transition-opacity duration-200 hover:text-muted-hover",{variants:{visible:{true:"opacity-100",false:"pointer-events-none opacity-0"},side:{left:"left-0 pr-16 pl-8",right:"right-0 pr-8 pl-16"}}})};function Y2(e,t){return`linear-gradient(to right, ${e?"transparent 0px, transparent 40px, black 72px":"black 0px"}, ${t?"black calc(100% - 72px), transparent calc(100% - 40px), transparent 100%":"black 100%"})`}function fw({side:e,icon:t,visible:r,onClick:n}){return v.jsx("button",{type:"button","aria-hidden":!0,tabIndex:-1,disabled:!r,onClick:n,className:Ll.arrow({visible:r,side:e}),children:v.jsx(t,{size:20})})}function K2({appearance:e,tabLayout:t,className:r,selectedIndex:n,children:o,...a}){const l=x.useRef(null),{canScrollLeft:u,canScrollRight:d,scrollBy:p}=G2(l);X2(l,n);const h=u||d?Y2(u,d):void 0;return v.jsxs("div",{...a,className:Qt(Ll.scrollArea({appearance:e,tabLayout:t}),r),children:[v.jsx("div",{ref:l,className:"scrollbar-none overflow-x-auto",style:h?{maskImage:h,WebkitMaskImage:h}:void 0,children:o}),v.jsx(fw,{side:"left",icon:B2,visible:u,onClick:()=>p("left")}),v.jsx(fw,{side:"right",icon:Nd,visible:d,onClick:()=>p("right")})]})}function Q2({layout:e,isReady:t,disabled:r}){return v.jsx("div",{"aria-hidden":!0,className:Ll.pill({disabled:r,isReady:t}),style:{width:e.width,height:e.height,transform:`translateX(${e.x}px)`}})}function J2({tabLayout:e,disabled:t,selectedIndex:r,children:n}){const o=x.useRef(null),{pill:a,isReady:l}=H2({ref:o,selectedIndex:r,children:n});return v.jsxs("div",{ref:o,role:"radiogroup","aria-disabled":t,className:Ll.root({tabLayout:e}),children:[n,v.jsx(Q2,{layout:a,isReady:l,disabled:t})]})}function pw({value:e,children:t,icon:r,trailingContent:n,onClick:o,className:a,disabled:l,...u}){const{selectedValue:d,onSelectedChange:p,disabled:h,tabLayout:m}=W2(),y=d===e,w=x.useMemo(()=>!!(l||h),[l,h]);return v.jsx("button",{type:"button",role:"radio","aria-checked":y,"aria-disabled":w,disabled:w,onClick:E=>{w||(p(e),o?.(E))},className:Qt(Ll.item({selected:y,disabled:w}),m==="fixed"&&"min-w-0 flex-1",a),...u,children:v.jsxs("span",{className:"inline-flex min-w-0 items-center justify-center gap-8",children:[r&&v.jsx(r,{size:16,className:"shrink-0"}),v.jsx("span",{className:"min-w-0 truncate",children:t}),n]})})}function Z2({selectedValue:e,onSelectedChange:t,children:r,className:n,disabled:o,appearance:a="background",tabLayout:l="fixed",...u}){const d=Ks({consumerName:"SegmentedControl",mergeWith:{disabled:o}}),p=q2(e,r);return v.jsx(U2,{value:{selectedValue:e,onSelectedChange:h=>t(h),disabled:d,tabLayout:l},children:v.jsx(K2,{...u,appearance:a,tabLayout:l,className:n,selectedIndex:p,children:v.jsx(J2,{tabLayout:l,disabled:d,selectedIndex:p,children:r})})})}const e5={md:16,sm:12},yg=({icon:e,size:t="md",...r})=>{const n=e,o=e5[t];return v.jsx(nj,{...r,size:t,variant:"tag",consumerName:"Tag",leadingContent:n?v.jsx(n,{size:o}):void 0})},gd={light:"light",dark:"dark",system:"system"},t5=()=>window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",r5=e=>{const t=window.matchMedia("(prefers-color-scheme: dark)");return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},n5=()=>()=>{},i5=e=>{const t=e===gd.system;return x.useSyncExternalStore(t?r5:n5,t?t5:()=>e,()=>"light")},o5=e=>{x.useLayoutEffect(()=>{const t=window.document.documentElement;t.classList.remove(gd.light,gd.dark),t.classList.add(e)},[e])},[s5,a5]=Cd("ThemeProvider"),l5=({children:e,colorScheme:t=gd.system,locale:r})=>{const n=i5(t);o5(n);const o=x.useMemo(()=>({colorScheme:n}),[n]);return v.jsx(s5,{value:o,children:v.jsx(xO,{locale:r,children:e})})},c5=()=>a5({consumerName:"useTheme",contextRequired:!0}),u5=pt("ArrowDown",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 12.667V3.333m3.334 5.994-3.34 3.333-3.34-3.34"})})),uR=pt("ArrowUp",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 3.333v9.334m-3.334-6L8 3.327l3.333 3.333"})})),dR=pt("Copy",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M10 4v-.667C10 2.6 9.4 2 8.667 2H3.333C2.593 2 2 2.6 2 3.333v5.334C2 9.407 2.593 10 3.333 10H4m2-2.667v5.334C6 13.403 6.597 14 7.333 14h5.334c.736 0 1.333-.597 1.333-1.333V7.333C14 6.597 13.403 6 12.667 6H7.333C6.597 6 6 6.597 6 7.333"})})),d5=pt("Devices",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M6.667 14H3.333C2.593 14 2 13.4 2 12.667V3.333C2 2.593 2.593 2 3.333 2H10c.733 0 1.333.593 1.333 1.333v1.334m-.666 7.66H12M12.8 14H9.867a1.2 1.2 0 0 1-1.2-1.2V7.867c0-.667.533-1.2 1.2-1.2H12.8c.66 0 1.2.533 1.2 1.2V12.8c0 .66-.54 1.2-1.2 1.2"})})),fR=pt("Download",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M5.63 7.407 8 9.778l2.37-2.37M8 9.777V2.667m5.333 8.296a2.37 2.37 0 0 1-2.37 2.37H5.037a2.37 2.37 0 0 1-2.37-2.37"})})),pR=pt("Flex",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{fill:"currentColor",d:"M12.017 14v.65h1.3V14h-1.3m-9.334 0v.65h1.3V14h-1.3m2.817-.65h-.65v1.3h.65v-1.3m5 1.3h.65v-1.3h-.65v1.3m-5-1.967a.65.65 0 1 0 0 1.3v-1.3m5 1.3a.65.65 0 1 0 0-1.3v1.3m2.167.017h.65V6.667h-1.3V14zm0-7.333h.65v-2h-1.3v2zm0-2h.65V4h-1.3v.667zm-2-2.667v-.65H5.333v1.3h5.334zM3.333 4h-.65v10h1.3V4zm2-2v-.65A2.65 2.65 0 0 0 2.683 4h1.3c0-.746.605-1.35 1.35-1.35zm7.334 2h.65a2.65 2.65 0 0 0-2.65-2.65v1.3c.745 0 1.35.604 1.35 1.35zm0 .667v.65h.466v-1.3h-.466zm.6.133h-.65v1.733h1.3V4.8zm-.134 1.867v-.65h-.466v1.3h.466zm.134-.134h-.65c0-.285.231-.516.516-.516v1.3c.433 0 .784-.351.784-.784zm-.134-1.866v.65a.517.517 0 0 1-.516-.517h1.3a.783.783 0 0 0-.784-.783zM5.5 14v.65h5v-1.3h-5zm0-.667v.65h5v-1.3h-5z"})})),f5=pt("Moon",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M13.133 10c-1.666.533-3.6.2-4.933-1.133-1.667-1.667-1.8-4.334-.467-6.2C5 2.933 2.867 5.2 2.867 8c0 2.933 2.4 5.333 5.333 5.333 2.2 0 4.133-1.4 4.933-3.333",clipRule:"evenodd"})})),Vu=pt("Nano",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M11.333 11.944a.279.279 0 0 0 .556 0 .28.28 0 0 0-.278-.277.28.28 0 0 0-.278.283M6.172 8 3.236 5.064a.333.333 0 0 1 0-.471l2.357-2.357c.13-.13.341-.13.471 0L11.83 8m-9.536 6H12a2 2 0 1 0 0-4H2.293a.293.293 0 0 0-.293.293v3.414c0 .162.131.293.293.293"})})),hR=pt("NanoGen5",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M11 1.333c.92 0 1.667.747 1.667 1.667v.333c.184 0 .333.15.333.334v1.666a.334.334 0 0 1-.266.327l-.067.007V13c0 .92-.746 1.667-1.667 1.667H5c-.92 0-1.667-.746-1.667-1.667V3c0-.92.747-1.667 1.667-1.667zM9.667 12.667a.667.667 0 0 0 0 1.333H11a.667.667 0 0 0 0-1.333zM5 2.333A.667.667 0 0 0 4.333 3v8c0 .368.299.667.667.667h6a.667.667 0 0 0 .667-.667V3A.667.667 0 0 0 11 2.333z",clipRule:"evenodd"})})),p5=pt("Screens",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M5.332 1.998h5.336m-6.67 2.5h8.004m.233 9.505h-8.47a1.334 1.334 0 0 1-1.327-1.2l-.434-4.336A1.334 1.334 0 0 1 3.331 7h9.338a1.334 1.334 0 0 1 1.327 1.467l-.434 4.335a1.334 1.334 0 0 1-1.327 1.2"})})),h5=pt("Send",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 2v9.334M13.332 14H2.667m1.999-8.666L8 2l3.333 3.334"})})),hv=pt("SparksFill",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{fill:"currentColor",d:"M8 1.333a.333.333 0 0 0-.667 0v.223c0 .39-.145.76-.398 1.029A1.28 1.28 0 0 1 6 3a.333.333 0 1 0 0 .667c.346 0 .683.146.935.415.253.27.398.64.398 1.03v.221a.333.333 0 1 0 .667 0v-.222c0-.39.145-.76.398-1.029.252-.269.589-.415.935-.415a.333.333 0 1 0 0-.667c-.346 0-.683-.147-.935-.415A1.5 1.5 0 0 1 8 1.555zM12 5.267a.333.333 0 1 0-.667 0c0 .55-.213 1.077-.589 1.464a1.97 1.97 0 0 1-1.41.602.333.333 0 0 0 0 .667c.527 0 1.034.215 1.41.602s.59.914.59 1.465a.333.333 0 0 0 .666 0c0-.551.213-1.078.59-1.465A1.97 1.97 0 0 1 14 8a.333.333 0 0 0 0-.667 1.97 1.97 0 0 1-1.41-.602A2.1 2.1 0 0 1 12 5.267M6 7.333a.333.333 0 0 0-.667 0A3.333 3.333 0 0 1 2 10.667a.333.333 0 1 0 0 .666 3.333 3.333 0 0 1 3.333 3.334.333.333 0 0 0 .667 0 3.334 3.334 0 0 1 3.333-3.334.333.333 0 1 0 0-.666A3.333 3.333 0 0 1 6 7.333"})})),mR=pt("Stax",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",d:"M12 4.667h.467c.073 0 .133.06.133.133v1.733c0 .074-.06.134-.133.134H12M4.333 14h6.334c.736 0 1.333-.597 1.333-1.333V3.333C12 2.597 11.403 2 10.667 2H4.333A.333.333 0 0 0 4 2.333v11.334c0 .184.15.333.333.333Z"})})),m5=pt("Sun",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 2.667V1.333m0 13.334v-1.334m4.24-9.573.473-.473m-9.426 9.426.473-.473M13.333 8h1.334M1.333 8h1.334m9.573 4.24.473.473M3.287 3.287l.473.473m6.597 1.883a3.333 3.333 0 1 1-4.714 4.714 3.333 3.333 0 0 1 4.714-4.714"})})),gR=pt("Trash",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M12.333 4.333v8.334A1.333 1.333 0 0 1 11 14H5a1.334 1.334 0 0 1-1.333-1.333V4.333m9.666 0H2.667m6.666 7v-4m-2.666 4v-4m-1-3V3a1 1 0 0 1 1-1h2.666a1 1 0 0 1 1 1v1"})})),g5=pt("Unlink",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"m11.403 8.36 1.458-1.458a2.75 2.75 0 0 0-3.889-3.89L7.514 4.472M5.5 10.374l1.25-1.25m2.5-2.5 1.25-1.25m2.187 7.187L3.313 3.187m1.284 4.201L3.139 8.846a2.75 2.75 0 1 0 3.889 3.89l1.458-1.459"})})),vt=({label:e,side:t="top",className:r="",children:n})=>v.jsxs(GC,{children:[v.jsx(XC,{asChild:!0,children:v.jsx("span",{className:`flex ${r}`,children:n})}),v.jsx(YC,{side:t,children:e})]}),vR=x.createContext(null),bg=x.createContext(!0),yR=x.createContext(!0),bR="AI debugging is not available here yet. Use the DevTools desktop app.",xR=({label:e,detail:t,onClear:r,onExplain:n})=>{const o=x.useContext(vR),a=x.useContext(bg),l=x.useContext(yR);if(!a)return null;const u=v.jsxs("button",{type:"button",onClick:n,disabled:!l,className:"flex cursor-pointer items-center gap-6 rounded-sm bg-accent px-12 py-6 body-3-semi-bold text-on-accent hover:bg-accent-hover disabled:pointer-events-none disabled:bg-muted-transparent disabled:text-disabled",children:[v.jsx(hv,{size:16}),"Explain with AI"]}),d=v.jsxs("div",{className:"flex shrink-0 items-center gap-10 border-t border-muted-subtle bg-surface px-12 py-8",children:[v.jsx("span",{className:"body-3-semi-bold",children:e}),v.jsx("span",{className:"truncate body-4 text-muted",children:t}),v.jsx("span",{className:"flex-1"}),v.jsx("button",{type:"button",onClick:r,className:"cursor-pointer rounded-sm bg-muted-transparent px-12 py-6 body-3-semi-bold hover:bg-muted-transparent-hover",children:"Clear"}),l?u:v.jsx(vt,{label:bR,children:u})]});return o?Lr.createPortal(d,o):d};var Di=(e=>(e.logs="logs",e.inspector="inspector",e))(Di||{});const v5=({size:e=16,className:t})=>v.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4","aria-hidden":"true",className:t,children:[v.jsx("rect",{x:"2",y:"2.5",width:"12",height:"11",rx:"1.5"}),v.jsx("path",{d:"M6 2.5v11"})]}),hw=({connected:e})=>v.jsx("span",{className:`size-8 shrink-0 rounded-full ${e?"bg-(--color-light-green-500)":"bg-(--color-light-yellow-500)"}`,title:e?"Connected":"Not connected"}),y5=({currentScreen:e,onScreenChange:t,aiOpen:r,onToggleAi:n,aiAvailable:o,sessions:a,liveScreen:l,isLoggerConnected:u,isInspectorConnected:d,mockServerWebsiteUrl:p,colorScheme:h,onColorSchemeChange:m})=>{const y=h==="dark"?"light":"dark";return v.jsxs("div",{className:"flex shrink-0 items-center gap-16 border-b border-muted-subtle px-12 py-8",children:[v.jsxs(Z2,{selectedValue:e,onSelectedChange:w=>t(w),tabLayout:"fixed",className:"w-256 shrink-0 bg-muted-transparent","aria-label":"Screen",children:[v.jsx(pw,{value:"logs",trailingContent:v.jsx(hw,{connected:u}),children:"Logger"}),v.jsx(pw,{value:"inspector",trailingContent:v.jsx(hw,{connected:d}),children:"Inspector"})]}),v.jsxs("div",{className:"ml-auto flex items-center gap-6",children:[a&&v.jsx(vt,{label:a.shown?"Hide the sessions menu":"Show the sessions menu",side:"bottom",children:v.jsx(sr,{"aria-label":a.shown?"Hide the sessions menu":"Show the sessions menu","aria-pressed":a.shown,icon:v5,size:"xs",appearance:"transparent",className:`rounded-sm ${a.shown?"bg-active-subtle [&>svg]:text-active":""}`,onClick:a.onToggle})}),l&&v.jsx(vt,{label:l.shown?"Hide the live screen":"Show the live screen",side:"bottom",children:v.jsx(sr,{"aria-label":l.shown?"Hide the live screen":"Show the live screen","aria-pressed":l.shown,icon:p5,size:"xs",appearance:"transparent",className:`rounded-sm ${l.shown?"bg-active-subtle [&>svg]:text-active":""}`,onClick:l.onToggle})}),v.jsx(vt,{label:o?r?"Hide the AI panel":"Show the AI panel":bR,side:"bottom",children:v.jsx(sr,{"aria-label":r?"Hide the AI panel":"Show the AI panel","aria-pressed":r,icon:hv,size:"xs",appearance:"transparent",className:`rounded-sm disabled:pointer-events-none ${r?"bg-active-subtle [&>svg]:text-active":""}`,onClick:n,disabled:!o})}),p&&v.jsx(vt,{label:"Open the mock server website",side:"bottom",children:v.jsx(sr,{"aria-label":"Open the mock server website",icon:tj,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:()=>window.open(p,"_blank","noopener")})}),v.jsx(vt,{label:`Switch to ${y} theme`,side:"bottom",children:v.jsx(sr,{"aria-label":`Switch to ${y} theme`,icon:h==="dark"?m5:f5,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:()=>m(y)})})]})]})},Es={CONNECTED_DEVICES_UPDATE:"connectedDevicesUpdate",DEVICE_SESSION_STATE_UPDATE:"deviceSessionStateUpdate",PROVIDER_VALUE:"providerValue",APDU_RESPONSE:"apduResponse",DISCOVERED_DEVICES_UPDATE:"discoveredDevicesUpdate",MOCK_SERVER_CONFIG:"mockServerConfig"},zi={SEND_APDU:"sendApdu",GET_PROVIDER:"getProvider",SET_PROVIDER:"setProvider",START_LISTENING_DEVICES:"startListeningDevices",STOP_LISTENING_DEVICES:"stopListeningDevices",START_DISCOVERING:"startDiscovering",STOP_DISCOVERING:"stopDiscovering",CONNECT_DEVICE:"connectDevice"},mw={LOGGER:"logger",DMK_INSPECTOR:"dmk-inspector"},b5="moduleConnected";var gw;(function(e){(function(t){var r=typeof globalThis=="object"?globalThis:typeof self=="object"||typeof self=="object"?self:typeof this=="object"?this:u(),n=o(e);typeof r.Reflect<"u"&&(n=o(r.Reflect,n)),t(n,r),typeof r.Reflect>"u"&&(r.Reflect=e);function o(d,p){return function(h,m){Object.defineProperty(d,h,{configurable:!0,writable:!0,value:m}),p&&p(h,m)}}function a(){try{return Function("return this;")()}catch{}}function l(){try{return(0,eval)("(function() { return this; })()")}catch{}}function u(){return a()||l()}})(function(t,r){var n=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",a=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",l=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",u=typeof Object.create=="function",d={__proto__:[]}instanceof Array,p=!u&&!d,h={create:u?function(){return rt(Object.create(null))}:d?function(){return rt({__proto__:null})}:function(){return rt({})},has:p?function(q,Q){return n.call(q,Q)}:function(q,Q){return Q in q},get:p?function(q,Q){return n.call(q,Q)?q[Q]:void 0}:function(q,Q){return q[Q]}},m=Object.getPrototypeOf(Function),y=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:jt(),w=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Vt(),E=typeof WeakMap=="function"?WeakMap:bt(),S=o?Symbol.for("@reflect-metadata:registry"):void 0,C=Je(),R=ht(C);function k(q,Q,ie,se){if(M(ie)){if(!qe(q))throw new TypeError;if(!we(Q))throw new TypeError;return ne(q,Q)}else{if(!qe(q))throw new TypeError;if(!G(Q))throw new TypeError;if(!G(se)&&!M(se)&&!te(se))throw new TypeError;return te(se)&&(se=void 0),ie=ge(ie),X(q,Q,ie,se)}}t("decorate",k);function $(q,Q){function ie(se,Ce){if(!G(se))throw new TypeError;if(!M(Ce)&&!ze(Ce))throw new TypeError;L(q,Q,se,Ce)}return ie}t("metadata",$);function A(q,Q,ie,se){if(!G(ie))throw new TypeError;return M(se)||(se=ge(se)),L(q,Q,ie,se)}t("defineMetadata",A);function D(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),F(q,Q,ie)}t("hasMetadata",D);function N(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),V(q,Q,ie)}t("hasOwnMetadata",N);function P(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),H(q,Q,ie)}t("getMetadata",P);function I(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),O(q,Q,ie)}t("getOwnMetadata",I);function re(q,Q){if(!G(q))throw new TypeError;return M(Q)||(Q=ge(Q)),U(q,Q)}t("getMetadataKeys",re);function Z(q,Q){if(!G(q))throw new TypeError;return M(Q)||(Q=ge(Q)),z(q,Q)}t("getOwnMetadataKeys",Z);function ee(q,Q,ie){if(!G(Q))throw new TypeError;if(M(ie)||(ie=ge(ie)),!G(Q))throw new TypeError;M(ie)||(ie=ge(ie));var se=Ut(Q,ie,!1);return M(se)?!1:se.OrdinaryDeleteMetadata(q,Q,ie)}t("deleteMetadata",ee);function ne(q,Q){for(var ie=q.length-1;ie>=0;--ie){var se=q[ie],Ce=se(Q);if(!M(Ce)&&!te(Ce)){if(!we(Ce))throw new TypeError;Q=Ce}}return Q}function X(q,Q,ie,se){for(var Ce=q.length-1;Ce>=0;--Ce){var Ve=q[Ce],Ke=Ve(Q,ie,se);if(!M(Ke)&&!te(Ke)){if(!G(Ke))throw new TypeError;se=Ke}}return se}function F(q,Q,ie){var se=V(q,Q,ie);if(se)return!0;var Ce=oe(Q);return te(Ce)?!1:F(q,Ce,ie)}function V(q,Q,ie){var se=Ut(Q,ie,!1);return M(se)?!1:pe(se.OrdinaryHasOwnMetadata(q,Q,ie))}function H(q,Q,ie){var se=V(q,Q,ie);if(se)return O(q,Q,ie);var Ce=oe(Q);if(!te(Ce))return H(q,Ce,ie)}function O(q,Q,ie){var se=Ut(Q,ie,!1);if(!M(se))return se.OrdinaryGetOwnMetadata(q,Q,ie)}function L(q,Q,ie,se){var Ce=Ut(ie,se,!0);Ce.OrdinaryDefineOwnMetadata(q,Q,ie,se)}function U(q,Q){var ie=z(q,Q),se=oe(q);if(se===null)return ie;var Ce=U(se,Q);if(Ce.length<=0)return ie;if(ie.length<=0)return Ce;for(var Ve=new w,Ke=[],Pe=0,he=ie;Pe<he.length;Pe++){var ve=he[Pe],ye=Ve.has(ve);ye||(Ve.add(ve),Ke.push(ve))}for(var xe=0,Ue=Ce;xe<Ue.length;xe++){var ve=Ue[xe],ye=Ve.has(ve);ye||(Ve.add(ve),Ke.push(ve))}return Ke}function z(q,Q){var ie=Ut(q,Q,!1);return ie?ie.OrdinaryOwnMetadataKeys(q,Q):[]}function T(q){if(q===null)return 1;switch(typeof q){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return q===null?1:6;default:return 6}}function M(q){return q===void 0}function te(q){return q===null}function le(q){return typeof q=="symbol"}function G(q){return typeof q=="object"?q!==null:typeof q=="function"}function fe(q,Q){switch(T(q)){case 0:return q;case 1:return q;case 2:return q;case 3:return q;case 4:return q;case 5:return q}var ie="string",se=tt(q,a);if(se!==void 0){var Ce=se.call(q,ie);if(G(Ce))throw new TypeError;return Ce}return be(q)}function be(q,Q){var ie,se,Ce;{var Ve=q.toString;if(Xe(Ve)){var se=Ve.call(q);if(!G(se))return se}var ie=q.valueOf;if(Xe(ie)){var se=ie.call(q);if(!G(se))return se}}throw new TypeError}function pe(q){return!!q}function ue(q){return""+q}function ge(q){var Q=fe(q);return le(Q)?Q:ue(Q)}function qe(q){return Array.isArray?Array.isArray(q):q instanceof Object?q instanceof Array:Object.prototype.toString.call(q)==="[object Array]"}function Xe(q){return typeof q=="function"}function we(q){return typeof q=="function"}function ze(q){switch(T(q)){case 3:return!0;case 4:return!0;default:return!1}}function We(q,Q){return q===Q||q!==q&&Q!==Q}function tt(q,Q){var ie=q[Q];if(ie!=null){if(!Xe(ie))throw new TypeError;return ie}}function De(q){var Q=tt(q,l);if(!Xe(Q))throw new TypeError;var ie=Q.call(q);if(!G(ie))throw new TypeError;return ie}function Fe(q){return q.value}function lt(q){var Q=q.next();return Q.done?!1:Q}function Ne(q){var Q=q.return;Q&&Q.call(q)}function oe(q){var Q=Object.getPrototypeOf(q);if(typeof q!="function"||q===m||Q!==m)return Q;var ie=q.prototype,se=ie&&Object.getPrototypeOf(ie);if(se==null||se===Object.prototype)return Q;var Ce=se.constructor;return typeof Ce!="function"||Ce===q?Q:Ce}function Se(){var q;!M(S)&&typeof r.Reflect<"u"&&!(S in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(q=Bt(r.Reflect));var Q,ie,se,Ce=new E,Ve={registerProvider:Ke,getProvider:he,setProvider:ye};return Ve;function Ke(xe){if(!Object.isExtensible(Ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case q===xe:break;case M(Q):Q=xe;break;case Q===xe:break;case M(ie):ie=xe;break;case ie===xe:break;default:se===void 0&&(se=new w),se.add(xe);break}}function Pe(xe,Ue){if(!M(Q)){if(Q.isProviderFor(xe,Ue))return Q;if(!M(ie)){if(ie.isProviderFor(xe,Ue))return Q;if(!M(se))for(var Ze=De(se);;){var dt=lt(Ze);if(!dt)return;var Wt=Fe(dt);if(Wt.isProviderFor(xe,Ue))return Ne(Ze),Wt}}}if(!M(q)&&q.isProviderFor(xe,Ue))return q}function he(xe,Ue){var Ze=Ce.get(xe),dt;return M(Ze)||(dt=Ze.get(Ue)),M(dt)&&(dt=Pe(xe,Ue),M(dt)||(M(Ze)&&(Ze=new y,Ce.set(xe,Ze)),Ze.set(Ue,dt))),dt}function ve(xe){if(M(xe))throw new TypeError;return Q===xe||ie===xe||!M(se)&&se.has(xe)}function ye(xe,Ue,Ze){if(!ve(Ze))throw new Error("Metadata provider not registered.");var dt=he(xe,Ue);if(dt!==Ze){if(!M(dt))return!1;var Wt=Ce.get(xe);M(Wt)&&(Wt=new y,Ce.set(xe,Wt)),Wt.set(Ue,Ze)}return!0}}function Je(){var q;return!M(S)&&G(r.Reflect)&&Object.isExtensible(r.Reflect)&&(q=r.Reflect[S]),M(q)&&(q=Se()),!M(S)&&G(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,S,{enumerable:!1,configurable:!1,writable:!1,value:q}),q}function ht(q){var Q=new E,ie={isProviderFor:function(ve,ye){var xe=Q.get(ve);return M(xe)?!1:xe.has(ye)},OrdinaryDefineOwnMetadata:Ke,OrdinaryHasOwnMetadata:Ce,OrdinaryGetOwnMetadata:Ve,OrdinaryOwnMetadataKeys:Pe,OrdinaryDeleteMetadata:he};return C.registerProvider(ie),ie;function se(ve,ye,xe){var Ue=Q.get(ve),Ze=!1;if(M(Ue)){if(!xe)return;Ue=new y,Q.set(ve,Ue),Ze=!0}var dt=Ue.get(ye);if(M(dt)){if(!xe)return;if(dt=new y,Ue.set(ye,dt),!q.setProvider(ve,ye,ie))throw Ue.delete(ye),Ze&&Q.delete(ve),new Error("Wrong provider for target.")}return dt}function Ce(ve,ye,xe){var Ue=se(ye,xe,!1);return M(Ue)?!1:pe(Ue.has(ve))}function Ve(ve,ye,xe){var Ue=se(ye,xe,!1);if(!M(Ue))return Ue.get(ve)}function Ke(ve,ye,xe,Ue){var Ze=se(xe,Ue,!0);Ze.set(ve,ye)}function Pe(ve,ye){var xe=[],Ue=se(ve,ye,!1);if(M(Ue))return xe;for(var Ze=Ue.keys(),dt=De(Ze),Wt=0;;){var Zr=lt(dt);if(!Zr)return xe.length=Wt,xe;var en=Fe(Zr);try{xe[Wt]=en}catch(pi){try{Ne(dt)}finally{throw pi}}Wt++}}function he(ve,ye,xe){var Ue=se(ye,xe,!1);if(M(Ue)||!Ue.delete(ve))return!1;if(Ue.size===0){var Ze=Q.get(ye);M(Ze)||(Ze.delete(xe),Ze.size===0&&Q.delete(Ze))}return!0}}function Bt(q){var Q=q.defineMetadata,ie=q.hasOwnMetadata,se=q.getOwnMetadata,Ce=q.getOwnMetadataKeys,Ve=q.deleteMetadata,Ke=new E,Pe={isProviderFor:function(he,ve){var ye=Ke.get(he);return!M(ye)&&ye.has(ve)?!0:Ce(he,ve).length?(M(ye)&&(ye=new w,Ke.set(he,ye)),ye.add(ve),!0):!1},OrdinaryDefineOwnMetadata:Q,OrdinaryHasOwnMetadata:ie,OrdinaryGetOwnMetadata:se,OrdinaryOwnMetadataKeys:Ce,OrdinaryDeleteMetadata:Ve};return Pe}function Ut(q,Q,ie){var se=C.getProvider(q,Q);if(!M(se))return se;if(ie){if(C.setProvider(q,Q,R))return R;throw new Error("Illegal state.")}}function jt(){var q={},Q=[],ie=(function(){function Pe(he,ve,ye){this._index=0,this._keys=he,this._values=ve,this._selector=ye}return Pe.prototype["@@iterator"]=function(){return this},Pe.prototype[l]=function(){return this},Pe.prototype.next=function(){var he=this._index;if(he>=0&&he<this._keys.length){var ve=this._selector(this._keys[he],this._values[he]);return he+1>=this._keys.length?(this._index=-1,this._keys=Q,this._values=Q):this._index++,{value:ve,done:!1}}return{value:void 0,done:!0}},Pe.prototype.throw=function(he){throw this._index>=0&&(this._index=-1,this._keys=Q,this._values=Q),he},Pe.prototype.return=function(he){return this._index>=0&&(this._index=-1,this._keys=Q,this._values=Q),{value:he,done:!0}},Pe})(),se=(function(){function Pe(){this._keys=[],this._values=[],this._cacheKey=q,this._cacheIndex=-2}return Object.defineProperty(Pe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Pe.prototype.has=function(he){return this._find(he,!1)>=0},Pe.prototype.get=function(he){var ve=this._find(he,!1);return ve>=0?this._values[ve]:void 0},Pe.prototype.set=function(he,ve){var ye=this._find(he,!0);return this._values[ye]=ve,this},Pe.prototype.delete=function(he){var ve=this._find(he,!1);if(ve>=0){for(var ye=this._keys.length,xe=ve+1;xe<ye;xe++)this._keys[xe-1]=this._keys[xe],this._values[xe-1]=this._values[xe];return this._keys.length--,this._values.length--,We(he,this._cacheKey)&&(this._cacheKey=q,this._cacheIndex=-2),!0}return!1},Pe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=q,this._cacheIndex=-2},Pe.prototype.keys=function(){return new ie(this._keys,this._values,Ce)},Pe.prototype.values=function(){return new ie(this._keys,this._values,Ve)},Pe.prototype.entries=function(){return new ie(this._keys,this._values,Ke)},Pe.prototype["@@iterator"]=function(){return this.entries()},Pe.prototype[l]=function(){return this.entries()},Pe.prototype._find=function(he,ve){if(!We(this._cacheKey,he)){this._cacheIndex=-1;for(var ye=0;ye<this._keys.length;ye++)if(We(this._keys[ye],he)){this._cacheIndex=ye;break}}return this._cacheIndex<0&&ve&&(this._cacheIndex=this._keys.length,this._keys.push(he),this._values.push(void 0)),this._cacheIndex},Pe})();return se;function Ce(Pe,he){return Pe}function Ve(Pe,he){return he}function Ke(Pe,he){return[Pe,he]}}function Vt(){var q=(function(){function Q(){this._map=new y}return Object.defineProperty(Q.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),Q.prototype.has=function(ie){return this._map.has(ie)},Q.prototype.add=function(ie){return this._map.set(ie,ie),this},Q.prototype.delete=function(ie){return this._map.delete(ie)},Q.prototype.clear=function(){this._map.clear()},Q.prototype.keys=function(){return this._map.keys()},Q.prototype.values=function(){return this._map.keys()},Q.prototype.entries=function(){return this._map.entries()},Q.prototype["@@iterator"]=function(){return this.keys()},Q.prototype[l]=function(){return this.keys()},Q})();return q}function bt(){var q=16,Q=h.create(),ie=se();return(function(){function he(){this._key=se()}return he.prototype.has=function(ve){var ye=Ce(ve,!1);return ye!==void 0?h.has(ye,this._key):!1},he.prototype.get=function(ve){var ye=Ce(ve,!1);return ye!==void 0?h.get(ye,this._key):void 0},he.prototype.set=function(ve,ye){var xe=Ce(ve,!0);return xe[this._key]=ye,this},he.prototype.delete=function(ve){var ye=Ce(ve,!1);return ye!==void 0?delete ye[this._key]:!1},he.prototype.clear=function(){this._key=se()},he})();function se(){var he;do he="@@WeakMap@@"+Pe();while(h.has(Q,he));return Q[he]=!0,he}function Ce(he,ve){if(!n.call(he,ie)){if(!ve)return;Object.defineProperty(he,ie,{value:h.create()})}return he[ie]}function Ve(he,ve){for(var ye=0;ye<ve;++ye)he[ye]=Math.random()*255|0;return he}function Ke(he){if(typeof Uint8Array=="function"){var ve=new Uint8Array(he);return typeof crypto<"u"?crypto.getRandomValues(ve):typeof msCrypto<"u"?msCrypto.getRandomValues(ve):Ve(ve,he),ve}return Ve(new Array(he),he)}function Pe(){var he=Ke(q);he[6]=he[6]&79|64,he[8]=he[8]&191|128;for(var ve="",ye=0;ye<q;++ye){var xe=he[ye];(ye===4||ye===6||ye===8)&&(ve+="-"),xe<16&&(ve+="0"),ve+=xe.toString(16).toLowerCase()}return ve}}function rt(q){return q.__=void 0,delete q.__,q}})})(gw||(gw={}));let x5=class{cla;ins;p1;p2;data;constructor(t,r,n,o,a){this.cla=t,this.ins=r,this.p1=n,this.p2=o,this.data=a??new Uint8Array}getRawApdu(){const t=Uint8Array.from([this.cla,this.ins,this.p1,this.p2,this.data.length]),r=new Uint8Array(t.length+this.data.length);return r.set(t,0),this.data.length>0&&r.set(this.data,t.length),r}};function vw(e){if(e.startsWith("0x")&&(e=e.slice(2)),e.length===0)return new Uint8Array;if(e.length%2!==0&&(e="0"+e),/^[0-9a-fA-F]*$/.test(e)===!1)return null;const t=e.match(/.{1,2}/g)?.map(r=>parseInt(r,16));return!t||t.some(isNaN)?null:new Uint8Array(t)}function si(e,t=!0){return`${t?"0x":""}${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`}let hh=class{_tag="ValueOverflow";originalError;message;constructor(t,r=wR){this.message=`Value overflow for ${t}, max is ${r}`}},$u=class{_tag="DataOverflow";message;originalError;constructor(t,r=0){this.message=r===0?`this.data is already full (value: ${t})`:`this.data will overflow with "${t}", remaining bytes: ${r}`}},yw=class{_tag="HexaString";message;originalError;constructor(t){this.message=`Invalid encoded hexa string or length is null: ${t}`}};const w5=4294967295;let S5=class{constructor(t=w5){this.maxPayloadSize=t}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=t=>this.addNumberToData(t,8n,!1,!1);add16BitUIntToData=(t,r=!0)=>this.addNumberToData(t,16n,!1,r);add32BitUIntToData=(t,r=!0)=>this.addNumberToData(t,32n,!1,r);add64BitUIntToData=(t,r=!0)=>this.addNumberToData(t,64n,!1,r);add128BitUIntToData=(t,r=!0)=>this.addNumberToData(t,128n,!1,r);add256BitUIntToData=(t,r=!0)=>this.addNumberToData(t,256n,!1,r);add16BitIntToData=(t,r=!0)=>this.addNumberToData(t,16n,!0,r);add32BitIntToData=(t,r=!0)=>this.addNumberToData(t,32n,!0,r);add64BitIntToData=(t,r=!0)=>this.addNumberToData(t,64n,!0,r);add128BitIntToData=(t,r=!0)=>this.addNumberToData(t,128n,!0,r);add256BitIntToData=(t,r=!0)=>this.addNumberToData(t,256n,!0,r);addBufferToData=t=>this.hasEnoughLengthRemaining(t)?(this.data=Uint8Array.from([...this.data,...t]),this):(this.errors.push(new $u(t.toString())),this);addHexaStringToData=t=>{const r=vw(t);return r===null||r.length===0?(this.errors.push(new yw(t)),this):(this.addBufferToData(r),this)};addAsciiStringToData=t=>{const r=new TextEncoder().encode(t);return this.addBufferToData(r),this};encodeInLVFromHexa=t=>{const r=vw(t);return r===null||r.length===0?(this.errors.push(new yw(t)),this):this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addBufferToData(r),this):(this.errors.push(new $u(t)),this)};encodeInLVFromBuffer=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addBufferToData(t),this):(this.errors.push(new $u(t.toString())),this);encodeInLVFromAscii=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addAsciiStringToData(t),this):(this.errors.push(new $u(t)),this);encodeInTLVFromAscii=(t,r)=>(this.add8BitUIntToData(t),this.encodeInLVFromAscii(r));encodeInTLVFromHexa=(t,r)=>(this.add8BitUIntToData(t),this.encodeInLVFromHexa(r));encodeInTLVFromBuffer=(t,r)=>(this.add8BitUIntToData(t),this.encodeInLVFromBuffer(r));encodeInTLVFromUInt8=(t,r)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(1),this.add8BitUIntToData(r));encodeInTLVFromUInt16=(t,r,n=!0)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(2),this.add16BitUIntToData(r,n));encodeInTLVFromUInt32=(t,r,n=!0)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(4),this.add32BitUIntToData(r,n));encodeInTLVFromUInt64=(t,r,n=!0)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(8),this.add64BitUIntToData(r,n));getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(t,r=!1)=>this.data.length+t.length+(r?1:0)<=this.maxPayloadSize;addNumberToData(t,r,n,o){let a=this.checkBoundsAndConvert(t,r,n);if(a===void 0)return this;const l=Number(r)/8,u=new Uint8Array(l);if(o)for(let d=l-1;d>=0;d--)u[d]=Number(a&0xffn),a>>=8n;else for(let d=0;d<l;d++)u[d]=Number(a&0xffn),a>>=8n;return this.addBufferToData(u)}checkBoundsAndConvert(t,r,n){if(typeof t=="number"){if(!Number.isInteger(t)||t>Number.MAX_SAFE_INTEGER){this.errors.push(new hh(t.toString()));return}t=BigInt(t)}if(n){const o=1n<<r-1n;if(t>=o||t<-o){this.errors.push(new hh(t.toString(),o-1n));return}if(t<0n){const a=(1n<<r)-1n;t=-t,t=(~t&a)+1n}}else{const o=1n<<r;if(t<0||t>=o){this.errors.push(new hh(t.toString(),o-1n));return}}return t}};const wR=255;let SR=class{_ins;_cla;_p1;p2;data=new S5(wR);constructor({ins:t,cla:r,p1:n,p2:o}){this._cla=r&255,this._ins=t&255,this._p1=n&255,this.p2=o&255}build=()=>new x5(this._cla,this._ins,this._p1,this.p2,this.data.build());add8BitUIntToData=t=>(this.data.add8BitUIntToData(t),this);add16BitUIntToData=t=>(this.data.add16BitUIntToData(t),this);add32BitUIntToData=t=>(this.data.add32BitUIntToData(t),this);add64BitUIntToData=(t,r=!0)=>(this.data.add64BitUIntToData(t,r),this);addBufferToData=t=>(this.data.addBufferToData(t),this);addHexaStringToData=t=>(this.data.addHexaStringToData(t),this);addAsciiStringToData=t=>(this.data.addAsciiStringToData(t),this);encodeInLVFromHexa=t=>(this.data.encodeInLVFromHexa(t),this);encodeInLVFromBuffer=t=>(this.data.encodeInLVFromBuffer(t),this);encodeInLVFromAscii=t=>(this.data.encodeInLVFromAscii(t),this);getAvailablePayloadLength=()=>this.data.getAvailablePayloadLength();getErrors=()=>this.data.getErrors()},E5=class{constructor(t){this.buffer=t}index=0;testMinimalLength(t){return t<=this.buffer.length-this.index}extract8BitUInt(){if(!this.outOfRange(1))return this.buffer[this.index++]}extract16BitUInt(t=!0){const r=this.extractNumber(16n,!1,t);return r===void 0?void 0:Number(r)}extract16BitInt(t=!0){const r=this.extractNumber(16n,!0,t);return r===void 0?void 0:Number(r)}extract32BitUInt(t=!0){const r=this.extractNumber(32n,!1,t);return r===void 0?void 0:Number(r)}extract32BitInt(t=!0){const r=this.extractNumber(32n,!0,t);return r===void 0?void 0:Number(r)}extract64BitUInt(t=!0){return this.extractNumber(64n,!1,t)}extract64BitInt(t=!0){return this.extractNumber(64n,!0,t)}extract128BitUInt(t=!0){return this.extractNumber(128n,!1,t)}extract128BitInt(t=!0){return this.extractNumber(128n,!0,t)}extract256BitUInt(t=!0){return this.extractNumber(256n,!1,t)}extract256BitInt(t=!0){return this.extractNumber(256n,!0,t)}extractFieldByLength(t){if(this.outOfRange(t))return;if(t===0)return new Uint8Array;const r=this.buffer.slice(this.index,this.index+t);return this.index+=t,r}extractFieldLVEncoded(){const t=this.extract8BitUInt();if(t===void 0)return;if(t===0)return new Uint8Array;const r=this.extractFieldByLength(t);return r===void 0&&this.index--,r}extractFieldTLVEncoded(){if(this.outOfRange(2))return;const t=this.index,r=this.extract8BitUInt(),n=this.extractFieldLVEncoded();if(r===void 0||n===void 0){this.index--;return}const o=this.index;return{tag:r,value:n,tlv:this.buffer.slice(t,o)}}encodeToHexaString(t,r=!1){if(t===void 0||t.length===0)return"";const n=si(t);return r?n:n.slice(2)}encodeToString(t){let r="",n=0;if(!t)return r;for(;n<=t.length;){const o=t[n];o&&(r+=String.fromCharCode(o)),n++}return r}getCurrentIndex(){return this.index}resetIndex(){this.index=0}getUnparsedRemainingLength(){return this.buffer.length-this.index}outOfRange(t){return this.index+t>this.buffer.length}extractNumber(t,r,n){const o=Number(t)/8;if(this.outOfRange(o))return;let a=0n;if(n)for(let l=0;l<o;l++)a=a<<8n|BigInt(this.buffer[l+this.index]);else for(let l=o-1;l>=0;l--)a=a<<8n|BigInt(this.buffer[l+this.index]);if(r){const l=1n<<t-1n;a&l&&(a-=l<<1n)}return this.index+=o,a}},mv=class{parser;constructor(t){this.parser=new E5(t.data)}testMinimalLength=t=>this.parser.testMinimalLength(t);extract8BitUInt=()=>this.parser.extract8BitUInt();extract16BitUInt=()=>this.parser.extract16BitUInt();extract32BitUInt=()=>this.parser.extract32BitUInt();extractFieldByLength=t=>this.parser.extractFieldByLength(t);extractFieldLVEncoded=()=>this.parser.extractFieldLVEncoded();extractFieldTLVEncoded=()=>this.parser.extractFieldTLVEncoded();encodeToHexaString(t,r=!1){return r?this.parser.encodeToHexaString(t,!0):this.parser.encodeToHexaString(t,!1)}encodeToString=t=>this.parser.encodeToString(t);getUnparsedRemainingLength=()=>this.parser.getUnparsedRemainingLength()},C5=class{_tag="InvalidStatusWordError";originalError;constructor(t){this.originalError=new Error(t??"Invalid status word.")}},k5=class{_tag="InvalidResponseFormatError";originalError;constructor(t){this.originalError=new Error(t??"Invalid response format.")}};var R5=(e=>(e.Error="ERROR",e.Success="SUCCESS",e))(R5||{});function _5(e){return"error"in e&&e.error!==void 0}function bw(e){return _5(e)?{status:"ERROR",error:e.error}:{status:"SUCCESS",data:e.data}}function $5(e){return e.status==="SUCCESS"}function Io({data:e,error:t}){return bw(t!==void 0?{error:t}:{data:e})}function A5(e){return $5(e)}let gv=class $s{static isValidStatusCode(t){return t.length===2}static isSuccessResponse({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===144&&t[1]===0:!1}static isLockedDeviceResponse({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===85&&t[1]===21||t[0]===105&&t[1]===130||t[0]===83&&t[1]===3:!1}static isRefusedByUser({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===85&&t[1]===1||t[0]===105&&t[1]===133:!1}static isAppAlreadyInstalled({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===106&&t[1]===128||t[0]===106&&t[1]===129||t[0]===106&&t[1]===142||t[0]===106&&t[1]===143:!1}static isOutOfMemory({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===106&&t[1]===132||t[0]===106&&t[1]===133||t[0]===81&&t[1]===2||t[0]===81&&t[1]===3:!1}static isApduThatTriggersDisconnection(t){const r=new Map;return r.set("openApp",new Uint8Array([224,216,0,0])),r.set("closeApp",new Uint8Array([176,167,0,0])),Array.from(r.values()).some(n=>{for(let o=0;o<4;o++)if(n[o]!==t[o])return!1;return!0})}},T5=class{_tag;originalError;errorCode;message;constructor({tag:t,errorCode:r,originalError:n,message:o}){this._tag=t,this.originalError=n,this.errorCode=r,this.message=o??"An error occured during device exchange."}},L5=class{_tag="UnknownDeviceExchangeError";originalError;message;constructor(t){this.originalError=t,this.message="Unexpected device exchange error happened."}};const I5=(e,t)=>Object.keys(t).includes(e);let O5=class extends T5{constructor(t){super({tag:"GlobalCommandError",...t})}};const xw={5515:{message:"Device is locked.",tag:"DeviceLockedError"},5501:{message:"Action refused on device.",tag:"ActionRefusedError"},5502:{message:"Pin is not set",tag:"PinNotSetError"},5223:{message:"Device internal error",tag:"DeviceInternalError"},"6e00":{message:"CLA not supported",tag:"DeviceInternalError"},"6d00":{message:"INS not supported",tag:"DeviceInternalError"}};let ER=class{static handle(t){const r=new mv(t).encodeToHexaString(t.statusCode);return I5(r,xw)?new O5({...xw[r],errorCode:r}):new L5({message:"UnknownError",errorCode:r})}},ww=class{name="getAppAndVersion";args=void 0;getApdu(){const t={cla:176,ins:1,p1:0,p2:0};return new SR(t).build()}parseResponse(t){if(!gv.isSuccessResponse(t))return Io({error:ER.handle(t)});const r=new mv(t);if(r.extract8BitUInt()!==1)return Io({error:new k5("getAppAndVersion: format not supported")});const n=r.encodeToString(r.extractFieldLVEncoded()),o=r.encodeToString(r.extractFieldLVEncoded());if(r.getUnparsedRemainingLength()===0)return Io({data:{name:n,version:o}});const a=r.extractFieldLVEncoded();return Io({data:{name:n,version:o,flags:a}})}};var N5=(e=>(e[e.BATTERY_PERCENTAGE=0]="BATTERY_PERCENTAGE",e[e.BATTERY_VOLTAGE=1]="BATTERY_VOLTAGE",e[e.BATTERY_TEMPERATURE=2]="BATTERY_TEMPERATURE",e[e.BATTERY_CURRENT=3]="BATTERY_CURRENT",e[e.BATTERY_FLAGS=4]="BATTERY_FLAGS",e))(N5||{}),P5=(e=>(e[e.NONE=0]="NONE",e[e.USB=1]="USB",e[e.QI=2]="QI",e))(P5||{}),Au={exports:{}},mh,Sw;function Ud(){if(Sw)return mh;Sw=1;const e="2.0.0",t=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,o=t-6;return mh={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:o,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:e,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},mh}var gh,Ew;function Vd(){if(Ew)return gh;Ew=1;var e={};return gh=typeof process=="object"&&e&&e.NODE_DEBUG&&/\bsemver\b/i.test(e.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},gh}var Cw;function Il(){return Cw||(Cw=1,(function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:o}=Ud(),a=Vd();t=e.exports={};const l=t.re=[],u=t.safeRe=[],d=t.src=[],p=t.safeSrc=[],h=t.t={};let m=0;const y="[a-zA-Z0-9-]",w=[["\\s",1],["\\d",o],[y,n]],E=C=>{for(const[R,k]of w)C=C.split(`${R}*`).join(`${R}{0,${k}}`).split(`${R}+`).join(`${R}{1,${k}}`);return C},S=(C,R,k)=>{const $=E(R),A=m++;a(C,A,R),h[C]=A,d[A]=R,p[A]=$,l[A]=new RegExp(R,k?"g":void 0),u[A]=new RegExp($,k?"g":void 0)};S("NUMERICIDENTIFIER","0|[1-9]\\d*"),S("NUMERICIDENTIFIERLOOSE","\\d+"),S("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${y}*`),S("MAINVERSION",`(${d[h.NUMERICIDENTIFIER]})\\.(${d[h.NUMERICIDENTIFIER]})\\.(${d[h.NUMERICIDENTIFIER]})`),S("MAINVERSIONLOOSE",`(${d[h.NUMERICIDENTIFIERLOOSE]})\\.(${d[h.NUMERICIDENTIFIERLOOSE]})\\.(${d[h.NUMERICIDENTIFIERLOOSE]})`),S("PRERELEASEIDENTIFIER",`(?:${d[h.NONNUMERICIDENTIFIER]}|${d[h.NUMERICIDENTIFIER]})`),S("PRERELEASEIDENTIFIERLOOSE",`(?:${d[h.NONNUMERICIDENTIFIER]}|${d[h.NUMERICIDENTIFIERLOOSE]})`),S("PRERELEASE",`(?:-(${d[h.PRERELEASEIDENTIFIER]}(?:\\.${d[h.PRERELEASEIDENTIFIER]})*))`),S("PRERELEASELOOSE",`(?:-?(${d[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${d[h.PRERELEASEIDENTIFIERLOOSE]})*))`),S("BUILDIDENTIFIER",`${y}+`),S("BUILD",`(?:\\+(${d[h.BUILDIDENTIFIER]}(?:\\.${d[h.BUILDIDENTIFIER]})*))`),S("FULLPLAIN",`v?${d[h.MAINVERSION]}${d[h.PRERELEASE]}?${d[h.BUILD]}?`),S("FULL",`^${d[h.FULLPLAIN]}$`),S("LOOSEPLAIN",`[v=\\s]*${d[h.MAINVERSIONLOOSE]}${d[h.PRERELEASELOOSE]}?${d[h.BUILD]}?`),S("LOOSE",`^${d[h.LOOSEPLAIN]}$`),S("GTLT","((?:<|>)?=?)"),S("XRANGEIDENTIFIERLOOSE",`${d[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),S("XRANGEIDENTIFIER",`${d[h.NUMERICIDENTIFIER]}|x|X|\\*`),S("XRANGEPLAIN",`[v=\\s]*(${d[h.XRANGEIDENTIFIER]})(?:\\.(${d[h.XRANGEIDENTIFIER]})(?:\\.(${d[h.XRANGEIDENTIFIER]})(?:${d[h.PRERELEASE]})?${d[h.BUILD]}?)?)?`),S("XRANGEPLAINLOOSE",`[v=\\s]*(${d[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[h.XRANGEIDENTIFIERLOOSE]})(?:${d[h.PRERELEASELOOSE]})?${d[h.BUILD]}?)?)?`),S("XRANGE",`^${d[h.GTLT]}\\s*${d[h.XRANGEPLAIN]}$`),S("XRANGELOOSE",`^${d[h.GTLT]}\\s*${d[h.XRANGEPLAINLOOSE]}$`),S("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),S("COERCE",`${d[h.COERCEPLAIN]}(?:$|[^\\d])`),S("COERCEFULL",d[h.COERCEPLAIN]+`(?:${d[h.PRERELEASE]})?(?:${d[h.BUILD]})?(?:$|[^\\d])`),S("COERCERTL",d[h.COERCE],!0),S("COERCERTLFULL",d[h.COERCEFULL],!0),S("LONETILDE","(?:~>?)"),S("TILDETRIM",`(\\s*)${d[h.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",S("TILDE",`^${d[h.LONETILDE]}${d[h.XRANGEPLAIN]}$`),S("TILDELOOSE",`^${d[h.LONETILDE]}${d[h.XRANGEPLAINLOOSE]}$`),S("LONECARET","(?:\\^)"),S("CARETTRIM",`(\\s*)${d[h.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",S("CARET",`^${d[h.LONECARET]}${d[h.XRANGEPLAIN]}$`),S("CARETLOOSE",`^${d[h.LONECARET]}${d[h.XRANGEPLAINLOOSE]}$`),S("COMPARATORLOOSE",`^${d[h.GTLT]}\\s*(${d[h.LOOSEPLAIN]})$|^$`),S("COMPARATOR",`^${d[h.GTLT]}\\s*(${d[h.FULLPLAIN]})$|^$`),S("COMPARATORTRIM",`(\\s*)${d[h.GTLT]}\\s*(${d[h.LOOSEPLAIN]}|${d[h.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",S("HYPHENRANGE",`^\\s*(${d[h.XRANGEPLAIN]})\\s+-\\s+(${d[h.XRANGEPLAIN]})\\s*$`),S("HYPHENRANGELOOSE",`^\\s*(${d[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${d[h.XRANGEPLAINLOOSE]})\\s*$`),S("STAR","(<|>)?=?\\s*\\*"),S("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),S("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Au,Au.exports)),Au.exports}var vh,kw;function vv(){if(kw)return vh;kw=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return vh=n=>n?typeof n!="object"?e:n:t,vh}var yh,Rw;function CR(){if(Rw)return yh;Rw=1;const e=/^[0-9]+$/,t=(n,o)=>{const a=e.test(n),l=e.test(o);return a&&l&&(n=+n,o=+o),n===o?0:a&&!l?-1:l&&!a?1:n<o?-1:1};return yh={compareIdentifiers:t,rcompareIdentifiers:(n,o)=>t(o,n)},yh}var bh,_w;function gr(){if(_w)return bh;_w=1;const e=Vd(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Ud(),{safeRe:n,t:o}=Il(),a=vv(),{compareIdentifiers:l}=CR();class u{constructor(p,h){if(h=a(h),p instanceof u){if(p.loose===!!h.loose&&p.includePrerelease===!!h.includePrerelease)return p;p=p.version}else if(typeof p!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof p}".`);if(p.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",p,h),this.options=h,this.loose=!!h.loose,this.includePrerelease=!!h.includePrerelease;const m=p.trim().match(h.loose?n[o.LOOSE]:n[o.FULL]);if(!m)throw new TypeError(`Invalid Version: ${p}`);if(this.raw=p,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(y=>{if(/^[0-9]+$/.test(y)){const w=+y;if(w>=0&&w<r)return w}return y}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(p){if(e("SemVer.compare",this.version,this.options,p),!(p instanceof u)){if(typeof p=="string"&&p===this.version)return 0;p=new u(p,this.options)}return p.version===this.version?0:this.compareMain(p)||this.comparePre(p)}compareMain(p){return p instanceof u||(p=new u(p,this.options)),l(this.major,p.major)||l(this.minor,p.minor)||l(this.patch,p.patch)}comparePre(p){if(p instanceof u||(p=new u(p,this.options)),this.prerelease.length&&!p.prerelease.length)return-1;if(!this.prerelease.length&&p.prerelease.length)return 1;if(!this.prerelease.length&&!p.prerelease.length)return 0;let h=0;do{const m=this.prerelease[h],y=p.prerelease[h];if(e("prerelease compare",h,m,y),m===void 0&&y===void 0)return 0;if(y===void 0)return 1;if(m===void 0)return-1;if(m===y)continue;return l(m,y)}while(++h)}compareBuild(p){p instanceof u||(p=new u(p,this.options));let h=0;do{const m=this.build[h],y=p.build[h];if(e("build compare",h,m,y),m===void 0&&y===void 0)return 0;if(y===void 0)return 1;if(m===void 0)return-1;if(m===y)continue;return l(m,y)}while(++h)}inc(p,h,m){if(p.startsWith("pre")){if(!h&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(h){const y=`-${h}`.match(this.options.loose?n[o.PRERELEASELOOSE]:n[o.PRERELEASE]);if(!y||y[1]!==h)throw new Error(`invalid identifier: ${h}`)}}switch(p){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",h,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",h,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",h,m),this.inc("pre",h,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",h,m),this.inc("pre",h,m);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const y=Number(m)?1:0;if(this.prerelease.length===0)this.prerelease=[y];else{let w=this.prerelease.length;for(;--w>=0;)typeof this.prerelease[w]=="number"&&(this.prerelease[w]++,w=-2);if(w===-1){if(h===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(y)}}if(h){let w=[h,y];m===!1&&(w=[h]),l(this.prerelease[0],h)===0?isNaN(this.prerelease[1])&&(this.prerelease=w):this.prerelease=w}break}default:throw new Error(`invalid increment argument: ${p}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return bh=u,bh}var xh,$w;function ia(){if($w)return xh;$w=1;const e=gr();return xh=(r,n,o=!1)=>{if(r instanceof e)return r;try{return new e(r,n)}catch(a){if(!o)return null;throw a}},xh}var wh,Aw;function D5(){if(Aw)return wh;Aw=1;const e=ia();return wh=(r,n)=>{const o=e(r,n);return o?o.version:null},wh}var Sh,Tw;function j5(){if(Tw)return Sh;Tw=1;const e=ia();return Sh=(r,n)=>{const o=e(r.trim().replace(/^[=v]+/,""),n);return o?o.version:null},Sh}var Eh,Lw;function M5(){if(Lw)return Eh;Lw=1;const e=gr();return Eh=(r,n,o,a,l)=>{typeof o=="string"&&(l=a,a=o,o=void 0);try{return new e(r instanceof e?r.version:r,o).inc(n,a,l).version}catch{return null}},Eh}var Ch,Iw;function z5(){if(Iw)return Ch;Iw=1;const e=ia();return Ch=(r,n)=>{const o=e(r,null,!0),a=e(n,null,!0),l=o.compare(a);if(l===0)return null;const u=l>0,d=u?o:a,p=u?a:o,h=!!d.prerelease.length;if(!!p.prerelease.length&&!h){if(!p.patch&&!p.minor)return"major";if(p.compareMain(d)===0)return p.minor&&!p.patch?"minor":"patch"}const y=h?"pre":"";return o.major!==a.major?y+"major":o.minor!==a.minor?y+"minor":o.patch!==a.patch?y+"patch":"prerelease"},Ch}var kh,Ow;function F5(){if(Ow)return kh;Ow=1;const e=gr();return kh=(r,n)=>new e(r,n).major,kh}var Rh,Nw;function B5(){if(Nw)return Rh;Nw=1;const e=gr();return Rh=(r,n)=>new e(r,n).minor,Rh}var _h,Pw;function U5(){if(Pw)return _h;Pw=1;const e=gr();return _h=(r,n)=>new e(r,n).patch,_h}var $h,Dw;function V5(){if(Dw)return $h;Dw=1;const e=ia();return $h=(r,n)=>{const o=e(r,n);return o&&o.prerelease.length?o.prerelease:null},$h}var Ah,jw;function bn(){if(jw)return Ah;jw=1;const e=gr();return Ah=(r,n,o)=>new e(r,o).compare(new e(n,o)),Ah}var Th,Mw;function W5(){if(Mw)return Th;Mw=1;const e=bn();return Th=(r,n,o)=>e(n,r,o),Th}var Lh,zw;function H5(){if(zw)return Lh;zw=1;const e=bn();return Lh=(r,n)=>e(r,n,!0),Lh}var Ih,Fw;function yv(){if(Fw)return Ih;Fw=1;const e=gr();return Ih=(r,n,o)=>{const a=new e(r,o),l=new e(n,o);return a.compare(l)||a.compareBuild(l)},Ih}var Oh,Bw;function q5(){if(Bw)return Oh;Bw=1;const e=yv();return Oh=(r,n)=>r.sort((o,a)=>e(o,a,n)),Oh}var Nh,Uw;function G5(){if(Uw)return Nh;Uw=1;const e=yv();return Nh=(r,n)=>r.sort((o,a)=>e(a,o,n)),Nh}var Ph,Vw;function Wd(){if(Vw)return Ph;Vw=1;const e=bn();return Ph=(r,n,o)=>e(r,n,o)>0,Ph}var Dh,Ww;function bv(){if(Ww)return Dh;Ww=1;const e=bn();return Dh=(r,n,o)=>e(r,n,o)<0,Dh}var jh,Hw;function kR(){if(Hw)return jh;Hw=1;const e=bn();return jh=(r,n,o)=>e(r,n,o)===0,jh}var Mh,qw;function RR(){if(qw)return Mh;qw=1;const e=bn();return Mh=(r,n,o)=>e(r,n,o)!==0,Mh}var zh,Gw;function xv(){if(Gw)return zh;Gw=1;const e=bn();return zh=(r,n,o)=>e(r,n,o)>=0,zh}var Fh,Xw;function wv(){if(Xw)return Fh;Xw=1;const e=bn();return Fh=(r,n,o)=>e(r,n,o)<=0,Fh}var Bh,Yw;function _R(){if(Yw)return Bh;Yw=1;const e=kR(),t=RR(),r=Wd(),n=xv(),o=bv(),a=wv();return Bh=(u,d,p,h)=>{switch(d){case"===":return typeof u=="object"&&(u=u.version),typeof p=="object"&&(p=p.version),u===p;case"!==":return typeof u=="object"&&(u=u.version),typeof p=="object"&&(p=p.version),u!==p;case"":case"=":case"==":return e(u,p,h);case"!=":return t(u,p,h);case">":return r(u,p,h);case">=":return n(u,p,h);case"<":return o(u,p,h);case"<=":return a(u,p,h);default:throw new TypeError(`Invalid operator: ${d}`)}},Bh}var Uh,Kw;function X5(){if(Kw)return Uh;Kw=1;const e=gr(),t=ia(),{safeRe:r,t:n}=Il();return Uh=(a,l)=>{if(a instanceof e)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;l=l||{};let u=null;if(!l.rtl)u=a.match(l.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const w=l.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let E;for(;(E=w.exec(a))&&(!u||u.index+u[0].length!==a.length);)(!u||E.index+E[0].length!==u.index+u[0].length)&&(u=E),w.lastIndex=E.index+E[1].length+E[2].length;w.lastIndex=-1}if(u===null)return null;const d=u[2],p=u[3]||"0",h=u[4]||"0",m=l.includePrerelease&&u[5]?`-${u[5]}`:"",y=l.includePrerelease&&u[6]?`+${u[6]}`:"";return t(`${d}.${p}.${h}${m}${y}`,l)},Uh}var Vh,Qw;function Y5(){if(Qw)return Vh;Qw=1;class e{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(r,n)}return this}}return Vh=e,Vh}var Wh,Jw;function xn(){if(Jw)return Wh;Jw=1;const e=/\s+/g;class t{constructor(V,H){if(H=o(H),V instanceof t)return V.loose===!!H.loose&&V.includePrerelease===!!H.includePrerelease?V:new t(V.raw,H);if(V instanceof a)return this.raw=V.value,this.set=[[V]],this.formatted=void 0,this;if(this.options=H,this.loose=!!H.loose,this.includePrerelease=!!H.includePrerelease,this.raw=V.trim().replace(e," "),this.set=this.raw.split("||").map(O=>this.parseRange(O.trim())).filter(O=>O.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const O=this.set[0];if(this.set=this.set.filter(L=>!S(L[0])),this.set.length===0)this.set=[O];else if(this.set.length>1){for(const L of this.set)if(L.length===1&&C(L[0])){this.set=[L];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let V=0;V<this.set.length;V++){V>0&&(this.formatted+="||");const H=this.set[V];for(let O=0;O<H.length;O++)O>0&&(this.formatted+=" "),this.formatted+=H[O].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(V){const O=((this.options.includePrerelease&&w)|(this.options.loose&&E))+":"+V,L=n.get(O);if(L)return L;const U=this.options.loose,z=U?d[p.HYPHENRANGELOOSE]:d[p.HYPHENRANGE];V=V.replace(z,ne(this.options.includePrerelease)),l("hyphen replace",V),V=V.replace(d[p.COMPARATORTRIM],h),l("comparator trim",V),V=V.replace(d[p.TILDETRIM],m),l("tilde trim",V),V=V.replace(d[p.CARETTRIM],y),l("caret trim",V);let T=V.split(" ").map(G=>k(G,this.options)).join(" ").split(/\s+/).map(G=>ee(G,this.options));U&&(T=T.filter(G=>(l("loose invalid filter",G,this.options),!!G.match(d[p.COMPARATORLOOSE])))),l("range list",T);const M=new Map,te=T.map(G=>new a(G,this.options));for(const G of te){if(S(G))return[G];M.set(G.value,G)}M.size>1&&M.has("")&&M.delete("");const le=[...M.values()];return n.set(O,le),le}intersects(V,H){if(!(V instanceof t))throw new TypeError("a Range is required");return this.set.some(O=>R(O,H)&&V.set.some(L=>R(L,H)&&O.every(U=>L.every(z=>U.intersects(z,H)))))}test(V){if(!V)return!1;if(typeof V=="string")try{V=new u(V,this.options)}catch{return!1}for(let H=0;H<this.set.length;H++)if(X(this.set[H],V,this.options))return!0;return!1}}Wh=t;const r=Y5(),n=new r,o=vv(),a=Hd(),l=Vd(),u=gr(),{safeRe:d,t:p,comparatorTrimReplace:h,tildeTrimReplace:m,caretTrimReplace:y}=Il(),{FLAG_INCLUDE_PRERELEASE:w,FLAG_LOOSE:E}=Ud(),S=F=>F.value==="<0.0.0-0",C=F=>F.value==="",R=(F,V)=>{let H=!0;const O=F.slice();let L=O.pop();for(;H&&O.length;)H=O.every(U=>L.intersects(U,V)),L=O.pop();return H},k=(F,V)=>(l("comp",F,V),F=N(F,V),l("caret",F),F=A(F,V),l("tildes",F),F=I(F,V),l("xrange",F),F=Z(F,V),l("stars",F),F),$=F=>!F||F.toLowerCase()==="x"||F==="*",A=(F,V)=>F.trim().split(/\s+/).map(H=>D(H,V)).join(" "),D=(F,V)=>{const H=V.loose?d[p.TILDELOOSE]:d[p.TILDE];return F.replace(H,(O,L,U,z,T)=>{l("tilde",F,O,L,U,z,T);let M;return $(L)?M="":$(U)?M=`>=${L}.0.0 <${+L+1}.0.0-0`:$(z)?M=`>=${L}.${U}.0 <${L}.${+U+1}.0-0`:T?(l("replaceTilde pr",T),M=`>=${L}.${U}.${z}-${T} <${L}.${+U+1}.0-0`):M=`>=${L}.${U}.${z} <${L}.${+U+1}.0-0`,l("tilde return",M),M})},N=(F,V)=>F.trim().split(/\s+/).map(H=>P(H,V)).join(" "),P=(F,V)=>{l("caret",F,V);const H=V.loose?d[p.CARETLOOSE]:d[p.CARET],O=V.includePrerelease?"-0":"";return F.replace(H,(L,U,z,T,M)=>{l("caret",F,L,U,z,T,M);let te;return $(U)?te="":$(z)?te=`>=${U}.0.0${O} <${+U+1}.0.0-0`:$(T)?U==="0"?te=`>=${U}.${z}.0${O} <${U}.${+z+1}.0-0`:te=`>=${U}.${z}.0${O} <${+U+1}.0.0-0`:M?(l("replaceCaret pr",M),U==="0"?z==="0"?te=`>=${U}.${z}.${T}-${M} <${U}.${z}.${+T+1}-0`:te=`>=${U}.${z}.${T}-${M} <${U}.${+z+1}.0-0`:te=`>=${U}.${z}.${T}-${M} <${+U+1}.0.0-0`):(l("no pr"),U==="0"?z==="0"?te=`>=${U}.${z}.${T}${O} <${U}.${z}.${+T+1}-0`:te=`>=${U}.${z}.${T}${O} <${U}.${+z+1}.0-0`:te=`>=${U}.${z}.${T} <${+U+1}.0.0-0`),l("caret return",te),te})},I=(F,V)=>(l("replaceXRanges",F,V),F.split(/\s+/).map(H=>re(H,V)).join(" ")),re=(F,V)=>{F=F.trim();const H=V.loose?d[p.XRANGELOOSE]:d[p.XRANGE];return F.replace(H,(O,L,U,z,T,M)=>{l("xRange",F,O,L,U,z,T,M);const te=$(U),le=te||$(z),G=le||$(T),fe=G;return L==="="&&fe&&(L=""),M=V.includePrerelease?"-0":"",te?L===">"||L==="<"?O="<0.0.0-0":O="*":L&&fe?(le&&(z=0),T=0,L===">"?(L=">=",le?(U=+U+1,z=0,T=0):(z=+z+1,T=0)):L==="<="&&(L="<",le?U=+U+1:z=+z+1),L==="<"&&(M="-0"),O=`${L+U}.${z}.${T}${M}`):le?O=`>=${U}.0.0${M} <${+U+1}.0.0-0`:G&&(O=`>=${U}.${z}.0${M} <${U}.${+z+1}.0-0`),l("xRange return",O),O})},Z=(F,V)=>(l("replaceStars",F,V),F.trim().replace(d[p.STAR],"")),ee=(F,V)=>(l("replaceGTE0",F,V),F.trim().replace(d[V.includePrerelease?p.GTE0PRE:p.GTE0],"")),ne=F=>(V,H,O,L,U,z,T,M,te,le,G,fe)=>($(O)?H="":$(L)?H=`>=${O}.0.0${F?"-0":""}`:$(U)?H=`>=${O}.${L}.0${F?"-0":""}`:z?H=`>=${H}`:H=`>=${H}${F?"-0":""}`,$(te)?M="":$(le)?M=`<${+te+1}.0.0-0`:$(G)?M=`<${te}.${+le+1}.0-0`:fe?M=`<=${te}.${le}.${G}-${fe}`:F?M=`<${te}.${le}.${+G+1}-0`:M=`<=${M}`,`${H} ${M}`.trim()),X=(F,V,H)=>{for(let O=0;O<F.length;O++)if(!F[O].test(V))return!1;if(V.prerelease.length&&!H.includePrerelease){for(let O=0;O<F.length;O++)if(l(F[O].semver),F[O].semver!==a.ANY&&F[O].semver.prerelease.length>0){const L=F[O].semver;if(L.major===V.major&&L.minor===V.minor&&L.patch===V.patch)return!0}return!1}return!0};return Wh}var Hh,Zw;function Hd(){if(Zw)return Hh;Zw=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(h,m){if(m=r(m),h instanceof t){if(h.loose===!!m.loose)return h;h=h.value}h=h.trim().split(/\s+/).join(" "),l("comparator",h,m),this.options=m,this.loose=!!m.loose,this.parse(h),this.semver===e?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}parse(h){const m=this.options.loose?n[o.COMPARATORLOOSE]:n[o.COMPARATOR],y=h.match(m);if(!y)throw new TypeError(`Invalid comparator: ${h}`);this.operator=y[1]!==void 0?y[1]:"",this.operator==="="&&(this.operator=""),y[2]?this.semver=new u(y[2],this.options.loose):this.semver=e}toString(){return this.value}test(h){if(l("Comparator.test",h,this.options.loose),this.semver===e||h===e)return!0;if(typeof h=="string")try{h=new u(h,this.options)}catch{return!1}return a(h,this.operator,this.semver,this.options)}intersects(h,m){if(!(h instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new d(h.value,m).test(this.value):h.operator===""?h.value===""?!0:new d(this.value,m).test(h.semver):(m=r(m),m.includePrerelease&&(this.value==="<0.0.0-0"||h.value==="<0.0.0-0")||!m.includePrerelease&&(this.value.startsWith("<0.0.0")||h.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&h.operator.startsWith(">")||this.operator.startsWith("<")&&h.operator.startsWith("<")||this.semver.version===h.semver.version&&this.operator.includes("=")&&h.operator.includes("=")||a(this.semver,"<",h.semver,m)&&this.operator.startsWith(">")&&h.operator.startsWith("<")||a(this.semver,">",h.semver,m)&&this.operator.startsWith("<")&&h.operator.startsWith(">")))}}Hh=t;const r=vv(),{safeRe:n,t:o}=Il(),a=_R(),l=Vd(),u=gr(),d=xn();return Hh}var qh,eS;function qd(){if(eS)return qh;eS=1;const e=xn();return qh=(r,n,o)=>{try{n=new e(n,o)}catch{return!1}return n.test(r)},qh}var Gh,tS;function K5(){if(tS)return Gh;tS=1;const e=xn();return Gh=(r,n)=>new e(r,n).set.map(o=>o.map(a=>a.value).join(" ").trim().split(" ")),Gh}var Xh,rS;function Q5(){if(rS)return Xh;rS=1;const e=gr(),t=xn();return Xh=(n,o,a)=>{let l=null,u=null,d=null;try{d=new t(o,a)}catch{return null}return n.forEach(p=>{d.test(p)&&(!l||u.compare(p)===-1)&&(l=p,u=new e(l,a))}),l},Xh}var Yh,nS;function J5(){if(nS)return Yh;nS=1;const e=gr(),t=xn();return Yh=(n,o,a)=>{let l=null,u=null,d=null;try{d=new t(o,a)}catch{return null}return n.forEach(p=>{d.test(p)&&(!l||u.compare(p)===1)&&(l=p,u=new e(l,a))}),l},Yh}var Kh,iS;function Z5(){if(iS)return Kh;iS=1;const e=gr(),t=xn(),r=Wd();return Kh=(o,a)=>{o=new t(o,a);let l=new e("0.0.0");if(o.test(l)||(l=new e("0.0.0-0"),o.test(l)))return l;l=null;for(let u=0;u<o.set.length;++u){const d=o.set[u];let p=null;d.forEach(h=>{const m=new e(h.semver.version);switch(h.operator){case">":m.prerelease.length===0?m.patch++:m.prerelease.push(0),m.raw=m.format();case"":case">=":(!p||r(m,p))&&(p=m);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${h.operator}`)}}),p&&(!l||r(l,p))&&(l=p)}return l&&o.test(l)?l:null},Kh}var Qh,oS;function ez(){if(oS)return Qh;oS=1;const e=xn();return Qh=(r,n)=>{try{return new e(r,n).range||"*"}catch{return null}},Qh}var Jh,sS;function Sv(){if(sS)return Jh;sS=1;const e=gr(),t=Hd(),{ANY:r}=t,n=xn(),o=qd(),a=Wd(),l=bv(),u=wv(),d=xv();return Jh=(h,m,y,w)=>{h=new e(h,w),m=new n(m,w);let E,S,C,R,k;switch(y){case">":E=a,S=u,C=l,R=">",k=">=";break;case"<":E=l,S=d,C=a,R="<",k="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(h,m,w))return!1;for(let $=0;$<m.set.length;++$){const A=m.set[$];let D=null,N=null;if(A.forEach(P=>{P.semver===r&&(P=new t(">=0.0.0")),D=D||P,N=N||P,E(P.semver,D.semver,w)?D=P:C(P.semver,N.semver,w)&&(N=P)}),D.operator===R||D.operator===k||(!N.operator||N.operator===R)&&S(h,N.semver))return!1;if(N.operator===k&&C(h,N.semver))return!1}return!0},Jh}var Zh,aS;function tz(){if(aS)return Zh;aS=1;const e=Sv();return Zh=(r,n,o)=>e(r,n,">",o),Zh}var em,lS;function rz(){if(lS)return em;lS=1;const e=Sv();return em=(r,n,o)=>e(r,n,"<",o),em}var tm,cS;function nz(){if(cS)return tm;cS=1;const e=xn();return tm=(r,n,o)=>(r=new e(r,o),n=new e(n,o),r.intersects(n,o)),tm}var rm,uS;function iz(){if(uS)return rm;uS=1;const e=qd(),t=bn();return rm=(r,n,o)=>{const a=[];let l=null,u=null;const d=r.sort((y,w)=>t(y,w,o));for(const y of d)e(y,n,o)?(u=y,l||(l=y)):(u&&a.push([l,u]),u=null,l=null);l&&a.push([l,null]);const p=[];for(const[y,w]of a)y===w?p.push(y):!w&&y===d[0]?p.push("*"):w?y===d[0]?p.push(`<=${w}`):p.push(`${y} - ${w}`):p.push(`>=${y}`);const h=p.join(" || "),m=typeof n.raw=="string"?n.raw:String(n);return h.length<m.length?h:n},rm}var nm,dS;function oz(){if(dS)return nm;dS=1;const e=xn(),t=Hd(),{ANY:r}=t,n=qd(),o=bn(),a=(m,y,w={})=>{if(m===y)return!0;m=new e(m,w),y=new e(y,w);let E=!1;e:for(const S of m.set){for(const C of y.set){const R=d(S,C,w);if(E=E||R!==null,R)continue e}if(E)return!1}return!0},l=[new t(">=0.0.0-0")],u=[new t(">=0.0.0")],d=(m,y,w)=>{if(m===y)return!0;if(m.length===1&&m[0].semver===r){if(y.length===1&&y[0].semver===r)return!0;w.includePrerelease?m=l:m=u}if(y.length===1&&y[0].semver===r){if(w.includePrerelease)return!0;y=u}const E=new Set;let S,C;for(const I of m)I.operator===">"||I.operator===">="?S=p(S,I,w):I.operator==="<"||I.operator==="<="?C=h(C,I,w):E.add(I.semver);if(E.size>1)return null;let R;if(S&&C){if(R=o(S.semver,C.semver,w),R>0)return null;if(R===0&&(S.operator!==">="||C.operator!=="<="))return null}for(const I of E){if(S&&!n(I,String(S),w)||C&&!n(I,String(C),w))return null;for(const re of y)if(!n(I,String(re),w))return!1;return!0}let k,$,A,D,N=C&&!w.includePrerelease&&C.semver.prerelease.length?C.semver:!1,P=S&&!w.includePrerelease&&S.semver.prerelease.length?S.semver:!1;N&&N.prerelease.length===1&&C.operator==="<"&&N.prerelease[0]===0&&(N=!1);for(const I of y){if(D=D||I.operator===">"||I.operator===">=",A=A||I.operator==="<"||I.operator==="<=",S){if(P&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===P.major&&I.semver.minor===P.minor&&I.semver.patch===P.patch&&(P=!1),I.operator===">"||I.operator===">="){if(k=p(S,I,w),k===I&&k!==S)return!1}else if(S.operator===">="&&!n(S.semver,String(I),w))return!1}if(C){if(N&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===N.major&&I.semver.minor===N.minor&&I.semver.patch===N.patch&&(N=!1),I.operator==="<"||I.operator==="<="){if($=h(C,I,w),$===I&&$!==C)return!1}else if(C.operator==="<="&&!n(C.semver,String(I),w))return!1}if(!I.operator&&(C||S)&&R!==0)return!1}return!(S&&A&&!C&&R!==0||C&&D&&!S&&R!==0||P||N)},p=(m,y,w)=>{if(!m)return y;const E=o(m.semver,y.semver,w);return E>0?m:E<0||y.operator===">"&&m.operator===">="?y:m},h=(m,y,w)=>{if(!m)return y;const E=o(m.semver,y.semver,w);return E<0?m:E>0||y.operator==="<"&&m.operator==="<="?y:m};return nm=a,nm}var im,fS;function sz(){if(fS)return im;fS=1;const e=Il(),t=Ud(),r=gr(),n=CR(),o=ia(),a=D5(),l=j5(),u=M5(),d=z5(),p=F5(),h=B5(),m=U5(),y=V5(),w=bn(),E=W5(),S=H5(),C=yv(),R=q5(),k=G5(),$=Wd(),A=bv(),D=kR(),N=RR(),P=xv(),I=wv(),re=_R(),Z=X5(),ee=Hd(),ne=xn(),X=qd(),F=K5(),V=Q5(),H=J5(),O=Z5(),L=ez(),U=Sv(),z=tz(),T=rz(),M=nz(),te=iz(),le=oz();return im={parse:o,valid:a,clean:l,inc:u,diff:d,major:p,minor:h,patch:m,prerelease:y,compare:w,rcompare:E,compareLoose:S,compareBuild:C,sort:R,rsort:k,gt:$,lt:A,eq:D,neq:N,gte:P,lte:I,cmp:re,coerce:Z,Comparator:ee,Range:ne,satisfies:X,toComparators:F,maxSatisfying:V,minSatisfying:H,minVersion:O,validRange:L,outside:U,gtr:z,ltr:T,intersects:M,simplifyRange:te,subset:le,SemVer:r,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},im}var jr=sz();const pS=Qr(jr);var wt=(e=>(e.NANO_S="nanoS",e.NANO_SP="nanoSP",e.NANO_X="nanoX",e.STAX="stax",e.FLEX="flex",e.APEX="apexp",e))(wt||{});let $R=class{id;model;name;constructor({id:t,model:r,name:n}){this.id=t,this.model=r,this.name=n}};const om={Twelve:12,Eighteen:18,TwentyFour:24};var Xt=(e=>(e.Unknown="unknown",e.WelcomeScreen1="welcome-screen-1",e.WelcomeScreen2="welcome-screen-2",e.WelcomeScreen3="welcome-screen-3",e.WelcomeScreen4="welcome-screen-4",e.WelcomeScreenReminder="welcome-screen-reminder",e.SetupChoice="setup-choice",e.Pin="pin",e.NewDevice="new-device",e.ConfirmNewDevice="confirm-new-device",e.RestoreRecoveryPhrase="restore-recovery-phrase",e.SafetyWarning="safety-warning",e.DeviceIsReady="device-is-ready",e.ChooseName="choose-name",e.RestoreRecoverBackup="restore-recover-backup",e.SetupRestoreChoice="setup-restore-choice",e.OnboardingStatusCheck="onboarding-status-check",e.RestoreWithRk="restore-with-rk",e))(Xt||{});const az={0:Xt.WelcomeScreen1,1:Xt.WelcomeScreen2,2:Xt.WelcomeScreen3,3:Xt.WelcomeScreen4,4:Xt.WelcomeScreenReminder,5:Xt.SetupChoice,6:Xt.Pin,7:Xt.NewDevice,8:Xt.ConfirmNewDevice,9:Xt.RestoreRecoveryPhrase,10:Xt.SafetyWarning,11:Xt.DeviceIsReady,12:Xt.ChooseName,13:Xt.RestoreRecoverBackup,14:Xt.SetupRestoreChoice,15:Xt.OnboardingStatusCheck,16:Xt.RestoreWithRk};let lz=class{seFlags;constructor(t){this.seFlags=new Uint8Array(4),this.seFlags.set(t.subarray(0,this.seFlags.length))}generalDeviceState(){const t=this.seFlags[0]??0;return{isPinValidated:this._checkNthBitInByte(t,1),hasMcuSerialNumber:this._checkNthBitInByte(t,2),hasValidCertificate:this._checkNthBitInByte(t,3),isCustomAuthorityConnectionAllowed:this._checkNthBitInByte(t,4),isSecureConnectionAllowed:this._checkNthBitInByte(t,5),isOnboarded:this._checkNthBitInByte(t,6),isMcuCodeSigned:this._checkNthBitInByte(t,7),isInRecoveryMode:this._checkNthBitInByte(t,8)}}endorsementInformation(){const t=this.seFlags[1]??0;return{hasEndorsementCertificateInSlot1:(t&1)!==0,hasEndorsementCertificateInSlot2:(t&2)!==0}}wordsInformation(){const t=this.seFlags[2]??0,r=t>>5&3;return{numberOfWords:[om.TwentyFour,om.Eighteen,om.Twelve,void 0][r],currentWordIndex:t&31}}onboardingStatus(){const t=this.seFlags[3]??0;return{onboardingState:az[t]??Xt.Unknown}}_checkNthBitInByte(t,r){return(t>>8-r&1)===1}},cz=class{name="getOsVersion";args=void 0;getApdu(){const t={cla:224,ins:1,p1:0,p2:0};return new SR(t).build()}parseResponse(t,r){if(!gv.isSuccessResponse(t))return Io({error:ER.handle(t)});const n=new mv(t),o=n.extract32BitUInt();if(o===void 0)return Io({error:new C5("Missing target ID in OS version")});let a=n.encodeToString(n.extractFieldLVEncoded()),l=n.extractFieldLVEncoded()??new Uint8Array(0);const u=new lz(l),d={...u.generalDeviceState(),...u.endorsementInformation(),...u.wordsInformation(),...u.onboardingStatus()};a||(a="0.0.0",l=new Uint8Array);const p=(o&4026531840)!==805306368,h=a.includes("-osu");let m="",y="",w="",E="",S,C,R,k;if(p){w=a,S=o;const $=n.extractFieldLVEncoded();$&&($.length>=5?(m=n.encodeToString($),C=parseInt(n.encodeToHexaString(n.extractFieldLVEncoded()),16)):C=parseInt(n.encodeToHexaString($),16))}else{if(m=a,C=o,y=n.encodeToString(n.extractFieldLVEncoded()),this.isBootloaderVersionSupported(m,r)&&(w=n.encodeToString(n.extractFieldLVEncoded())),this.isHardwareVersionSupported(m,r)?E=n.encodeToHexaString(n.extractFieldLVEncoded()):E="00",this.isLocalizationSupported(m,r)){const $=n.extractFieldLVEncoded();$!==void 0&&(R=parseInt(n.encodeToHexaString($),16))}if(this.isRecoverSupported(m,r)){const $=n.extractFieldLVEncoded();$!==void 0&&(k=parseInt(n.encodeToHexaString($),16))}}return Io({data:{isBootloader:p,isOsu:h,targetId:o,seTargetId:C,mcuTargetId:S,seVersion:m,seFlags:l,mcuSephVersion:y,mcuBootloaderVersion:w,hwVersion:E,langId:R,recoverState:k,secureElementFlags:d}})}isBootloaderVersionSupported(t,r){const n=jr.coerce(t)??"";switch(r){case wt.NANO_S:case wt.NANO_X:return jr.gte(n,"2.0.0");default:return!0}}isHardwareVersionSupported(t,r){const n=jr.coerce(t)??"";return r===wt.NANO_X?jr.gte(n,"2.0.0"):!1}isLocalizationSupported(t,r){const n=jr.coerce(t)??"";switch(r){case wt.NANO_S:return!1;case wt.NANO_SP:return jr.gte(n,"1.1.0");case wt.NANO_X:return jr.gte(n,"2.1.0");default:return!0}}isRecoverSupported(t,r){const n=jr.coerce(t)??"";switch(r){case wt.NANO_S:return!1;case wt.NANO_SP:return jr.gte(n,"1.1.2");case wt.NANO_X:return jr.gte(n,"2.2.3");case wt.STAX:return jr.gte(n,"1.4.0");case wt.FLEX:return jr.gte(n,"1.0.1");default:return!0}}};var Ln=(e=>(e.LOCKED="LOCKED",e.BUSY="BUSY",e.CONNECTED="CONNECTED",e.NOT_CONNECTED="NOT CONNECTED",e))(Ln||{}),uz=(e=>(e.NotStarted="not-started",e.Pending="pending",e.Stopped="stopped",e.Completed="completed",e.Error="error",e))(uz||{}),dz=(e=>(e.None="none",e.UnlockDevice="unlock-device",e.AllowSecureConnection="allow-secure-connection",e.ConfirmOpenApp="confirm-open-app",e.SignTransaction="sign-transaction",e.SignTypedData="sign-typed-data",e.AllowListApps="allow-list-apps",e.VerifyAddress="verify-address",e.SignPersonalMessage="sign-personal-message",e.SignDelegationAuthorization="sign-delegation-authorization",e.Web3ChecksOptIn="web3-checks-opt-in",e.VerifySafeAddress="verify-safe-address",e.RegisterWallet="register-wallet",e.ConfirmLoadImage="confirm-load-image",e.ConfirmCommitImage="confirm-commit-image",e.ConfirmRemoveImage="confirm-remove-image",e.GrantConsent="grant-consent",e.AllowInstallFirmware="allow-install-firmware",e))(dz||{});const Ar={of(e){return or(e)},empty(){return ft},zero(){return ft},fromNullable(e){return e==null?ft:or(e)},fromFalsy(e){return e?or(e):ft},fromPredicate(e,t){return arguments.length===1?r=>Ar.fromPredicate(e,r):e(t)?or(t):ft},mapMaybe(e,t){return arguments.length===1?r=>Ar.mapMaybe(e,r):Ar.catMaybes(t.map(e))},catMaybes(e){let t=[];for(const r of e)r.isJust()&&t.push(r.extract());return t},encase(e){try{return or(e())}catch{return ft}},isMaybe(e){return e instanceof Ev||e instanceof Cv},sequence(e){let t=[];for(const r of e)if(r.isJust())t.push(r.extract());else return ft;return or(t)},"fantasy-land/of"(e){return this.of(e)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};class Ev{constructor(t){this.__value=t,this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!0}isNothing(){return!1}inspect(){return`Just(${this.__value})`}toString(){return this.inspect()}toJSON(){const t=this.__value;return t instanceof Date?t.toJSON():t}equals(t){return this.extract()===t.extract()}map(t){return or(t(this.__value))}ap(t){return t.isJust()?this.map(t.extract()):ft}alt(t){return this}altLazy(t){return this}chain(t){return t(this.__value)}chainNullable(t){return Ar.fromNullable(t(this.__value))}join(){return this.__value}reduce(t,r){return t(r,this.__value)}extend(t){return or(t(this))}unsafeCoerce(){return this.__value}caseOf(t){return"_"in t?t._():t.Just(this.__value)}orDefault(t){return this.__value}orDefaultLazy(t){return this.__value}toList(){return[this.__value]}mapOrDefault(t,r){return t(this.__value)}extract(){return this.__value}extractNullable(){return this.__value}toEither(t){return Tt(this.__value)}ifJust(t){return t(this.__value),this}ifNothing(t){return this}filter(t){return t(this.__value)?or(this.__value):ft}}Ev.prototype.constructor=Ar;class Cv{constructor(){this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!1}isNothing(){return!0}inspect(){return"Nothing"}toString(){return this.inspect()}toJSON(){return this.__value}equals(t){return this.extract()===t.extract()}map(t){return ft}ap(t){return ft}alt(t){return t}altLazy(t){return t()}chain(t){return ft}chainNullable(t){return ft}join(){return ft}reduce(t,r){return r}extend(t){return ft}unsafeCoerce(){throw new Error("Maybe#unsafeCoerce was ran on a Nothing")}caseOf(t){return"_"in t?t._():t.Nothing()}orDefault(t){return t}orDefaultLazy(t){return t()}toList(){return[]}mapOrDefault(t,r){return r}extract(){}extractNullable(){return null}toEither(t){return yt(t)}ifJust(t){return this}ifNothing(t){return t(),this}filter(t){return ft}}Cv.prototype.constructor=Ar;const or=e=>new Ev(e),ft=new Cv,Tr={of(e){return Tt(e)},lefts(e){let t=[];for(const r of e)r.isLeft()&&t.push(r.extract());return t},rights(e){let t=[];for(const r of e)r.isRight()&&t.push(r.extract());return t},encase(e){try{return Tt(e())}catch(t){return yt(t)}},sequence(e){let t=[];for(const r of e){if(r.isLeft())return r;t.push(r.extract())}return Tt(t)},isEither(e){return e instanceof Rv||e instanceof kv},"fantasy-land/of"(e){return Tr.of(e)}};class kv{constructor(t){this.__value=t,this._="R",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!1}isRight(){return!0}toJSON(){return this.__value}inspect(){return`Right(${this.__value})`}toString(){return this.inspect()}bimap(t,r){return Tt(r(this.__value))}map(t){return Tt(t(this.__value))}mapLeft(t){return this}ap(t){return t.isRight()?this.map(t.extract()):t}equals(t){return t.isRight()?this.__value===t.extract():!1}chain(t){return t(this.__value)}chainLeft(t){return this}join(){return this.__value}alt(t){return this}altLazy(t){return this}reduce(t,r){return t(r,this.__value)}extend(t){return Tt(t(this))}unsafeCoerce(){return this.__value}caseOf(t){return"_"in t?t._():t.Right(this.__value)}leftOrDefault(t){return t}orDefault(t){return this.__value}orDefaultLazy(t){return this.__value}leftOrDefaultLazy(t){return t()}ifLeft(t){return this}ifRight(t){return t(this.__value),this}toMaybe(){return or(this.__value)}leftToMaybe(){return ft}extract(){return this.__value}swap(){return yt(this.__value)}}kv.prototype.constructor=Tr;class Rv{constructor(t){this.__value=t,this._="L",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!0}isRight(){return!1}toJSON(){return this.__value}inspect(){return`Left(${JSON.stringify(this.__value)})`}toString(){return this.inspect()}bimap(t,r){return yt(t(this.__value))}map(t){return this}mapLeft(t){return yt(t(this.__value))}ap(t){return t.isLeft()?t:this}equals(t){return t.isLeft()?t.extract()===this.__value:!1}chain(t){return this}chainLeft(t){return t(this.__value)}join(){return this}alt(t){return t}altLazy(t){return t()}reduce(t,r){return r}extend(t){return this}unsafeCoerce(){throw this.__value instanceof Error?this.__value:new Error("Either#unsafeCoerce was ran on a Left")}caseOf(t){return"_"in t?t._():t.Left(this.__value)}leftOrDefault(t){return this.__value}orDefault(t){return t}orDefaultLazy(t){return t()}leftOrDefaultLazy(t){return this.__value}ifLeft(t){return t(this.__value),this}ifRight(t){return this}toMaybe(){return ft}leftToMaybe(){return or(this.__value)}extract(){return this.__value}swap(){return Tt(this.__value)}}Rv.prototype.constructor=Tr;const yt=e=>new Rv(e),Tt=e=>new kv(e),Ol=e=>e,fz=e=>e,sm=Object.assign(fz,{fromArray:e=>sm.isNonEmpty(e)?or(e):ft,unsafeCoerce:e=>{if(sm.isNonEmpty(e))return e;throw new Error("NonEmptyList#unsafeCoerce was ran on an empty array")},fromTuple:e=>sm(e.toArray()),head:e=>e[0],last:e=>e[e.length-1],isNonEmpty:e=>e.length>0,tail:e=>e.slice(1)}),Wu=(e,t)=>typeof t=="bigint"?t.toString():t,pz=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wo=(e,t)=>{let r="";switch(typeof t){case"undefined":r="undefined";break;case"object":r=t===null?"null":Array.isArray(t)?"an array with value "+JSON.stringify(t,Wu):"an object with value "+JSON.stringify(t,Wu);break;case"boolean":r="a boolean";break;case"symbol":r="a symbol";break;case"function":r="a function";break;case"bigint":r=`a bigint with value ${t.toString()}`}return r=r||`a ${typeof t} with value ${JSON.stringify(t,Wu)}`,`Expected ${e}, but received ${r}`},hz=e=>(Object.keys(e).length===1&&e.oneOf?.length===1&&typeof e.oneOf[0]=="object"&&(Object.assign(e,e.oneOf[0]),delete e.oneOf),e),mz=e=>{if(Array.isArray(e.oneOf))for(let t=0;t<e.oneOf.length;t++){const r=e.oneOf[t];if(typeof r=="object"&&r.oneOf)return e.oneOf.splice(t,1),e.oneOf.push(...r.oneOf),AR(e)}return e},AR=e=>(mz(e),hz(e),e),Ft={interface(e){const t=Object.keys(e),r=o=>{if(!pz(o))return yt(Wo("an object",o));const a={};for(const l of t){if(!o.hasOwnProperty(l)&&!e[l]._isOptional)return yt(`Problem with property "${l}": it does not exist in received object ${JSON.stringify(o,Wu)}`);const u=e[l].decode(o[l]);if(u.isLeft())return yt(`Problem with the value of property "${l}": ${u.extract()}`);const d=u.extract();d!==void 0&&(a[l]=d)}return Tt(a)};return{decode:r,encode:o=>{const a={};for(const l of t)a[l]=e[l].encode(o[l]);return a},unsafeDecode:o=>r(o).mapLeft(Error).unsafeCoerce(),schema:()=>t.reduce((o,a)=>(e[a]._isOptional||o.required.push(a),o.properties[a]=AR(e[a].schema()),o),{type:"object",properties:{},required:[]})}},custom({decode:e,encode:t,schema:r}){return{decode:e,encode:t,unsafeDecode:n=>e(n).mapLeft(Error).unsafeCoerce(),schema:r??(()=>({}))}}},ut=Ft.custom({decode:e=>typeof e=="string"?Tt(e):yt(Wo("a string",e)),encode:Ol,schema:()=>({type:"string"})}),Mo=Ft.custom({decode:e=>typeof e=="number"?Tt(e):yt(Wo("a number",e)),encode:Ol,schema:()=>({type:"number"})}),gz=Ft.custom({decode:e=>e===void 0?Tt(e):yt(Wo("an undefined",e)),encode:Ol}),Yt=e=>({...vz([e,gz]),schema:e.schema,_isOptional:!0}),vd=Ft.custom({decode:e=>typeof e=="boolean"?Tt(e):yt(Wo("a boolean",e)),encode:Ol,schema:()=>({type:"boolean"})}),vz=e=>Ft.custom({decode:t=>{let r=[];for(const n of e){const o=n.decode(t);if(o.isRight())return o;r.push(o.extract())}return yt(`One of the following problems occured: ${r.map((n,o)=>`(${o}) ${n}`).join(", ")}`)},encode:t=>{for(const r of e)if(Tr.encase(()=>r.encode(t)).mapLeft(o=>"").chain(r.decode).isRight())return r.encode(t);return t},schema:()=>({oneOf:e.map(t=>t.schema())})}),Yr=e=>Ft.custom({decode:t=>{if(Array.isArray(t)){const r=[];for(let n=0;n<t.length;n++){const o=e.decode(t[n]);if(o.isRight())r.push(o.extract());else return yt(`Problem with the value at index ${n}: ${o.extract()}`)}return Tt(r)}else return yt(Wo("an array",t))},encode:t=>t.map(e.encode),schema:()=>({type:"array",items:e.schema()})});Ft.custom({decode:e=>ut.decode(e).chain(t=>isFinite(+t)?Tt(t):yt(Wo("a number",e))),encode:Ol,schema:Mo.schema});var TR;const LR={liftEither(e){if(e.isRight())return Promise.resolve(e.extract());throw e.extract()},fromPromise(e){return e.then(LR.liftEither)},throwE(e){throw e}};class IR{constructor(t){this.runPromise=t,this[TR]="EitherAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this.then=(r,n)=>this.run().then(r,n)}leftOrDefault(t){return this.run().then(r=>r.leftOrDefault(t))}orDefault(t){return this.run().then(r=>r.orDefault(t))}join(){return He(async t=>{const r=await this;if(r.isRight()){const n=await r.extract();return t.liftEither(n)}return t.liftEither(r)})}ap(t){return He(async r=>{const n=await t;if(n.isRight()){const o=await this.run();return o.isRight()?n.extract()(o.extract()):r.liftEither(o)}return r.liftEither(n)})}alt(t){return He(async r=>{const n=await this.run();if(n.isRight())return n.extract();{const o=await t;return r.liftEither(o)}})}extend(t){return He(async r=>{const n=await this.run();if(n.isRight()){const o=He.liftEither(n);return r.liftEither(Tt(t(o)))}return r.liftEither(n)})}async run(){try{return Tt(await this.runPromise(LR))}catch(t){return yt(t)}}bimap(t,r){return He(async n=>{const o=await this.run();try{return await n.liftEither(o.bimap(t,r))}catch(a){throw await a}})}map(t){return He(r=>this.runPromise(r).then(t))}mapLeft(t){return He(async r=>{try{return await this.runPromise(r)}catch(n){throw await t(n)}})}chain(t){return He(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}chainLeft(t){return He(async r=>{try{return await this.runPromise(r)}catch(n){return r.fromPromise(t(n))}})}toMaybeAsync(){return hr(async({liftMaybe:t})=>{const r=await this.run();return t(r.toMaybe())})}swap(){return He(async t=>{const r=await this.run();return r.isRight()&&t.throwE(r.extract()),t.liftEither(Tt(r.extract()))})}ifLeft(t){return He(async r=>{const n=await this.run();return n.ifLeft(t),r.liftEither(n)})}ifRight(t){return He(async r=>{const n=await this.run();return n.ifRight(t),r.liftEither(n)})}void(){return this.map(t=>{})}caseOf(t){return this.run().then(r=>r.caseOf(t))}finally(t){return He(({fromPromise:r})=>r(this.run().finally(t)))}}TR=Symbol.toStringTag;const He=Object.assign(e=>new IR(e),{fromPromise:e=>He(({fromPromise:t})=>t(e())),liftEither:e=>He(({liftEither:t})=>t(e)),lefts:e=>Promise.all(e.map(t=>t.run())).then(Tr.lefts),rights:e=>Promise.all(e.map(t=>t.run())).then(Tr.rights),sequence:e=>He(async t=>{let r=[];for await(const n of e){if(n.isLeft())return t.liftEither(n);r.push(n.extract())}return t.liftEither(Tt(r))}),all:e=>He.fromPromise(async()=>Promise.all(e).then(Tr.sequence))});IR.prototype.constructor=He;var OR;const NR={liftMaybe(e){if(e.isJust())return Promise.resolve(e.extract());throw ft},fromPromise(e){return e.then(NR.liftMaybe)}};class PR{constructor(t){this.runPromise=t,this[OR]="MaybeAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/filter"]=this.filter,this["fantasy-land/alt"]=this.alt}orDefault(t){return this.run().then(r=>r.orDefault(t))}join(){return hr(async t=>{const r=await this.run();if(r.isJust()){const n=await r.extract();return t.liftMaybe(n)}return t.liftMaybe(ft)})}ap(t){return hr(async r=>{const n=await t;if(n.isJust()){const o=await this.run();return o.isJust()?n.extract()(o.extract()):r.liftMaybe(ft)}return r.liftMaybe(ft)})}alt(t){return hr(async r=>{const n=await this.run();if(n.isJust())return n.extract();{const o=await t;return r.liftMaybe(o)}})}extend(t){return hr(async r=>{const n=await this.run();if(n.isJust()){const o=hr.liftMaybe(n);return r.liftMaybe(or(t(o)))}return r.liftMaybe(ft)})}filter(t){return hr(async r=>{const n=await this.run();return r.liftMaybe(n.filter(t))})}async run(){try{return or(await this.runPromise(NR))}catch{return ft}}map(t){return hr(r=>this.runPromise(r).then(t))}chain(t){return hr(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}toEitherAsync(t){return He(async({liftEither:r})=>{const n=await this.run();return r(n.toEither(t))})}ifJust(t){return hr(async r=>{const n=await this.run();return n.ifJust(t),r.liftMaybe(n)})}ifNothing(t){return hr(async r=>{const n=await this.run();return n.ifNothing(t),r.liftMaybe(n)})}void(){return this.map(t=>{})}caseOf(t){return this.run().then(r=>r.caseOf(t))}finally(t){return hr(({fromPromise:r})=>r(this.run().finally(t)))}then(t,r){return this.run().then(t,r)}}OR=Symbol.toStringTag;const hr=Object.assign(e=>new PR(e),{catMaybes:e=>Promise.all(e).then(Ar.catMaybes),fromPromise:e=>hr(({fromPromise:t})=>t(e())),liftMaybe:e=>hr(({liftMaybe:t})=>t(e))});PR.prototype.constructor=hr;function Pt(e){return typeof e=="function"}function Gd(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var am=Gd(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription:
27
+ )`}return v.jsx("div",{ref:t,role:"presentation","data-base-ui-inert":"",...n,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:o}})});function iR(e){return e==="starting"?Lj:Rr}const t2=x.createContext(void 0);function r2(e){return x.useContext(t2)}const n2="ArrowUp",i2="ArrowDown",o2="ArrowLeft",s2="ArrowRight",a2="Home",l2=new Set([n2,i2,o2,s2,a2,"End"]);function c2(e,t={}){const r="rootStore"in e?e.rootStore:e,n=r.useState("open"),o=r.useState("floatingElement"),a=r.useState("domReferenceElement"),{dataRef:l}=r.context,{enabled:u=!0,closeDelay:d=0}=t,p=Pk(r),h=ta(),m=Vo(),y=et(()=>Dk(l.current.openEvent?.type,p.interactedInside)),w=et(()=>{const $=l.current.openEvent?.type;return $?.includes("mouse")&&$!=="mousedown"}),E=et($=>Ck($,r.context.triggerElements)),S=x.useCallback($=>{const A=Fu(d,"close",p.pointerType),D=()=>{r.setOpen(!1,zt(Cr,$)),h?.events.emit("floating.closed",$)};A?p.openChangeTimeout.start(A,D):(p.openChangeTimeout.clear(),D())},[d,r,p,h]),C=et(()=>{uv(p)}),R=et($=>{const A=gn($);if(!$M(A)){p.interactedInside=!1;return}p.interactedInside=A?.closest("[aria-haspopup]")!=null});at(()=>{n||(p.pointerType=void 0,p.restTimeoutPending=!1,p.interactedInside=!1,C())},[n,p,C]),x.useEffect(()=>C,[C]),at(()=>{if(u&&n&&p.handleCloseOptions?.blockPointerEvents&&w()&&gt(a)&&o){const $=a,A=o,D=_t(o),N=h?.nodesRef.current.find(I=>I.id===m)?.context?.elements.floating;N&&(N.style.pointerEvents="");const P=p.handleCloseOptions?.getScope?.()??p.pointerEventsScopeElement??N??$.closest("[data-rootownerid]")??D.body;return TM(p,{scopeElement:P,referenceElement:$,floatingElement:A}),()=>{C()}}},[u,n,a,o,p,w,h,m,C]);const k=Vs();x.useEffect(()=>{if(!u)return;function $(){p.openChangeTimeout.clear(),k.clear(),h?.events.off("floating.closed",D),C()}function A(P){if(h&&m&&oi(h.nodesRef.current,m).length>0){h.events.on("floating.closed",D);return}if(!E(P.relatedTarget)){if(p.handler){p.handler(P);return}C(),y()||S(P)}}function D(P){!h||!m||oi(h.nodesRef.current,m).length>0||k.start(0,()=>{h.events.off("floating.closed",D),r.setOpen(!1,zt(Cr,P)),h.events.emit("floating.closed",P)})}const N=o;return N&&(N.addEventListener("mouseenter",$),N.addEventListener("mouseleave",A),N.addEventListener("pointerdown",R,!0)),()=>{N&&(N.removeEventListener("mouseenter",$),N.removeEventListener("mouseleave",A),N.removeEventListener("pointerdown",R,!0)),h?.events.off("floating.closed",D)}},[u,o,r,l,y,E,S,C,R,p,h,m,k])}const uh={inert:new WeakMap,"aria-hidden":new WeakMap},ow="data-base-ui-inert",vg={inert:new WeakSet,"aria-hidden":new WeakSet};let Ja=new WeakMap,dh=0;function u2(e){return vg[e]}function oR(e){return e?bl(e)?e.host:oR(e.parentNode):null}const fh=(e,t)=>t.map(r=>{if(e.contains(r))return r;const n=oR(r);return e.contains(n)?n:null}).filter(r=>r!=null),sw=e=>{const t=new Set;return e.forEach(r=>{let n=r;for(;n&&!t.has(n);)t.add(n),n=n.parentNode}),t},aw=(e,t,r)=>{const n=[],o=a=>{!a||r.has(a)||Array.from(a.children).forEach(l=>{Qi(l)!=="script"&&(t.has(l)?o(l):n.push(l))})};return o(e),n};function d2(e,t,r,n,{mark:o=!0,markerIgnoreElements:a=[]}){const l=n?"inert":r?"aria-hidden":null;let u=null,d=null;const p=fh(t,e),h=o?fh(t,a):[],m=new Set(h),y=o?aw(t,sw(p),new Set(p)).filter(S=>!m.has(S)):[],w=[],E=[];if(l){const S=uh[l],C=u2(l);d=C,u=S;const R=fh(t,Array.from(t.querySelectorAll("[aria-live]"))),k=p.concat(R);aw(t,sw(k),new Set(k)).forEach($=>{const A=$.getAttribute(l),D=A!==null&&A!=="false",N=(S.get($)||0)+1;S.set($,N),w.push($),N===1&&D&&C.add($),D||$.setAttribute(l,l==="inert"?"":"true")})}return o&&y.forEach(S=>{const C=(Ja.get(S)||0)+1;Ja.set(S,C),E.push(S),C===1&&S.setAttribute(ow,"")}),dh+=1,()=>{u&&w.forEach(S=>{const C=(u.get(S)||0)-1;u.set(S,C),C||(!d?.has(S)&&l&&S.removeAttribute(l),d?.delete(S))}),o&&E.forEach(S=>{const C=(Ja.get(S)||0)-1;Ja.set(S,C),C||S.removeAttribute(ow)}),dh-=1,dh||(uh.inert=new WeakMap,uh["aria-hidden"]=new WeakMap,vg.inert=new WeakSet,vg["aria-hidden"]=new WeakSet,Ja=new WeakMap)}}function lw(e,t={}){const{ariaHidden:r=!1,inert:n=!1,mark:o=!0,markerIgnoreElements:a=[]}=t,l=_t(e[0]).body;return d2(e,l,r,n,{mark:o,markerIgnoreElements:a})}function f2(e,t){const r=tr(e.target);return e instanceof r.KeyboardEvent?"keyboard":e instanceof r.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof r.MouseEvent?t||(e.detail===0?"keyboard":"mouse"):""}const cw=20;let Fi=[];function pv(){Fi=Fi.filter(e=>e.deref()?.isConnected)}function p2(e){pv(),e&&Qi(e)!=="body"&&(Fi.push(new WeakRef(e)),Fi.length>cw&&(Fi=Fi.slice(-cw)))}function ph(){return pv(),Fi[Fi.length-1]?.deref()}function h2(e){if(!e)return null;const t=ra();return Vk(e,t)?e:Tl(e,t)[0]||e}function m2(e){return!e||!e.isConnected?!1:typeof e.checkVisibility=="function"?e.checkVisibility():K6(e)}function uw(e,t){if(!t.current.includes("floating")&&!e.getAttribute("role")?.includes("dialog"))return;const r=ra(),n=JM(e,r).filter(a=>{const l=a.getAttribute("data-tabindex")||"";return Vk(a,r)||a.hasAttribute("data-tabindex")&&!l.startsWith("-")}),o=e.getAttribute("tabindex");t.current.includes("floating")||n.length===0?o!=="0"&&e.setAttribute("tabindex","0"):(o!=="-1"||e.hasAttribute("data-tabindex")&&e.getAttribute("data-tabindex")!=="-1")&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function g2(e){const{context:t,children:r,disabled:n=!1,initialFocus:o=!0,returnFocus:a=!0,restoreFocus:l=!1,modal:u=!0,closeOnFocusOut:d=!0,openInteractionType:p="",nextFocusableElement:h,previousFocusableElement:m,beforeContentFocusGuardRef:y,externalTree:w,getInsideElements:E}=e,S="rootStore"in t?t.rootStore:t,C=S.useState("open"),R=S.useState("domReferenceElement"),k=S.useState("floatingElement"),{events:$,dataRef:A}=S.context,D=et(()=>A.current.floatingContext?.nodeId),N=o===!1,P=Mx(R)&&N,I=x.useRef(["content"]),re=Nn(o),Z=Nn(a),ee=Nn(p),ne=ta(w),X=Xk(),F=x.useRef(!1),V=x.useRef(!1),H=x.useRef(!1),O=x.useRef(-1),L=x.useRef(""),U=x.useRef(""),z=x.useRef(null),T=x.useRef(null),M=ud(z,y,X?.beforeInsideRef),te=ud(T,X?.afterInsideRef),le=Vs(),G=Vs(),fe=ev(),be=X!=null,pe=lg(k),ue=et((we=pe)=>we?Tl(we,ra()):[]),ge=et(()=>E?.().filter(we=>we!=null)??[]),qe=et(we=>{const ze=ue(we);return I.current.map(()=>ze).filter(Boolean).flat()});x.useEffect(()=>{if(n||!u)return;function we(We){We.key==="Tab"&&st(pe,$o(_t(pe)))&&ue().length===0&&!P&&p6(We)}const ze=_t(pe);return ze.addEventListener("keydown",we),()=>{ze.removeEventListener("keydown",we)}},[n,R,pe,u,I,P,ue,qe]),x.useEffect(()=>{if(n||!C)return;const we=_t(pe);function ze(){H.current=!1}function We(De){const Fe=gn(De),lt=ge(),Ne=st(k,Fe)||st(R,Fe)||st(X?.portalNode,Fe)||lt.some(oe=>oe===Fe||st(oe,Fe));H.current=!Ne,U.current=De.pointerType||"keyboard",Fe?.closest(`[${lk}]`)&&(V.current=!0)}function tt(){U.current="keyboard"}return we.addEventListener("pointerdown",We,!0),we.addEventListener("pointerup",ze,!0),we.addEventListener("pointercancel",ze,!0),we.addEventListener("keydown",tt,!0),()=>{we.removeEventListener("pointerdown",We,!0),we.removeEventListener("pointerup",ze,!0),we.removeEventListener("pointercancel",ze,!0),we.removeEventListener("keydown",tt,!0)}},[n,k,R,pe,C,X,ge]),x.useEffect(()=>{if(n||!d)return;const we=_t(pe);function ze(){V.current=!0,G.start(0,()=>{V.current=!1})}function We(Ne){const oe=gn(Ne),Se=ue().indexOf(oe);Se!==-1&&(O.current=Se)}function tt(Ne){const oe=Ne.relatedTarget,Se=Ne.currentTarget,Je=gn(Ne);queueMicrotask(()=>{const ht=D(),Bt=S.context.triggerElements,Ut=ge(),jt=oe?.hasAttribute(sd("focus-guard"))&&[z.current,T.current,X?.beforeInsideRef.current,X?.afterInsideRef.current,X?.beforeOutsideRef.current,X?.afterOutsideRef.current,Zn(m),Zn(h)].includes(oe),Vt=!(st(R,oe)||st(k,oe)||st(oe,k)||st(X?.portalNode,oe)||Ut.some(bt=>bt===oe||st(bt,oe))||oe!=null&&Bt.hasElement(oe)||Bt.hasMatchingElement(bt=>st(bt,oe))||jt||ne&&(oi(ne.nodesRef.current,ht).find(bt=>st(bt.context?.elements.floating,oe)||st(bt.context?.elements.domReference,oe))||zx(ne.nodesRef.current,ht).find(bt=>[bt.context?.elements.floating,lg(bt.context?.elements.floating)].includes(oe)||bt.context?.elements.domReference===oe)));if(Se===R&&pe&&uw(pe,I),l&&Se!==R&&!m2(Je)&&$o(we)===we.body){if(Kt(pe)&&(pe.focus(),l==="popup")){fe.request(()=>{pe.focus()});return}const bt=O.current,rt=ue(),q=rt[bt]||rt[rt.length-1]||pe;Kt(q)&&q.focus()}if(A.current.insideReactTree){A.current.insideReactTree=!1;return}(P||!u)&&oe&&Vt&&!V.current&&(P||oe!==ph())&&(F.current=!0,S.setOpen(!1,zt(El,Ne)))})}function De(){H.current||(A.current.insideReactTree=!0,le.start(0,()=>{A.current.insideReactTree=!1}))}const Fe=Kt(R)?R:null,lt=[];if(!(!k&&!Fe))return Fe&&(Fe.addEventListener("focusout",tt),Fe.addEventListener("pointerdown",ze),lt.push(()=>{Fe.removeEventListener("focusout",tt),Fe.removeEventListener("pointerdown",ze)})),k&&(k.addEventListener("focusin",We),k.addEventListener("focusout",tt),X&&(k.addEventListener("focusout",De,!0),lt.push(()=>{k.removeEventListener("focusout",De,!0)})),lt.push(()=>{k.removeEventListener("focusin",We),k.removeEventListener("focusout",tt)})),()=>{lt.forEach(Ne=>{Ne()})}},[n,R,k,pe,u,ne,X,S,d,l,ue,P,D,I,A,le,G,fe,h,m,ge]),x.useEffect(()=>{if(n||!k||!C)return;const we=Array.from(X?.portalNode?.querySelectorAll(`[${sd("portal")}]`)||[]),ze=(ne?zx(ne.nodesRef.current,D()):[]).find(lt=>Mx(lt.context?.elements.domReference||null))?.context?.elements.domReference,We=[k,...we,z.current,T.current,X?.beforeOutsideRef.current,X?.afterOutsideRef.current,...ge(),ze,Zn(m),Zn(h),P?R:null].filter(lt=>lt!=null),tt=lw(We,{ariaHidden:u||P,mark:!1}),De=[k,...we].filter(lt=>lt!=null),Fe=lw(De);return()=>{Fe(),tt()}},[C,n,R,k,u,I,X,P,ne,D,h,m,ge]),at(()=>{if(!C||n||!Kt(pe))return;const we=_t(pe),ze=$o(we);queueMicrotask(()=>{const We=qe(pe),tt=re.current,De=typeof tt=="function"?tt(ee.current||""):tt;if(De===void 0||De===!1)return;let Fe;De===!0||De===null?Fe=We[0]||pe:Fe=Zn(De),Fe=Fe||We[0]||pe,!st(pe,ze)&&sh(Fe,{preventScroll:Fe===pe})})},[n,C,pe,N,qe,re,ee]),at(()=>{if(n||!pe)return;const we=_t(pe),ze=$o(we);p2(ze);function We(De){if(De.open||(L.current=f2(De.nativeEvent,U.current)),De.reason===Cr&&De.nativeEvent.type==="mouseleave"&&(F.current=!0),De.reason===kk)if(De.nested)F.current=!1;else if(m6(De.nativeEvent)||g6(De.nativeEvent))F.current=!1;else{let Fe=!1;document.createElement("div").focus({get preventScroll(){return Fe=!0,!1}}),Fe?F.current=!1:F.current=!0}}$.on("openchange",We);function tt(){const De=Z.current;let Fe=typeof De=="function"?De(L.current):De;if(Fe===void 0||Fe===!1)return null;if(Fe===null&&(Fe=!0),typeof Fe=="boolean"){const Ne=R||ph();return Ne&&Ne.isConnected?Ne:null}const lt=R||ph();return Zn(Fe)||lt||null}return()=>{$.off("openchange",We);const De=$o(we),Fe=ge(),lt=st(k,De)||Fe.some(oe=>oe===De||st(oe,De))||ne&&oi(ne.nodesRef.current,D(),!1).some(oe=>st(oe.context?.elements.floating,De)),Ne=tt();queueMicrotask(()=>{const oe=h2(Ne),Se=typeof Z.current!="boolean";Z.current&&!F.current&&Kt(oe)&&(!(!Se&&oe!==De&&De!==we.body)||lt)&&oe.focus({preventScroll:!0}),F.current=!1})}},[n,k,pe,Z,A,$,ne,R,D,ge]),at(()=>{if(!ik||C||!k)return;const we=$o(_t(k));!Kt(we)||!iv(we)||st(k,we)&&we.blur()},[C,k]),at(()=>{if(!(n||!X))return X.setFocusManagerState({modal:u,closeOnFocusOut:d,open:C,onOpenChange:S.setOpen,domReference:R}),()=>{X.setFocusManagerState(null)}},[n,X,u,C,S,d,R]),at(()=>{if(!(n||!pe))return uw(pe,I),()=>{queueMicrotask(pv)}},[n,pe,I]);const Xe=!n&&(u?!P:!0)&&(be||u);return v.jsxs(x.Fragment,{children:[Xe&&v.jsx(qs,{"data-type":"inside",ref:M,onFocus:we=>{if(u){const ze=qe();sh(ze[ze.length-1])}else X?.portalNode&&(F.current=!1,Ps(we,X.portalNode)?dv(R)?.focus():Zn(m??X.beforeOutsideRef)?.focus())}}),r,Xe&&v.jsx(qs,{"data-type":"inside",ref:te,onFocus:we=>{u?sh(qe()[0]):X?.portalNode&&(d&&(F.current=!0),Ps(we,X.portalNode)?Hk(R)?.focus():Zn(h??X.afterOutsideRef)?.focus())}})]})}function v2(){return{...b6(),disabled:!1,modal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,nested:!1,openOnHover:!1,closeDelay:0,hasViewport:!1}}const y2={...x6,disabled:ct(e=>e.disabled),instantType:ct(e=>e.instantType),openMethod:ct(e=>e.openMethod),openChangeReason:ct(e=>e.openChangeReason),modal:ct(e=>e.modal),stickIfOpen:ct(e=>e.stickIfOpen),titleElementId:ct(e=>e.titleElementId),descriptionElementId:ct(e=>e.descriptionElementId),openOnHover:ct(e=>e.openOnHover),closeDelay:ct(e=>e.closeDelay),hasViewport:ct(e=>e.hasViewport)};let b2=class sR extends fk{constructor(t){const r={...v2(),...t};r.open&&t?.mounted===void 0&&(r.mounted=!0),super(r,{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),stickIfOpenTimeout:new li,triggerElements:new nv},y2)}setOpen=(t,r)=>{const n=r.reason===Cr,o=r.reason===Ws&&r.event.detail===0,a=!t&&(r.reason===Rk||r.reason==null);if(r.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},this.context.onOpenChange?.(t,r),r.isCanceled)return;const l={open:t,nativeEvent:r.event,reason:r.reason,nested:this.state.nested,triggerElement:r.trigger};this.state.floatingRootContext.context.events?.emit("openchange",l);const u=()=>{const d={open:t,openChangeReason:r.reason},p=r.trigger?.id??null;(p||t)&&(d.activeTriggerId=p,d.activeTriggerElement=r.trigger??null),this.update(d)};n?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(Tj,()=>{this.set("stickIfOpen",!1)}),Lr.flushSync(u)):u(),o||a?this.set("instantType",o?"click":"dismiss"):r.reason===El?this.set("instantType","focus"):this.set("instantType",void 0)};static useStore(t,r){const n=yn(()=>new sR(r)).current,o=t??n;return Dd(n.disposeEffect),o}disposeEffect=()=>this.context.stickIfOpenTimeout.disposeEffect()};const aR=x.createContext(void 0);function na(e){const t=x.useContext(aR);if(t===void 0&&!e)throw new Error(Uo(47));return t}function dw({props:e}){const{children:t,open:r,defaultOpen:n=!1,onOpenChange:o,onOpenChangeComplete:a,modal:l=!1,handle:u,triggerId:d,defaultTriggerId:p=null}=e,h=b2.useStore(u?.store,{modal:l,open:n,openProp:r,activeTriggerId:p,triggerIdProp:d});dj(()=>{r===void 0&&h.state.open===!1&&n===!0&&h.update({open:!0,activeTriggerId:p})}),h.useControlledProp("openProp",r),h.useControlledProp("triggerIdProp",d);const m=h.useState("open"),y=h.useState("positionerElement"),w=h.useState("payload"),E=h.useState("openChangeReason");h.useContextCallback("onOpenChange",o),h.useContextCallback("onOpenChangeComplete",a);const{openMethod:S,triggerProps:C}=Mj(m);A6(h);const{forceUnmount:R}=T6(m,h,()=>{h.update({stickIfOpen:!0,openChangeReason:null})});$j(m&&l===!0&&E!==Cr&&S!=="touch",y),x.useEffect(()=>{m||h.context.stickIfOpenTimeout.clear()},[h,m]);const k=x.useCallback(F=>{const V=zt(F);return V.preventUnmountOnClose=()=>{h.set("preventUnmountingOnClose",!0)},V},[h]),$=x.useCallback(()=>{h.setOpen(!1,k(O6))},[h,k]);x.useImperativeHandle(e.actionsRef,()=>({unmount:R,close:$}),[R,$]);const A=L6({popupStore:h,onOpenChange:h.setOpen}),D=j6(A,{outsidePressEvent:{mouse:l==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),N=z6(A),{getReferenceProps:P,getFloatingProps:I,getTriggerProps:re}=$k([D,N]),Z=x.useMemo(()=>P(C),[P,C]),ee=x.useMemo(()=>re(C),[re,C]),ne=x.useMemo(()=>I(),[I]);h.useSyncedValues({modal:l,openMethod:S,activeTriggerProps:Z,inactiveTriggerProps:ee,popupProps:ne,floatingRootContext:A,nested:Vo()!=null});const X=x.useMemo(()=>({store:h}),[h]);return v.jsx(aR.Provider,{value:X,children:typeof t=="function"?t({payload:w}):t})}function x2(e){return na(!0)?v.jsx(dw,{props:e}):v.jsx(E6,{children:v.jsx(dw,{props:e})})}const w2=300,S2=x.forwardRef(function(e,t){const{render:r,className:n,disabled:o=!1,nativeButton:a=!0,handle:l,payload:u,openOnHover:d=!1,delay:p=w2,closeDelay:h=0,id:m,...y}=e,w=na(!0),E=l?.store??w?.store;if(!E)throw new Error(Uo(74));const S=CM(m),C=E.useState("isTriggerActive",S),R=E.useState("floatingRootContext"),k=E.useState("isOpenedByTrigger",S),$=x.useRef(null),{registerTrigger:A,isMountedByThisTrigger:D}=$6(S,$,E,{payload:u,disabled:o,openOnHover:d,closeDelay:h}),N=E.useState("openChangeReason"),P=E.useState("stickIfOpen"),I=E.useState("openMethod"),re=OM(R,{enabled:R!=null&&d&&(I!=="touch"||N!==Ws),mouseOnly:!0,move:!1,handleClose:DM(),restMs:p,delay:{close:h},triggerElementRef:$,isActiveTrigger:C}),Z=jM(R,{enabled:R!=null,stickIfOpen:P}),ee=$k([Z]),ne=E.useState("triggerProps",D),X={disabled:o,open:k},{getButtonProps:F,buttonRef:V}=SM({disabled:o,native:a}),H=x.useMemo(()=>({open(T){return T&&N===Ws?lM.open(T):aM.open(T)}}),[N]),O=Al("button",e,{state:X,ref:[V,t,A,$],props:[ee.getReferenceProps(),re,ne,{[lk]:"",id:S},y,F],stateAttributesMapping:H}),L=x.useRef(null),U=et(T=>{Lr.flushSync(()=>{E.setOpen(!1,zt(El,T.nativeEvent,T.currentTarget))}),e4(L.current)?.focus()}),z=et(T=>{const M=E.select("positionerElement");if(M&&Ps(T,M))E.context.beforeContentFocusGuardRef.current?.focus();else{Lr.flushSync(()=>{E.setOpen(!1,zt(El,T.nativeEvent,T.currentTarget))});let te=ZM(E.context.triggerFocusTargetRef.current||$.current);for(;te!==null&&st(M,te);){const le=te;if(te=dv(te),te===le)break}te?.focus()}});return C?v.jsxs(x.Fragment,{children:[v.jsx(qs,{ref:L,onFocus:U}),v.jsx(x.Fragment,{children:O},S),v.jsx(qs,{ref:E.context.triggerFocusTargetRef,onFocus:z})]}):v.jsx(x.Fragment,{children:O},S)}),lR=x.createContext(void 0);function E2(){const e=x.useContext(lR);if(e===void 0)throw new Error(Uo(45));return e}const C2=x.forwardRef(function(e,t){const{keepMounted:r=!1,...n}=e,{store:o}=na();return o.useState("mounted")||r?v.jsx(lR.Provider,{value:r,children:v.jsx(i4,{ref:t,...n})}):null}),k2={...cv,...yk},R2=x.forwardRef(function(e,t){const{className:r,render:n,...o}=e,{store:a}=na(),l=a.useState("open"),u=a.useState("mounted"),d=a.useState("transitionStatus"),p=a.useState("openChangeReason");return Al("div",e,{state:{open:l,transitionStatus:d},ref:[a.context.backdropRef,t],props:[{role:"presentation",hidden:!u,style:{pointerEvents:p===Cr?"none":void 0,userSelect:"none",WebkitUserSelect:"none"}},o],stateAttributesMapping:k2})}),cR=x.createContext(void 0);function _2(){const e=x.useContext(cR);if(!e)throw new Error(Uo(46));return e}const $2=x.forwardRef(function(e,t){const{render:r,className:n,anchor:o,positionMethod:a="absolute",side:l="bottom",align:u="center",sideOffset:d=0,alignOffset:p=0,collisionBoundary:h="clipping-ancestors",collisionPadding:m=5,arrowPadding:y=5,sticky:w=!1,disableAnchorTracking:E=!1,collisionAvoidance:S=Ij,...C}=e,{store:R}=na(),k=E2(),$=w6(),A=R.useState("floatingRootContext"),D=R.useState("mounted"),N=R.useState("open"),P=R.useState("openChangeReason"),I=R.useState("activeTriggerElement"),re=R.useState("modal"),Z=R.useState("positionerElement"),ee=R.useState("instantType"),ne=R.useState("transitionStatus"),X=R.useState("hasViewport"),F=x.useRef(null),V=bk(Z,!1,!1),H=Z4({anchor:o,floatingRootContext:A,positionMethod:a,mounted:D,side:l,sideOffset:d,align:u,alignOffset:p,arrowPadding:y,collisionBoundary:h,collisionPadding:m,sticky:w,disableAnchorTracking:E,keepMounted:k,nodeId:$,collisionAvoidance:S,adaptiveOrigin:X?K4:void 0}),O=x.useMemo(()=>{const te={};return N||(te.pointerEvents="none"),{role:"presentation",hidden:!D,style:{...H.positionerStyles,...te}}},[N,D,H.positionerStyles]),L=x.useMemo(()=>({props:O,...H}),[O,H]),U=A.useState("domReferenceElement");at(()=>{const te=U,le=F.current;if(te&&(F.current=te),le&&te&&te!==le){R.set("instantType",void 0);const G=new AbortController;return V(()=>{R.set("instantType","trigger-change")},G.signal),()=>{G.abort()}}},[U,V,R]);const z={open:N,side:L.side,align:L.align,anchorHidden:L.anchorHidden,instant:ee},T=x.useCallback(te=>{R.set("positionerElement",te)},[R]),M=Al("div",e,{state:z,props:[L.props,iR(ne),C],ref:[t,T],stateAttributesMapping:cv});return v.jsxs(cR.Provider,{value:L,children:[D&&re===!0&&P!==Cr&&v.jsx(e2,{ref:R.context.internalBackdropRef,inert:o4(!N),cutout:I}),v.jsx(S6,{id:$,children:M})]})}),A2=x.createContext(void 0);function T2(){const[e,t]=x.useState(0),r=et(()=>(t(n=>n+1),()=>{t(n=>Math.max(0,n-1))}));return{context:x.useMemo(()=>({register:r}),[r]),hasClosePart:e>0}}function L2(e){const{value:t,children:r}=e;return v.jsx(A2.Provider,{value:t,children:r})}const I2={...cv,...yk},O2=x.forwardRef(function(e,t){const{className:r,render:n,initialFocus:o,finalFocus:a,...l}=e,{store:u}=na(),d=_2(),p=r2()!=null,{context:h,hasClosePart:m}=T2(),y=u.useState("open"),w=u.useState("openMethod"),E=u.useState("instantType"),S=u.useState("transitionStatus"),C=u.useState("popupProps"),R=u.useState("titleElementId"),k=u.useState("descriptionElementId"),$=u.useState("modal"),A=u.useState("mounted"),D=u.useState("openChangeReason"),N=u.useState("activeTriggerElement"),P=u.useState("floatingRootContext");xk({open:y,ref:u.context.popupRef,onComplete(){y&&u.context.onOpenChangeComplete?.(!0)}});const I=u.useState("disabled"),re=u.useState("openOnHover"),Z=u.useState("closeDelay");c2(P,{enabled:re&&!I,closeDelay:Z});function ee(O){return O==="touch"?u.context.popupRef.current:!0}const ne=o===void 0?ee:o,X={open:y,side:d.side,align:d.align,instant:E,transitionStatus:S},F=$!==!1&&m,V=x.useCallback(O=>{u.set("popupElement",O)},[u]),H=Al("div",e,{state:X,ref:[t,u.context.popupRef,V],props:[C,{"aria-labelledby":R,"aria-describedby":k,onKeyDown(O){p&&l2.has(O.key)&&O.stopPropagation()}},iR(S),l],stateAttributesMapping:I2});return v.jsx(g2,{context:P,openInteractionType:w,modal:F,disabled:!A||D===Cr,initialFocus:ne,returnFocus:a,restoreFocus:"popup",previousFocusableElement:Kt(N)?N:void 0,nextFocusableElement:u.context.triggerFocusTargetRef,beforeContentFocusGuardRef:u.context.beforeContentFocusGuardRef,children:v.jsx(L2,{value:h,children:H})})}),[N2,P2]=Cd("Popover"),D2=kr(["overflow-hidden rounded-md bg-canvas-sheet p-16 outline-none","shadow-xl","data-open:data-[side=top]:animate-slide-in-from-bottom","data-closed:data-[side=top]:animate-slide-out-to-bottom","data-open:data-[side=bottom]:animate-slide-in-from-top","data-closed:data-[side=bottom]:animate-slide-out-to-top","data-open:data-[side=left]:animate-slide-in-from-right","data-closed:data-[side=left]:animate-slide-out-to-right","data-open:data-[side=right]:animate-slide-in-from-left","data-closed:data-[side=right]:animate-slide-out-to-left"],{variants:{width:{fit:"",fixed:"w-400"}},defaultVariants:{width:"fit"}}),j2=Qt("fixed inset-0 z-dialog-overlay bg-canvas-overlay-subtle","data-open:animate-fade-in","data-closed:animate-fade-out"),M2=({open:e,defaultOpen:t,onOpenChange:r,overlay:n=!1,handle:o,children:a})=>v.jsx(N2,{value:{overlay:n},children:v.jsx(x2,{open:e,defaultOpen:t,onOpenChange:r,modal:n,handle:o,children:a})}),z2=({handle:e,payload:t,render:r,className:n,...o})=>v.jsx(S2,{"data-slot":"popover-trigger",handle:e,payload:t,render:r,className:Qt("data-popup-open:z-menu",n),...o}),F2=({side:e="bottom",sideOffset:t=8,align:r="start",width:n="fit",initialFocus:o=!1,className:a,children:l})=>{const{overlay:u}=P2({consumerName:"PopoverContent",contextRequired:!0});return v.jsxs(C2,{children:[u&&v.jsx(R2,{"data-slot":"popover-overlay",className:j2}),v.jsx($2,{"data-slot":"popover-positioner",className:"z-menu",side:e,sideOffset:t,align:r,children:v.jsx(O2,{"data-slot":"popover-content",initialFocus:o,className:Qt(D2({width:n}),a),children:l})})]})},B2=pt("ChevronLeft",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M9.333 5.333 6.667 8l2.666 2.667"})})),[U2,V2]=Cd("SegmentedControl"),W2=()=>V2({consumerName:"SegmentedControlButton",contextRequired:!0});function H2({ref:e,selectedIndex:t,children:r}){const[n,o]=x.useState({width:0,height:0,x:0}),[a,l]=x.useState(!1);return x.useLayoutEffect(()=>{const u=e.current;if(!u)return;const d=()=>{const h=Array.from(u.children).slice(0,-1),m=t>=0?h[t]:void 0;o({width:m?.offsetWidth??0,height:u.offsetHeight,x:m?.offsetLeft??0})};if(d(),typeof ResizeObserver>"u")return;const p=new ResizeObserver(d);return p.observe(u),()=>p.disconnect()},[r,t,e]),x.useEffect(()=>{const u=requestAnimationFrame(()=>{l(!0)});return()=>cancelAnimationFrame(u)},[]),{pill:n,isReady:a}}function q2(e,t){return x.useMemo(()=>x.Children.toArray(t).findIndex(r=>x.isValidElement(r)&&r.props.value===e),[e,t])}function G2(e){const{canScrollLeft:t,canScrollRight:r}=qD(e),n=x.useCallback(o=>{const a=e.current;if(!a)return;const l=a.clientWidth/2;a.scrollBy({left:o==="left"?-l:l,behavior:"smooth"})},[e]);return{canScrollLeft:t,canScrollRight:r,scrollBy:n}}function X2(e,t){x.useLayoutEffect(()=>{if(t<0)return;const r=e.current;if(!r)return;const n=r.querySelectorAll('button[role="radio"]')[t];if(n){const{offsetLeft:o,offsetWidth:a}=n,{clientWidth:l}=r;r.scrollLeft=o-(l-a)/2}},[])}const Ll={root:kr("relative flex-row items-center rounded-sm",{variants:{tabLayout:{fit:"inline-flex",fixed:"flex w-full"}}}),pill:kr("pointer-events-none absolute top-0 left-0 z-0 rounded-sm",{variants:{disabled:{true:"bg-base-transparent-pressed",false:"bg-muted-transparent"},isReady:{true:"transition-[transform,width] duration-250 ease-in-out",false:"transition-none"}}}),item:kr("z-10 flex cursor-pointer flex-row items-center justify-center rounded-sm px-16 py-8 select-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus disabled:cursor-not-allowed",{variants:{selected:{true:"body-2-semi-bold",false:"body-2"},disabled:{true:"text-muted",false:""}},compoundVariants:[{selected:!0,disabled:!1,className:"text-base"},{selected:!1,disabled:!1,className:"text-muted hover:text-muted-hover"}]}),scrollArea:kr("relative rounded-sm",{variants:{appearance:{background:"bg-surface","no-background":"bg-transparent"},tabLayout:{fit:"",fixed:"w-full"}}}),arrow:kr("absolute inset-y-0 z-20 flex cursor-pointer items-center justify-center rounded-sm py-8 text-muted transition-opacity duration-200 hover:text-muted-hover",{variants:{visible:{true:"opacity-100",false:"pointer-events-none opacity-0"},side:{left:"left-0 pr-16 pl-8",right:"right-0 pr-8 pl-16"}}})};function Y2(e,t){return`linear-gradient(to right, ${e?"transparent 0px, transparent 40px, black 72px":"black 0px"}, ${t?"black calc(100% - 72px), transparent calc(100% - 40px), transparent 100%":"black 100%"})`}function fw({side:e,icon:t,visible:r,onClick:n}){return v.jsx("button",{type:"button","aria-hidden":!0,tabIndex:-1,disabled:!r,onClick:n,className:Ll.arrow({visible:r,side:e}),children:v.jsx(t,{size:20})})}function K2({appearance:e,tabLayout:t,className:r,selectedIndex:n,children:o,...a}){const l=x.useRef(null),{canScrollLeft:u,canScrollRight:d,scrollBy:p}=G2(l);X2(l,n);const h=u||d?Y2(u,d):void 0;return v.jsxs("div",{...a,className:Qt(Ll.scrollArea({appearance:e,tabLayout:t}),r),children:[v.jsx("div",{ref:l,className:"scrollbar-none overflow-x-auto",style:h?{maskImage:h,WebkitMaskImage:h}:void 0,children:o}),v.jsx(fw,{side:"left",icon:B2,visible:u,onClick:()=>p("left")}),v.jsx(fw,{side:"right",icon:Nd,visible:d,onClick:()=>p("right")})]})}function Q2({layout:e,isReady:t,disabled:r}){return v.jsx("div",{"aria-hidden":!0,className:Ll.pill({disabled:r,isReady:t}),style:{width:e.width,height:e.height,transform:`translateX(${e.x}px)`}})}function J2({tabLayout:e,disabled:t,selectedIndex:r,children:n}){const o=x.useRef(null),{pill:a,isReady:l}=H2({ref:o,selectedIndex:r,children:n});return v.jsxs("div",{ref:o,role:"radiogroup","aria-disabled":t,className:Ll.root({tabLayout:e}),children:[n,v.jsx(Q2,{layout:a,isReady:l,disabled:t})]})}function pw({value:e,children:t,icon:r,trailingContent:n,onClick:o,className:a,disabled:l,...u}){const{selectedValue:d,onSelectedChange:p,disabled:h,tabLayout:m}=W2(),y=d===e,w=x.useMemo(()=>!!(l||h),[l,h]);return v.jsx("button",{type:"button",role:"radio","aria-checked":y,"aria-disabled":w,disabled:w,onClick:E=>{w||(p(e),o?.(E))},className:Qt(Ll.item({selected:y,disabled:w}),m==="fixed"&&"min-w-0 flex-1",a),...u,children:v.jsxs("span",{className:"inline-flex min-w-0 items-center justify-center gap-8",children:[r&&v.jsx(r,{size:16,className:"shrink-0"}),v.jsx("span",{className:"min-w-0 truncate",children:t}),n]})})}function Z2({selectedValue:e,onSelectedChange:t,children:r,className:n,disabled:o,appearance:a="background",tabLayout:l="fixed",...u}){const d=Ks({consumerName:"SegmentedControl",mergeWith:{disabled:o}}),p=q2(e,r);return v.jsx(U2,{value:{selectedValue:e,onSelectedChange:h=>t(h),disabled:d,tabLayout:l},children:v.jsx(K2,{...u,appearance:a,tabLayout:l,className:n,selectedIndex:p,children:v.jsx(J2,{tabLayout:l,disabled:d,selectedIndex:p,children:r})})})}const e5={md:16,sm:12},yg=({icon:e,size:t="md",...r})=>{const n=e,o=e5[t];return v.jsx(nj,{...r,size:t,variant:"tag",consumerName:"Tag",leadingContent:n?v.jsx(n,{size:o}):void 0})},gd={light:"light",dark:"dark",system:"system"},t5=()=>window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",r5=e=>{const t=window.matchMedia("(prefers-color-scheme: dark)");return t.addEventListener("change",e),()=>t.removeEventListener("change",e)},n5=()=>()=>{},i5=e=>{const t=e===gd.system;return x.useSyncExternalStore(t?r5:n5,t?t5:()=>e,()=>"light")},o5=e=>{x.useLayoutEffect(()=>{const t=window.document.documentElement;t.classList.remove(gd.light,gd.dark),t.classList.add(e)},[e])},[s5,a5]=Cd("ThemeProvider"),l5=({children:e,colorScheme:t=gd.system,locale:r})=>{const n=i5(t);o5(n);const o=x.useMemo(()=>({colorScheme:n}),[n]);return v.jsx(s5,{value:o,children:v.jsx(xO,{locale:r,children:e})})},c5=()=>a5({consumerName:"useTheme",contextRequired:!0}),u5=pt("ArrowDown",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 12.667V3.333m3.334 5.994-3.34 3.333-3.34-3.34"})})),uR=pt("ArrowUp",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 3.333v9.334m-3.334-6L8 3.327l3.333 3.333"})})),dR=pt("Copy",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M10 4v-.667C10 2.6 9.4 2 8.667 2H3.333C2.593 2 2 2.6 2 3.333v5.334C2 9.407 2.593 10 3.333 10H4m2-2.667v5.334C6 13.403 6.597 14 7.333 14h5.334c.736 0 1.333-.597 1.333-1.333V7.333C14 6.597 13.403 6 12.667 6H7.333C6.597 6 6 6.597 6 7.333"})})),d5=pt("Devices",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M6.667 14H3.333C2.593 14 2 13.4 2 12.667V3.333C2 2.593 2.593 2 3.333 2H10c.733 0 1.333.593 1.333 1.333v1.334m-.666 7.66H12M12.8 14H9.867a1.2 1.2 0 0 1-1.2-1.2V7.867c0-.667.533-1.2 1.2-1.2H12.8c.66 0 1.2.533 1.2 1.2V12.8c0 .66-.54 1.2-1.2 1.2"})})),fR=pt("Download",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M5.63 7.407 8 9.778l2.37-2.37M8 9.777V2.667m5.333 8.296a2.37 2.37 0 0 1-2.37 2.37H5.037a2.37 2.37 0 0 1-2.37-2.37"})})),pR=pt("Flex",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{fill:"currentColor",d:"M12.017 14v.65h1.3V14h-1.3m-9.334 0v.65h1.3V14h-1.3m2.817-.65h-.65v1.3h.65v-1.3m5 1.3h.65v-1.3h-.65v1.3m-5-1.967a.65.65 0 1 0 0 1.3v-1.3m5 1.3a.65.65 0 1 0 0-1.3v1.3m2.167.017h.65V6.667h-1.3V14zm0-7.333h.65v-2h-1.3v2zm0-2h.65V4h-1.3v.667zm-2-2.667v-.65H5.333v1.3h5.334zM3.333 4h-.65v10h1.3V4zm2-2v-.65A2.65 2.65 0 0 0 2.683 4h1.3c0-.746.605-1.35 1.35-1.35zm7.334 2h.65a2.65 2.65 0 0 0-2.65-2.65v1.3c.745 0 1.35.604 1.35 1.35zm0 .667v.65h.466v-1.3h-.466zm.6.133h-.65v1.733h1.3V4.8zm-.134 1.867v-.65h-.466v1.3h.466zm.134-.134h-.65c0-.285.231-.516.516-.516v1.3c.433 0 .784-.351.784-.784zm-.134-1.866v.65a.517.517 0 0 1-.516-.517h1.3a.783.783 0 0 0-.784-.783zM5.5 14v.65h5v-1.3h-5zm0-.667v.65h5v-1.3h-5z"})})),f5=pt("Moon",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M13.133 10c-1.666.533-3.6.2-4.933-1.133-1.667-1.667-1.8-4.334-.467-6.2C5 2.933 2.867 5.2 2.867 8c0 2.933 2.4 5.333 5.333 5.333 2.2 0 4.133-1.4 4.933-3.333",clipRule:"evenodd"})})),Vu=pt("Nano",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M11.333 11.944a.279.279 0 0 0 .556 0 .28.28 0 0 0-.278-.277.28.28 0 0 0-.278.283M6.172 8 3.236 5.064a.333.333 0 0 1 0-.471l2.357-2.357c.13-.13.341-.13.471 0L11.83 8m-9.536 6H12a2 2 0 1 0 0-4H2.293a.293.293 0 0 0-.293.293v3.414c0 .162.131.293.293.293"})})),hR=pt("NanoGen5",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M11 1.333c.92 0 1.667.747 1.667 1.667v.333c.184 0 .333.15.333.334v1.666a.334.334 0 0 1-.266.327l-.067.007V13c0 .92-.746 1.667-1.667 1.667H5c-.92 0-1.667-.746-1.667-1.667V3c0-.92.747-1.667 1.667-1.667zM9.667 12.667a.667.667 0 0 0 0 1.333H11a.667.667 0 0 0 0-1.333zM5 2.333A.667.667 0 0 0 4.333 3v8c0 .368.299.667.667.667h6a.667.667 0 0 0 .667-.667V3A.667.667 0 0 0 11 2.333z",clipRule:"evenodd"})})),p5=pt("Screens",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M5.332 1.998h5.336m-6.67 2.5h8.004m.233 9.505h-8.47a1.334 1.334 0 0 1-1.327-1.2l-.434-4.336A1.334 1.334 0 0 1 3.331 7h9.338a1.334 1.334 0 0 1 1.327 1.467l-.434 4.335a1.334 1.334 0 0 1-1.327 1.2"})})),h5=pt("Send",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 2v9.334M13.332 14H2.667m1.999-8.666L8 2l3.333 3.334"})})),hv=pt("SparksFill",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{fill:"currentColor",d:"M8 1.333a.333.333 0 0 0-.667 0v.223c0 .39-.145.76-.398 1.029A1.28 1.28 0 0 1 6 3a.333.333 0 1 0 0 .667c.346 0 .683.146.935.415.253.27.398.64.398 1.03v.221a.333.333 0 1 0 .667 0v-.222c0-.39.145-.76.398-1.029.252-.269.589-.415.935-.415a.333.333 0 1 0 0-.667c-.346 0-.683-.147-.935-.415A1.5 1.5 0 0 1 8 1.555zM12 5.267a.333.333 0 1 0-.667 0c0 .55-.213 1.077-.589 1.464a1.97 1.97 0 0 1-1.41.602.333.333 0 0 0 0 .667c.527 0 1.034.215 1.41.602s.59.914.59 1.465a.333.333 0 0 0 .666 0c0-.551.213-1.078.59-1.465A1.97 1.97 0 0 1 14 8a.333.333 0 0 0 0-.667 1.97 1.97 0 0 1-1.41-.602A2.1 2.1 0 0 1 12 5.267M6 7.333a.333.333 0 0 0-.667 0A3.333 3.333 0 0 1 2 10.667a.333.333 0 1 0 0 .666 3.333 3.333 0 0 1 3.333 3.334.333.333 0 0 0 .667 0 3.334 3.334 0 0 1 3.333-3.334.333.333 0 1 0 0-.666A3.333 3.333 0 0 1 6 7.333"})})),mR=pt("Stax",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",d:"M12 4.667h.467c.073 0 .133.06.133.133v1.733c0 .074-.06.134-.133.134H12M4.333 14h6.334c.736 0 1.333-.597 1.333-1.333V3.333C12 2.597 11.403 2 10.667 2H4.333A.333.333 0 0 0 4 2.333v11.334c0 .184.15.333.333.333Z"})})),m5=pt("Sun",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M8 2.667V1.333m0 13.334v-1.334m4.24-9.573.473-.473m-9.426 9.426.473-.473M13.333 8h1.334M1.333 8h1.334m9.573 4.24.473.473M3.287 3.287l.473.473m6.597 1.883a3.333 3.333 0 1 1-4.714 4.714 3.333 3.333 0 0 1 4.714-4.714"})})),gR=pt("Trash",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"M12.333 4.333v8.334A1.333 1.333 0 0 1 11 14H5a1.334 1.334 0 0 1-1.333-1.333V4.333m9.666 0H2.667m6.666 7v-4m-2.666 4v-4m-1-3V3a1 1 0 0 1 1-1h2.666a1 1 0 0 1 1 1v1"})})),g5=pt("Unlink",v.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 16 16",children:v.jsx("path",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",d:"m11.403 8.36 1.458-1.458a2.75 2.75 0 0 0-3.889-3.89L7.514 4.472M5.5 10.374l1.25-1.25m2.5-2.5 1.25-1.25m2.187 7.187L3.313 3.187m1.284 4.201L3.139 8.846a2.75 2.75 0 1 0 3.889 3.89l1.458-1.459"})})),vt=({label:e,side:t="top",className:r="",children:n})=>v.jsxs(GC,{children:[v.jsx(XC,{asChild:!0,children:v.jsx("span",{className:`flex ${r}`,children:n})}),v.jsx(YC,{side:t,children:e})]}),vR=x.createContext(null),bg=x.createContext(!0),yR=x.createContext(!0),bR="AI debugging is not available here yet. Use the DevTools desktop app.",xR=({label:e,detail:t,onClear:r,onExplain:n})=>{const o=x.useContext(vR),a=x.useContext(bg),l=x.useContext(yR);if(!a)return null;const u=v.jsxs("button",{type:"button",onClick:n,disabled:!l,className:"flex cursor-pointer items-center gap-6 rounded-sm bg-accent px-12 py-6 body-3-semi-bold text-on-accent hover:bg-accent-hover disabled:pointer-events-none disabled:bg-muted-transparent disabled:text-disabled",children:[v.jsx(hv,{size:16}),"Explain with AI"]}),d=v.jsxs("div",{className:"flex shrink-0 items-center gap-10 border-t border-muted-subtle bg-surface px-12 py-8",children:[v.jsx("span",{className:"body-3-semi-bold",children:e}),v.jsx("span",{className:"truncate body-4 text-muted",children:t}),v.jsx("span",{className:"flex-1"}),v.jsx("button",{type:"button",onClick:r,className:"cursor-pointer rounded-sm bg-muted-transparent px-12 py-6 body-3-semi-bold hover:bg-muted-transparent-hover",children:"Clear"}),l?u:v.jsx(vt,{label:bR,children:u})]});return o?Lr.createPortal(d,o):d};var Di=(e=>(e.logs="logs",e.inspector="inspector",e))(Di||{});const v5=({size:e=16,className:t})=>v.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.4","aria-hidden":"true",className:t,children:[v.jsx("rect",{x:"2",y:"2.5",width:"12",height:"11",rx:"1.5"}),v.jsx("path",{d:"M6 2.5v11"})]}),hw=({connected:e})=>v.jsx("span",{className:`size-8 shrink-0 rounded-full ${e?"bg-(--color-light-green-500)":"bg-(--color-light-yellow-500)"}`,title:e?"Connected":"Not connected"}),y5=({currentScreen:e,onScreenChange:t,aiOpen:r,onToggleAi:n,aiAvailable:o,sessions:a,liveScreen:l,isLoggerConnected:u,isInspectorConnected:d,mockServerWebsiteUrl:p,colorScheme:h,onColorSchemeChange:m})=>{const y=h==="dark"?"light":"dark";return v.jsxs("div",{className:"flex shrink-0 items-center gap-16 border-b border-muted-subtle px-12 py-8",children:[v.jsxs(Z2,{selectedValue:e,onSelectedChange:w=>t(w),tabLayout:"fixed",className:"w-256 shrink-0 bg-muted-transparent","aria-label":"Screen",children:[v.jsx(pw,{value:"logs",trailingContent:v.jsx(hw,{connected:u}),children:"Logger"}),v.jsx(pw,{value:"inspector",trailingContent:v.jsx(hw,{connected:d}),children:"Inspector"})]}),v.jsxs("div",{className:"ml-auto flex items-center gap-6",children:[a&&v.jsx(vt,{label:a.shown?"Hide the sessions menu":"Show the sessions menu",side:"bottom",children:v.jsx(sr,{"aria-label":a.shown?"Hide the sessions menu":"Show the sessions menu","aria-pressed":a.shown,icon:v5,size:"xs",appearance:"transparent",className:`rounded-sm ${a.shown?"bg-active-subtle [&>svg]:text-active":""}`,onClick:a.onToggle})}),l&&v.jsx(vt,{label:l.shown?"Hide the live screen":"Show the live screen",side:"bottom",children:v.jsx(sr,{"aria-label":l.shown?"Hide the live screen":"Show the live screen","aria-pressed":l.shown,icon:p5,size:"xs",appearance:"transparent",className:`rounded-sm ${l.shown?"bg-active-subtle [&>svg]:text-active":""}`,onClick:l.onToggle})}),v.jsx(vt,{label:o?r?"Hide the AI panel":"Show the AI panel":bR,side:"bottom",children:v.jsx(sr,{"aria-label":r?"Hide the AI panel":"Show the AI panel","aria-pressed":r,icon:hv,size:"xs",appearance:"transparent",className:`rounded-sm disabled:pointer-events-none ${r?"bg-active-subtle [&>svg]:text-active":""}`,onClick:n,disabled:!o})}),p&&v.jsx(vt,{label:"Open the mock server website",side:"bottom",children:v.jsx(sr,{"aria-label":"Open the mock server website",icon:tj,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:()=>window.open(p,"_blank","noopener")})}),v.jsx(vt,{label:`Switch to ${y} theme`,side:"bottom",children:v.jsx(sr,{"aria-label":`Switch to ${y} theme`,icon:h==="dark"?m5:f5,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:()=>m(y)})})]})]})},Es={CONNECTED_DEVICES_UPDATE:"connectedDevicesUpdate",DEVICE_SESSION_STATE_UPDATE:"deviceSessionStateUpdate",PROVIDER_VALUE:"providerValue",APDU_RESPONSE:"apduResponse",DISCOVERED_DEVICES_UPDATE:"discoveredDevicesUpdate",MOCK_SERVER_CONFIG:"mockServerConfig"},zi={SEND_APDU:"sendApdu",GET_PROVIDER:"getProvider",SET_PROVIDER:"setProvider",START_LISTENING_DEVICES:"startListeningDevices",STOP_LISTENING_DEVICES:"stopListeningDevices",START_DISCOVERING:"startDiscovering",STOP_DISCOVERING:"stopDiscovering",CONNECT_DEVICE:"connectDevice"},mw={LOGGER:"logger",DMK_INSPECTOR:"dmk-inspector"},b5="moduleConnected";var gw;(function(e){(function(t){var r=typeof globalThis=="object"?globalThis:typeof self=="object"||typeof self=="object"?self:typeof this=="object"?this:u(),n=o(e);typeof r.Reflect<"u"&&(n=o(r.Reflect,n)),t(n,r),typeof r.Reflect>"u"&&(r.Reflect=e);function o(d,p){return function(h,m){Object.defineProperty(d,h,{configurable:!0,writable:!0,value:m}),p&&p(h,m)}}function a(){try{return Function("return this;")()}catch{}}function l(){try{return(0,eval)("(function() { return this; })()")}catch{}}function u(){return a()||l()}})(function(t,r){var n=Object.prototype.hasOwnProperty,o=typeof Symbol=="function",a=o&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",l=o&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",u=typeof Object.create=="function",d={__proto__:[]}instanceof Array,p=!u&&!d,h={create:u?function(){return rt(Object.create(null))}:d?function(){return rt({__proto__:null})}:function(){return rt({})},has:p?function(q,Q){return n.call(q,Q)}:function(q,Q){return Q in q},get:p?function(q,Q){return n.call(q,Q)?q[Q]:void 0}:function(q,Q){return q[Q]}},m=Object.getPrototypeOf(Function),y=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:jt(),w=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Vt(),E=typeof WeakMap=="function"?WeakMap:bt(),S=o?Symbol.for("@reflect-metadata:registry"):void 0,C=Je(),R=ht(C);function k(q,Q,ie,se){if(M(ie)){if(!qe(q))throw new TypeError;if(!we(Q))throw new TypeError;return ne(q,Q)}else{if(!qe(q))throw new TypeError;if(!G(Q))throw new TypeError;if(!G(se)&&!M(se)&&!te(se))throw new TypeError;return te(se)&&(se=void 0),ie=ge(ie),X(q,Q,ie,se)}}t("decorate",k);function $(q,Q){function ie(se,Ce){if(!G(se))throw new TypeError;if(!M(Ce)&&!ze(Ce))throw new TypeError;L(q,Q,se,Ce)}return ie}t("metadata",$);function A(q,Q,ie,se){if(!G(ie))throw new TypeError;return M(se)||(se=ge(se)),L(q,Q,ie,se)}t("defineMetadata",A);function D(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),F(q,Q,ie)}t("hasMetadata",D);function N(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),V(q,Q,ie)}t("hasOwnMetadata",N);function P(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),H(q,Q,ie)}t("getMetadata",P);function I(q,Q,ie){if(!G(Q))throw new TypeError;return M(ie)||(ie=ge(ie)),O(q,Q,ie)}t("getOwnMetadata",I);function re(q,Q){if(!G(q))throw new TypeError;return M(Q)||(Q=ge(Q)),U(q,Q)}t("getMetadataKeys",re);function Z(q,Q){if(!G(q))throw new TypeError;return M(Q)||(Q=ge(Q)),z(q,Q)}t("getOwnMetadataKeys",Z);function ee(q,Q,ie){if(!G(Q))throw new TypeError;if(M(ie)||(ie=ge(ie)),!G(Q))throw new TypeError;M(ie)||(ie=ge(ie));var se=Ut(Q,ie,!1);return M(se)?!1:se.OrdinaryDeleteMetadata(q,Q,ie)}t("deleteMetadata",ee);function ne(q,Q){for(var ie=q.length-1;ie>=0;--ie){var se=q[ie],Ce=se(Q);if(!M(Ce)&&!te(Ce)){if(!we(Ce))throw new TypeError;Q=Ce}}return Q}function X(q,Q,ie,se){for(var Ce=q.length-1;Ce>=0;--Ce){var Ve=q[Ce],Ke=Ve(Q,ie,se);if(!M(Ke)&&!te(Ke)){if(!G(Ke))throw new TypeError;se=Ke}}return se}function F(q,Q,ie){var se=V(q,Q,ie);if(se)return!0;var Ce=oe(Q);return te(Ce)?!1:F(q,Ce,ie)}function V(q,Q,ie){var se=Ut(Q,ie,!1);return M(se)?!1:pe(se.OrdinaryHasOwnMetadata(q,Q,ie))}function H(q,Q,ie){var se=V(q,Q,ie);if(se)return O(q,Q,ie);var Ce=oe(Q);if(!te(Ce))return H(q,Ce,ie)}function O(q,Q,ie){var se=Ut(Q,ie,!1);if(!M(se))return se.OrdinaryGetOwnMetadata(q,Q,ie)}function L(q,Q,ie,se){var Ce=Ut(ie,se,!0);Ce.OrdinaryDefineOwnMetadata(q,Q,ie,se)}function U(q,Q){var ie=z(q,Q),se=oe(q);if(se===null)return ie;var Ce=U(se,Q);if(Ce.length<=0)return ie;if(ie.length<=0)return Ce;for(var Ve=new w,Ke=[],Pe=0,he=ie;Pe<he.length;Pe++){var ve=he[Pe],ye=Ve.has(ve);ye||(Ve.add(ve),Ke.push(ve))}for(var xe=0,Ue=Ce;xe<Ue.length;xe++){var ve=Ue[xe],ye=Ve.has(ve);ye||(Ve.add(ve),Ke.push(ve))}return Ke}function z(q,Q){var ie=Ut(q,Q,!1);return ie?ie.OrdinaryOwnMetadataKeys(q,Q):[]}function T(q){if(q===null)return 1;switch(typeof q){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return q===null?1:6;default:return 6}}function M(q){return q===void 0}function te(q){return q===null}function le(q){return typeof q=="symbol"}function G(q){return typeof q=="object"?q!==null:typeof q=="function"}function fe(q,Q){switch(T(q)){case 0:return q;case 1:return q;case 2:return q;case 3:return q;case 4:return q;case 5:return q}var ie="string",se=tt(q,a);if(se!==void 0){var Ce=se.call(q,ie);if(G(Ce))throw new TypeError;return Ce}return be(q)}function be(q,Q){var ie,se,Ce;{var Ve=q.toString;if(Xe(Ve)){var se=Ve.call(q);if(!G(se))return se}var ie=q.valueOf;if(Xe(ie)){var se=ie.call(q);if(!G(se))return se}}throw new TypeError}function pe(q){return!!q}function ue(q){return""+q}function ge(q){var Q=fe(q);return le(Q)?Q:ue(Q)}function qe(q){return Array.isArray?Array.isArray(q):q instanceof Object?q instanceof Array:Object.prototype.toString.call(q)==="[object Array]"}function Xe(q){return typeof q=="function"}function we(q){return typeof q=="function"}function ze(q){switch(T(q)){case 3:return!0;case 4:return!0;default:return!1}}function We(q,Q){return q===Q||q!==q&&Q!==Q}function tt(q,Q){var ie=q[Q];if(ie!=null){if(!Xe(ie))throw new TypeError;return ie}}function De(q){var Q=tt(q,l);if(!Xe(Q))throw new TypeError;var ie=Q.call(q);if(!G(ie))throw new TypeError;return ie}function Fe(q){return q.value}function lt(q){var Q=q.next();return Q.done?!1:Q}function Ne(q){var Q=q.return;Q&&Q.call(q)}function oe(q){var Q=Object.getPrototypeOf(q);if(typeof q!="function"||q===m||Q!==m)return Q;var ie=q.prototype,se=ie&&Object.getPrototypeOf(ie);if(se==null||se===Object.prototype)return Q;var Ce=se.constructor;return typeof Ce!="function"||Ce===q?Q:Ce}function Se(){var q;!M(S)&&typeof r.Reflect<"u"&&!(S in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(q=Bt(r.Reflect));var Q,ie,se,Ce=new E,Ve={registerProvider:Ke,getProvider:he,setProvider:ye};return Ve;function Ke(xe){if(!Object.isExtensible(Ve))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case q===xe:break;case M(Q):Q=xe;break;case Q===xe:break;case M(ie):ie=xe;break;case ie===xe:break;default:se===void 0&&(se=new w),se.add(xe);break}}function Pe(xe,Ue){if(!M(Q)){if(Q.isProviderFor(xe,Ue))return Q;if(!M(ie)){if(ie.isProviderFor(xe,Ue))return Q;if(!M(se))for(var Ze=De(se);;){var dt=lt(Ze);if(!dt)return;var Wt=Fe(dt);if(Wt.isProviderFor(xe,Ue))return Ne(Ze),Wt}}}if(!M(q)&&q.isProviderFor(xe,Ue))return q}function he(xe,Ue){var Ze=Ce.get(xe),dt;return M(Ze)||(dt=Ze.get(Ue)),M(dt)&&(dt=Pe(xe,Ue),M(dt)||(M(Ze)&&(Ze=new y,Ce.set(xe,Ze)),Ze.set(Ue,dt))),dt}function ve(xe){if(M(xe))throw new TypeError;return Q===xe||ie===xe||!M(se)&&se.has(xe)}function ye(xe,Ue,Ze){if(!ve(Ze))throw new Error("Metadata provider not registered.");var dt=he(xe,Ue);if(dt!==Ze){if(!M(dt))return!1;var Wt=Ce.get(xe);M(Wt)&&(Wt=new y,Ce.set(xe,Wt)),Wt.set(Ue,Ze)}return!0}}function Je(){var q;return!M(S)&&G(r.Reflect)&&Object.isExtensible(r.Reflect)&&(q=r.Reflect[S]),M(q)&&(q=Se()),!M(S)&&G(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,S,{enumerable:!1,configurable:!1,writable:!1,value:q}),q}function ht(q){var Q=new E,ie={isProviderFor:function(ve,ye){var xe=Q.get(ve);return M(xe)?!1:xe.has(ye)},OrdinaryDefineOwnMetadata:Ke,OrdinaryHasOwnMetadata:Ce,OrdinaryGetOwnMetadata:Ve,OrdinaryOwnMetadataKeys:Pe,OrdinaryDeleteMetadata:he};return C.registerProvider(ie),ie;function se(ve,ye,xe){var Ue=Q.get(ve),Ze=!1;if(M(Ue)){if(!xe)return;Ue=new y,Q.set(ve,Ue),Ze=!0}var dt=Ue.get(ye);if(M(dt)){if(!xe)return;if(dt=new y,Ue.set(ye,dt),!q.setProvider(ve,ye,ie))throw Ue.delete(ye),Ze&&Q.delete(ve),new Error("Wrong provider for target.")}return dt}function Ce(ve,ye,xe){var Ue=se(ye,xe,!1);return M(Ue)?!1:pe(Ue.has(ve))}function Ve(ve,ye,xe){var Ue=se(ye,xe,!1);if(!M(Ue))return Ue.get(ve)}function Ke(ve,ye,xe,Ue){var Ze=se(xe,Ue,!0);Ze.set(ve,ye)}function Pe(ve,ye){var xe=[],Ue=se(ve,ye,!1);if(M(Ue))return xe;for(var Ze=Ue.keys(),dt=De(Ze),Wt=0;;){var Zr=lt(dt);if(!Zr)return xe.length=Wt,xe;var en=Fe(Zr);try{xe[Wt]=en}catch(pi){try{Ne(dt)}finally{throw pi}}Wt++}}function he(ve,ye,xe){var Ue=se(ye,xe,!1);if(M(Ue)||!Ue.delete(ve))return!1;if(Ue.size===0){var Ze=Q.get(ye);M(Ze)||(Ze.delete(xe),Ze.size===0&&Q.delete(Ze))}return!0}}function Bt(q){var Q=q.defineMetadata,ie=q.hasOwnMetadata,se=q.getOwnMetadata,Ce=q.getOwnMetadataKeys,Ve=q.deleteMetadata,Ke=new E,Pe={isProviderFor:function(he,ve){var ye=Ke.get(he);return!M(ye)&&ye.has(ve)?!0:Ce(he,ve).length?(M(ye)&&(ye=new w,Ke.set(he,ye)),ye.add(ve),!0):!1},OrdinaryDefineOwnMetadata:Q,OrdinaryHasOwnMetadata:ie,OrdinaryGetOwnMetadata:se,OrdinaryOwnMetadataKeys:Ce,OrdinaryDeleteMetadata:Ve};return Pe}function Ut(q,Q,ie){var se=C.getProvider(q,Q);if(!M(se))return se;if(ie){if(C.setProvider(q,Q,R))return R;throw new Error("Illegal state.")}}function jt(){var q={},Q=[],ie=(function(){function Pe(he,ve,ye){this._index=0,this._keys=he,this._values=ve,this._selector=ye}return Pe.prototype["@@iterator"]=function(){return this},Pe.prototype[l]=function(){return this},Pe.prototype.next=function(){var he=this._index;if(he>=0&&he<this._keys.length){var ve=this._selector(this._keys[he],this._values[he]);return he+1>=this._keys.length?(this._index=-1,this._keys=Q,this._values=Q):this._index++,{value:ve,done:!1}}return{value:void 0,done:!0}},Pe.prototype.throw=function(he){throw this._index>=0&&(this._index=-1,this._keys=Q,this._values=Q),he},Pe.prototype.return=function(he){return this._index>=0&&(this._index=-1,this._keys=Q,this._values=Q),{value:he,done:!0}},Pe})(),se=(function(){function Pe(){this._keys=[],this._values=[],this._cacheKey=q,this._cacheIndex=-2}return Object.defineProperty(Pe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Pe.prototype.has=function(he){return this._find(he,!1)>=0},Pe.prototype.get=function(he){var ve=this._find(he,!1);return ve>=0?this._values[ve]:void 0},Pe.prototype.set=function(he,ve){var ye=this._find(he,!0);return this._values[ye]=ve,this},Pe.prototype.delete=function(he){var ve=this._find(he,!1);if(ve>=0){for(var ye=this._keys.length,xe=ve+1;xe<ye;xe++)this._keys[xe-1]=this._keys[xe],this._values[xe-1]=this._values[xe];return this._keys.length--,this._values.length--,We(he,this._cacheKey)&&(this._cacheKey=q,this._cacheIndex=-2),!0}return!1},Pe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=q,this._cacheIndex=-2},Pe.prototype.keys=function(){return new ie(this._keys,this._values,Ce)},Pe.prototype.values=function(){return new ie(this._keys,this._values,Ve)},Pe.prototype.entries=function(){return new ie(this._keys,this._values,Ke)},Pe.prototype["@@iterator"]=function(){return this.entries()},Pe.prototype[l]=function(){return this.entries()},Pe.prototype._find=function(he,ve){if(!We(this._cacheKey,he)){this._cacheIndex=-1;for(var ye=0;ye<this._keys.length;ye++)if(We(this._keys[ye],he)){this._cacheIndex=ye;break}}return this._cacheIndex<0&&ve&&(this._cacheIndex=this._keys.length,this._keys.push(he),this._values.push(void 0)),this._cacheIndex},Pe})();return se;function Ce(Pe,he){return Pe}function Ve(Pe,he){return he}function Ke(Pe,he){return[Pe,he]}}function Vt(){var q=(function(){function Q(){this._map=new y}return Object.defineProperty(Q.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),Q.prototype.has=function(ie){return this._map.has(ie)},Q.prototype.add=function(ie){return this._map.set(ie,ie),this},Q.prototype.delete=function(ie){return this._map.delete(ie)},Q.prototype.clear=function(){this._map.clear()},Q.prototype.keys=function(){return this._map.keys()},Q.prototype.values=function(){return this._map.keys()},Q.prototype.entries=function(){return this._map.entries()},Q.prototype["@@iterator"]=function(){return this.keys()},Q.prototype[l]=function(){return this.keys()},Q})();return q}function bt(){var q=16,Q=h.create(),ie=se();return(function(){function he(){this._key=se()}return he.prototype.has=function(ve){var ye=Ce(ve,!1);return ye!==void 0?h.has(ye,this._key):!1},he.prototype.get=function(ve){var ye=Ce(ve,!1);return ye!==void 0?h.get(ye,this._key):void 0},he.prototype.set=function(ve,ye){var xe=Ce(ve,!0);return xe[this._key]=ye,this},he.prototype.delete=function(ve){var ye=Ce(ve,!1);return ye!==void 0?delete ye[this._key]:!1},he.prototype.clear=function(){this._key=se()},he})();function se(){var he;do he="@@WeakMap@@"+Pe();while(h.has(Q,he));return Q[he]=!0,he}function Ce(he,ve){if(!n.call(he,ie)){if(!ve)return;Object.defineProperty(he,ie,{value:h.create()})}return he[ie]}function Ve(he,ve){for(var ye=0;ye<ve;++ye)he[ye]=Math.random()*255|0;return he}function Ke(he){if(typeof Uint8Array=="function"){var ve=new Uint8Array(he);return typeof crypto<"u"?crypto.getRandomValues(ve):typeof msCrypto<"u"?msCrypto.getRandomValues(ve):Ve(ve,he),ve}return Ve(new Array(he),he)}function Pe(){var he=Ke(q);he[6]=he[6]&79|64,he[8]=he[8]&191|128;for(var ve="",ye=0;ye<q;++ye){var xe=he[ye];(ye===4||ye===6||ye===8)&&(ve+="-"),xe<16&&(ve+="0"),ve+=xe.toString(16).toLowerCase()}return ve}}function rt(q){return q.__=void 0,delete q.__,q}})})(gw||(gw={}));let x5=class{cla;ins;p1;p2;data;constructor(t,r,n,o,a){this.cla=t,this.ins=r,this.p1=n,this.p2=o,this.data=a??new Uint8Array}getRawApdu(){const t=Uint8Array.from([this.cla,this.ins,this.p1,this.p2,this.data.length]),r=new Uint8Array(t.length+this.data.length);return r.set(t,0),this.data.length>0&&r.set(this.data,t.length),r}};function vw(e){if(e.startsWith("0x")&&(e=e.slice(2)),e.length===0)return new Uint8Array;if(e.length%2!==0&&(e="0"+e),/^[0-9a-fA-F]*$/.test(e)===!1)return null;const t=e.match(/.{1,2}/g)?.map(r=>parseInt(r,16));return!t||t.some(isNaN)?null:new Uint8Array(t)}function si(e,t=!0){return`${t?"0x":""}${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`}let hh=class{_tag="ValueOverflow";originalError;message;constructor(t,r=wR){this.message=`Value overflow for ${t}, max is ${r}`}},$u=class{_tag="DataOverflow";message;originalError;constructor(t,r=0){this.message=r===0?`this.data is already full (value: ${t})`:`this.data will overflow with "${t}", remaining bytes: ${r}`}},yw=class{_tag="HexaString";message;originalError;constructor(t){this.message=`Invalid encoded hexa string or length is null: ${t}`}};const w5=4294967295;let S5=class{constructor(t=w5){this.maxPayloadSize=t}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=t=>this.addNumberToData(t,8n,!1,!1);add16BitUIntToData=(t,r=!0)=>this.addNumberToData(t,16n,!1,r);add32BitUIntToData=(t,r=!0)=>this.addNumberToData(t,32n,!1,r);add64BitUIntToData=(t,r=!0)=>this.addNumberToData(t,64n,!1,r);add128BitUIntToData=(t,r=!0)=>this.addNumberToData(t,128n,!1,r);add256BitUIntToData=(t,r=!0)=>this.addNumberToData(t,256n,!1,r);add16BitIntToData=(t,r=!0)=>this.addNumberToData(t,16n,!0,r);add32BitIntToData=(t,r=!0)=>this.addNumberToData(t,32n,!0,r);add64BitIntToData=(t,r=!0)=>this.addNumberToData(t,64n,!0,r);add128BitIntToData=(t,r=!0)=>this.addNumberToData(t,128n,!0,r);add256BitIntToData=(t,r=!0)=>this.addNumberToData(t,256n,!0,r);addBufferToData=t=>this.hasEnoughLengthRemaining(t)?(this.data=Uint8Array.from([...this.data,...t]),this):(this.errors.push(new $u(t.toString())),this);addHexaStringToData=t=>{const r=vw(t);return r===null||r.length===0?(this.errors.push(new yw(t)),this):(this.addBufferToData(r),this)};addAsciiStringToData=t=>{const r=new TextEncoder().encode(t);return this.addBufferToData(r),this};encodeInLVFromHexa=t=>{const r=vw(t);return r===null||r.length===0?(this.errors.push(new yw(t)),this):this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addBufferToData(r),this):(this.errors.push(new $u(t)),this)};encodeInLVFromBuffer=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addBufferToData(t),this):(this.errors.push(new $u(t.toString())),this);encodeInLVFromAscii=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addAsciiStringToData(t),this):(this.errors.push(new $u(t)),this);encodeInTLVFromAscii=(t,r)=>(this.add8BitUIntToData(t),this.encodeInLVFromAscii(r));encodeInTLVFromHexa=(t,r)=>(this.add8BitUIntToData(t),this.encodeInLVFromHexa(r));encodeInTLVFromBuffer=(t,r)=>(this.add8BitUIntToData(t),this.encodeInLVFromBuffer(r));encodeInTLVFromUInt8=(t,r)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(1),this.add8BitUIntToData(r));encodeInTLVFromUInt16=(t,r,n=!0)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(2),this.add16BitUIntToData(r,n));encodeInTLVFromUInt32=(t,r,n=!0)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(4),this.add32BitUIntToData(r,n));encodeInTLVFromUInt64=(t,r,n=!0)=>(this.add8BitUIntToData(t),this.add8BitUIntToData(8),this.add64BitUIntToData(r,n));getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(t,r=!1)=>this.data.length+t.length+(r?1:0)<=this.maxPayloadSize;addNumberToData(t,r,n,o){let a=this.checkBoundsAndConvert(t,r,n);if(a===void 0)return this;const l=Number(r)/8,u=new Uint8Array(l);if(o)for(let d=l-1;d>=0;d--)u[d]=Number(a&0xffn),a>>=8n;else for(let d=0;d<l;d++)u[d]=Number(a&0xffn),a>>=8n;return this.addBufferToData(u)}checkBoundsAndConvert(t,r,n){if(typeof t=="number"){if(!Number.isInteger(t)||t>Number.MAX_SAFE_INTEGER){this.errors.push(new hh(t.toString()));return}t=BigInt(t)}if(n){const o=1n<<r-1n;if(t>=o||t<-o){this.errors.push(new hh(t.toString(),o-1n));return}if(t<0n){const a=(1n<<r)-1n;t=-t,t=(~t&a)+1n}}else{const o=1n<<r;if(t<0||t>=o){this.errors.push(new hh(t.toString(),o-1n));return}}return t}};const wR=255;let SR=class{_ins;_cla;_p1;p2;data=new S5(wR);constructor({ins:t,cla:r,p1:n,p2:o}){this._cla=r&255,this._ins=t&255,this._p1=n&255,this.p2=o&255}build=()=>new x5(this._cla,this._ins,this._p1,this.p2,this.data.build());add8BitUIntToData=t=>(this.data.add8BitUIntToData(t),this);add16BitUIntToData=t=>(this.data.add16BitUIntToData(t),this);add32BitUIntToData=t=>(this.data.add32BitUIntToData(t),this);add64BitUIntToData=(t,r=!0)=>(this.data.add64BitUIntToData(t,r),this);addBufferToData=t=>(this.data.addBufferToData(t),this);addHexaStringToData=t=>(this.data.addHexaStringToData(t),this);addAsciiStringToData=t=>(this.data.addAsciiStringToData(t),this);encodeInLVFromHexa=t=>(this.data.encodeInLVFromHexa(t),this);encodeInLVFromBuffer=t=>(this.data.encodeInLVFromBuffer(t),this);encodeInLVFromAscii=t=>(this.data.encodeInLVFromAscii(t),this);getAvailablePayloadLength=()=>this.data.getAvailablePayloadLength();getErrors=()=>this.data.getErrors()},E5=class{constructor(t){this.buffer=t}index=0;testMinimalLength(t){return t<=this.buffer.length-this.index}extract8BitUInt(){if(!this.outOfRange(1))return this.buffer[this.index++]}extract16BitUInt(t=!0){const r=this.extractNumber(16n,!1,t);return r===void 0?void 0:Number(r)}extract16BitInt(t=!0){const r=this.extractNumber(16n,!0,t);return r===void 0?void 0:Number(r)}extract32BitUInt(t=!0){const r=this.extractNumber(32n,!1,t);return r===void 0?void 0:Number(r)}extract32BitInt(t=!0){const r=this.extractNumber(32n,!0,t);return r===void 0?void 0:Number(r)}extract64BitUInt(t=!0){return this.extractNumber(64n,!1,t)}extract64BitInt(t=!0){return this.extractNumber(64n,!0,t)}extract128BitUInt(t=!0){return this.extractNumber(128n,!1,t)}extract128BitInt(t=!0){return this.extractNumber(128n,!0,t)}extract256BitUInt(t=!0){return this.extractNumber(256n,!1,t)}extract256BitInt(t=!0){return this.extractNumber(256n,!0,t)}extractFieldByLength(t){if(this.outOfRange(t))return;if(t===0)return new Uint8Array;const r=this.buffer.slice(this.index,this.index+t);return this.index+=t,r}extractFieldLVEncoded(){const t=this.extract8BitUInt();if(t===void 0)return;if(t===0)return new Uint8Array;const r=this.extractFieldByLength(t);return r===void 0&&this.index--,r}extractFieldTLVEncoded(){if(this.outOfRange(2))return;const t=this.index,r=this.extract8BitUInt(),n=this.extractFieldLVEncoded();if(r===void 0||n===void 0){this.index--;return}const o=this.index;return{tag:r,value:n,tlv:this.buffer.slice(t,o)}}encodeToHexaString(t,r=!1){if(t===void 0||t.length===0)return"";const n=si(t);return r?n:n.slice(2)}encodeToString(t){let r="",n=0;if(!t)return r;for(;n<=t.length;){const o=t[n];o&&(r+=String.fromCharCode(o)),n++}return r}getCurrentIndex(){return this.index}resetIndex(){this.index=0}getUnparsedRemainingLength(){return this.buffer.length-this.index}outOfRange(t){return this.index+t>this.buffer.length}extractNumber(t,r,n){const o=Number(t)/8;if(this.outOfRange(o))return;let a=0n;if(n)for(let l=0;l<o;l++)a=a<<8n|BigInt(this.buffer[l+this.index]);else for(let l=o-1;l>=0;l--)a=a<<8n|BigInt(this.buffer[l+this.index]);if(r){const l=1n<<t-1n;a&l&&(a-=l<<1n)}return this.index+=o,a}},mv=class{parser;constructor(t){this.parser=new E5(t.data)}testMinimalLength=t=>this.parser.testMinimalLength(t);extract8BitUInt=()=>this.parser.extract8BitUInt();extract16BitUInt=()=>this.parser.extract16BitUInt();extract32BitUInt=()=>this.parser.extract32BitUInt();extractFieldByLength=t=>this.parser.extractFieldByLength(t);extractFieldLVEncoded=()=>this.parser.extractFieldLVEncoded();extractFieldTLVEncoded=()=>this.parser.extractFieldTLVEncoded();encodeToHexaString(t,r=!1){return r?this.parser.encodeToHexaString(t,!0):this.parser.encodeToHexaString(t,!1)}encodeToString=t=>this.parser.encodeToString(t);getUnparsedRemainingLength=()=>this.parser.getUnparsedRemainingLength()},C5=class{_tag="InvalidStatusWordError";originalError;constructor(t){this.originalError=new Error(t??"Invalid status word.")}},k5=class{_tag="InvalidResponseFormatError";originalError;constructor(t){this.originalError=new Error(t??"Invalid response format.")}};var R5=(e=>(e.Error="ERROR",e.Success="SUCCESS",e))(R5||{});function _5(e){return"error"in e&&e.error!==void 0}function bw(e){return _5(e)?{status:"ERROR",error:e.error}:{status:"SUCCESS",data:e.data}}function $5(e){return e.status==="SUCCESS"}function Io({data:e,error:t}){return bw(t!==void 0?{error:t}:{data:e})}function A5(e){return $5(e)}let gv=class $s{static isValidStatusCode(t){return t.length===2}static isSuccessResponse({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===144&&t[1]===0:!1}static isLockedDeviceResponse({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===85&&t[1]===21||t[0]===105&&t[1]===130||t[0]===83&&t[1]===3:!1}static isRefusedByUser({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===85&&t[1]===1||t[0]===105&&t[1]===133:!1}static isAppAlreadyInstalled({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===106&&t[1]===128||t[0]===106&&t[1]===129||t[0]===106&&t[1]===142||t[0]===106&&t[1]===143:!1}static isOutOfMemory({statusCode:t}){return $s.isValidStatusCode(t)?t[0]===106&&t[1]===132||t[0]===106&&t[1]===133||t[0]===81&&t[1]===2||t[0]===81&&t[1]===3||t[0]===103&&t[1]===51:!1}static isApduThatTriggersDisconnection(t){const r=new Map;return r.set("openApp",new Uint8Array([224,216,0,0])),r.set("closeApp",new Uint8Array([176,167,0,0])),Array.from(r.values()).some(n=>{for(let o=0;o<4;o++)if(n[o]!==t[o])return!1;return!0})}},T5=class{_tag;originalError;errorCode;message;constructor({tag:t,errorCode:r,originalError:n,message:o}){this._tag=t,this.originalError=n,this.errorCode=r,this.message=o??"An error occured during device exchange."}},L5=class{_tag="UnknownDeviceExchangeError";originalError;message;constructor(t){this.originalError=t,this.message="Unexpected device exchange error happened."}};const I5=(e,t)=>Object.keys(t).includes(e);let O5=class extends T5{constructor(t){super({tag:"GlobalCommandError",...t})}};const xw={5515:{message:"Device is locked.",tag:"DeviceLockedError"},5501:{message:"Action refused on device.",tag:"ActionRefusedError"},5502:{message:"Pin is not set",tag:"PinNotSetError"},5223:{message:"Device internal error",tag:"DeviceInternalError"},"6e00":{message:"CLA not supported",tag:"DeviceInternalError"},"6d00":{message:"INS not supported",tag:"DeviceInternalError"}};let ER=class{static handle(t){const r=new mv(t).encodeToHexaString(t.statusCode);return I5(r,xw)?new O5({...xw[r],errorCode:r}):new L5({message:"UnknownError",errorCode:r})}},ww=class{name="getAppAndVersion";args=void 0;getApdu(){const t={cla:176,ins:1,p1:0,p2:0};return new SR(t).build()}parseResponse(t){if(!gv.isSuccessResponse(t))return Io({error:ER.handle(t)});const r=new mv(t);if(r.extract8BitUInt()!==1)return Io({error:new k5("getAppAndVersion: format not supported")});const n=r.encodeToString(r.extractFieldLVEncoded()),o=r.encodeToString(r.extractFieldLVEncoded());if(r.getUnparsedRemainingLength()===0)return Io({data:{name:n,version:o}});const a=r.extractFieldLVEncoded();return Io({data:{name:n,version:o,flags:a}})}};var N5=(e=>(e[e.BATTERY_PERCENTAGE=0]="BATTERY_PERCENTAGE",e[e.BATTERY_VOLTAGE=1]="BATTERY_VOLTAGE",e[e.BATTERY_TEMPERATURE=2]="BATTERY_TEMPERATURE",e[e.BATTERY_CURRENT=3]="BATTERY_CURRENT",e[e.BATTERY_FLAGS=4]="BATTERY_FLAGS",e))(N5||{}),P5=(e=>(e[e.NONE=0]="NONE",e[e.USB=1]="USB",e[e.QI=2]="QI",e))(P5||{}),Au={exports:{}},mh,Sw;function Ud(){if(Sw)return mh;Sw=1;const e="2.0.0",t=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,o=t-6;return mh={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:o,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:e,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},mh}var gh,Ew;function Vd(){if(Ew)return gh;Ew=1;var e={};return gh=typeof process=="object"&&e&&e.NODE_DEBUG&&/\bsemver\b/i.test(e.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},gh}var Cw;function Il(){return Cw||(Cw=1,(function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:o}=Ud(),a=Vd();t=e.exports={};const l=t.re=[],u=t.safeRe=[],d=t.src=[],p=t.safeSrc=[],h=t.t={};let m=0;const y="[a-zA-Z0-9-]",w=[["\\s",1],["\\d",o],[y,n]],E=C=>{for(const[R,k]of w)C=C.split(`${R}*`).join(`${R}{0,${k}}`).split(`${R}+`).join(`${R}{1,${k}}`);return C},S=(C,R,k)=>{const $=E(R),A=m++;a(C,A,R),h[C]=A,d[A]=R,p[A]=$,l[A]=new RegExp(R,k?"g":void 0),u[A]=new RegExp($,k?"g":void 0)};S("NUMERICIDENTIFIER","0|[1-9]\\d*"),S("NUMERICIDENTIFIERLOOSE","\\d+"),S("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${y}*`),S("MAINVERSION",`(${d[h.NUMERICIDENTIFIER]})\\.(${d[h.NUMERICIDENTIFIER]})\\.(${d[h.NUMERICIDENTIFIER]})`),S("MAINVERSIONLOOSE",`(${d[h.NUMERICIDENTIFIERLOOSE]})\\.(${d[h.NUMERICIDENTIFIERLOOSE]})\\.(${d[h.NUMERICIDENTIFIERLOOSE]})`),S("PRERELEASEIDENTIFIER",`(?:${d[h.NONNUMERICIDENTIFIER]}|${d[h.NUMERICIDENTIFIER]})`),S("PRERELEASEIDENTIFIERLOOSE",`(?:${d[h.NONNUMERICIDENTIFIER]}|${d[h.NUMERICIDENTIFIERLOOSE]})`),S("PRERELEASE",`(?:-(${d[h.PRERELEASEIDENTIFIER]}(?:\\.${d[h.PRERELEASEIDENTIFIER]})*))`),S("PRERELEASELOOSE",`(?:-?(${d[h.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${d[h.PRERELEASEIDENTIFIERLOOSE]})*))`),S("BUILDIDENTIFIER",`${y}+`),S("BUILD",`(?:\\+(${d[h.BUILDIDENTIFIER]}(?:\\.${d[h.BUILDIDENTIFIER]})*))`),S("FULLPLAIN",`v?${d[h.MAINVERSION]}${d[h.PRERELEASE]}?${d[h.BUILD]}?`),S("FULL",`^${d[h.FULLPLAIN]}$`),S("LOOSEPLAIN",`[v=\\s]*${d[h.MAINVERSIONLOOSE]}${d[h.PRERELEASELOOSE]}?${d[h.BUILD]}?`),S("LOOSE",`^${d[h.LOOSEPLAIN]}$`),S("GTLT","((?:<|>)?=?)"),S("XRANGEIDENTIFIERLOOSE",`${d[h.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),S("XRANGEIDENTIFIER",`${d[h.NUMERICIDENTIFIER]}|x|X|\\*`),S("XRANGEPLAIN",`[v=\\s]*(${d[h.XRANGEIDENTIFIER]})(?:\\.(${d[h.XRANGEIDENTIFIER]})(?:\\.(${d[h.XRANGEIDENTIFIER]})(?:${d[h.PRERELEASE]})?${d[h.BUILD]}?)?)?`),S("XRANGEPLAINLOOSE",`[v=\\s]*(${d[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[h.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[h.XRANGEIDENTIFIERLOOSE]})(?:${d[h.PRERELEASELOOSE]})?${d[h.BUILD]}?)?)?`),S("XRANGE",`^${d[h.GTLT]}\\s*${d[h.XRANGEPLAIN]}$`),S("XRANGELOOSE",`^${d[h.GTLT]}\\s*${d[h.XRANGEPLAINLOOSE]}$`),S("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),S("COERCE",`${d[h.COERCEPLAIN]}(?:$|[^\\d])`),S("COERCEFULL",d[h.COERCEPLAIN]+`(?:${d[h.PRERELEASE]})?(?:${d[h.BUILD]})?(?:$|[^\\d])`),S("COERCERTL",d[h.COERCE],!0),S("COERCERTLFULL",d[h.COERCEFULL],!0),S("LONETILDE","(?:~>?)"),S("TILDETRIM",`(\\s*)${d[h.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",S("TILDE",`^${d[h.LONETILDE]}${d[h.XRANGEPLAIN]}$`),S("TILDELOOSE",`^${d[h.LONETILDE]}${d[h.XRANGEPLAINLOOSE]}$`),S("LONECARET","(?:\\^)"),S("CARETTRIM",`(\\s*)${d[h.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",S("CARET",`^${d[h.LONECARET]}${d[h.XRANGEPLAIN]}$`),S("CARETLOOSE",`^${d[h.LONECARET]}${d[h.XRANGEPLAINLOOSE]}$`),S("COMPARATORLOOSE",`^${d[h.GTLT]}\\s*(${d[h.LOOSEPLAIN]})$|^$`),S("COMPARATOR",`^${d[h.GTLT]}\\s*(${d[h.FULLPLAIN]})$|^$`),S("COMPARATORTRIM",`(\\s*)${d[h.GTLT]}\\s*(${d[h.LOOSEPLAIN]}|${d[h.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",S("HYPHENRANGE",`^\\s*(${d[h.XRANGEPLAIN]})\\s+-\\s+(${d[h.XRANGEPLAIN]})\\s*$`),S("HYPHENRANGELOOSE",`^\\s*(${d[h.XRANGEPLAINLOOSE]})\\s+-\\s+(${d[h.XRANGEPLAINLOOSE]})\\s*$`),S("STAR","(<|>)?=?\\s*\\*"),S("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),S("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Au,Au.exports)),Au.exports}var vh,kw;function vv(){if(kw)return vh;kw=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return vh=n=>n?typeof n!="object"?e:n:t,vh}var yh,Rw;function CR(){if(Rw)return yh;Rw=1;const e=/^[0-9]+$/,t=(n,o)=>{const a=e.test(n),l=e.test(o);return a&&l&&(n=+n,o=+o),n===o?0:a&&!l?-1:l&&!a?1:n<o?-1:1};return yh={compareIdentifiers:t,rcompareIdentifiers:(n,o)=>t(o,n)},yh}var bh,_w;function gr(){if(_w)return bh;_w=1;const e=Vd(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Ud(),{safeRe:n,t:o}=Il(),a=vv(),{compareIdentifiers:l}=CR();class u{constructor(p,h){if(h=a(h),p instanceof u){if(p.loose===!!h.loose&&p.includePrerelease===!!h.includePrerelease)return p;p=p.version}else if(typeof p!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof p}".`);if(p.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",p,h),this.options=h,this.loose=!!h.loose,this.includePrerelease=!!h.includePrerelease;const m=p.trim().match(h.loose?n[o.LOOSE]:n[o.FULL]);if(!m)throw new TypeError(`Invalid Version: ${p}`);if(this.raw=p,this.major=+m[1],this.minor=+m[2],this.patch=+m[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");m[4]?this.prerelease=m[4].split(".").map(y=>{if(/^[0-9]+$/.test(y)){const w=+y;if(w>=0&&w<r)return w}return y}):this.prerelease=[],this.build=m[5]?m[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(p){if(e("SemVer.compare",this.version,this.options,p),!(p instanceof u)){if(typeof p=="string"&&p===this.version)return 0;p=new u(p,this.options)}return p.version===this.version?0:this.compareMain(p)||this.comparePre(p)}compareMain(p){return p instanceof u||(p=new u(p,this.options)),l(this.major,p.major)||l(this.minor,p.minor)||l(this.patch,p.patch)}comparePre(p){if(p instanceof u||(p=new u(p,this.options)),this.prerelease.length&&!p.prerelease.length)return-1;if(!this.prerelease.length&&p.prerelease.length)return 1;if(!this.prerelease.length&&!p.prerelease.length)return 0;let h=0;do{const m=this.prerelease[h],y=p.prerelease[h];if(e("prerelease compare",h,m,y),m===void 0&&y===void 0)return 0;if(y===void 0)return 1;if(m===void 0)return-1;if(m===y)continue;return l(m,y)}while(++h)}compareBuild(p){p instanceof u||(p=new u(p,this.options));let h=0;do{const m=this.build[h],y=p.build[h];if(e("build compare",h,m,y),m===void 0&&y===void 0)return 0;if(y===void 0)return 1;if(m===void 0)return-1;if(m===y)continue;return l(m,y)}while(++h)}inc(p,h,m){if(p.startsWith("pre")){if(!h&&m===!1)throw new Error("invalid increment argument: identifier is empty");if(h){const y=`-${h}`.match(this.options.loose?n[o.PRERELEASELOOSE]:n[o.PRERELEASE]);if(!y||y[1]!==h)throw new Error(`invalid identifier: ${h}`)}}switch(p){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",h,m);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",h,m);break;case"prepatch":this.prerelease.length=0,this.inc("patch",h,m),this.inc("pre",h,m);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",h,m),this.inc("pre",h,m);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const y=Number(m)?1:0;if(this.prerelease.length===0)this.prerelease=[y];else{let w=this.prerelease.length;for(;--w>=0;)typeof this.prerelease[w]=="number"&&(this.prerelease[w]++,w=-2);if(w===-1){if(h===this.prerelease.join(".")&&m===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(y)}}if(h){let w=[h,y];m===!1&&(w=[h]),l(this.prerelease[0],h)===0?isNaN(this.prerelease[1])&&(this.prerelease=w):this.prerelease=w}break}default:throw new Error(`invalid increment argument: ${p}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return bh=u,bh}var xh,$w;function ia(){if($w)return xh;$w=1;const e=gr();return xh=(r,n,o=!1)=>{if(r instanceof e)return r;try{return new e(r,n)}catch(a){if(!o)return null;throw a}},xh}var wh,Aw;function D5(){if(Aw)return wh;Aw=1;const e=ia();return wh=(r,n)=>{const o=e(r,n);return o?o.version:null},wh}var Sh,Tw;function j5(){if(Tw)return Sh;Tw=1;const e=ia();return Sh=(r,n)=>{const o=e(r.trim().replace(/^[=v]+/,""),n);return o?o.version:null},Sh}var Eh,Lw;function M5(){if(Lw)return Eh;Lw=1;const e=gr();return Eh=(r,n,o,a,l)=>{typeof o=="string"&&(l=a,a=o,o=void 0);try{return new e(r instanceof e?r.version:r,o).inc(n,a,l).version}catch{return null}},Eh}var Ch,Iw;function z5(){if(Iw)return Ch;Iw=1;const e=ia();return Ch=(r,n)=>{const o=e(r,null,!0),a=e(n,null,!0),l=o.compare(a);if(l===0)return null;const u=l>0,d=u?o:a,p=u?a:o,h=!!d.prerelease.length;if(!!p.prerelease.length&&!h){if(!p.patch&&!p.minor)return"major";if(p.compareMain(d)===0)return p.minor&&!p.patch?"minor":"patch"}const y=h?"pre":"";return o.major!==a.major?y+"major":o.minor!==a.minor?y+"minor":o.patch!==a.patch?y+"patch":"prerelease"},Ch}var kh,Ow;function F5(){if(Ow)return kh;Ow=1;const e=gr();return kh=(r,n)=>new e(r,n).major,kh}var Rh,Nw;function B5(){if(Nw)return Rh;Nw=1;const e=gr();return Rh=(r,n)=>new e(r,n).minor,Rh}var _h,Pw;function U5(){if(Pw)return _h;Pw=1;const e=gr();return _h=(r,n)=>new e(r,n).patch,_h}var $h,Dw;function V5(){if(Dw)return $h;Dw=1;const e=ia();return $h=(r,n)=>{const o=e(r,n);return o&&o.prerelease.length?o.prerelease:null},$h}var Ah,jw;function bn(){if(jw)return Ah;jw=1;const e=gr();return Ah=(r,n,o)=>new e(r,o).compare(new e(n,o)),Ah}var Th,Mw;function W5(){if(Mw)return Th;Mw=1;const e=bn();return Th=(r,n,o)=>e(n,r,o),Th}var Lh,zw;function H5(){if(zw)return Lh;zw=1;const e=bn();return Lh=(r,n)=>e(r,n,!0),Lh}var Ih,Fw;function yv(){if(Fw)return Ih;Fw=1;const e=gr();return Ih=(r,n,o)=>{const a=new e(r,o),l=new e(n,o);return a.compare(l)||a.compareBuild(l)},Ih}var Oh,Bw;function q5(){if(Bw)return Oh;Bw=1;const e=yv();return Oh=(r,n)=>r.sort((o,a)=>e(o,a,n)),Oh}var Nh,Uw;function G5(){if(Uw)return Nh;Uw=1;const e=yv();return Nh=(r,n)=>r.sort((o,a)=>e(a,o,n)),Nh}var Ph,Vw;function Wd(){if(Vw)return Ph;Vw=1;const e=bn();return Ph=(r,n,o)=>e(r,n,o)>0,Ph}var Dh,Ww;function bv(){if(Ww)return Dh;Ww=1;const e=bn();return Dh=(r,n,o)=>e(r,n,o)<0,Dh}var jh,Hw;function kR(){if(Hw)return jh;Hw=1;const e=bn();return jh=(r,n,o)=>e(r,n,o)===0,jh}var Mh,qw;function RR(){if(qw)return Mh;qw=1;const e=bn();return Mh=(r,n,o)=>e(r,n,o)!==0,Mh}var zh,Gw;function xv(){if(Gw)return zh;Gw=1;const e=bn();return zh=(r,n,o)=>e(r,n,o)>=0,zh}var Fh,Xw;function wv(){if(Xw)return Fh;Xw=1;const e=bn();return Fh=(r,n,o)=>e(r,n,o)<=0,Fh}var Bh,Yw;function _R(){if(Yw)return Bh;Yw=1;const e=kR(),t=RR(),r=Wd(),n=xv(),o=bv(),a=wv();return Bh=(u,d,p,h)=>{switch(d){case"===":return typeof u=="object"&&(u=u.version),typeof p=="object"&&(p=p.version),u===p;case"!==":return typeof u=="object"&&(u=u.version),typeof p=="object"&&(p=p.version),u!==p;case"":case"=":case"==":return e(u,p,h);case"!=":return t(u,p,h);case">":return r(u,p,h);case">=":return n(u,p,h);case"<":return o(u,p,h);case"<=":return a(u,p,h);default:throw new TypeError(`Invalid operator: ${d}`)}},Bh}var Uh,Kw;function X5(){if(Kw)return Uh;Kw=1;const e=gr(),t=ia(),{safeRe:r,t:n}=Il();return Uh=(a,l)=>{if(a instanceof e)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;l=l||{};let u=null;if(!l.rtl)u=a.match(l.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const w=l.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let E;for(;(E=w.exec(a))&&(!u||u.index+u[0].length!==a.length);)(!u||E.index+E[0].length!==u.index+u[0].length)&&(u=E),w.lastIndex=E.index+E[1].length+E[2].length;w.lastIndex=-1}if(u===null)return null;const d=u[2],p=u[3]||"0",h=u[4]||"0",m=l.includePrerelease&&u[5]?`-${u[5]}`:"",y=l.includePrerelease&&u[6]?`+${u[6]}`:"";return t(`${d}.${p}.${h}${m}${y}`,l)},Uh}var Vh,Qw;function Y5(){if(Qw)return Vh;Qw=1;class e{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(r,n)}return this}}return Vh=e,Vh}var Wh,Jw;function xn(){if(Jw)return Wh;Jw=1;const e=/\s+/g;class t{constructor(V,H){if(H=o(H),V instanceof t)return V.loose===!!H.loose&&V.includePrerelease===!!H.includePrerelease?V:new t(V.raw,H);if(V instanceof a)return this.raw=V.value,this.set=[[V]],this.formatted=void 0,this;if(this.options=H,this.loose=!!H.loose,this.includePrerelease=!!H.includePrerelease,this.raw=V.trim().replace(e," "),this.set=this.raw.split("||").map(O=>this.parseRange(O.trim())).filter(O=>O.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const O=this.set[0];if(this.set=this.set.filter(L=>!S(L[0])),this.set.length===0)this.set=[O];else if(this.set.length>1){for(const L of this.set)if(L.length===1&&C(L[0])){this.set=[L];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let V=0;V<this.set.length;V++){V>0&&(this.formatted+="||");const H=this.set[V];for(let O=0;O<H.length;O++)O>0&&(this.formatted+=" "),this.formatted+=H[O].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(V){const O=((this.options.includePrerelease&&w)|(this.options.loose&&E))+":"+V,L=n.get(O);if(L)return L;const U=this.options.loose,z=U?d[p.HYPHENRANGELOOSE]:d[p.HYPHENRANGE];V=V.replace(z,ne(this.options.includePrerelease)),l("hyphen replace",V),V=V.replace(d[p.COMPARATORTRIM],h),l("comparator trim",V),V=V.replace(d[p.TILDETRIM],m),l("tilde trim",V),V=V.replace(d[p.CARETTRIM],y),l("caret trim",V);let T=V.split(" ").map(G=>k(G,this.options)).join(" ").split(/\s+/).map(G=>ee(G,this.options));U&&(T=T.filter(G=>(l("loose invalid filter",G,this.options),!!G.match(d[p.COMPARATORLOOSE])))),l("range list",T);const M=new Map,te=T.map(G=>new a(G,this.options));for(const G of te){if(S(G))return[G];M.set(G.value,G)}M.size>1&&M.has("")&&M.delete("");const le=[...M.values()];return n.set(O,le),le}intersects(V,H){if(!(V instanceof t))throw new TypeError("a Range is required");return this.set.some(O=>R(O,H)&&V.set.some(L=>R(L,H)&&O.every(U=>L.every(z=>U.intersects(z,H)))))}test(V){if(!V)return!1;if(typeof V=="string")try{V=new u(V,this.options)}catch{return!1}for(let H=0;H<this.set.length;H++)if(X(this.set[H],V,this.options))return!0;return!1}}Wh=t;const r=Y5(),n=new r,o=vv(),a=Hd(),l=Vd(),u=gr(),{safeRe:d,t:p,comparatorTrimReplace:h,tildeTrimReplace:m,caretTrimReplace:y}=Il(),{FLAG_INCLUDE_PRERELEASE:w,FLAG_LOOSE:E}=Ud(),S=F=>F.value==="<0.0.0-0",C=F=>F.value==="",R=(F,V)=>{let H=!0;const O=F.slice();let L=O.pop();for(;H&&O.length;)H=O.every(U=>L.intersects(U,V)),L=O.pop();return H},k=(F,V)=>(l("comp",F,V),F=N(F,V),l("caret",F),F=A(F,V),l("tildes",F),F=I(F,V),l("xrange",F),F=Z(F,V),l("stars",F),F),$=F=>!F||F.toLowerCase()==="x"||F==="*",A=(F,V)=>F.trim().split(/\s+/).map(H=>D(H,V)).join(" "),D=(F,V)=>{const H=V.loose?d[p.TILDELOOSE]:d[p.TILDE];return F.replace(H,(O,L,U,z,T)=>{l("tilde",F,O,L,U,z,T);let M;return $(L)?M="":$(U)?M=`>=${L}.0.0 <${+L+1}.0.0-0`:$(z)?M=`>=${L}.${U}.0 <${L}.${+U+1}.0-0`:T?(l("replaceTilde pr",T),M=`>=${L}.${U}.${z}-${T} <${L}.${+U+1}.0-0`):M=`>=${L}.${U}.${z} <${L}.${+U+1}.0-0`,l("tilde return",M),M})},N=(F,V)=>F.trim().split(/\s+/).map(H=>P(H,V)).join(" "),P=(F,V)=>{l("caret",F,V);const H=V.loose?d[p.CARETLOOSE]:d[p.CARET],O=V.includePrerelease?"-0":"";return F.replace(H,(L,U,z,T,M)=>{l("caret",F,L,U,z,T,M);let te;return $(U)?te="":$(z)?te=`>=${U}.0.0${O} <${+U+1}.0.0-0`:$(T)?U==="0"?te=`>=${U}.${z}.0${O} <${U}.${+z+1}.0-0`:te=`>=${U}.${z}.0${O} <${+U+1}.0.0-0`:M?(l("replaceCaret pr",M),U==="0"?z==="0"?te=`>=${U}.${z}.${T}-${M} <${U}.${z}.${+T+1}-0`:te=`>=${U}.${z}.${T}-${M} <${U}.${+z+1}.0-0`:te=`>=${U}.${z}.${T}-${M} <${+U+1}.0.0-0`):(l("no pr"),U==="0"?z==="0"?te=`>=${U}.${z}.${T}${O} <${U}.${z}.${+T+1}-0`:te=`>=${U}.${z}.${T}${O} <${U}.${+z+1}.0-0`:te=`>=${U}.${z}.${T} <${+U+1}.0.0-0`),l("caret return",te),te})},I=(F,V)=>(l("replaceXRanges",F,V),F.split(/\s+/).map(H=>re(H,V)).join(" ")),re=(F,V)=>{F=F.trim();const H=V.loose?d[p.XRANGELOOSE]:d[p.XRANGE];return F.replace(H,(O,L,U,z,T,M)=>{l("xRange",F,O,L,U,z,T,M);const te=$(U),le=te||$(z),G=le||$(T),fe=G;return L==="="&&fe&&(L=""),M=V.includePrerelease?"-0":"",te?L===">"||L==="<"?O="<0.0.0-0":O="*":L&&fe?(le&&(z=0),T=0,L===">"?(L=">=",le?(U=+U+1,z=0,T=0):(z=+z+1,T=0)):L==="<="&&(L="<",le?U=+U+1:z=+z+1),L==="<"&&(M="-0"),O=`${L+U}.${z}.${T}${M}`):le?O=`>=${U}.0.0${M} <${+U+1}.0.0-0`:G&&(O=`>=${U}.${z}.0${M} <${U}.${+z+1}.0-0`),l("xRange return",O),O})},Z=(F,V)=>(l("replaceStars",F,V),F.trim().replace(d[p.STAR],"")),ee=(F,V)=>(l("replaceGTE0",F,V),F.trim().replace(d[V.includePrerelease?p.GTE0PRE:p.GTE0],"")),ne=F=>(V,H,O,L,U,z,T,M,te,le,G,fe)=>($(O)?H="":$(L)?H=`>=${O}.0.0${F?"-0":""}`:$(U)?H=`>=${O}.${L}.0${F?"-0":""}`:z?H=`>=${H}`:H=`>=${H}${F?"-0":""}`,$(te)?M="":$(le)?M=`<${+te+1}.0.0-0`:$(G)?M=`<${te}.${+le+1}.0-0`:fe?M=`<=${te}.${le}.${G}-${fe}`:F?M=`<${te}.${le}.${+G+1}-0`:M=`<=${M}`,`${H} ${M}`.trim()),X=(F,V,H)=>{for(let O=0;O<F.length;O++)if(!F[O].test(V))return!1;if(V.prerelease.length&&!H.includePrerelease){for(let O=0;O<F.length;O++)if(l(F[O].semver),F[O].semver!==a.ANY&&F[O].semver.prerelease.length>0){const L=F[O].semver;if(L.major===V.major&&L.minor===V.minor&&L.patch===V.patch)return!0}return!1}return!0};return Wh}var Hh,Zw;function Hd(){if(Zw)return Hh;Zw=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(h,m){if(m=r(m),h instanceof t){if(h.loose===!!m.loose)return h;h=h.value}h=h.trim().split(/\s+/).join(" "),l("comparator",h,m),this.options=m,this.loose=!!m.loose,this.parse(h),this.semver===e?this.value="":this.value=this.operator+this.semver.version,l("comp",this)}parse(h){const m=this.options.loose?n[o.COMPARATORLOOSE]:n[o.COMPARATOR],y=h.match(m);if(!y)throw new TypeError(`Invalid comparator: ${h}`);this.operator=y[1]!==void 0?y[1]:"",this.operator==="="&&(this.operator=""),y[2]?this.semver=new u(y[2],this.options.loose):this.semver=e}toString(){return this.value}test(h){if(l("Comparator.test",h,this.options.loose),this.semver===e||h===e)return!0;if(typeof h=="string")try{h=new u(h,this.options)}catch{return!1}return a(h,this.operator,this.semver,this.options)}intersects(h,m){if(!(h instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new d(h.value,m).test(this.value):h.operator===""?h.value===""?!0:new d(this.value,m).test(h.semver):(m=r(m),m.includePrerelease&&(this.value==="<0.0.0-0"||h.value==="<0.0.0-0")||!m.includePrerelease&&(this.value.startsWith("<0.0.0")||h.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&h.operator.startsWith(">")||this.operator.startsWith("<")&&h.operator.startsWith("<")||this.semver.version===h.semver.version&&this.operator.includes("=")&&h.operator.includes("=")||a(this.semver,"<",h.semver,m)&&this.operator.startsWith(">")&&h.operator.startsWith("<")||a(this.semver,">",h.semver,m)&&this.operator.startsWith("<")&&h.operator.startsWith(">")))}}Hh=t;const r=vv(),{safeRe:n,t:o}=Il(),a=_R(),l=Vd(),u=gr(),d=xn();return Hh}var qh,eS;function qd(){if(eS)return qh;eS=1;const e=xn();return qh=(r,n,o)=>{try{n=new e(n,o)}catch{return!1}return n.test(r)},qh}var Gh,tS;function K5(){if(tS)return Gh;tS=1;const e=xn();return Gh=(r,n)=>new e(r,n).set.map(o=>o.map(a=>a.value).join(" ").trim().split(" ")),Gh}var Xh,rS;function Q5(){if(rS)return Xh;rS=1;const e=gr(),t=xn();return Xh=(n,o,a)=>{let l=null,u=null,d=null;try{d=new t(o,a)}catch{return null}return n.forEach(p=>{d.test(p)&&(!l||u.compare(p)===-1)&&(l=p,u=new e(l,a))}),l},Xh}var Yh,nS;function J5(){if(nS)return Yh;nS=1;const e=gr(),t=xn();return Yh=(n,o,a)=>{let l=null,u=null,d=null;try{d=new t(o,a)}catch{return null}return n.forEach(p=>{d.test(p)&&(!l||u.compare(p)===1)&&(l=p,u=new e(l,a))}),l},Yh}var Kh,iS;function Z5(){if(iS)return Kh;iS=1;const e=gr(),t=xn(),r=Wd();return Kh=(o,a)=>{o=new t(o,a);let l=new e("0.0.0");if(o.test(l)||(l=new e("0.0.0-0"),o.test(l)))return l;l=null;for(let u=0;u<o.set.length;++u){const d=o.set[u];let p=null;d.forEach(h=>{const m=new e(h.semver.version);switch(h.operator){case">":m.prerelease.length===0?m.patch++:m.prerelease.push(0),m.raw=m.format();case"":case">=":(!p||r(m,p))&&(p=m);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${h.operator}`)}}),p&&(!l||r(l,p))&&(l=p)}return l&&o.test(l)?l:null},Kh}var Qh,oS;function ez(){if(oS)return Qh;oS=1;const e=xn();return Qh=(r,n)=>{try{return new e(r,n).range||"*"}catch{return null}},Qh}var Jh,sS;function Sv(){if(sS)return Jh;sS=1;const e=gr(),t=Hd(),{ANY:r}=t,n=xn(),o=qd(),a=Wd(),l=bv(),u=wv(),d=xv();return Jh=(h,m,y,w)=>{h=new e(h,w),m=new n(m,w);let E,S,C,R,k;switch(y){case">":E=a,S=u,C=l,R=">",k=">=";break;case"<":E=l,S=d,C=a,R="<",k="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(h,m,w))return!1;for(let $=0;$<m.set.length;++$){const A=m.set[$];let D=null,N=null;if(A.forEach(P=>{P.semver===r&&(P=new t(">=0.0.0")),D=D||P,N=N||P,E(P.semver,D.semver,w)?D=P:C(P.semver,N.semver,w)&&(N=P)}),D.operator===R||D.operator===k||(!N.operator||N.operator===R)&&S(h,N.semver))return!1;if(N.operator===k&&C(h,N.semver))return!1}return!0},Jh}var Zh,aS;function tz(){if(aS)return Zh;aS=1;const e=Sv();return Zh=(r,n,o)=>e(r,n,">",o),Zh}var em,lS;function rz(){if(lS)return em;lS=1;const e=Sv();return em=(r,n,o)=>e(r,n,"<",o),em}var tm,cS;function nz(){if(cS)return tm;cS=1;const e=xn();return tm=(r,n,o)=>(r=new e(r,o),n=new e(n,o),r.intersects(n,o)),tm}var rm,uS;function iz(){if(uS)return rm;uS=1;const e=qd(),t=bn();return rm=(r,n,o)=>{const a=[];let l=null,u=null;const d=r.sort((y,w)=>t(y,w,o));for(const y of d)e(y,n,o)?(u=y,l||(l=y)):(u&&a.push([l,u]),u=null,l=null);l&&a.push([l,null]);const p=[];for(const[y,w]of a)y===w?p.push(y):!w&&y===d[0]?p.push("*"):w?y===d[0]?p.push(`<=${w}`):p.push(`${y} - ${w}`):p.push(`>=${y}`);const h=p.join(" || "),m=typeof n.raw=="string"?n.raw:String(n);return h.length<m.length?h:n},rm}var nm,dS;function oz(){if(dS)return nm;dS=1;const e=xn(),t=Hd(),{ANY:r}=t,n=qd(),o=bn(),a=(m,y,w={})=>{if(m===y)return!0;m=new e(m,w),y=new e(y,w);let E=!1;e:for(const S of m.set){for(const C of y.set){const R=d(S,C,w);if(E=E||R!==null,R)continue e}if(E)return!1}return!0},l=[new t(">=0.0.0-0")],u=[new t(">=0.0.0")],d=(m,y,w)=>{if(m===y)return!0;if(m.length===1&&m[0].semver===r){if(y.length===1&&y[0].semver===r)return!0;w.includePrerelease?m=l:m=u}if(y.length===1&&y[0].semver===r){if(w.includePrerelease)return!0;y=u}const E=new Set;let S,C;for(const I of m)I.operator===">"||I.operator===">="?S=p(S,I,w):I.operator==="<"||I.operator==="<="?C=h(C,I,w):E.add(I.semver);if(E.size>1)return null;let R;if(S&&C){if(R=o(S.semver,C.semver,w),R>0)return null;if(R===0&&(S.operator!==">="||C.operator!=="<="))return null}for(const I of E){if(S&&!n(I,String(S),w)||C&&!n(I,String(C),w))return null;for(const re of y)if(!n(I,String(re),w))return!1;return!0}let k,$,A,D,N=C&&!w.includePrerelease&&C.semver.prerelease.length?C.semver:!1,P=S&&!w.includePrerelease&&S.semver.prerelease.length?S.semver:!1;N&&N.prerelease.length===1&&C.operator==="<"&&N.prerelease[0]===0&&(N=!1);for(const I of y){if(D=D||I.operator===">"||I.operator===">=",A=A||I.operator==="<"||I.operator==="<=",S){if(P&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===P.major&&I.semver.minor===P.minor&&I.semver.patch===P.patch&&(P=!1),I.operator===">"||I.operator===">="){if(k=p(S,I,w),k===I&&k!==S)return!1}else if(S.operator===">="&&!n(S.semver,String(I),w))return!1}if(C){if(N&&I.semver.prerelease&&I.semver.prerelease.length&&I.semver.major===N.major&&I.semver.minor===N.minor&&I.semver.patch===N.patch&&(N=!1),I.operator==="<"||I.operator==="<="){if($=h(C,I,w),$===I&&$!==C)return!1}else if(C.operator==="<="&&!n(C.semver,String(I),w))return!1}if(!I.operator&&(C||S)&&R!==0)return!1}return!(S&&A&&!C&&R!==0||C&&D&&!S&&R!==0||P||N)},p=(m,y,w)=>{if(!m)return y;const E=o(m.semver,y.semver,w);return E>0?m:E<0||y.operator===">"&&m.operator===">="?y:m},h=(m,y,w)=>{if(!m)return y;const E=o(m.semver,y.semver,w);return E<0?m:E>0||y.operator==="<"&&m.operator==="<="?y:m};return nm=a,nm}var im,fS;function sz(){if(fS)return im;fS=1;const e=Il(),t=Ud(),r=gr(),n=CR(),o=ia(),a=D5(),l=j5(),u=M5(),d=z5(),p=F5(),h=B5(),m=U5(),y=V5(),w=bn(),E=W5(),S=H5(),C=yv(),R=q5(),k=G5(),$=Wd(),A=bv(),D=kR(),N=RR(),P=xv(),I=wv(),re=_R(),Z=X5(),ee=Hd(),ne=xn(),X=qd(),F=K5(),V=Q5(),H=J5(),O=Z5(),L=ez(),U=Sv(),z=tz(),T=rz(),M=nz(),te=iz(),le=oz();return im={parse:o,valid:a,clean:l,inc:u,diff:d,major:p,minor:h,patch:m,prerelease:y,compare:w,rcompare:E,compareLoose:S,compareBuild:C,sort:R,rsort:k,gt:$,lt:A,eq:D,neq:N,gte:P,lte:I,cmp:re,coerce:Z,Comparator:ee,Range:ne,satisfies:X,toComparators:F,maxSatisfying:V,minSatisfying:H,minVersion:O,validRange:L,outside:U,gtr:z,ltr:T,intersects:M,simplifyRange:te,subset:le,SemVer:r,re:e.re,src:e.src,tokens:e.t,SEMVER_SPEC_VERSION:t.SEMVER_SPEC_VERSION,RELEASE_TYPES:t.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},im}var jr=sz();const pS=Qr(jr);var wt=(e=>(e.NANO_S="nanoS",e.NANO_SP="nanoSP",e.NANO_X="nanoX",e.STAX="stax",e.FLEX="flex",e.APEX="apexp",e))(wt||{});let $R=class{id;model;name;constructor({id:t,model:r,name:n}){this.id=t,this.model=r,this.name=n}};const om={Twelve:12,Eighteen:18,TwentyFour:24};var Xt=(e=>(e.Unknown="unknown",e.WelcomeScreen1="welcome-screen-1",e.WelcomeScreen2="welcome-screen-2",e.WelcomeScreen3="welcome-screen-3",e.WelcomeScreen4="welcome-screen-4",e.WelcomeScreenReminder="welcome-screen-reminder",e.SetupChoice="setup-choice",e.Pin="pin",e.NewDevice="new-device",e.ConfirmNewDevice="confirm-new-device",e.RestoreRecoveryPhrase="restore-recovery-phrase",e.SafetyWarning="safety-warning",e.DeviceIsReady="device-is-ready",e.ChooseName="choose-name",e.RestoreRecoverBackup="restore-recover-backup",e.SetupRestoreChoice="setup-restore-choice",e.OnboardingStatusCheck="onboarding-status-check",e.RestoreWithRk="restore-with-rk",e))(Xt||{});const az={0:Xt.WelcomeScreen1,1:Xt.WelcomeScreen2,2:Xt.WelcomeScreen3,3:Xt.WelcomeScreen4,4:Xt.WelcomeScreenReminder,5:Xt.SetupChoice,6:Xt.Pin,7:Xt.NewDevice,8:Xt.ConfirmNewDevice,9:Xt.RestoreRecoveryPhrase,10:Xt.SafetyWarning,11:Xt.DeviceIsReady,12:Xt.ChooseName,13:Xt.RestoreRecoverBackup,14:Xt.SetupRestoreChoice,15:Xt.OnboardingStatusCheck,16:Xt.RestoreWithRk};let lz=class{seFlags;constructor(t){this.seFlags=new Uint8Array(4),this.seFlags.set(t.subarray(0,this.seFlags.length))}generalDeviceState(){const t=this.seFlags[0]??0;return{isPinValidated:this._checkNthBitInByte(t,1),hasMcuSerialNumber:this._checkNthBitInByte(t,2),hasValidCertificate:this._checkNthBitInByte(t,3),isCustomAuthorityConnectionAllowed:this._checkNthBitInByte(t,4),isSecureConnectionAllowed:this._checkNthBitInByte(t,5),isOnboarded:this._checkNthBitInByte(t,6),isMcuCodeSigned:this._checkNthBitInByte(t,7),isInRecoveryMode:this._checkNthBitInByte(t,8)}}endorsementInformation(){const t=this.seFlags[1]??0;return{hasEndorsementCertificateInSlot1:(t&1)!==0,hasEndorsementCertificateInSlot2:(t&2)!==0}}wordsInformation(){const t=this.seFlags[2]??0,r=t>>5&3;return{numberOfWords:[om.TwentyFour,om.Eighteen,om.Twelve,void 0][r],currentWordIndex:t&31}}onboardingStatus(){const t=this.seFlags[3]??0;return{onboardingState:az[t]??Xt.Unknown}}_checkNthBitInByte(t,r){return(t>>8-r&1)===1}},cz=class{name="getOsVersion";args=void 0;getApdu(){const t={cla:224,ins:1,p1:0,p2:0};return new SR(t).build()}parseResponse(t,r){if(!gv.isSuccessResponse(t))return Io({error:ER.handle(t)});const n=new mv(t),o=n.extract32BitUInt();if(o===void 0)return Io({error:new C5("Missing target ID in OS version")});let a=n.encodeToString(n.extractFieldLVEncoded()),l=n.extractFieldLVEncoded()??new Uint8Array(0);const u=new lz(l),d={...u.generalDeviceState(),...u.endorsementInformation(),...u.wordsInformation(),...u.onboardingStatus()};a||(a="0.0.0",l=new Uint8Array);const p=(o&4026531840)!==805306368,h=a.includes("-osu");let m="",y="",w="",E="",S,C,R,k;if(p){w=a,S=o;const $=n.extractFieldLVEncoded();$&&($.length>=5?(m=n.encodeToString($),C=parseInt(n.encodeToHexaString(n.extractFieldLVEncoded()),16)):C=parseInt(n.encodeToHexaString($),16))}else{if(m=a,C=o,y=n.encodeToString(n.extractFieldLVEncoded()),this.isBootloaderVersionSupported(m,r)&&(w=n.encodeToString(n.extractFieldLVEncoded())),this.isHardwareVersionSupported(m,r)?E=n.encodeToHexaString(n.extractFieldLVEncoded()):E="00",this.isLocalizationSupported(m,r)){const $=n.extractFieldLVEncoded();$!==void 0&&(R=parseInt(n.encodeToHexaString($),16))}if(this.isRecoverSupported(m,r)){const $=n.extractFieldLVEncoded();$!==void 0&&(k=parseInt(n.encodeToHexaString($),16))}}return Io({data:{isBootloader:p,isOsu:h,targetId:o,seTargetId:C,mcuTargetId:S,seVersion:m,seFlags:l,mcuSephVersion:y,mcuBootloaderVersion:w,hwVersion:E,langId:R,recoverState:k,secureElementFlags:d}})}isBootloaderVersionSupported(t,r){const n=jr.coerce(t)??"";switch(r){case wt.NANO_S:case wt.NANO_X:return jr.gte(n,"2.0.0");default:return!0}}isHardwareVersionSupported(t,r){const n=jr.coerce(t)??"";return r===wt.NANO_X?jr.gte(n,"2.0.0"):!1}isLocalizationSupported(t,r){const n=jr.coerce(t)??"";switch(r){case wt.NANO_S:return!1;case wt.NANO_SP:return jr.gte(n,"1.1.0");case wt.NANO_X:return jr.gte(n,"2.1.0");default:return!0}}isRecoverSupported(t,r){const n=jr.coerce(t)??"";switch(r){case wt.NANO_S:return!1;case wt.NANO_SP:return jr.gte(n,"1.1.2");case wt.NANO_X:return jr.gte(n,"2.2.3");case wt.STAX:return jr.gte(n,"1.4.0");case wt.FLEX:return jr.gte(n,"1.0.1");default:return!0}}};var Ln=(e=>(e.LOCKED="LOCKED",e.BUSY="BUSY",e.CONNECTED="CONNECTED",e.NOT_CONNECTED="NOT CONNECTED",e))(Ln||{}),uz=(e=>(e.NotStarted="not-started",e.Pending="pending",e.Stopped="stopped",e.Completed="completed",e.Error="error",e))(uz||{}),dz=(e=>(e.None="none",e.UnlockDevice="unlock-device",e.AllowSecureConnection="allow-secure-connection",e.ConfirmOpenApp="confirm-open-app",e.SignTransaction="sign-transaction",e.SignTypedData="sign-typed-data",e.AllowListApps="allow-list-apps",e.VerifyAddress="verify-address",e.SignPersonalMessage="sign-personal-message",e.SignDelegationAuthorization="sign-delegation-authorization",e.Web3ChecksOptIn="web3-checks-opt-in",e.VerifySafeAddress="verify-safe-address",e.RegisterWallet="register-wallet",e.ConfirmLoadImage="confirm-load-image",e.ConfirmCommitImage="confirm-commit-image",e.ConfirmRemoveImage="confirm-remove-image",e.GrantConsent="grant-consent",e.AllowInstallFirmware="allow-install-firmware",e))(dz||{});const Ar={of(e){return or(e)},empty(){return ft},zero(){return ft},fromNullable(e){return e==null?ft:or(e)},fromFalsy(e){return e?or(e):ft},fromPredicate(e,t){return arguments.length===1?r=>Ar.fromPredicate(e,r):e(t)?or(t):ft},mapMaybe(e,t){return arguments.length===1?r=>Ar.mapMaybe(e,r):Ar.catMaybes(t.map(e))},catMaybes(e){let t=[];for(const r of e)r.isJust()&&t.push(r.extract());return t},encase(e){try{return or(e())}catch{return ft}},isMaybe(e){return e instanceof Ev||e instanceof Cv},sequence(e){let t=[];for(const r of e)if(r.isJust())t.push(r.extract());else return ft;return or(t)},"fantasy-land/of"(e){return this.of(e)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};class Ev{constructor(t){this.__value=t,this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!0}isNothing(){return!1}inspect(){return`Just(${this.__value})`}toString(){return this.inspect()}toJSON(){const t=this.__value;return t instanceof Date?t.toJSON():t}equals(t){return this.extract()===t.extract()}map(t){return or(t(this.__value))}ap(t){return t.isJust()?this.map(t.extract()):ft}alt(t){return this}altLazy(t){return this}chain(t){return t(this.__value)}chainNullable(t){return Ar.fromNullable(t(this.__value))}join(){return this.__value}reduce(t,r){return t(r,this.__value)}extend(t){return or(t(this))}unsafeCoerce(){return this.__value}caseOf(t){return"_"in t?t._():t.Just(this.__value)}orDefault(t){return this.__value}orDefaultLazy(t){return this.__value}toList(){return[this.__value]}mapOrDefault(t,r){return t(this.__value)}extract(){return this.__value}extractNullable(){return this.__value}toEither(t){return Tt(this.__value)}ifJust(t){return t(this.__value),this}ifNothing(t){return this}filter(t){return t(this.__value)?or(this.__value):ft}}Ev.prototype.constructor=Ar;class Cv{constructor(){this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!1}isNothing(){return!0}inspect(){return"Nothing"}toString(){return this.inspect()}toJSON(){return this.__value}equals(t){return this.extract()===t.extract()}map(t){return ft}ap(t){return ft}alt(t){return t}altLazy(t){return t()}chain(t){return ft}chainNullable(t){return ft}join(){return ft}reduce(t,r){return r}extend(t){return ft}unsafeCoerce(){throw new Error("Maybe#unsafeCoerce was ran on a Nothing")}caseOf(t){return"_"in t?t._():t.Nothing()}orDefault(t){return t}orDefaultLazy(t){return t()}toList(){return[]}mapOrDefault(t,r){return r}extract(){}extractNullable(){return null}toEither(t){return yt(t)}ifJust(t){return this}ifNothing(t){return t(),this}filter(t){return ft}}Cv.prototype.constructor=Ar;const or=e=>new Ev(e),ft=new Cv,Tr={of(e){return Tt(e)},lefts(e){let t=[];for(const r of e)r.isLeft()&&t.push(r.extract());return t},rights(e){let t=[];for(const r of e)r.isRight()&&t.push(r.extract());return t},encase(e){try{return Tt(e())}catch(t){return yt(t)}},sequence(e){let t=[];for(const r of e){if(r.isLeft())return r;t.push(r.extract())}return Tt(t)},isEither(e){return e instanceof Rv||e instanceof kv},"fantasy-land/of"(e){return Tr.of(e)}};class kv{constructor(t){this.__value=t,this._="R",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!1}isRight(){return!0}toJSON(){return this.__value}inspect(){return`Right(${this.__value})`}toString(){return this.inspect()}bimap(t,r){return Tt(r(this.__value))}map(t){return Tt(t(this.__value))}mapLeft(t){return this}ap(t){return t.isRight()?this.map(t.extract()):t}equals(t){return t.isRight()?this.__value===t.extract():!1}chain(t){return t(this.__value)}chainLeft(t){return this}join(){return this.__value}alt(t){return this}altLazy(t){return this}reduce(t,r){return t(r,this.__value)}extend(t){return Tt(t(this))}unsafeCoerce(){return this.__value}caseOf(t){return"_"in t?t._():t.Right(this.__value)}leftOrDefault(t){return t}orDefault(t){return this.__value}orDefaultLazy(t){return this.__value}leftOrDefaultLazy(t){return t()}ifLeft(t){return this}ifRight(t){return t(this.__value),this}toMaybe(){return or(this.__value)}leftToMaybe(){return ft}extract(){return this.__value}swap(){return yt(this.__value)}}kv.prototype.constructor=Tr;class Rv{constructor(t){this.__value=t,this._="L",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!0}isRight(){return!1}toJSON(){return this.__value}inspect(){return`Left(${JSON.stringify(this.__value)})`}toString(){return this.inspect()}bimap(t,r){return yt(t(this.__value))}map(t){return this}mapLeft(t){return yt(t(this.__value))}ap(t){return t.isLeft()?t:this}equals(t){return t.isLeft()?t.extract()===this.__value:!1}chain(t){return this}chainLeft(t){return t(this.__value)}join(){return this}alt(t){return t}altLazy(t){return t()}reduce(t,r){return r}extend(t){return this}unsafeCoerce(){throw this.__value instanceof Error?this.__value:new Error("Either#unsafeCoerce was ran on a Left")}caseOf(t){return"_"in t?t._():t.Left(this.__value)}leftOrDefault(t){return this.__value}orDefault(t){return t}orDefaultLazy(t){return t()}leftOrDefaultLazy(t){return this.__value}ifLeft(t){return t(this.__value),this}ifRight(t){return this}toMaybe(){return ft}leftToMaybe(){return or(this.__value)}extract(){return this.__value}swap(){return Tt(this.__value)}}Rv.prototype.constructor=Tr;const yt=e=>new Rv(e),Tt=e=>new kv(e),Ol=e=>e,fz=e=>e,sm=Object.assign(fz,{fromArray:e=>sm.isNonEmpty(e)?or(e):ft,unsafeCoerce:e=>{if(sm.isNonEmpty(e))return e;throw new Error("NonEmptyList#unsafeCoerce was ran on an empty array")},fromTuple:e=>sm(e.toArray()),head:e=>e[0],last:e=>e[e.length-1],isNonEmpty:e=>e.length>0,tail:e=>e.slice(1)}),Wu=(e,t)=>typeof t=="bigint"?t.toString():t,pz=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wo=(e,t)=>{let r="";switch(typeof t){case"undefined":r="undefined";break;case"object":r=t===null?"null":Array.isArray(t)?"an array with value "+JSON.stringify(t,Wu):"an object with value "+JSON.stringify(t,Wu);break;case"boolean":r="a boolean";break;case"symbol":r="a symbol";break;case"function":r="a function";break;case"bigint":r=`a bigint with value ${t.toString()}`}return r=r||`a ${typeof t} with value ${JSON.stringify(t,Wu)}`,`Expected ${e}, but received ${r}`},hz=e=>(Object.keys(e).length===1&&e.oneOf?.length===1&&typeof e.oneOf[0]=="object"&&(Object.assign(e,e.oneOf[0]),delete e.oneOf),e),mz=e=>{if(Array.isArray(e.oneOf))for(let t=0;t<e.oneOf.length;t++){const r=e.oneOf[t];if(typeof r=="object"&&r.oneOf)return e.oneOf.splice(t,1),e.oneOf.push(...r.oneOf),AR(e)}return e},AR=e=>(mz(e),hz(e),e),Ft={interface(e){const t=Object.keys(e),r=o=>{if(!pz(o))return yt(Wo("an object",o));const a={};for(const l of t){if(!o.hasOwnProperty(l)&&!e[l]._isOptional)return yt(`Problem with property "${l}": it does not exist in received object ${JSON.stringify(o,Wu)}`);const u=e[l].decode(o[l]);if(u.isLeft())return yt(`Problem with the value of property "${l}": ${u.extract()}`);const d=u.extract();d!==void 0&&(a[l]=d)}return Tt(a)};return{decode:r,encode:o=>{const a={};for(const l of t)a[l]=e[l].encode(o[l]);return a},unsafeDecode:o=>r(o).mapLeft(Error).unsafeCoerce(),schema:()=>t.reduce((o,a)=>(e[a]._isOptional||o.required.push(a),o.properties[a]=AR(e[a].schema()),o),{type:"object",properties:{},required:[]})}},custom({decode:e,encode:t,schema:r}){return{decode:e,encode:t,unsafeDecode:n=>e(n).mapLeft(Error).unsafeCoerce(),schema:r??(()=>({}))}}},ut=Ft.custom({decode:e=>typeof e=="string"?Tt(e):yt(Wo("a string",e)),encode:Ol,schema:()=>({type:"string"})}),Mo=Ft.custom({decode:e=>typeof e=="number"?Tt(e):yt(Wo("a number",e)),encode:Ol,schema:()=>({type:"number"})}),gz=Ft.custom({decode:e=>e===void 0?Tt(e):yt(Wo("an undefined",e)),encode:Ol}),Yt=e=>({...vz([e,gz]),schema:e.schema,_isOptional:!0}),vd=Ft.custom({decode:e=>typeof e=="boolean"?Tt(e):yt(Wo("a boolean",e)),encode:Ol,schema:()=>({type:"boolean"})}),vz=e=>Ft.custom({decode:t=>{let r=[];for(const n of e){const o=n.decode(t);if(o.isRight())return o;r.push(o.extract())}return yt(`One of the following problems occured: ${r.map((n,o)=>`(${o}) ${n}`).join(", ")}`)},encode:t=>{for(const r of e)if(Tr.encase(()=>r.encode(t)).mapLeft(o=>"").chain(r.decode).isRight())return r.encode(t);return t},schema:()=>({oneOf:e.map(t=>t.schema())})}),Yr=e=>Ft.custom({decode:t=>{if(Array.isArray(t)){const r=[];for(let n=0;n<t.length;n++){const o=e.decode(t[n]);if(o.isRight())r.push(o.extract());else return yt(`Problem with the value at index ${n}: ${o.extract()}`)}return Tt(r)}else return yt(Wo("an array",t))},encode:t=>t.map(e.encode),schema:()=>({type:"array",items:e.schema()})});Ft.custom({decode:e=>ut.decode(e).chain(t=>isFinite(+t)?Tt(t):yt(Wo("a number",e))),encode:Ol,schema:Mo.schema});var TR;const LR={liftEither(e){if(e.isRight())return Promise.resolve(e.extract());throw e.extract()},fromPromise(e){return e.then(LR.liftEither)},throwE(e){throw e}};class IR{constructor(t){this.runPromise=t,this[TR]="EitherAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this.then=(r,n)=>this.run().then(r,n)}leftOrDefault(t){return this.run().then(r=>r.leftOrDefault(t))}orDefault(t){return this.run().then(r=>r.orDefault(t))}join(){return He(async t=>{const r=await this;if(r.isRight()){const n=await r.extract();return t.liftEither(n)}return t.liftEither(r)})}ap(t){return He(async r=>{const n=await t;if(n.isRight()){const o=await this.run();return o.isRight()?n.extract()(o.extract()):r.liftEither(o)}return r.liftEither(n)})}alt(t){return He(async r=>{const n=await this.run();if(n.isRight())return n.extract();{const o=await t;return r.liftEither(o)}})}extend(t){return He(async r=>{const n=await this.run();if(n.isRight()){const o=He.liftEither(n);return r.liftEither(Tt(t(o)))}return r.liftEither(n)})}async run(){try{return Tt(await this.runPromise(LR))}catch(t){return yt(t)}}bimap(t,r){return He(async n=>{const o=await this.run();try{return await n.liftEither(o.bimap(t,r))}catch(a){throw await a}})}map(t){return He(r=>this.runPromise(r).then(t))}mapLeft(t){return He(async r=>{try{return await this.runPromise(r)}catch(n){throw await t(n)}})}chain(t){return He(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}chainLeft(t){return He(async r=>{try{return await this.runPromise(r)}catch(n){return r.fromPromise(t(n))}})}toMaybeAsync(){return hr(async({liftMaybe:t})=>{const r=await this.run();return t(r.toMaybe())})}swap(){return He(async t=>{const r=await this.run();return r.isRight()&&t.throwE(r.extract()),t.liftEither(Tt(r.extract()))})}ifLeft(t){return He(async r=>{const n=await this.run();return n.ifLeft(t),r.liftEither(n)})}ifRight(t){return He(async r=>{const n=await this.run();return n.ifRight(t),r.liftEither(n)})}void(){return this.map(t=>{})}caseOf(t){return this.run().then(r=>r.caseOf(t))}finally(t){return He(({fromPromise:r})=>r(this.run().finally(t)))}}TR=Symbol.toStringTag;const He=Object.assign(e=>new IR(e),{fromPromise:e=>He(({fromPromise:t})=>t(e())),liftEither:e=>He(({liftEither:t})=>t(e)),lefts:e=>Promise.all(e.map(t=>t.run())).then(Tr.lefts),rights:e=>Promise.all(e.map(t=>t.run())).then(Tr.rights),sequence:e=>He(async t=>{let r=[];for await(const n of e){if(n.isLeft())return t.liftEither(n);r.push(n.extract())}return t.liftEither(Tt(r))}),all:e=>He.fromPromise(async()=>Promise.all(e).then(Tr.sequence))});IR.prototype.constructor=He;var OR;const NR={liftMaybe(e){if(e.isJust())return Promise.resolve(e.extract());throw ft},fromPromise(e){return e.then(NR.liftMaybe)}};class PR{constructor(t){this.runPromise=t,this[OR]="MaybeAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/filter"]=this.filter,this["fantasy-land/alt"]=this.alt}orDefault(t){return this.run().then(r=>r.orDefault(t))}join(){return hr(async t=>{const r=await this.run();if(r.isJust()){const n=await r.extract();return t.liftMaybe(n)}return t.liftMaybe(ft)})}ap(t){return hr(async r=>{const n=await t;if(n.isJust()){const o=await this.run();return o.isJust()?n.extract()(o.extract()):r.liftMaybe(ft)}return r.liftMaybe(ft)})}alt(t){return hr(async r=>{const n=await this.run();if(n.isJust())return n.extract();{const o=await t;return r.liftMaybe(o)}})}extend(t){return hr(async r=>{const n=await this.run();if(n.isJust()){const o=hr.liftMaybe(n);return r.liftMaybe(or(t(o)))}return r.liftMaybe(ft)})}filter(t){return hr(async r=>{const n=await this.run();return r.liftMaybe(n.filter(t))})}async run(){try{return or(await this.runPromise(NR))}catch{return ft}}map(t){return hr(r=>this.runPromise(r).then(t))}chain(t){return hr(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}toEitherAsync(t){return He(async({liftEither:r})=>{const n=await this.run();return r(n.toEither(t))})}ifJust(t){return hr(async r=>{const n=await this.run();return n.ifJust(t),r.liftMaybe(n)})}ifNothing(t){return hr(async r=>{const n=await this.run();return n.ifNothing(t),r.liftMaybe(n)})}void(){return this.map(t=>{})}caseOf(t){return this.run().then(r=>r.caseOf(t))}finally(t){return hr(({fromPromise:r})=>r(this.run().finally(t)))}then(t,r){return this.run().then(t,r)}}OR=Symbol.toStringTag;const hr=Object.assign(e=>new PR(e),{catMaybes:e=>Promise.all(e).then(Ar.catMaybes),fromPromise:e=>hr(({fromPromise:t})=>t(e())),liftMaybe:e=>hr(({liftMaybe:t})=>t(e))});PR.prototype.constructor=hr;function Pt(e){return typeof e=="function"}function Gd(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var am=Gd(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription:
28
28
  `+r.map(function(n,o){return o+1+") "+n.toString()}).join(`
29
29
  `):"",this.name="UnsubscriptionError",this.errors=r}});function yd(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Nl=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,a;if(!this.closed){this.closed=!0;var l=this._parentage;if(l)if(this._parentage=null,Array.isArray(l))try{for(var u=Fs(l),d=u.next();!d.done;d=u.next()){var p=d.value;p.remove(this)}}catch(S){t={error:S}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}else l.remove(this);var h=this.initialTeardown;if(Pt(h))try{h()}catch(S){a=S instanceof am?S.errors:[S]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=Fs(m),w=y.next();!w.done;w=y.next()){var E=w.value;try{hS(E)}catch(S){a=a??[],S instanceof am?a=Us(Us([],Bs(a)),Bs(S.errors)):a.push(S)}}}catch(S){n={error:S}}finally{try{w&&!w.done&&(o=y.return)&&o.call(y)}finally{if(n)throw n.error}}}if(a)throw new am(a)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)hS(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&yd(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&yd(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),DR=Nl.EMPTY;function jR(e){return e instanceof Nl||e&&"closed"in e&&Pt(e.remove)&&Pt(e.add)&&Pt(e.unsubscribe)}function hS(e){Pt(e)?e():e.unsubscribe()}var yz={Promise:void 0},bz={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,Us([e,t],Bs(r)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function MR(e){bz.setTimeout(function(){throw e})}function xg(){}function Hu(e){e()}var _v=(function(e){zn(t,e);function t(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,jR(r)&&r.add(n)):n.destination=Sz,n}return t.create=function(r,n,o){return new wg(r,n,o)},t.prototype.next=function(r){this.isStopped||this._next(r)},t.prototype.error=function(r){this.isStopped||(this.isStopped=!0,this._error(r))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(r){this.destination.next(r)},t.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(Nl),xz=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var r=this.partialObserver;if(r.next)try{r.next(t)}catch(n){Tu(n)}},e.prototype.error=function(t){var r=this.partialObserver;if(r.error)try{r.error(t)}catch(n){Tu(n)}else Tu(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(r){Tu(r)}},e})(),wg=(function(e){zn(t,e);function t(r,n,o){var a=e.call(this)||this,l;return Pt(r)||!r?l={next:r??void 0,error:n??void 0,complete:o??void 0}:l=r,a.destination=new xz(l),a}return t})(_v);function Tu(e){MR(e)}function wz(e){throw e}var Sz={closed:!0,next:xg,error:wz,complete:xg},$v=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Pl(e){return e}function Ez(e){return e.length===0?Pl:e.length===1?e[0]:function(r){return e.reduce(function(n,o){return o(n)},r)}}var Fr=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(t,r,n){var o=this,a=kz(t)?t:new wg(t,r,n);return Hu(function(){var l=o,u=l.operator,d=l.source;a.add(u?u.call(a,d):d?o._subscribe(a):o._trySubscribe(a))}),a},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(r){t.error(r)}},e.prototype.forEach=function(t,r){var n=this;return r=mS(r),new r(function(o,a){var l=new wg({next:function(u){try{t(u)}catch(d){a(d),l.unsubscribe()}},error:a,complete:o});n.subscribe(l)})},e.prototype._subscribe=function(t){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(t)},e.prototype[$v]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Ez(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=mS(t),new t(function(n,o){var a;r.subscribe(function(l){return a=l},function(l){return o(l)},function(){return n(a)})})},e.create=function(t){return new e(t)},e})();function mS(e){var t;return(t=e??yz.Promise)!==null&&t!==void 0?t:Promise}function Cz(e){return e&&Pt(e.next)&&Pt(e.error)&&Pt(e.complete)}function kz(e){return e&&e instanceof _v||Cz(e)&&jR(e)}function Rz(e){return Pt(e?.lift)}function Jr(e){return function(t){if(Rz(t))return t.lift(function(r){try{return e(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}function vn(e,t,r,n,o){return new _z(e,t,r,n,o)}var _z=(function(e){zn(t,e);function t(r,n,o,a,l,u){var d=e.call(this,r)||this;return d.onFinalize=l,d.shouldUnsubscribe=u,d._next=n?function(p){try{n(p)}catch(h){r.error(h)}}:e.prototype._next,d._error=a?function(p){try{a(p)}catch(h){r.error(h)}finally{this.unsubscribe()}}:e.prototype._error,d._complete=o?function(){try{o()}catch(p){r.error(p)}finally{this.unsubscribe()}}:e.prototype._complete,d}return t.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},t})(_v),$z=Gd(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),oa=(function(e){zn(t,e);function t(){var r=e.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return t.prototype.lift=function(r){var n=new gS(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new $z},t.prototype.next=function(r){var n=this;Hu(function(){var o,a;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var l=Fs(n.currentObservers),u=l.next();!u.done;u=l.next()){var d=u.value;d.next(r)}}catch(p){o={error:p}}finally{try{u&&!u.done&&(a=l.return)&&a.call(l)}finally{if(o)throw o.error}}}})},t.prototype.error=function(r){var n=this;Hu(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var o=n.observers;o.length;)o.shift().error(r)}})},t.prototype.complete=function(){var r=this;Hu(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,a=o.hasError,l=o.isStopped,u=o.observers;return a||l?DR:(this.currentObservers=null,u.push(r),new Nl(function(){n.currentObservers=null,yd(u,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,a=n.thrownError,l=n.isStopped;o?r.error(a):l&&r.complete()},t.prototype.asObservable=function(){var r=new Fr;return r.source=this,r},t.create=function(r,n){return new gS(r,n)},t})(Fr),gS=(function(e){zn(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},t.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:DR},t})(oa),Az=(function(e){zn(t,e);function t(r){var n=e.call(this)||this;return n._value=r,n}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(r){var n=e.prototype._subscribe.call(this,r);return!n.closed&&r.next(this._value),n},t.prototype.getValue=function(){var r=this,n=r.hasError,o=r.thrownError,a=r._value;if(n)throw o;return this._throwIfClosed(),a},t.prototype.next=function(r){e.prototype.next.call(this,this._value=r)},t})(oa),Av={now:function(){return(Av.delegate||Date).now()},delegate:void 0},zR=(function(e){zn(t,e);function t(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=Av);var a=e.call(this)||this;return a._bufferSize=r,a._windowTime=n,a._timestampProvider=o,a._buffer=[],a._infiniteTimeWindow=!0,a._infiniteTimeWindow=n===1/0,a._bufferSize=Math.max(1,r),a._windowTime=Math.max(1,n),a}return t.prototype.next=function(r){var n=this,o=n.isStopped,a=n._buffer,l=n._infiniteTimeWindow,u=n._timestampProvider,d=n._windowTime;o||(a.push(r),!l&&a.push(u.now()+d)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,a=o._infiniteTimeWindow,l=o._buffer,u=l.slice(),d=0;d<u.length&&!r.closed;d+=a?1:2)r.next(u[d]);return this._checkFinalizedStatuses(r),n},t.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,o=r._timestampProvider,a=r._buffer,l=r._infiniteTimeWindow,u=(l?1:2)*n;if(n<1/0&&u<a.length&&a.splice(0,a.length-u),!l){for(var d=o.now(),p=0,h=1;h<a.length&&a[h]<=d;h+=2)p=h;p&&a.splice(0,p+1)}},t})(oa),Tz=(function(e){zn(t,e);function t(r,n){return e.call(this)||this}return t.prototype.schedule=function(r,n){return this},t})(Nl),vS={setInterval:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,Us([e,t],Bs(r)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},Lz=(function(e){zn(t,e);function t(r,n){var o=e.call(this,r,n)||this;return o.scheduler=r,o.work=n,o.pending=!1,o}return t.prototype.schedule=function(r,n){var o;if(n===void 0&&(n=0),this.closed)return this;this.state=r;var a=this.id,l=this.scheduler;return a!=null&&(this.id=this.recycleAsyncId(l,a,n)),this.pending=!0,this.delay=n,this.id=(o=this.id)!==null&&o!==void 0?o:this.requestAsyncId(l,this.id,n),this},t.prototype.requestAsyncId=function(r,n,o){return o===void 0&&(o=0),vS.setInterval(r.flush.bind(r,this),o)},t.prototype.recycleAsyncId=function(r,n,o){if(o===void 0&&(o=0),o!=null&&this.delay===o&&this.pending===!1)return n;n!=null&&vS.clearInterval(n)},t.prototype.execute=function(r,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var o=this._execute(r,n);if(o)return o;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(r,n){var o=!1,a;try{this.work(r)}catch(l){o=!0,a=l||new Error("Scheduled action threw falsy error")}if(o)return this.unsubscribe(),a},t.prototype.unsubscribe=function(){if(!this.closed){var r=this,n=r.id,o=r.scheduler,a=o.actions;this.work=this.state=this.scheduler=null,this.pending=!1,yd(a,this),n!=null&&(this.id=this.recycleAsyncId(o,n,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t})(Tz),yS=(function(){function e(t,r){r===void 0&&(r=e.now),this.schedulerActionCtor=t,this.now=r}return e.prototype.schedule=function(t,r,n){return r===void 0&&(r=0),new this.schedulerActionCtor(this,t).schedule(n,r)},e.now=Av.now,e})(),Iz=(function(e){zn(t,e);function t(r,n){n===void 0&&(n=yS.now);var o=e.call(this,r,n)||this;return o.actions=[],o._active=!1,o}return t.prototype.flush=function(r){var n=this.actions;if(this._active){n.push(r);return}var o;this._active=!0;do if(o=r.execute(r.state,r.delay))break;while(r=n.shift());if(this._active=!1,o){for(;r=n.shift();)r.unsubscribe();throw o}},t})(yS),FR=new Iz(Lz),Oz=FR,Nz=new Fr(function(e){return e.complete()});function BR(e){return e&&Pt(e.schedule)}function Tv(e){return e[e.length-1]}function Pz(e){return Pt(Tv(e))?e.pop():void 0}function Xd(e){return BR(Tv(e))?e.pop():void 0}function Dz(e,t){return typeof Tv(e)=="number"?e.pop():t}var UR=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function VR(e){return Pt(e?.then)}function WR(e){return Pt(e[$v])}function HR(e){return Symbol.asyncIterator&&Pt(e?.[Symbol.asyncIterator])}function qR(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function jz(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var GR=jz();function XR(e){return Pt(e?.[GR])}function YR(e){return ZD(this,arguments,function(){var r,n,o,a;return ZC(this,function(l){switch(l.label){case 0:r=e.getReader(),l.label=1;case 1:l.trys.push([1,,9,10]),l.label=2;case 2:return[4,Ns(r.read())];case 3:return n=l.sent(),o=n.value,a=n.done,a?[4,Ns(void 0)]:[3,5];case 4:return[2,l.sent()];case 5:return[4,Ns(o)];case 6:return[4,l.sent()];case 7:return l.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function KR(e){return Pt(e?.getReader)}function eo(e){if(e instanceof Fr)return e;if(e!=null){if(WR(e))return Mz(e);if(UR(e))return zz(e);if(VR(e))return Fz(e);if(HR(e))return QR(e);if(XR(e))return Bz(e);if(KR(e))return Uz(e)}throw qR(e)}function Mz(e){return new Fr(function(t){var r=e[$v]();if(Pt(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function zz(e){return new Fr(function(t){for(var r=0;r<e.length&&!t.closed;r++)t.next(e[r]);t.complete()})}function Fz(e){return new Fr(function(t){e.then(function(r){t.closed||(t.next(r),t.complete())},function(r){return t.error(r)}).then(null,MR)})}function Bz(e){return new Fr(function(t){var r,n;try{for(var o=Fs(e),a=o.next();!a.done;a=o.next()){var l=a.value;if(t.next(l),t.closed)return}}catch(u){r={error:u}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}t.complete()})}function QR(e){return new Fr(function(t){Vz(e,t).catch(function(r){return t.error(r)})})}function Uz(e){return QR(YR(e))}function Vz(e,t){var r,n,o,a;return JD(this,void 0,void 0,function(){var l,u;return ZC(this,function(d){switch(d.label){case 0:d.trys.push([0,5,6,11]),r=ej(e),d.label=1;case 1:return[4,r.next()];case 2:if(n=d.sent(),!!n.done)return[3,4];if(l=n.value,t.next(l),t.closed)return[2];d.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=d.sent(),o={error:u},[3,11];case 6:return d.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:d.sent(),d.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Bi(e,t,r,n,o){n===void 0&&(n=0),o===void 0&&(o=!1);var a=t.schedule(function(){r(),o?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(a),!o)return a}function JR(e,t){return t===void 0&&(t=0),Jr(function(r,n){r.subscribe(vn(n,function(o){return Bi(n,e,function(){return n.next(o)},t)},function(){return Bi(n,e,function(){return n.complete()},t)},function(o){return Bi(n,e,function(){return n.error(o)},t)}))})}function ZR(e,t){return t===void 0&&(t=0),Jr(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}function Wz(e,t){return eo(e).pipe(ZR(t),JR(t))}function Hz(e,t){return eo(e).pipe(ZR(t),JR(t))}function qz(e,t){return new Fr(function(r){var n=0;return t.schedule(function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())})})}function Gz(e,t){return new Fr(function(r){var n;return Bi(r,t,function(){n=e[GR](),Bi(r,t,function(){var o,a,l;try{o=n.next(),a=o.value,l=o.done}catch(u){r.error(u);return}l?r.complete():r.next(a)},0,!0)}),function(){return Pt(n?.return)&&n.return()}})}function e_(e,t){if(!e)throw new Error("Iterable cannot be null");return new Fr(function(r){Bi(r,t,function(){var n=e[Symbol.asyncIterator]();Bi(r,t,function(){n.next().then(function(o){o.done?r.complete():r.next(o.value)})},0,!0)})})}function Xz(e,t){return e_(YR(e),t)}function Yz(e,t){if(e!=null){if(WR(e))return Wz(e,t);if(UR(e))return qz(e,t);if(VR(e))return Hz(e,t);if(HR(e))return e_(e,t);if(XR(e))return Gz(e,t);if(KR(e))return Xz(e,t)}throw qR(e)}function Xs(e,t){return t?Yz(e,t):eo(e)}function t_(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Xd(e);return Xs(e,r)}var Kz=Gd(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function bS(e,t){return new Promise(function(r,n){var o=!1,a;e.subscribe({next:function(l){a=l,o=!0},error:n,complete:function(){o?r(a):n(new Kz)}})})}function r_(e){return e instanceof Date&&!isNaN(e)}var Qz=Gd(function(e){return function(r){r===void 0&&(r=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=r}});function xS(e,t){var r=r_(e)?{first:e}:typeof e=="number"?{each:e}:e,n=r.first,o=r.each,a=r.with,l=a===void 0?Jz:a,u=r.scheduler,d=u===void 0?FR:u,p=r.meta,h=p===void 0?null:p;if(n==null&&o==null)throw new TypeError("No timeout provided.");return Jr(function(m,y){var w,E,S=null,C=0,R=function(k){E=Bi(y,d,function(){try{w.unsubscribe(),eo(l({meta:h,lastValue:S,seen:C})).subscribe(y)}catch($){y.error($)}},k)};w=m.subscribe(vn(y,function(k){E?.unsubscribe(),C++,y.next(S=k),o>0&&R(o)},void 0,void 0,function(){E?.closed||E?.unsubscribe(),S=null})),!C&&R(n!=null?typeof n=="number"?n:+n-d.now():o)})}function Jz(e){throw new Qz(e)}function Ui(e,t){return Jr(function(r,n){var o=0;r.subscribe(vn(n,function(a){n.next(e.call(t,a,o++))}))})}function Zz(e,t,r,n,o,a,l,u){var d=[],p=0,h=0,m=!1,y=function(){m&&!d.length&&!p&&t.complete()},w=function(S){return p<n?E(S):d.push(S)},E=function(S){p++;var C=!1;eo(r(S,h++)).subscribe(vn(t,function(R){t.next(R)},function(){C=!0},void 0,function(){if(C)try{p--;for(var R=function(){var k=d.shift();l||E(k)};d.length&&p<n;)R();y()}catch(k){t.error(k)}}))};return e.subscribe(vn(t,w,function(){m=!0,y()})),function(){}}function Lv(e,t,r){return r===void 0&&(r=1/0),Pt(t)?Lv(function(n,o){return Ui(function(a,l){return t(n,a,o,l)})(eo(e(n,o)))},r):(typeof t=="number"&&(r=t),Jr(function(n,o){return Zz(n,o,e,r)}))}function n_(e){return e===void 0&&(e=1/0),Lv(Pl,e)}function eF(){return n_(1)}function wS(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return eF()(Xs(e,Xd(e)))}function tF(e,t,r){r===void 0&&(r=Oz);var n=-1;return t!=null&&(BR(t)?r=t:n=t),new Fr(function(o){var a=r_(e)?+e-r.now():e;a<0&&(a=0);var l=0;return r.schedule(function(){o.closed||(o.next(l++),0<=n?this.schedule(void 0,n):o.complete())},a)})}function rF(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Xd(e),n=Dz(e,1/0),o=e;return o.length?o.length===1?eo(o[0]):n_(n)(Xs(o,r)):Nz}function SS(e,t){return Jr(function(r,n){var o=0;r.subscribe(vn(n,function(a){return e.call(t,a,o++)&&n.next(a)}))})}function nF(e,t,r,n,o){return function(a,l){var u=r,d=t,p=0;a.subscribe(vn(l,function(h){var m=p++;d=u?e(d,h,m):(u=!0,h),l.next(d)},o))}}function iF(e,t){return t===void 0&&(t=Pl),e=e??oF,Jr(function(r,n){var o,a=!0;r.subscribe(vn(n,function(l){var u=t(l);(a||!e(o,u))&&(a=!1,o=u,n.next(l))}))})}function oF(e,t){return e===t}function sF(e){return Jr(function(t,r){try{t.subscribe(r)}finally{r.add(e)}})}function aF(e,t){return Jr(nF(e,t,arguments.length>=2,!0))}function lF(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Xd(e);return Jr(function(n,o){(r?wS(e,n,r):wS(e,n)).subscribe(o)})}function ES(e,t,r){var n=Pt(e)||t||r?{next:e,error:t,complete:r}:e;return n?Jr(function(o,a){var l;(l=n.subscribe)===null||l===void 0||l.call(n);var u=!0;o.subscribe(vn(a,function(d){var p;(p=n.next)===null||p===void 0||p.call(n,d),a.next(d)},function(){var d;u=!1,(d=n.complete)===null||d===void 0||d.call(n),a.complete()},function(d){var p;u=!1,(p=n.error)===null||p===void 0||p.call(n,d),a.error(d)},function(){var d,p;u&&((d=n.unsubscribe)===null||d===void 0||d.call(n)),(p=n.finalize)===null||p===void 0||p.call(n)}))}):Pl}function cF(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Pz(e);return Jr(function(n,o){for(var a=e.length,l=new Array(a),u=e.map(function(){return!1}),d=!1,p=function(m){eo(e[m]).subscribe(vn(o,function(y){l[m]=y,!d&&!u[m]&&(u[m]=!0,(d=u.every(Pl))&&(u=null))},xg))},h=0;h<a;h++)p(h);n.subscribe(vn(o,function(m){if(d){var y=Us([m],Bs(l));o.next(r?r.apply(void 0,Us([],Bs(y))):y)}}))})}const uF="BOLOS",dF=[uF,"OLOS","OLOS\0"],Iv=e=>e!=null&&dF.includes(e);var Ys=(e=>(e[e.Connected=0]="Connected",e[e.ReadyWithoutSecureChannel=1]="ReadyWithoutSecureChannel",e[e.ReadyWithSecureChannel=2]="ReadyWithSecureChannel",e))(Ys||{});let Dl=class{_tag="GeneralDmkError";originalError;constructor(t){t instanceof Error?this.originalError=t:t!==void 0&&(this.originalError=new Error(String(t)))}},Ov=class extends Dl{constructor(t){super(t),this.err=t}_tag="TransportNotSupportedError"},fF=class extends Dl{constructor(t){super(t),this.err=t}_tag="SendApduTimeoutError"},pF=class extends Dl{constructor(t){super(t),this.err=t}_tag="SendCommandTimeoutError"},hF=class extends Dl{constructor(t){super(t),this.err=t}_tag="TransportAlreadyExistsError"},mF=class extends Dl{constructor(t){super(t),this.err=t}_tag="NoTransportProvidedError"};var As=null;typeof WebSocket<"u"?As=WebSocket:typeof MozWebSocket<"u"?As=MozWebSocket:typeof self<"u"?As=self.WebSocket||self.MozWebSocket:typeof window<"u"?As=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(As=self.WebSocket||self.MozWebSocket);const gF=As;var vF=(e=>(e.GenuineCheck="GenuineCheck",e.ListInstalledApps="ListInstalledApps",e.UpdateMcu="UpdateMcu",e.UpdateFirmware="UpdateFirmware",e.InstallApp="InstallApp",e.UninstallApp="UninstallApp",e))(vF||{}),yF=(e=>(e.EXCHANGE="exchange",e.BULK="bulk",e.ERROR="error",e.WARNING="warning",e.SUCCESS="success",e))(yF||{}),bF=(e=>(e.SUCCESS="success",e.ERROR="error",e))(bF||{}),xF=(e=>(e.Opened="opened",e.Closed="closed",e.PermissionRequested="permission-requested",e.PermissionGranted="permission-granted",e.PreExchange="pre-exchange",e.Exchange="exchange",e.DeviceId="device-id",e.Progress="progress",e.Warning="warning",e.Error="error",e.Result="result",e))(xF||{}),wF=(e=>(e[e.AppAlreadyInstalled=0]="AppAlreadyInstalled",e[e.DeviceLocked=1]="DeviceLocked",e[e.OutOfMemory=2]="OutOfMemory",e[e.RefusedByUser=3]="RefusedByUser",e[e.Unknown=4]="Unknown",e))(wF||{});let SF=class{constructor(t){this.error=t,this.originalError=t}_tag="WebSocketConnectionError";originalError};function Nv(e,t){return Reflect.getOwnMetadata(t,e)}function EF(e,t,r){Reflect.defineMetadata(t,r,e)}function cl(e,t,r,n){const o=n(Nv(e,t)??r());Reflect.defineMetadata(t,o,e)}var CS,kS,RS;(function(e){e.moduleId="moduleId",e.serviceId="serviceId"})(CS||(CS={}));(function(e){e.id="id",e.moduleId="moduleId",e.serviceId="serviceId"})(kS||(kS={}));(function(e){e.moduleId="moduleId",e.serviceId="serviceId"})(RS||(RS={}));const qu="@inversifyjs/core/classMetadataReflectKey";function Gu(){return{constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}const CF="@inversifyjs/core/pendingClassMetadataCountReflectKey",lm=Symbol.for("@inversifyjs/core/InversifyCoreError");let Vi=class i_ extends Error{[lm];kind;constructor(t,r,n){super(r,n),this[lm]=!0,this.kind=t}static is(t){return typeof t=="object"&&t!==null&&t[lm]===!0}static isErrorOfKind(t,r){return i_.is(t)&&t.kind===r}};var Dn,bd,Cl;function kF(){return 0}function RF(e){return t=>{t!==void 0&&t.kind===bd.unknown&&cl(e,CF,kF,(r=>r-1))}}function _F(e,t){return(...r)=>n=>{if(n===void 0)return e(...r);if(n.kind===Cl.unmanaged)throw new Vi(Dn.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return t(n,...r)}}function $F(e){if(e.kind!==bd.unknown&&e.isFromTypescriptParamType!==!0)throw new Vi(Dn.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found")}(function(e){e[e.injectionDecoratorConflict=0]="injectionDecoratorConflict",e[e.missingInjectionDecorator=1]="missingInjectionDecorator",e[e.planning=2]="planning",e[e.resolution=3]="resolution",e[e.unknown=4]="unknown"})(Dn||(Dn={})),(function(e){e[e.unknown=32]="unknown"})(bd||(bd={})),(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection",e[e.unmanaged=2]="unmanaged"})(Cl||(Cl={}));const AF=_F((function(e,t){return{kind:e,name:void 0,optional:!1,tags:new Map,value:t}}),(function(e,t,r){return $F(e),{...e,kind:t,value:r}}));function _S(e,t){return r=>{const n=r.properties.get(t);return r.properties.set(t,e(n)),r}}var Mi;function TF(e,t,r,n){if(Vi.isErrorOfKind(n,Dn.injectionDecoratorConflict)){const o=(function(a,l,u){if(u===void 0){if(l===void 0)throw new Vi(Dn.unknown,"Unexpected undefined property and index values");return{kind:Mi.property,property:l,targetClass:a.constructor}}return typeof u=="number"?{index:u,kind:Mi.parameter,targetClass:a}:{kind:Mi.method,method:l,targetClass:a}})(e,t,r);throw new Vi(Dn.injectionDecoratorConflict,`Unexpected injection error.
30
30
 
@@ -36,7 +36,7 @@ Details
36
36
 
37
37
  ${(function(a){switch(a.kind){case Mi.method:return`[class: "${a.targetClass.name}", method: "${a.method.toString()}"]`;case Mi.parameter:return`[class: "${a.targetClass.name}", index: "${a.index.toString()}"]`;case Mi.property:return`[class: "${a.targetClass.name}", property: "${a.property.toString()}"]`}})(o)}`,{cause:n})}throw n}function LF(e,t){return(r,n,o)=>{try{o===void 0?(function(a,l){const u=cm(a,l);return(d,p)=>{cl(d.constructor,qu,Gu,_S(u(d),p))}})(e,t)(r,n):typeof o=="number"?(function(a,l){const u=cm(a,l);return(d,p,h)=>{if(!(function(m,y){return typeof m=="function"&&y===void 0})(d,p))throw new Vi(Dn.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
38
38
  Found @inject decorator at method "${p?.toString()??""}" at class "${d.constructor.name}"`);cl(d,qu,Gu,(function(m,y){return w=>{const E=w.constructorArguments[y];return w.constructorArguments[y]=m(E),w}})(u(d),h))}})(e,t)(r,n,o):(function(a,l){const u=cm(a,l);return(d,p,h)=>{if(!(function(m){return m.set!==void 0})(h))throw new Vi(Dn.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
39
- Found @inject decorator at method "${p.toString()}" at class "${d.constructor.name}"`);cl(d.constructor,qu,Gu,_S(u(d),p))}})(e,t)(r,n,o)}catch(a){TF(r,n,o,a)}}}function cm(e,t){return r=>{const n=t(r);return o=>(n(o),e(o))}}function Oe(e){return LF(AF(Cl.singleInjection,e),RF)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(Mi||(Mi={}));const $S="@inversifyjs/core/classIsInjectableFlagReflectKey",IF=[Array,BigInt,Boolean,Function,Number,Object,String];function OF(e){const t=Nv(e,"design:paramtypes");t!==void 0&&cl(e,qu,Gu,(function(r){return n=>(r.forEach(((o,a)=>{var l;n.constructorArguments[a]!==void 0||(l=o,IF.includes(l))||(n.constructorArguments[a]=(function(u){return{isFromTypescriptParamType:!0,kind:Cl.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(o))})),n)})(t))}function Qe(e){return t=>{(function(r){if(Nv(r,$S)!==void 0)throw new Vi(Dn.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);EF(r,$S,!0)})(t),OF(t)}}var AS;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(AS||(AS={}));var TS;(function(e){e[e.singleMandatory=0]="singleMandatory",e[e.singleOptional=1]="singleOptional",e[e.multipleMandatory=2]="multipleMandatory",e[e.multipleOptional=3]="multipleOptional",e[e.length=4]="length"})(TS||(TS={}));let NF=class{constructor(t,r,n,o,a){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=o,this.notifyUuid=a}},Cs=class{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(t){this.id=t.id,this.productName=t.productName,this.usbProductId=t.usbProductId,this.bootloaderUsbProductId=t.bootloaderUsbProductId,this.usbOnly=t.usbOnly,this.memorySize=t.memorySize,this.getBlockSize=t.getBlockSize,this.masks=t.masks,this.bluetoothSpec=t.bluetoothSpec}};var PF=Object.defineProperty,DF=(e,t,r)=>t in e?PF(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,jF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},MF=(e,t,r)=>DF(e,t+"",r);let Oo=class{getAllDeviceModels(){return Object.values(Oo.deviceModelByIds)}getDeviceModel(t){return Oo.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,o])=>r[n]===o))}getBluetoothServicesInfos(){return Object.values(Oo.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((o,a)=>({...o,[a.serviceUuid]:new NF(r,a.serviceUuid,a.writeUuid,a.writeCmdUuid,a.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values(Oo.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};MF(Oo,"deviceModelByIds",{[wt.NANO_S]:new Cs({id:wt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>pS.lt(pS.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[wt.NANO_SP]:new Cs({id:wt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[wt.NANO_X]:new Cs({id:wt.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2*1024*1024,getBlockSize:()=>4*1024,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}]}),[wt.STAX]:new Cs({id:wt.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>512,masks:[857735168],bluetoothSpec:[{serviceUuid:"13d63400-2c97-6004-0000-4c6564676572",notifyUuid:"13d63400-2c97-6004-0001-4c6564676572",writeUuid:"13d63400-2c97-6004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-6004-0003-4c6564676572"}]}),[wt.FLEX]:new Cs({id:wt.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>512,masks:[858783744],bluetoothSpec:[{serviceUuid:"13d63400-2c97-3004-0000-4c6564676572",notifyUuid:"13d63400-2c97-3004-0001-4c6564676572",writeUuid:"13d63400-2c97-3004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-3004-0003-4c6564676572"}]}),[wt.APEX]:new Cs({id:wt.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>512,masks:[859832320],bluetoothSpec:[{serviceUuid:"13d63400-2c97-8004-0000-4c6564676572",notifyUuid:"13d63400-2c97-8004-0001-4c6564676572",writeUuid:"13d63400-2c97-8004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-8004-0003-4c6564676572"},{serviceUuid:"13d63400-2c97-9004-0000-4c6564676572",notifyUuid:"13d63400-2c97-9004-0001-4c6564676572",writeUuid:"13d63400-2c97-9004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-9004-0003-4c6564676572"}]})}),Oo=jF([Qe()],Oo);let zF=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const FF=5,Ao=1,Sg=2,Ls=2,Eg=2,ir=[];for(let e=0;e<256;++e)ir.push((e+256).toString(16).slice(1));function BF(e,t=0){return(ir[e[t+0]]+ir[e[t+1]]+ir[e[t+2]]+ir[e[t+3]]+"-"+ir[e[t+4]]+ir[e[t+5]]+"-"+ir[e[t+6]]+ir[e[t+7]]+"-"+ir[e[t+8]]+ir[e[t+9]]+"-"+ir[e[t+10]]+ir[e[t+11]]+ir[e[t+12]]+ir[e[t+13]]+ir[e[t+14]]+ir[e[t+15]]).toLowerCase()}let um;const UF=new Uint8Array(16);function VF(){if(!um){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");um=crypto.getRandomValues.bind(crypto)}return um(UF)}const WF=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),LS={randomUUID:WF};function Yd(e,t,r){if(LS.randomUUID&&!e)return LS.randomUUID();e=e||{};const n=e.random||(e.rng||VF)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,BF(n)}const No={getLastBytesFrom(e,t){return e.slice(-t)},getFirstBytesFrom(e,t){return e.slice(0,t)},bytesToNumber(e){return e.reduce((t,r,n)=>t+r*Math.pow(256,e.length-1-n),0)},numberToByteArray(e,t){return new Uint8Array(t).map((r,n)=>e>>8*(t-1-n)&255)}},IS=2,dm=800;let OS=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},HF=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},NS=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},PS=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},o_=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:si(this._data)},null,2)}getRawData(){const t=this._header.getRawData(),r=new Uint8Array(t.length+this._data.length);return r.set(t,0),r.set(this._data,t.length),r}getHeader(){return this._header}getData(){return this._data}},s_=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:o,length:a,channel:l}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=o,this._length=a,this._channel=l}getDataLength(){return this._dataLength.map(t=>No.bytesToNumber(t))}setDataSize(t){return this._dataLength=t,this}getLength(){return this._length}toString(){return JSON.stringify({uuid:this._uuid.toString(),dataSize:this._dataLength.extract()?.toString(),index:this._index.toString(),headTag:this._headTag.toString(),length:this._length.toString(),channel:this._channel.extract()?.toString()})}getRawData(){return new Uint8Array([...this._channel.caseOf({Just:t=>[...t],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:t=>[...t],Nothing:()=>[]})])}};const Dt={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var qF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},GF=(e,t)=>(r,n)=>t(r,n,e);let DS=class{_channel;_logger;_pendingFrames;constructor({channel:t=Ar.zero()},r){this._channel=t,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(t){return this.getFrameFromBytes(t).map(r=>{if(this._pendingFrames.push(r),!this._pendingFrames[0])return ft;const n=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(n)})}getCompleteFrame(t){return t.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),ft;const n=No.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),o=No.getFirstBytesFrom(n,n.length-IS),a=No.getLastBytesFrom(n,IS);return this._pendingFrames=[],or(new zF({data:o,statusCode:a}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>Sg,Nothing:()=>0}),n=t.slice(r,r+Ao),o=t.slice(r+Ao,r+Ao+Ls),a=o.reduce((y,w)=>y+w,0)===0;if(!a&&this._pendingFrames.length===0)return yt(new NS);const l=r+Ao+Ls,u=a?Eg:0;if(t.length<r+Ao+Ls+u)return yt(new NS("Unable to parse header from apdu"));const d=a?or(t.slice(l,l+u)):ft,p=l+u,h=t.slice(p),m=new o_({header:new s_({uuid:Yd(),channel:this._channel,dataSize:d,headTag:n,index:o,length:r+Ao+Ls+u}),data:h});return Tt(m)}isComplete(t){return this._pendingFrames.reduce((r,n)=>r+n.getData().length,0)>=t}concatFrames(t){return t.reduce((r,n)=>Uint8Array.from([...r,...n.getData()]),new Uint8Array(0))}};DS=qF([Qe(),GF(1,Oe(Dt.LoggerPublisherServiceFactory))],DS);var XF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},YF=(e,t)=>(r,n)=>t(r,n,e);let jS=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=Ar.zero(),padding:n=!1},o){this._frameSize=t,this._channel=r,this._padding=n,this._logger=o("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,o=this.getFrameAtIndex(t,n);for(;o.isRight();)r.push(o.extract()),n+=1,o=this.getFrameAtIndex(t,n).mapLeft(a=>(a instanceof OS||this._logger.error("Error while parsing frame",{data:{error:a}}),a));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),o=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(o>=t.length)return yt(new OS);if(n.getLength()>this._frameSize)return yt(new HF);const a=this._frameSize-n.getLength(),l=t.slice(o,o+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(a).fill(0):new Uint8Array(l.length<a?l.length:a);u.set(l,0);const d=new o_({header:n,data:u});return Tt(d)}getFrameHeaderFrom(t,r){const n=new s_({uuid:Yd(),channel:this._channel.map(o=>No.getLastBytesFrom(o,Sg)),headTag:new Uint8Array([FF]),index:No.numberToByteArray(t,Ls),length:this.getFrameHeaderSizeFromIndex(t),dataSize:Ar.zero()});return t===0&&n.setDataSize(Ar.of(No.numberToByteArray(r,Eg))),n}getHeaderSizeSumFrom(t){let r=this.getFrameHeaderSizeFromIndex(0),n=1;for(;n<t;)r+=this.getFrameHeaderSizeFromIndex(n),n+=1;return r}getFrameHeaderSizeFromIndex(t){return this._channel.caseOf({Just:()=>Sg,Nothing:()=>0})+Ls+Ao+(t===0?Eg:0)}};jS=XF([Qe(),YF(1,Oe(Dt.LoggerPublisherServiceFactory))],jS);const Cg={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},dr={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},MS={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},jl={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Kd={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")},Gi={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var KF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},zS=(e,t)=>(r,n)=>t(r,n,e);let FS=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendCommandUseCase")}async execute({sessionId:t,command:r,abortTimeout:n}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async o=>await o.sendCommand(r,n),Left:o=>{throw this._logger.error("Error getting session",{data:{error:o}}),o}})}};FS=KF([Qe(),zS(0,Oe(dr.DeviceSessionService)),zS(1,Oe(Dt.LoggerPublisherServiceFactory))],FS);var QF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let BS=class{execute=vi.fn(()=>"stub")};BS=QF([Qe()],BS);var JF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},US=(e,t)=>(r,n)=>t(r,n,e);let VS=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ExecuteDeviceActionUseCase")}execute({sessionId:t,deviceAction:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:n=>n.executeDeviceAction(r),Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n}})}};VS=JF([Qe(),US(0,Oe(dr.DeviceSessionService)),US(1,Oe(Dt.LoggerPublisherServiceFactory))],VS);function ZF(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let WS=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},eB=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},a_=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},tB=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const rB="@ledgerhq/device-management-kit",nB="0.0.0-develop-20261109000905",HS={name:rB,version:nB};var iB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};const oB={name:HS.name,version:HS.version},sB=()=>JSON.stringify(oB);let qS=class{getConfig(){return Tr.encase(()=>sB()).mapLeft(t=>new tB(t)).chain(t=>Tr.encase(()=>{const r=JSON.parse(t);if(ZF(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new a_(r)))}};qS=iB([Qe()],qS);var aB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let GS=class{getConfig(){return Tr.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};GS=aB([Qe()],GS);var lB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let XS=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return yt(new WS(t.extract()));if(!t.extract().ok)return yt(new WS(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?yt(new a_):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?yt(new eB):Tr.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(Tr.of({ok:!0,json:async()=>new Promise(r=>{r(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};XS=lB([Qe()],XS);var cB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let YS=class{async getConfig(){return new Promise(t=>t(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};YS=cB([Qe()],YS);var uB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},fm=(e,t)=>(r,n)=>t(r,n,e);let KS=class{_local;_remote;_logger;constructor(t,r,n){this._local=t,this._remote=r,this._logger=n("config")}async getDmkConfig(){const t=this._local.getConfig().ifLeft(r=>{this._logger.error("Local config not available",{data:{error:r}})});if(t.isRight()){const r=t.extract();return this._logger.info("Local config available",{data:{config:r}}),r}return this._remote.getConfig().then(r=>r.mapLeft(n=>(this._logger.error("Local config available",{data:{error:n}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};KS=uB([Qe(),fm(0,Oe(Cg.LocalConfigDataSource)),fm(1,Oe(Cg.RemoteConfigDataSource)),fm(2,Oe(Dt.LoggerPublisherServiceFactory))],KS);var dB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},fB=(e,t)=>(r,n)=>t(r,n,e);let QS=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};QS=dB([Qe(),fB(0,Oe(Cg.ConfigService))],QS);const pB={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var hB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},JS=(e,t)=>(r,n)=>t(r,n,e);let ZS=class{constructor(t,r){this._sessionService=t,this._logger=r("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:t,blockerId:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting device session",{data:{error:n}}),n},Right:n=>n.disableRefresher(r)})}};ZS=hB([Qe(),JS(0,Oe(dr.DeviceSessionService)),JS(1,Oe(Dt.LoggerPublisherServiceFactory))],ZS);var mB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},gB=(e,t)=>(r,n)=>t(r,n,e);let e1=class{_sessions;_sessionsSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new zR,this._logger=t("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(t){return this._sessions.find(r=>r.id===t.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:t}}),this):(this._sessions.push(t),this._sessionsSubject.next(t),this._logger.info("DeviceSession added",{data:{sessionId:t.id}}),this)}removeDeviceSession(t){const r=this._sessions.find(n=>n.id===t);return r?(r.close(),this._sessions=this._sessions.filter(n=>n.id!==t),this._logger.info("DeviceSession removed",{data:{sessionId:t}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:t}}),this)}getDeviceSessionById(t){return Ar.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new PS)}getDeviceSessionsByDeviceId(t){return Ar.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new PS)}getDeviceSessions(){return this._sessions}};e1=mB([Qe(),gB(0,Oe(Dt.LoggerPublisherServiceFactory))],e1);var vB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},t1=(e,t)=>(r,n)=>t(r,n,e);let r1=class{_sessionService;_transportService;constructor(t,r){this._sessionService=t,this._transportService=r}execute(){const t=this._sessionService.getDeviceSessions();for(const r of t)this._transportService.closeConnection(r.connectedDevice),this._sessionService.removeDeviceSession(r.id)}};r1=vB([Qe(),t1(0,Oe(dr.DeviceSessionService)),t1(1,Oe(Gi.TransportService))],r1);var yB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},n1=(e,t)=>(r,n)=>t(r,n,e);let i1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetDeviceSessionStateUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:r=>{throw this._logger.error("Error getting session device",{data:{error:r}}),r},Right:r=>r.state})}};i1=yB([Qe(),n1(0,Oe(dr.DeviceSessionService)),n1(1,Oe(Dt.LoggerPublisherServiceFactory))],i1);var bB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},o1=(e,t)=>(r,n)=>t(r,n,e);let s1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("UnsafeBypassIntentQueueUseCase")}execute({sessionId:t,bypass:r}){this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n},Right:n=>{this._logger.warn(`UNSAFE: ${r?"Enabling":"Disabling"} intent queue bypass for session ${t}`),n._unsafeBypassIntentQueue(r)}})}};s1=bB([Qe(),o1(0,Oe(dr.DeviceSessionService)),o1(1,Oe(Dt.LoggerPublisherServiceFactory))],s1);function xB(e){return`[will send APDU] ~...> ${si(e,!1)}`}function wB(e){return`[exchange] <= ${si(e.data,!1)}${si(e.statusCode,!1)}`}const SB="apdu-exchange";function EB(e,t,r){const n=si(t,!1),o=`${si(r.data,!1)}${si(r.statusCode,!1)}`;return{message:wB(r),data:{type:SB,sessionId:e,apdu:n,response:o}}}const kg=1e3,pm=1e3,CB={isRefresherDisabled:!1,pollingInterval:1e3};var Nt=(e=>(e.NEW_STATE="NEW_STATE",e.REFRESH_NEEDED="REFRESH_NEEDED",e.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",e.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",e.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",e.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",e.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",e))(Nt||{});let kB=class{_eventEmitter=new oa;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},RB=class{constructor(t,r){this.loggerModuleFactory=t,this.sessionEventDispatcher=r,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(t){this._logger.debug("Enqueueing intent",{data:{type:t.type}});const r=new oa,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const o=()=>{this._logger.debug("Cancelling intent",{data:{type:t.type}}),n.isCancelled=!0,this._queue[0]===n&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,r.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==n)&&r.complete()};return this._isProcessing||this._processQueue(),{observable:r.asObservable().pipe(sF(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:o}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:Nt.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;const t=this._queue[0];if(t.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:t.intent.type}}),t.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:t.intent.type}}),this._currentSubscription=t.intent.execute().subscribe({next:r=>{t.isCancelled||t.subject.next(r)},error:r=>{t.isCancelled||t.subject.error(r),this._onIntentComplete()},complete:()=>{t.isCancelled||t.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}},_B=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${Yd()}`;this.addRefresherBlocker(r),this._logger.debug("Refresher disabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}});let n=!1;return()=>{n||(n=!0,this.removeRefresherBlocker(r),this._logger.debug("Refresher re-enabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.add(t),r===0&&this._refresher.stop()}removeRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.delete(t),r>0&&this._refresherBlockers.size===0&&this._refresher.start()}},$B=class{constructor(t,r,n,o){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=o,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async a=>await this.mapEventAction(a))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(t){return this._logger.error("Error while pinging device",{data:{error:t}}),null}}mapEventAction=async t=>t.eventName===Nt.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===wt.NANO_S){const r=async()=>{const a=await this._sendCommandFunction(new ww,dm);return this._sendCommandFunction(new cz,dm),a},n=new Promise(a=>{setTimeout(()=>a(null),kg*2+100)}),o=await Promise.race([r(),n]);return o?this._sessionEventDispatcher.dispatch({eventName:Nt.COMMAND_SUCCEEDED,eventData:o}):this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_LOCKED}),o}else{const r=await this._sendCommandFunction(new ww,dm);return this._sessionEventDispatcher.dispatch({eventName:Nt.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},AB=class{constructor(t,r,n,o){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=o.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;const t=this.getValidPollingInterval(this._refresherOptions,this._logger),r=this._sessionEventDispatcher.listen().pipe(SS(n=>n.eventName===Nt.DEVICE_STATE_UPDATE_BUSY||n.eventName===Nt.NEW_STATE),Ui(n=>n.eventName===Nt.DEVICE_STATE_UPDATE_BUSY),lF(!1),iF());this._refresherSubscription=tF(0,t).pipe(cF(r),ES(([n,o])=>{o&&this._logger.debug("Refresh skipped: device is busy")}),SS(([n,o])=>!o),ES(()=>this._sessionEventDispatcher.dispatch({eventName:Nt.REFRESH_NEEDED}))).subscribe(),this._logger.info("Refresher started.")}stopRefresher(){this._refresherSubscription&&(this._refresherSubscription.unsubscribe(),this._refresherSubscription=void 0,this._logger.info("Refresher stopped."))}restartRefresher(){this.stopRefresher(),this.startRefresher(),this._logger.info("Refresher restarted.")}getValidPollingInterval=(t,r)=>{const{pollingInterval:n}=t;if(this._connectedDeviceID===wt.NANO_S){const o=kg*2;return n!==void 0&&n<o?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${o}`),o):n??o}else return n!==void 0&&n<pm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${pm}`),pm):n??kg}},TB=class{constructor(t,r,n,o,a){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=o,this.setDeviceSessionState=a,this._subscription=this._sessionEventDispatcher.listen().subscribe(l=>this.mapEventAction(l)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=Ln.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:o,currentApp:a}=r,l=this._deviceState.getValue();l.sessionStateType===Ys.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...l,sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case Nt.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case Nt.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Nt.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=Ln.LOCKED;return;case Nt.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=Ln.CONNECTED;return;case Nt.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=Ln.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case Nt.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Nt.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return A5(t)?{sessionStateType:Ys.ReadyWithoutSecureChannel,deviceStatus:Ln.CONNECTED,currentApp:{name:t.data.name,version:t.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:t}}),null)}unsubscribe(){this._subscription.unsubscribe()}};class LB{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new kB;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=Yd()},n,o,a,l,u=d=>new RB(n,d)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=o,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=a,this._refresherOptions={...CB,...l},this._deviceState=new Az({sessionStateType:Ys.Connected,deviceStatus:Ln.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new $B(n,t,this._sessionEventDispatcher,(d,p)=>this.sendCommand(d,p)),this._deviceSessionRefresher=new AB(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new TB(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,d=>this.setDeviceSessionState(d)),this._refresherService=new _B(n,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(t){throw this._logger.error("Error while initialising session",{data:{error:t}}),t}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(t){this._deviceState.next(t)}sendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(t,r):this._internalSendApdu(t,r)}_internalSendApdu(t,r){const n=r.abortTimeout,o=Date.now(),{observable:a,cancel:l}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Xs((async()=>{const d=Date.now()-o;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-d:void 0})})())}),u=n?a.pipe(xS({each:n,with:()=>{throw l(),new fF}})):a;return bS(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(xB(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:o,data:a}=EB(this._id,t,n);this._logger.debug(o,{data:a}),gv.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(t,r){return this._logger.debug(`[sendCommand] ${t.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(t,r):this._internalSendCommand(t,r)}_internalSendCommand(t,r){const n=Date.now(),{observable:o,cancel:a}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Xs((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),l=r?o.pipe(xS({each:r,with:()=>{throw a(),new pF}})):o;return bS(l)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:o=>{throw this._logger.error("[sendCommand] error",{data:{err:o}}),o},Right:o=>{const a=t.parseResponse(o,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:a}}),a}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:o}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:a,cancel:l}=this._unsafeInternalExecuteDeviceAction(t);return r=l,a}});return{observable:n,cancel:()=>{r?.(),o()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async o=>this._unsafeInternalSendApdu(o),sendCommand:async o=>this._unsafeInternalSendCommand(o),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:o=>(this.setDeviceSessionState(o),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(Ln.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(t){return this._refresherService.disableRefresher(t)}_unsafeBypassIntentQueue(t){this._bypassIntentQueue=t}_updateDeviceStatus(t){const r=this._deviceState.getValue();this._deviceState.next({...r,deviceStatus:t})}}var IB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},Za=(e,t)=>(r,n)=>t(r,n,e);let a1=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,o,a){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=o,this._secureChannel=a}handleDeviceDisconnect(t){this._sessionService.getDeviceSessionsByDeviceId(t).ifRight(r=>{r.forEach(n=>{this._sessionService.removeDeviceSession(n.id),this._logger.info("Session removed",{data:{deviceId:t,sessionId:n.id}})})})}async execute({device:t,sessionRefresherOptions:r}){const n=this._transportService.getTransport(t.transport),o="sessionId"in t?t.sessionId:void 0;return He.liftEither(n.toEither(new Ov(new Error("Unknown transport")))).chain(async a=>a.connect({deviceId:t.id,onDisconnect:l=>this.handleDeviceDisconnect(l)})).ifLeft(a=>{this._logger.error("Error connecting to device")}).map(async a=>{const l=new LB({connectedDevice:a,id:o},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(l),await l.initialiseSession(),l.id}).caseOf({Left:a=>{throw a},Right:a=>a})}};a1=IB([Qe(),Za(0,Oe(Gi.TransportService)),Za(1,Oe(dr.DeviceSessionService)),Za(2,Oe(Dt.LoggerPublisherServiceFactory)),Za(3,Oe(jl.ManagerApiService)),Za(4,Oe(Kd.SecureChannelService))],a1);var OB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},hm=(e,t)=>(r,n)=>t(r,n,e);let l1=class{_transportService;_sessionService;_logger;constructor(t,r,n){this._sessionService=r,this._transportService=t,this._logger=n("DisconnectUseCase")}async execute({sessionId:t}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map(r=>r.id)}}),He(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(l=>{this._logger.error("Device session not found",{data:{sessionId:t,error:l}})})),o=n.connectedDevice.transport,a=await r(this._transportService.getTransport(o).toEither(new Ov(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await a.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};l1=OB([Qe(),hm(0,Oe(Gi.TransportService)),hm(1,Oe(dr.DeviceSessionService)),hm(2,Oe(Dt.LoggerPublisherServiceFactory))],l1);let Pv=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:o,transport:a,name:l},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=l??n,this.type=o,this.transport=a}};var NB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},c1=(e,t)=>(r,n)=>t(r,n,e);let u1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetConnectedDeviceUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:r=>new Pv({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};u1=NB([Qe(),c1(0,Oe(dr.DeviceSessionService)),c1(1,Oe(Dt.LoggerPublisherServiceFactory))],u1);var PB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},d1=(e,t)=>(r,n)=>t(r,n,e);let f1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map(t=>new Pv({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};f1=PB([Qe(),d1(0,Oe(dr.DeviceSessionService)),d1(1,Oe(Dt.LoggerPublisherServiceFactory))],f1);var DB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},p1=(e,t)=>(r,n)=>t(r,n,e);let h1=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new $R({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),Xs([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,o)=>n.listenToAvailableDevices().pipe(Ui(a=>({index:o,arr:a}))));return rF(...r).pipe(aF((n,{index:o,arr:a})=>(n[o]=a,n),{}),Ui(n=>Object.values(n).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${t}`),this._transportService.getTransport(t).caseOf({Nothing:()=>(this._logger.error(`Transport ${t} not found`),t_([])),Just:r=>r.listenToAvailableDevices().pipe(Ui(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};h1=DB([Qe(),p1(0,Oe(Gi.TransportService)),p1(1,Oe(Dt.LoggerPublisherServiceFactory))],h1);var jB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},m1=(e,t)=>(r,n)=>t(r,n,e);let g1=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(Ui(t=>new Pv({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};g1=jB([Qe(),m1(0,Oe(dr.DeviceSessionService)),m1(1,Oe(Dt.LoggerPublisherServiceFactory))],g1);var MB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},mm=(e,t)=>(r,n)=>t(r,n,e);let v1=class{constructor(t,r,n){this.connectUseCase=t,this.disconnectUseCase=r,this._logger=n("ReconnectUseCase")}_logger;async execute({device:t,sessionRefresherOptions:r}){return this._logger.debug("Reconnecting device session",{data:{deviceId:t.id,transport:t.transport}}),await this.disconnectUseCase.execute({sessionId:t.sessionId}),this.connectUseCase.execute({device:t,sessionRefresherOptions:r})}};v1=MB([Qe(),mm(0,Oe(MS.ConnectUseCase)),mm(1,Oe(MS.DisconnectUseCase)),mm(2,Oe(Dt.LoggerPublisherServiceFactory))],v1);var zB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},FB=(e,t)=>(r,n)=>t(r,n,e);let y1=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new $R({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(!t){const r=this._transportService.getAllTransports();return t_(...r).pipe(Lv(n=>n.startDiscovering().pipe(Ui(o=>this.mapDiscoveredDevice(o)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(Ui(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new Ov(new Error("Unknown transport"))}})}};y1=zB([Qe(),FB(0,Oe(Gi.TransportService))],y1);var BB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},b1=(e,t)=>(r,n)=>t(r,n,e);let x1=class{constructor(t,r){this.transportService=t,this._logger=r("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(const t of this.transportService.getAllTransports())await t.stopDiscovering()}};x1=BB([Qe(),b1(0,Oe(Gi.TransportService)),b1(1,Oe(Dt.LoggerPublisherServiceFactory))],x1);var nl=(e=>(e[e.Fatal=0]="Fatal",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug",e))(nl||{});let UB=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function Rg(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>Rg(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=Rg(o,t);return r}return e}function VB(e){const t=new WeakSet;t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=Rg(o,t);return r}var WB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let w1=class{subscribers;tag;tagFormatter;constructor(t,r,n=new UB){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const o=n?.data?VB(n.data):void 0,a=n?.tag??this.tag,l=this.tagFormatter.format(a);this.subscribers.forEach(u=>{const d={timestamp:n?.timestamp??Date.now(),tag:l,data:o};u.log(t,r,d)})}info(t,r){this._log(nl.Info,t,r)}warn(t,r){this._log(nl.Warning,t,r)}debug(t,r){this._log(nl.Debug,t,r)}error(t,r){this._log(nl.Error,t,r)}};w1=WB([Qe()],w1);let kl=class extends Error{status;statusText;responseBody;isTimeout;cause;constructor(t){super(t.message),this.name="DmkNetworkClientError",this.status=t.status,this.statusText=t.statusText,this.responseBody=t.responseBody,this.isTimeout=t.isTimeout??!1,this.cause=t.cause}};const HB="application/json";function qB(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function GB(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function To(e){const{url:t,params:r,baseUrl:n}=e,o=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?qB(n,t):t,a=r?GB(r):"";if(a.length===0)return o;const l=o.includes("?")?"&":"?";return`${o}${l}${a}`}function XB(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function YB(e){return!!(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||typeof URLSearchParams<"u"&&e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream)}function KB(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:o}=e,a={...n,...o};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:a}:YB(r)?{body:r,headers:a}:(XB(a,"content-type")||(a["Content-Type"]=HB),{body:JSON.stringify(r),headers:a})}function QB(e){const{timeoutMs:t}=e;if(!t||t<=0)return{signal:void 0,cleanup:()=>{}};const r=new AbortController,n=setTimeout(()=>{r.abort()},t);return{signal:r.signal,cleanup:()=>clearTimeout(n)}}async function JB(e,t){switch(t){case"void":return;case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();default:{const r=await e.text();if(r.length===0)return;try{return JSON.parse(r)}catch(n){throw new kl({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function ZB(e){try{return await e.text()}catch{return}}function e8(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const o=t.name==="TimeoutError"||n;return new kl({message:o?"Request timed out":"Request aborted",isTimeout:o,cause:t})}return new kl({message:t instanceof Error?t.message:"Network request failed",cause:t})}let l_=class{baseUrl;defaultHeaders;fetchImpl;constructor(t={}){this.baseUrl=t.baseUrl,this.defaultHeaders=t.headers??{},this.fetchImpl=t.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(t,r){return this.request({...r,method:"GET",url:t}).then(n=>n.data)}post(t,r,n){return this.request({...n,method:"POST",url:t,body:r}).then(o=>o.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(o=>o.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(o=>o.data)}delete(t,r){return this.request({...r,method:"DELETE",url:t}).then(n=>n.data)}head(t,r){return this.request({...r,method:"HEAD",url:t,responseType:"void"}).then(()=>{})}async request(t){const r=To({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:o}=KB({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:a,cleanup:l}=QB({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,d=t.responseType??"json";try{let p;try{p=await this.getFetch()(r,{method:t.method,headers:o,body:n,signal:a})}catch(h){throw e8({cause:h,timeoutMs:t.timeoutMs})}if(!p.ok&&u){const h=await ZB(p);throw new kl({message:`HTTP error ${p.status} ${p.statusText}`.trim(),status:p.status,statusText:p.statusText,responseBody:h})}return{data:await JB(p,d),status:p.status,statusText:p.statusText,headers:p.headers,ok:p.ok}}finally{l()}}};var il=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(il||{});const t8=1,r8="0";let xd=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var ol=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(ol||{}),n8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},S1=(e,t)=>(r,n)=>t(r,n,e);const Qn=e=>e instanceof kl&&e.cause!==void 0?new xd(e.cause):new xd(e);let E1=class{http;_provider=t8;_firmwareDistributionSalt=r8;_logger;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n},o){this.http=new l_({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n,this._logger=o("HttpManagerApiDataSource")}setProvider(t){this._provider===t||t<1||(this._provider=t)}getProvider(){return this._provider}setFirmwareDistributionSalt(t){this._firmwareDistributionSalt===t||t.trim()===""||(this._firmwareDistributionSalt=t)}getFirmwareDistributionSalt(){return this._firmwareDistributionSalt}getAppList(t){const{targetId:r,firmwareVersionName:n}=t;return He(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(o=>this.mapApplicationDtoToApplication(o)).mapLeft(Qn)}getMcuList(){return He(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(Qn)}getDeviceVersion(t){const{targetId:r}=t;return He(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(Qn)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapFinalFirmwareDto(o)).mapLeft(Qn)}getFirmwareVersionById(t){return He(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(Qn)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapOsuFirmwareDto(o)).mapLeft(Qn)}getLatestFirmwareVersion(t){const{currentFinalFirmwareId:r,deviceId:n}=t;return He(()=>{const o=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:o}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:r,device_version:n,provider:this._provider,salt:o}})}).chain(o=>this.mapLatestFirmwareDto(o)).mapLeft(Qn)}getAppsByHash(t){const{hashes:r}=t;return He(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(Qn)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return He(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(o=>this.mapLanguagesDtoToLanguages(o)).mapLeft(Qn)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case ol.currency:return il.currency;case ol.plugin:return il.plugin;case ol.tool:return il.tool;case ol.swap:return il.swap}}mapApplicationDtoToApplication(t){return He(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return He(()=>Promise.resolve(t.map(r=>r===null?null:this.mapApplicationDto(r))))}mapApplicationDto(t){if(typeof t!="object"||typeof t.versionId!="number"||typeof t.versionName!="string"||t.versionDisplayName!==null&&typeof t.versionDisplayName!="string"||typeof t.version!="string"||t.currencyId!==null&&typeof t.currencyId!="string"||t.description!==null&&typeof t.description!="string"||t.applicationType!==null&&typeof t.applicationType!="string"||typeof t.dateModified!="string"||t.icon!==null&&typeof t.icon!="string"||t.authorName!==null&&typeof t.authorName!="string"||t.supportURL!==null&&typeof t.supportURL!="string"||t.contactURL!==null&&typeof t.contactURL!="string"||t.sourceURL!==null&&typeof t.sourceURL!="string"||t.compatibleWallets!==null&&typeof t.compatibleWallets!="string"||typeof t.hash!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmwareKey!="string"||typeof t.delete!="string"||typeof t.deleteKey!="string"||t.bytes!==null&&typeof t.bytes!="number"||t.warning!==null&&typeof t.warning!="string"||typeof t.isDevTools!="boolean"||t.category!==null&&typeof t.category!="number"||t.parent!==null&&typeof t.parent!="number"||t.parentName!==null&&typeof t.parentName!="string")throw new Error(`Incomplete application: ${JSON.stringify(t)}`);const{applicationType:r,hash:n,perso:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,...p}=t;return{...p,hash:n,perso:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return He(()=>Promise.resolve(t.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string"||typeof r.from_bootloader_version!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name,fromBootloaderVersion:r.from_bootloader_version,providers:r.providers}})))}mapDeviceVersionDto(t){return He(()=>{if(typeof t!="object"||typeof t.id!="number")throw new Error(`Incomplete device version: ${JSON.stringify(t)}`);const r={id:t.id};return Promise.resolve(r)})}mapFinalFirmwareDto(t){return He(()=>{if(typeof t!="object"||typeof t.id!="number"||typeof t.version!="string"||typeof t.perso!="string"||t.firmware!==null&&typeof t.firmware!="string"||t.firmware_key!==null&&typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||t.bytes!==null&&typeof t.bytes!="number"||!Array.isArray(t.mcu_versions))throw new Error(`Incomplete final firmware: ${JSON.stringify(t)}`);const r={id:t.id,version:t.version,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,bytes:t.bytes,mcuVersions:t.mcu_versions};return Promise.resolve(r)})}mapLatestFirmwareDto(t){return He(()=>{if(t.result==="null")return Promise.resolve(null);if(t.result!=="success"||!t.se_firmware_osu_version)throw new Error(`Latest firmware could not be retrieved: ${t.result}`);const r=t.se_firmware_osu_version;return Promise.resolve(r)}).chain(r=>r===null?He(()=>Promise.resolve(ft)):this.mapOsuFirmwareDto(r).map(n=>or(n)))}mapOsuFirmwareDto(t){return He(()=>{if(typeof t!="object"||typeof t.id!="number"||t.notes!==null&&typeof t.notes!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||typeof t.next_se_firmware_final_version!="number")throw new Error(`Incomplete latest firmware: ${JSON.stringify(t)}`);const r={id:t.id,notes:t.notes,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,nextFinalFirmware:t.next_se_firmware_final_version};return Promise.resolve(r)})}mapLanguagesDtoToLanguages(t){return He(()=>Promise.resolve(t.map(r=>this.mapLanguageDto(r))))}mapLanguageDto(t){if(typeof t!="object"||typeof t.language!="string"||typeof t.languagePackageVersionId!="number"||typeof t.version!="string"||typeof t.language_package_id!="number"||typeof t.apdu_install_url!="string"||typeof t.apdu_uninstall_url!="string"||typeof t.bytes!="number"||typeof t.date_creation!="string"||typeof t.date_last_modified!="string")throw new Error(`Incomplete language version: ${JSON.stringify(t)}`);return{language:t.language,languagePackageVersionId:t.languagePackageVersionId,version:t.version,languagePackageId:t.language_package_id,apduInstallUrl:t.apdu_install_url,apduUninstallUrl:t.apdu_uninstall_url,bytes:t.bytes,dateCreation:t.date_creation,dateLastModified:t.date_last_modified}}};E1=n8([Qe(),S1(0,Oe(jl.DmkConfig)),S1(1,Oe(Dt.LoggerPublisherServiceFactory))],E1);var i8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},o8=(e,t)=>(r,n)=>t(r,n,e);let C1=class{constructor(t){this.dataSource=t}getAppList(t){const r={targetId:t.targetId.toString(),firmwareVersionName:t.seVersion};return this.dataSource.getAppList(r)}getDeviceVersion(t){const r={targetId:t.targetId.toString()};return this.dataSource.getDeviceVersion(r)}getFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getFirmwareVersion(n)}getOsuFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getOsuFirmwareVersion(n)}getLatestFirmwareVersion(t,r){const n={currentFinalFirmwareId:t.id,deviceId:r.id};return this.dataSource.getLatestFirmwareVersion(n)}getNextFirmwareVersion(t){return this.dataSource.getFirmwareVersionById(t.nextFinalFirmware)}getLanguagePackages(t,r){const n={deviceId:t.id,currentFinalFirmwareId:r.id};return this.dataSource.getLanguagePackages(n)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(t){const r={hashes:t};return He(async({fromPromise:n,throwE:o})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(a){return a instanceof xd?o(a):o(new xd(a))}})}getProvider(){return this.dataSource.getProvider()}};C1=i8([Qe(),o8(0,Oe(jl.ManagerApiDataSource))],C1);var s8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},gm=(e,t)=>(r,n)=>t(r,n,e);let k1=class{constructor(t,r,n){this.sessionService=t,this.managerApiDataSource=r,this._logger=n("SetFirmwareDistributionSaltUseCase")}_logger;execute(t){if(t.trim()===""){this._logger.warn("Ignoring empty firmware distribution salt");return}const r=this.managerApiDataSource.getFirmwareDistributionSalt();if(t===r){this._logger.debug("Firmware distribution salt unchanged",{data:{salt:t}});return}this.managerApiDataSource.setFirmwareDistributionSalt(t);let n=0;for(const o of this.sessionService.getDeviceSessions()){const a=o.getDeviceSessionState();a.sessionStateType!==Ys.Connected&&a.firmwareUpdateContext!==void 0&&(o.setDeviceSessionState({...a,firmwareUpdateContext:void 0}),n++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:r,salt:t,invalidatedSessions:n}})}};k1=s8([Qe(),gm(0,Oe(dr.DeviceSessionService)),gm(1,Oe(jl.ManagerApiDataSource)),gm(2,Oe(Dt.LoggerPublisherServiceFactory))],k1);var a8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},R1=(e,t)=>(r,n)=>t(r,n,e);let _1=class{constructor(t,r){this.sessionService=t,this.managerApiDataSource=r}execute(t){for(const r of this.sessionService.getDeviceSessions()){const n=r.getDeviceSessionState();n.sessionStateType!==Ys.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};_1=a8([Qe(),R1(0,Oe(dr.DeviceSessionService)),R1(1,Oe(jl.ManagerApiDataSource))],_1);var l8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},c8=(e,t)=>(r,n)=>t(r,n,e);let $1=class{webSocketBaseUrl;constructor({webSocketUrl:t}){this.webSocketBaseUrl=t}setWebSocketUrl(t){this.webSocketBaseUrl===t||t.length===0||(this.webSocketBaseUrl=t)}getWebSocketUrl(){return this.webSocketBaseUrl}genuineCheck(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return Tt(new gF(t))}catch(r){return yt(new SF(r))}}};$1=l8([Qe(),c8(0,Oe(Kd.DmkConfig))],$1);var u8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},d8=(e,t)=>(r,n)=>t(r,n,e);let A1=class{constructor(t){this.dataSource=t}genuineCheck(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.genuineCheck(n)}installApp(t,r){const{perso:n,firmware:o,firmwareKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};return this.dataSource.installApp(u)}listInstalledApps(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.listInstalledApps(n)}uninstallApp(t,r){const{perso:n,delete:o,deleteKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};return this.dataSource.uninstallApp(u)}updateFirmware(t,r){const n={targetId:t.targetId.toString(),perso:r.perso,firmware:r.firmware,firmwareKey:r.firmwareKey};return this.dataSource.updateFirmware(n)}updateMcu(t,r){const n={targetId:t.targetId.toString(),version:r.version};return this.dataSource.updateMcu(n)}};A1=u8([Qe(),d8(0,Oe(Kd.SecureChannelDataSource))],A1);var f8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},p8=(e,t)=>(r,n)=>t(r,n,e);let T1=class{constructor(t){this.secureChannelDataSource=t}execute(t){this.secureChannelDataSource.setWebSocketUrl(t)}};T1=f8([Qe(),p8(0,Oe(Kd.SecureChannelDataSource))],T1);var h8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},L1=(e,t)=>(r,n)=>t(r,n,e);let I1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:o}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async a=>(await a.sendApdu(r,{abortTimeout:n,triggersDisconnection:o})).caseOf({Right:l=>l,Left:l=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:l}}),l}}),Left:a=>{throw this._logger.error("Error getting deviceSession",{data:{error:a}}),a}})}};I1=h8([Qe(),L1(0,Oe(dr.DeviceSessionService)),L1(1,Oe(Dt.LoggerPublisherServiceFactory))],I1);var m8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},ks=(e,t)=>(r,n)=>t(r,n,e);let O1=class{constructor(t,r,n,o,a,l){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=o,this._apduSenderServiceFactory=a,this._apduReceiverServiceFactory=l,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new mF("No transports provided, please check your configuration");for(const u of t){const d=this.addTransport(u);if(d.isLeft())throw d.extract()}}_transports=new Map;_logger;addTransport(t){const r=t({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(r)}addTransportInternal(t){return this.getTransport(t.getIdentifier()).isJust()?(this._logger.warn(`Transport ${t.getIdentifier()} already exists, please check your configuration`),yt(new hF(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),Tt(void 0))}getTransport(t){return Ar.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};O1=m8([Qe(),ks(0,Oe(Gi.TransportsInput)),ks(1,Oe(Gi.DmkConfig)),ks(2,Oe(Dt.LoggerPublisherServiceFactory)),ks(3,Oe(pB.DeviceModelDataSource)),ks(4,Oe(dr.ApduSenderServiceFactory)),ks(5,Oe(dr.ApduReceiverServiceFactory))],O1);const g8={ADD_LOG:"addLog"};function v8(e){return{startListeningCommand:()=>e.sendMessage(zi.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(zi.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(zi.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(zi.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(zi.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function y8(e){return{getProviderCommand:()=>e.sendMessage(zi.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(zi.SET_PROVIDER,JSON.stringify({provider:t}))}}let b8=0;function x8(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++b8}`,o=r.match(/.{1,2}/g)?.map(a=>parseInt(a,16))||[];return e.sendMessage(zi.SEND_APDU,JSON.stringify({sessionId:t,apdu:o,requestId:n})),n}}}const w8=e=>{try{const t=JSON.parse(e);return typeof t=="string"||t!==null&&typeof t=="object"?t:t===null?{}:JSON.stringify(t)}catch{return e}},S8=new Set(["debug","info","warning","error","fatal"]),E8=e=>{if(e===null||typeof e!="object")return!1;const{timestamp:t,tag:r,verbosity:n,message:o,payloadJSON:a}=e;return typeof t=="string"&&typeof r=="string"&&typeof o=="string"&&typeof n=="string"&&S8.has(n)&&(a===void 0||typeof a=="string")};function C8(e){let t;try{t=JSON.parse(e)}catch{return null}if(!E8(t))return null;const r=t.payloadJSON??"{}";return{timestamp:t.timestamp,tag:t.tag,verbosity:t.verbosity,message:t.message,payloadJSON:r,payload:w8(r)}}function k8(e,t){try{const{module:r}=JSON.parse(e);t(n=>new Set([...n,r]))}catch(r){console.error("Failed to parse moduleConnected payload",r)}}function R8(e,t){const r=C8(e);return r!==null?(t(r),!0):!1}function _8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function $8(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(o=>new Map(o).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function A8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function T8(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}const L8=e=>{try{const{protocol:t,host:r}=new URL(e);return(t==="http:"||t==="https:")&&r!==""}catch{return!1}};function I8(e){try{const t=JSON.parse(e);if(t===null)return null;if(typeof t!="object")return;const{url:r,sessionToken:n}=t;return typeof r!="string"||!L8(r)||n!==void 0&&typeof n!="string"?void 0:n===void 0?{url:r}:{url:r,sessionToken:n}}catch{return}}function O8(e,t){const r=I8(e);if(r===void 0){console.error("Ignored an invalid mockServerConfig payload");return}t(r)}function N8(e,t){try{const r=JSON.parse(e);t(n=>new Map(n).set(r.requestId,r))}catch(r){console.error("Failed to parse apduResponse payload",r)}}const P8=250;function D8(e){const[t,r]=x.useState([]),[n,o]=x.useState(new Set),[a,l]=x.useState([]),[u,d]=x.useState(new Map),[p,h]=x.useState([]),[m,y]=x.useState(!1),[w,E]=x.useState(!1),[S,C]=x.useState(null),[R,k]=x.useState(new Map),[$,A]=x.useState(null),D=x.useRef([]);x.useEffect(()=>{let H;const O=()=>{H=void 0;const U=D.current;D.current=[],U.length>0&&r(z=>[...z,...U].slice(-2e4))},{unsubscribe:L}=e.listenToMessages((U,z)=>{switch(H??=setTimeout(O,P8),U){case b5:k8(z,o);break;case Es.CONNECTED_DEVICES_UPDATE:_8(z,l);break;case Es.DEVICE_SESSION_STATE_UPDATE:$8(z,d);break;case Es.DISCOVERED_DEVICES_UPDATE:A8(z,h);break;case Es.PROVIDER_VALUE:T8(z,C);break;case Es.APDU_RESPONSE:N8(z,k);break;case Es.MOCK_SERVER_CONFIG:O8(z,A);break;case g8.ADD_LOG:R8(z,T=>D.current.push(T));break}});return()=>{L(),clearTimeout(H),D.current=[]}},[e]);const N=x.useMemo(()=>v8(e),[e]),P=x.useMemo(()=>y8(e),[e]),I=x.useMemo(()=>x8(e),[e]),re=x.useCallback(()=>{y(!0),h([]),N.startListeningCommand()},[N]),Z=x.useCallback(()=>{y(!1),h([]),N.stopListeningCommand()},[N]),ee=x.useCallback(()=>{E(!0),h([]),N.startDiscoveringCommand()},[N]),ne=x.useCallback(()=>{E(!1),h([]),N.stopDiscoveringCommand()},[N]),X=x.useCallback(()=>{D.current=[],r([])},[]),F=n.has(mw.LOGGER),V=n.has(mw.DMK_INSPECTOR);return{logs:t,connectedModules:n,connectedDevices:a,sessionStates:u,discoveredDevices:p,isListening:m,isActivelyDiscovering:w,isLoggerConnected:F,isInspectorConnected:V,providerValue:S,apduResponses:R,mockServer:$,sendMessage:e.sendMessage,clearLogs:X,startListening:re,stopListening:Z,startDiscovering:ee,stopDiscovering:ne,connectDevice:N.connectDeviceCommand,getProvider:P.getProviderCommand,setProvider:P.setProviderCommand,sendApdu:I.sendApduCommand}}const _g=e=>`devtools-panel-width-${e}`,j8=e=>{try{const t=Number(localStorage.getItem(_g(e)));return t>0?t:null}catch{return null}},vm=(e,t)=>{try{t===null?localStorage.removeItem(_g(e)):localStorage.setItem(_g(e),String(t))}catch{}},Dv=({name:e,defaultWidth:t,minWidth:r,maxWidth:n,edge:o,className:a="",children:l})=>{const[u,d]=x.useState(()=>j8(e)??t),p=y=>{y.preventDefault();const w=y.clientX,E=u;let S=E;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const C=k=>{const $=k.clientX-w;S=Math.min(n,Math.max(r,E+(o==="right"?$:-$))),d(S)},R=()=>{document.body.style.cursor="",document.body.style.userSelect="",vm(e,S),window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",R)};window.addEventListener("mousemove",C),window.addEventListener("mouseup",R)},h=y=>{const w=y.key==="ArrowRight"?16:y.key==="ArrowLeft"?-16:0;if(w===0)return;y.preventDefault();const E=Math.min(n,Math.max(r,u+(o==="right"?w:-w)));d(E),vm(e,E)},m=()=>{d(t),vm(e,null)};return v.jsxs("div",{className:`relative flex flex-col ${a}`,style:{flex:`0 1 ${u}px`,minWidth:r},children:[l,v.jsx("span",{role:"separator","aria-orientation":"vertical","aria-label":"Resize the panel","aria-valuenow":u,"aria-valuemin":r,"aria-valuemax":n,tabIndex:0,title:"Drag or use the arrow keys to resize, double-click to reset",onMouseDown:p,onKeyDown:h,onDoubleClick:m,className:`absolute inset-y-0 z-10 w-6 cursor-col-resize border-transparent hover:border-active focus-visible:border-active focus-visible:outline-none ${o==="right"?"-right-3 border-r-2":"-left-3 border-l-2"}`})]})},c_="relative w-320 min-w-160 shrink",Ml="flex h-32 items-center gap-6 overflow-hidden rounded-sm border border-muted-subtle bg-surface px-8 transition-colors hover:border-muted focus-within:border-active",zl="min-w-0 flex-1 bg-transparent font-mono! body-3 text-base outline-none placeholder:text-muted",Lo="flex size-24 shrink-0 cursor-pointer items-center justify-center rounded-xs text-muted transition-colors hover:bg-base-transparent-hover hover:text-base disabled:cursor-default disabled:text-disabled disabled:hover:bg-transparent",u_=/Mac|iPhone|iPad/.test(navigator.userAgent)?"⌘":"Ctrl+",d_="rounded-xs border border-muted px-4 font-mono! body-4 text-muted",M8="body-4-semi-bold text-muted uppercase",z8=e=>{const t=[{title:null,blocks:[]}],r=e.split(`
39
+ Found @inject decorator at method "${p.toString()}" at class "${d.constructor.name}"`);cl(d.constructor,qu,Gu,_S(u(d),p))}})(e,t)(r,n,o)}catch(a){TF(r,n,o,a)}}}function cm(e,t){return r=>{const n=t(r);return o=>(n(o),e(o))}}function Oe(e){return LF(AF(Cl.singleInjection,e),RF)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(Mi||(Mi={}));const $S="@inversifyjs/core/classIsInjectableFlagReflectKey",IF=[Array,BigInt,Boolean,Function,Number,Object,String];function OF(e){const t=Nv(e,"design:paramtypes");t!==void 0&&cl(e,qu,Gu,(function(r){return n=>(r.forEach(((o,a)=>{var l;n.constructorArguments[a]!==void 0||(l=o,IF.includes(l))||(n.constructorArguments[a]=(function(u){return{isFromTypescriptParamType:!0,kind:Cl.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(o))})),n)})(t))}function Qe(e){return t=>{(function(r){if(Nv(r,$S)!==void 0)throw new Vi(Dn.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);EF(r,$S,!0)})(t),OF(t)}}var AS;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(AS||(AS={}));var TS;(function(e){e[e.singleMandatory=0]="singleMandatory",e[e.singleOptional=1]="singleOptional",e[e.multipleMandatory=2]="multipleMandatory",e[e.multipleOptional=3]="multipleOptional",e[e.length=4]="length"})(TS||(TS={}));let NF=class{constructor(t,r,n,o,a){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=o,this.notifyUuid=a}},Cs=class{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(t){this.id=t.id,this.productName=t.productName,this.usbProductId=t.usbProductId,this.bootloaderUsbProductId=t.bootloaderUsbProductId,this.usbOnly=t.usbOnly,this.memorySize=t.memorySize,this.getBlockSize=t.getBlockSize,this.masks=t.masks,this.bluetoothSpec=t.bluetoothSpec}};var PF=Object.defineProperty,DF=(e,t,r)=>t in e?PF(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,jF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},MF=(e,t,r)=>DF(e,t+"",r);let Oo=class{getAllDeviceModels(){return Object.values(Oo.deviceModelByIds)}getDeviceModel(t){return Oo.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,o])=>r[n]===o))}getBluetoothServicesInfos(){return Object.values(Oo.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((o,a)=>({...o,[a.serviceUuid]:new NF(r,a.serviceUuid,a.writeUuid,a.writeCmdUuid,a.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values(Oo.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};MF(Oo,"deviceModelByIds",{[wt.NANO_S]:new Cs({id:wt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>pS.lt(pS.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[wt.NANO_SP]:new Cs({id:wt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[wt.NANO_X]:new Cs({id:wt.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2*1024*1024,getBlockSize:()=>4*1024,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}]}),[wt.STAX]:new Cs({id:wt.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>512,masks:[857735168],bluetoothSpec:[{serviceUuid:"13d63400-2c97-6004-0000-4c6564676572",notifyUuid:"13d63400-2c97-6004-0001-4c6564676572",writeUuid:"13d63400-2c97-6004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-6004-0003-4c6564676572"}]}),[wt.FLEX]:new Cs({id:wt.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>512,masks:[858783744],bluetoothSpec:[{serviceUuid:"13d63400-2c97-3004-0000-4c6564676572",notifyUuid:"13d63400-2c97-3004-0001-4c6564676572",writeUuid:"13d63400-2c97-3004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-3004-0003-4c6564676572"}]}),[wt.APEX]:new Cs({id:wt.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1533*1024,getBlockSize:()=>512,masks:[859832320],bluetoothSpec:[{serviceUuid:"13d63400-2c97-8004-0000-4c6564676572",notifyUuid:"13d63400-2c97-8004-0001-4c6564676572",writeUuid:"13d63400-2c97-8004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-8004-0003-4c6564676572"},{serviceUuid:"13d63400-2c97-9004-0000-4c6564676572",notifyUuid:"13d63400-2c97-9004-0001-4c6564676572",writeUuid:"13d63400-2c97-9004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-9004-0003-4c6564676572"}]})}),Oo=jF([Qe()],Oo);let zF=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const FF=5,Ao=1,Sg=2,Ls=2,Eg=2,ir=[];for(let e=0;e<256;++e)ir.push((e+256).toString(16).slice(1));function BF(e,t=0){return(ir[e[t+0]]+ir[e[t+1]]+ir[e[t+2]]+ir[e[t+3]]+"-"+ir[e[t+4]]+ir[e[t+5]]+"-"+ir[e[t+6]]+ir[e[t+7]]+"-"+ir[e[t+8]]+ir[e[t+9]]+"-"+ir[e[t+10]]+ir[e[t+11]]+ir[e[t+12]]+ir[e[t+13]]+ir[e[t+14]]+ir[e[t+15]]).toLowerCase()}let um;const UF=new Uint8Array(16);function VF(){if(!um){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");um=crypto.getRandomValues.bind(crypto)}return um(UF)}const WF=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),LS={randomUUID:WF};function Yd(e,t,r){if(LS.randomUUID&&!e)return LS.randomUUID();e=e||{};const n=e.random||(e.rng||VF)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,BF(n)}const No={getLastBytesFrom(e,t){return e.slice(-t)},getFirstBytesFrom(e,t){return e.slice(0,t)},bytesToNumber(e){return e.reduce((t,r,n)=>t+r*Math.pow(256,e.length-1-n),0)},numberToByteArray(e,t){return new Uint8Array(t).map((r,n)=>e>>8*(t-1-n)&255)}},IS=2,dm=800;let OS=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},HF=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},NS=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},PS=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},o_=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:si(this._data)},null,2)}getRawData(){const t=this._header.getRawData(),r=new Uint8Array(t.length+this._data.length);return r.set(t,0),r.set(this._data,t.length),r}getHeader(){return this._header}getData(){return this._data}},s_=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:o,length:a,channel:l}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=o,this._length=a,this._channel=l}getDataLength(){return this._dataLength.map(t=>No.bytesToNumber(t))}setDataSize(t){return this._dataLength=t,this}getLength(){return this._length}toString(){return JSON.stringify({uuid:this._uuid.toString(),dataSize:this._dataLength.extract()?.toString(),index:this._index.toString(),headTag:this._headTag.toString(),length:this._length.toString(),channel:this._channel.extract()?.toString()})}getRawData(){return new Uint8Array([...this._channel.caseOf({Just:t=>[...t],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:t=>[...t],Nothing:()=>[]})])}};const Dt={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var qF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},GF=(e,t)=>(r,n)=>t(r,n,e);let DS=class{_channel;_logger;_pendingFrames;constructor({channel:t=Ar.zero()},r){this._channel=t,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(t){return this.getFrameFromBytes(t).map(r=>{if(this._pendingFrames.push(r),!this._pendingFrames[0])return ft;const n=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(n)})}getCompleteFrame(t){return t.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),ft;const n=No.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),o=No.getFirstBytesFrom(n,n.length-IS),a=No.getLastBytesFrom(n,IS);return this._pendingFrames=[],or(new zF({data:o,statusCode:a}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>Sg,Nothing:()=>0}),n=t.slice(r,r+Ao),o=t.slice(r+Ao,r+Ao+Ls),a=o.reduce((y,w)=>y+w,0)===0;if(!a&&this._pendingFrames.length===0)return yt(new NS);const l=r+Ao+Ls,u=a?Eg:0;if(t.length<r+Ao+Ls+u)return yt(new NS("Unable to parse header from apdu"));const d=a?or(t.slice(l,l+u)):ft,p=l+u,h=t.slice(p),m=new o_({header:new s_({uuid:Yd(),channel:this._channel,dataSize:d,headTag:n,index:o,length:r+Ao+Ls+u}),data:h});return Tt(m)}isComplete(t){return this._pendingFrames.reduce((r,n)=>r+n.getData().length,0)>=t}concatFrames(t){return t.reduce((r,n)=>Uint8Array.from([...r,...n.getData()]),new Uint8Array(0))}};DS=qF([Qe(),GF(1,Oe(Dt.LoggerPublisherServiceFactory))],DS);var XF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},YF=(e,t)=>(r,n)=>t(r,n,e);let jS=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=Ar.zero(),padding:n=!1},o){this._frameSize=t,this._channel=r,this._padding=n,this._logger=o("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,o=this.getFrameAtIndex(t,n);for(;o.isRight();)r.push(o.extract()),n+=1,o=this.getFrameAtIndex(t,n).mapLeft(a=>(a instanceof OS||this._logger.error("Error while parsing frame",{data:{error:a}}),a));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),o=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(o>=t.length)return yt(new OS);if(n.getLength()>this._frameSize)return yt(new HF);const a=this._frameSize-n.getLength(),l=t.slice(o,o+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(a).fill(0):new Uint8Array(l.length<a?l.length:a);u.set(l,0);const d=new o_({header:n,data:u});return Tt(d)}getFrameHeaderFrom(t,r){const n=new s_({uuid:Yd(),channel:this._channel.map(o=>No.getLastBytesFrom(o,Sg)),headTag:new Uint8Array([FF]),index:No.numberToByteArray(t,Ls),length:this.getFrameHeaderSizeFromIndex(t),dataSize:Ar.zero()});return t===0&&n.setDataSize(Ar.of(No.numberToByteArray(r,Eg))),n}getHeaderSizeSumFrom(t){let r=this.getFrameHeaderSizeFromIndex(0),n=1;for(;n<t;)r+=this.getFrameHeaderSizeFromIndex(n),n+=1;return r}getFrameHeaderSizeFromIndex(t){return this._channel.caseOf({Just:()=>Sg,Nothing:()=>0})+Ls+Ao+(t===0?Eg:0)}};jS=XF([Qe(),YF(1,Oe(Dt.LoggerPublisherServiceFactory))],jS);const Cg={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},dr={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},MS={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},jl={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Kd={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")},Gi={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var KF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},zS=(e,t)=>(r,n)=>t(r,n,e);let FS=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendCommandUseCase")}async execute({sessionId:t,command:r,abortTimeout:n}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async o=>await o.sendCommand(r,n),Left:o=>{throw this._logger.error("Error getting session",{data:{error:o}}),o}})}};FS=KF([Qe(),zS(0,Oe(dr.DeviceSessionService)),zS(1,Oe(Dt.LoggerPublisherServiceFactory))],FS);var QF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let BS=class{execute=vi.fn(()=>"stub")};BS=QF([Qe()],BS);var JF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},US=(e,t)=>(r,n)=>t(r,n,e);let VS=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ExecuteDeviceActionUseCase")}execute({sessionId:t,deviceAction:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:n=>n.executeDeviceAction(r),Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n}})}};VS=JF([Qe(),US(0,Oe(dr.DeviceSessionService)),US(1,Oe(Dt.LoggerPublisherServiceFactory))],VS);function ZF(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let WS=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},eB=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},a_=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},tB=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const rB="@ledgerhq/device-management-kit",nB="0.0.0-develop-20261110000801",HS={name:rB,version:nB};var iB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};const oB={name:HS.name,version:HS.version},sB=()=>JSON.stringify(oB);let qS=class{getConfig(){return Tr.encase(()=>sB()).mapLeft(t=>new tB(t)).chain(t=>Tr.encase(()=>{const r=JSON.parse(t);if(ZF(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new a_(r)))}};qS=iB([Qe()],qS);var aB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let GS=class{getConfig(){return Tr.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};GS=aB([Qe()],GS);var lB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let XS=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return yt(new WS(t.extract()));if(!t.extract().ok)return yt(new WS(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?yt(new a_):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?yt(new eB):Tr.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(Tr.of({ok:!0,json:async()=>new Promise(r=>{r(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};XS=lB([Qe()],XS);var cB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let YS=class{async getConfig(){return new Promise(t=>t(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};YS=cB([Qe()],YS);var uB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},fm=(e,t)=>(r,n)=>t(r,n,e);let KS=class{_local;_remote;_logger;constructor(t,r,n){this._local=t,this._remote=r,this._logger=n("config")}async getDmkConfig(){const t=this._local.getConfig().ifLeft(r=>{this._logger.error("Local config not available",{data:{error:r}})});if(t.isRight()){const r=t.extract();return this._logger.info("Local config available",{data:{config:r}}),r}return this._remote.getConfig().then(r=>r.mapLeft(n=>(this._logger.error("Local config available",{data:{error:n}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};KS=uB([Qe(),fm(0,Oe(Cg.LocalConfigDataSource)),fm(1,Oe(Cg.RemoteConfigDataSource)),fm(2,Oe(Dt.LoggerPublisherServiceFactory))],KS);var dB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},fB=(e,t)=>(r,n)=>t(r,n,e);let QS=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};QS=dB([Qe(),fB(0,Oe(Cg.ConfigService))],QS);const pB={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var hB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},JS=(e,t)=>(r,n)=>t(r,n,e);let ZS=class{constructor(t,r){this._sessionService=t,this._logger=r("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:t,blockerId:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting device session",{data:{error:n}}),n},Right:n=>n.disableRefresher(r)})}};ZS=hB([Qe(),JS(0,Oe(dr.DeviceSessionService)),JS(1,Oe(Dt.LoggerPublisherServiceFactory))],ZS);var mB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},gB=(e,t)=>(r,n)=>t(r,n,e);let e1=class{_sessions;_sessionsSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new zR,this._logger=t("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(t){return this._sessions.find(r=>r.id===t.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:t}}),this):(this._sessions.push(t),this._sessionsSubject.next(t),this._logger.info("DeviceSession added",{data:{sessionId:t.id}}),this)}removeDeviceSession(t){const r=this._sessions.find(n=>n.id===t);return r?(r.close(),this._sessions=this._sessions.filter(n=>n.id!==t),this._logger.info("DeviceSession removed",{data:{sessionId:t}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:t}}),this)}getDeviceSessionById(t){return Ar.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new PS)}getDeviceSessionsByDeviceId(t){return Ar.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new PS)}getDeviceSessions(){return this._sessions}};e1=mB([Qe(),gB(0,Oe(Dt.LoggerPublisherServiceFactory))],e1);var vB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},t1=(e,t)=>(r,n)=>t(r,n,e);let r1=class{_sessionService;_transportService;constructor(t,r){this._sessionService=t,this._transportService=r}execute(){const t=this._sessionService.getDeviceSessions();for(const r of t)this._transportService.closeConnection(r.connectedDevice),this._sessionService.removeDeviceSession(r.id)}};r1=vB([Qe(),t1(0,Oe(dr.DeviceSessionService)),t1(1,Oe(Gi.TransportService))],r1);var yB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},n1=(e,t)=>(r,n)=>t(r,n,e);let i1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetDeviceSessionStateUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:r=>{throw this._logger.error("Error getting session device",{data:{error:r}}),r},Right:r=>r.state})}};i1=yB([Qe(),n1(0,Oe(dr.DeviceSessionService)),n1(1,Oe(Dt.LoggerPublisherServiceFactory))],i1);var bB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},o1=(e,t)=>(r,n)=>t(r,n,e);let s1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("UnsafeBypassIntentQueueUseCase")}execute({sessionId:t,bypass:r}){this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n},Right:n=>{this._logger.warn(`UNSAFE: ${r?"Enabling":"Disabling"} intent queue bypass for session ${t}`),n._unsafeBypassIntentQueue(r)}})}};s1=bB([Qe(),o1(0,Oe(dr.DeviceSessionService)),o1(1,Oe(Dt.LoggerPublisherServiceFactory))],s1);function xB(e){return`[will send APDU] ~...> ${si(e,!1)}`}function wB(e){return`[exchange] <= ${si(e.data,!1)}${si(e.statusCode,!1)}`}const SB="apdu-exchange";function EB(e,t,r){const n=si(t,!1),o=`${si(r.data,!1)}${si(r.statusCode,!1)}`;return{message:wB(r),data:{type:SB,sessionId:e,apdu:n,response:o}}}const kg=1e3,pm=1e3,CB={isRefresherDisabled:!1,pollingInterval:1e3};var Nt=(e=>(e.NEW_STATE="NEW_STATE",e.REFRESH_NEEDED="REFRESH_NEEDED",e.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",e.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",e.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",e.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",e.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",e))(Nt||{});let kB=class{_eventEmitter=new oa;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},RB=class{constructor(t,r){this.loggerModuleFactory=t,this.sessionEventDispatcher=r,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(t){this._logger.debug("Enqueueing intent",{data:{type:t.type}});const r=new oa,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const o=()=>{this._logger.debug("Cancelling intent",{data:{type:t.type}}),n.isCancelled=!0,this._queue[0]===n&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,r.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==n)&&r.complete()};return this._isProcessing||this._processQueue(),{observable:r.asObservable().pipe(sF(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:o}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:Nt.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;const t=this._queue[0];if(t.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:t.intent.type}}),t.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:t.intent.type}}),this._currentSubscription=t.intent.execute().subscribe({next:r=>{t.isCancelled||t.subject.next(r)},error:r=>{t.isCancelled||t.subject.error(r),this._onIntentComplete()},complete:()=>{t.isCancelled||t.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}},_B=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${Yd()}`;this.addRefresherBlocker(r),this._logger.debug("Refresher disabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}});let n=!1;return()=>{n||(n=!0,this.removeRefresherBlocker(r),this._logger.debug("Refresher re-enabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.add(t),r===0&&this._refresher.stop()}removeRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.delete(t),r>0&&this._refresherBlockers.size===0&&this._refresher.start()}},$B=class{constructor(t,r,n,o){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=o,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async a=>await this.mapEventAction(a))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(t){return this._logger.error("Error while pinging device",{data:{error:t}}),null}}mapEventAction=async t=>t.eventName===Nt.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===wt.NANO_S){const r=async()=>{const a=await this._sendCommandFunction(new ww,dm);return this._sendCommandFunction(new cz,dm),a},n=new Promise(a=>{setTimeout(()=>a(null),kg*2+100)}),o=await Promise.race([r(),n]);return o?this._sessionEventDispatcher.dispatch({eventName:Nt.COMMAND_SUCCEEDED,eventData:o}):this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_LOCKED}),o}else{const r=await this._sendCommandFunction(new ww,dm);return this._sessionEventDispatcher.dispatch({eventName:Nt.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},AB=class{constructor(t,r,n,o){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=o.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;const t=this.getValidPollingInterval(this._refresherOptions,this._logger),r=this._sessionEventDispatcher.listen().pipe(SS(n=>n.eventName===Nt.DEVICE_STATE_UPDATE_BUSY||n.eventName===Nt.NEW_STATE),Ui(n=>n.eventName===Nt.DEVICE_STATE_UPDATE_BUSY),lF(!1),iF());this._refresherSubscription=tF(0,t).pipe(cF(r),ES(([n,o])=>{o&&this._logger.debug("Refresh skipped: device is busy")}),SS(([n,o])=>!o),ES(()=>this._sessionEventDispatcher.dispatch({eventName:Nt.REFRESH_NEEDED}))).subscribe(),this._logger.info("Refresher started.")}stopRefresher(){this._refresherSubscription&&(this._refresherSubscription.unsubscribe(),this._refresherSubscription=void 0,this._logger.info("Refresher stopped."))}restartRefresher(){this.stopRefresher(),this.startRefresher(),this._logger.info("Refresher restarted.")}getValidPollingInterval=(t,r)=>{const{pollingInterval:n}=t;if(this._connectedDeviceID===wt.NANO_S){const o=kg*2;return n!==void 0&&n<o?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${o}`),o):n??o}else return n!==void 0&&n<pm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${pm}`),pm):n??kg}},TB=class{constructor(t,r,n,o,a){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=o,this.setDeviceSessionState=a,this._subscription=this._sessionEventDispatcher.listen().subscribe(l=>this.mapEventAction(l)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=Ln.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:o,currentApp:a}=r,l=this._deviceState.getValue();l.sessionStateType===Ys.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...l,sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case Nt.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case Nt.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Nt.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=Ln.LOCKED;return;case Nt.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=Ln.CONNECTED;return;case Nt.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=Ln.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case Nt.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Nt.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return A5(t)?{sessionStateType:Ys.ReadyWithoutSecureChannel,deviceStatus:Ln.CONNECTED,currentApp:{name:t.data.name,version:t.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:t}}),null)}unsubscribe(){this._subscription.unsubscribe()}};class LB{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new kB;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=Yd()},n,o,a,l,u=d=>new RB(n,d)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=o,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=a,this._refresherOptions={...CB,...l},this._deviceState=new Az({sessionStateType:Ys.Connected,deviceStatus:Ln.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new $B(n,t,this._sessionEventDispatcher,(d,p)=>this.sendCommand(d,p)),this._deviceSessionRefresher=new AB(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new TB(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,d=>this.setDeviceSessionState(d)),this._refresherService=new _B(n,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(t){throw this._logger.error("Error while initialising session",{data:{error:t}}),t}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(t){this._deviceState.next(t)}sendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(t,r):this._internalSendApdu(t,r)}_internalSendApdu(t,r){const n=r.abortTimeout,o=Date.now(),{observable:a,cancel:l}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Xs((async()=>{const d=Date.now()-o;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-d:void 0})})())}),u=n?a.pipe(xS({each:n,with:()=>{throw l(),new fF}})):a;return bS(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(xB(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:o,data:a}=EB(this._id,t,n);this._logger.debug(o,{data:a}),gv.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:Nt.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(t,r){return this._logger.debug(`[sendCommand] ${t.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(t,r):this._internalSendCommand(t,r)}_internalSendCommand(t,r){const n=Date.now(),{observable:o,cancel:a}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Xs((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),l=r?o.pipe(xS({each:r,with:()=>{throw a(),new pF}})):o;return bS(l)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:o=>{throw this._logger.error("[sendCommand] error",{data:{err:o}}),o},Right:o=>{const a=t.parseResponse(o,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:a}}),a}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:o}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:a,cancel:l}=this._unsafeInternalExecuteDeviceAction(t);return r=l,a}});return{observable:n,cancel:()=>{r?.(),o()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async o=>this._unsafeInternalSendApdu(o),sendCommand:async o=>this._unsafeInternalSendCommand(o),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:o=>(this.setDeviceSessionState(o),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(Ln.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(t){return this._refresherService.disableRefresher(t)}_unsafeBypassIntentQueue(t){this._bypassIntentQueue=t}_updateDeviceStatus(t){const r=this._deviceState.getValue();this._deviceState.next({...r,deviceStatus:t})}}var IB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},Za=(e,t)=>(r,n)=>t(r,n,e);let a1=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,o,a){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=o,this._secureChannel=a}handleDeviceDisconnect(t){this._sessionService.getDeviceSessionsByDeviceId(t).ifRight(r=>{r.forEach(n=>{this._sessionService.removeDeviceSession(n.id),this._logger.info("Session removed",{data:{deviceId:t,sessionId:n.id}})})})}async execute({device:t,sessionRefresherOptions:r}){const n=this._transportService.getTransport(t.transport),o="sessionId"in t?t.sessionId:void 0;return He.liftEither(n.toEither(new Ov(new Error("Unknown transport")))).chain(async a=>a.connect({deviceId:t.id,onDisconnect:l=>this.handleDeviceDisconnect(l)})).ifLeft(a=>{this._logger.error("Error connecting to device")}).map(async a=>{const l=new LB({connectedDevice:a,id:o},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(l),await l.initialiseSession(),l.id}).caseOf({Left:a=>{throw a},Right:a=>a})}};a1=IB([Qe(),Za(0,Oe(Gi.TransportService)),Za(1,Oe(dr.DeviceSessionService)),Za(2,Oe(Dt.LoggerPublisherServiceFactory)),Za(3,Oe(jl.ManagerApiService)),Za(4,Oe(Kd.SecureChannelService))],a1);var OB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},hm=(e,t)=>(r,n)=>t(r,n,e);let l1=class{_transportService;_sessionService;_logger;constructor(t,r,n){this._sessionService=r,this._transportService=t,this._logger=n("DisconnectUseCase")}async execute({sessionId:t}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map(r=>r.id)}}),He(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(l=>{this._logger.error("Device session not found",{data:{sessionId:t,error:l}})})),o=n.connectedDevice.transport,a=await r(this._transportService.getTransport(o).toEither(new Ov(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await a.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};l1=OB([Qe(),hm(0,Oe(Gi.TransportService)),hm(1,Oe(dr.DeviceSessionService)),hm(2,Oe(Dt.LoggerPublisherServiceFactory))],l1);let Pv=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:o,transport:a,name:l},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=l??n,this.type=o,this.transport=a}};var NB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},c1=(e,t)=>(r,n)=>t(r,n,e);let u1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetConnectedDeviceUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:r=>new Pv({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};u1=NB([Qe(),c1(0,Oe(dr.DeviceSessionService)),c1(1,Oe(Dt.LoggerPublisherServiceFactory))],u1);var PB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},d1=(e,t)=>(r,n)=>t(r,n,e);let f1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map(t=>new Pv({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};f1=PB([Qe(),d1(0,Oe(dr.DeviceSessionService)),d1(1,Oe(Dt.LoggerPublisherServiceFactory))],f1);var DB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},p1=(e,t)=>(r,n)=>t(r,n,e);let h1=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new $R({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),Xs([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,o)=>n.listenToAvailableDevices().pipe(Ui(a=>({index:o,arr:a}))));return rF(...r).pipe(aF((n,{index:o,arr:a})=>(n[o]=a,n),{}),Ui(n=>Object.values(n).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${t}`),this._transportService.getTransport(t).caseOf({Nothing:()=>(this._logger.error(`Transport ${t} not found`),t_([])),Just:r=>r.listenToAvailableDevices().pipe(Ui(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};h1=DB([Qe(),p1(0,Oe(Gi.TransportService)),p1(1,Oe(Dt.LoggerPublisherServiceFactory))],h1);var jB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},m1=(e,t)=>(r,n)=>t(r,n,e);let g1=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(Ui(t=>new Pv({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};g1=jB([Qe(),m1(0,Oe(dr.DeviceSessionService)),m1(1,Oe(Dt.LoggerPublisherServiceFactory))],g1);var MB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},mm=(e,t)=>(r,n)=>t(r,n,e);let v1=class{constructor(t,r,n){this.connectUseCase=t,this.disconnectUseCase=r,this._logger=n("ReconnectUseCase")}_logger;async execute({device:t,sessionRefresherOptions:r}){return this._logger.debug("Reconnecting device session",{data:{deviceId:t.id,transport:t.transport}}),await this.disconnectUseCase.execute({sessionId:t.sessionId}),this.connectUseCase.execute({device:t,sessionRefresherOptions:r})}};v1=MB([Qe(),mm(0,Oe(MS.ConnectUseCase)),mm(1,Oe(MS.DisconnectUseCase)),mm(2,Oe(Dt.LoggerPublisherServiceFactory))],v1);var zB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},FB=(e,t)=>(r,n)=>t(r,n,e);let y1=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new $R({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(!t){const r=this._transportService.getAllTransports();return t_(...r).pipe(Lv(n=>n.startDiscovering().pipe(Ui(o=>this.mapDiscoveredDevice(o)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(Ui(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new Ov(new Error("Unknown transport"))}})}};y1=zB([Qe(),FB(0,Oe(Gi.TransportService))],y1);var BB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},b1=(e,t)=>(r,n)=>t(r,n,e);let x1=class{constructor(t,r){this.transportService=t,this._logger=r("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(const t of this.transportService.getAllTransports())await t.stopDiscovering()}};x1=BB([Qe(),b1(0,Oe(Gi.TransportService)),b1(1,Oe(Dt.LoggerPublisherServiceFactory))],x1);var nl=(e=>(e[e.Fatal=0]="Fatal",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug",e))(nl||{});let UB=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function Rg(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>Rg(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=Rg(o,t);return r}return e}function VB(e){const t=new WeakSet;t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=Rg(o,t);return r}var WB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let w1=class{subscribers;tag;tagFormatter;constructor(t,r,n=new UB){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const o=n?.data?VB(n.data):void 0,a=n?.tag??this.tag,l=this.tagFormatter.format(a);this.subscribers.forEach(u=>{const d={timestamp:n?.timestamp??Date.now(),tag:l,data:o};u.log(t,r,d)})}info(t,r){this._log(nl.Info,t,r)}warn(t,r){this._log(nl.Warning,t,r)}debug(t,r){this._log(nl.Debug,t,r)}error(t,r){this._log(nl.Error,t,r)}};w1=WB([Qe()],w1);let kl=class extends Error{status;statusText;responseBody;isTimeout;cause;constructor(t){super(t.message),this.name="DmkNetworkClientError",this.status=t.status,this.statusText=t.statusText,this.responseBody=t.responseBody,this.isTimeout=t.isTimeout??!1,this.cause=t.cause}};const HB="application/json";function qB(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function GB(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function To(e){const{url:t,params:r,baseUrl:n}=e,o=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?qB(n,t):t,a=r?GB(r):"";if(a.length===0)return o;const l=o.includes("?")?"&":"?";return`${o}${l}${a}`}function XB(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function YB(e){return!!(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||typeof URLSearchParams<"u"&&e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream)}function KB(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:o}=e,a={...n,...o};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:a}:YB(r)?{body:r,headers:a}:(XB(a,"content-type")||(a["Content-Type"]=HB),{body:JSON.stringify(r),headers:a})}function QB(e){const{timeoutMs:t}=e;if(!t||t<=0)return{signal:void 0,cleanup:()=>{}};const r=new AbortController,n=setTimeout(()=>{r.abort()},t);return{signal:r.signal,cleanup:()=>clearTimeout(n)}}async function JB(e,t){switch(t){case"void":return;case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();default:{const r=await e.text();if(r.length===0)return;try{return JSON.parse(r)}catch(n){throw new kl({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function ZB(e){try{return await e.text()}catch{return}}function e8(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const o=t.name==="TimeoutError"||n;return new kl({message:o?"Request timed out":"Request aborted",isTimeout:o,cause:t})}return new kl({message:t instanceof Error?t.message:"Network request failed",cause:t})}let l_=class{baseUrl;defaultHeaders;fetchImpl;constructor(t={}){this.baseUrl=t.baseUrl,this.defaultHeaders=t.headers??{},this.fetchImpl=t.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(t,r){return this.request({...r,method:"GET",url:t}).then(n=>n.data)}post(t,r,n){return this.request({...n,method:"POST",url:t,body:r}).then(o=>o.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(o=>o.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(o=>o.data)}delete(t,r){return this.request({...r,method:"DELETE",url:t}).then(n=>n.data)}head(t,r){return this.request({...r,method:"HEAD",url:t,responseType:"void"}).then(()=>{})}async request(t){const r=To({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:o}=KB({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:a,cleanup:l}=QB({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,d=t.responseType??"json";try{let p;try{p=await this.getFetch()(r,{method:t.method,headers:o,body:n,signal:a})}catch(h){throw e8({cause:h,timeoutMs:t.timeoutMs})}if(!p.ok&&u){const h=await ZB(p);throw new kl({message:`HTTP error ${p.status} ${p.statusText}`.trim(),status:p.status,statusText:p.statusText,responseBody:h})}return{data:await JB(p,d),status:p.status,statusText:p.statusText,headers:p.headers,ok:p.ok}}finally{l()}}};var il=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(il||{});const t8=1,r8="0";let xd=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var ol=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(ol||{}),n8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},S1=(e,t)=>(r,n)=>t(r,n,e);const Qn=e=>e instanceof kl&&e.cause!==void 0?new xd(e.cause):new xd(e);let E1=class{http;_provider=t8;_firmwareDistributionSalt=r8;_logger;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n},o){this.http=new l_({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n,this._logger=o("HttpManagerApiDataSource")}setProvider(t){this._provider===t||t<1||(this._provider=t)}getProvider(){return this._provider}setFirmwareDistributionSalt(t){this._firmwareDistributionSalt===t||t.trim()===""||(this._firmwareDistributionSalt=t)}getFirmwareDistributionSalt(){return this._firmwareDistributionSalt}getAppList(t){const{targetId:r,firmwareVersionName:n}=t;return He(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(o=>this.mapApplicationDtoToApplication(o)).mapLeft(Qn)}getMcuList(){return He(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(Qn)}getDeviceVersion(t){const{targetId:r}=t;return He(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(Qn)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapFinalFirmwareDto(o)).mapLeft(Qn)}getFirmwareVersionById(t){return He(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(Qn)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapOsuFirmwareDto(o)).mapLeft(Qn)}getLatestFirmwareVersion(t){const{currentFinalFirmwareId:r,deviceId:n}=t;return He(()=>{const o=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:o}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:r,device_version:n,provider:this._provider,salt:o}})}).chain(o=>this.mapLatestFirmwareDto(o)).mapLeft(Qn)}getAppsByHash(t){const{hashes:r}=t;return He(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(Qn)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return He(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(o=>this.mapLanguagesDtoToLanguages(o)).mapLeft(Qn)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case ol.currency:return il.currency;case ol.plugin:return il.plugin;case ol.tool:return il.tool;case ol.swap:return il.swap}}mapApplicationDtoToApplication(t){return He(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return He(()=>Promise.resolve(t.map(r=>r===null?null:this.mapApplicationDto(r))))}mapApplicationDto(t){if(typeof t!="object"||typeof t.versionId!="number"||typeof t.versionName!="string"||t.versionDisplayName!==null&&typeof t.versionDisplayName!="string"||typeof t.version!="string"||t.currencyId!==null&&typeof t.currencyId!="string"||t.description!==null&&typeof t.description!="string"||t.applicationType!==null&&typeof t.applicationType!="string"||typeof t.dateModified!="string"||t.icon!==null&&typeof t.icon!="string"||t.authorName!==null&&typeof t.authorName!="string"||t.supportURL!==null&&typeof t.supportURL!="string"||t.contactURL!==null&&typeof t.contactURL!="string"||t.sourceURL!==null&&typeof t.sourceURL!="string"||t.compatibleWallets!==null&&typeof t.compatibleWallets!="string"||typeof t.hash!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmwareKey!="string"||typeof t.delete!="string"||typeof t.deleteKey!="string"||t.bytes!==null&&typeof t.bytes!="number"||t.warning!==null&&typeof t.warning!="string"||typeof t.isDevTools!="boolean"||t.category!==null&&typeof t.category!="number"||t.parent!==null&&typeof t.parent!="number"||t.parentName!==null&&typeof t.parentName!="string")throw new Error(`Incomplete application: ${JSON.stringify(t)}`);const{applicationType:r,hash:n,perso:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,...p}=t;return{...p,hash:n,perso:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return He(()=>Promise.resolve(t.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string"||typeof r.from_bootloader_version!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name,fromBootloaderVersion:r.from_bootloader_version,providers:r.providers}})))}mapDeviceVersionDto(t){return He(()=>{if(typeof t!="object"||typeof t.id!="number")throw new Error(`Incomplete device version: ${JSON.stringify(t)}`);const r={id:t.id};return Promise.resolve(r)})}mapFinalFirmwareDto(t){return He(()=>{if(typeof t!="object"||typeof t.id!="number"||typeof t.version!="string"||typeof t.perso!="string"||t.firmware!==null&&typeof t.firmware!="string"||t.firmware_key!==null&&typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||t.bytes!==null&&typeof t.bytes!="number"||!Array.isArray(t.mcu_versions))throw new Error(`Incomplete final firmware: ${JSON.stringify(t)}`);const r={id:t.id,version:t.version,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,bytes:t.bytes,mcuVersions:t.mcu_versions};return Promise.resolve(r)})}mapLatestFirmwareDto(t){return He(()=>{if(t.result==="null")return Promise.resolve(null);if(t.result!=="success"||!t.se_firmware_osu_version)throw new Error(`Latest firmware could not be retrieved: ${t.result}`);const r=t.se_firmware_osu_version;return Promise.resolve(r)}).chain(r=>r===null?He(()=>Promise.resolve(ft)):this.mapOsuFirmwareDto(r).map(n=>or(n)))}mapOsuFirmwareDto(t){return He(()=>{if(typeof t!="object"||typeof t.id!="number"||t.notes!==null&&typeof t.notes!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||typeof t.next_se_firmware_final_version!="number")throw new Error(`Incomplete latest firmware: ${JSON.stringify(t)}`);const r={id:t.id,notes:t.notes,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,nextFinalFirmware:t.next_se_firmware_final_version};return Promise.resolve(r)})}mapLanguagesDtoToLanguages(t){return He(()=>Promise.resolve(t.map(r=>this.mapLanguageDto(r))))}mapLanguageDto(t){if(typeof t!="object"||typeof t.language!="string"||typeof t.languagePackageVersionId!="number"||typeof t.version!="string"||typeof t.language_package_id!="number"||typeof t.apdu_install_url!="string"||typeof t.apdu_uninstall_url!="string"||typeof t.bytes!="number"||typeof t.date_creation!="string"||typeof t.date_last_modified!="string")throw new Error(`Incomplete language version: ${JSON.stringify(t)}`);return{language:t.language,languagePackageVersionId:t.languagePackageVersionId,version:t.version,languagePackageId:t.language_package_id,apduInstallUrl:t.apdu_install_url,apduUninstallUrl:t.apdu_uninstall_url,bytes:t.bytes,dateCreation:t.date_creation,dateLastModified:t.date_last_modified}}};E1=n8([Qe(),S1(0,Oe(jl.DmkConfig)),S1(1,Oe(Dt.LoggerPublisherServiceFactory))],E1);var i8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},o8=(e,t)=>(r,n)=>t(r,n,e);let C1=class{constructor(t){this.dataSource=t}getAppList(t){const r={targetId:t.targetId.toString(),firmwareVersionName:t.seVersion};return this.dataSource.getAppList(r)}getDeviceVersion(t){const r={targetId:t.targetId.toString()};return this.dataSource.getDeviceVersion(r)}getFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getFirmwareVersion(n)}getOsuFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getOsuFirmwareVersion(n)}getLatestFirmwareVersion(t,r){const n={currentFinalFirmwareId:t.id,deviceId:r.id};return this.dataSource.getLatestFirmwareVersion(n)}getNextFirmwareVersion(t){return this.dataSource.getFirmwareVersionById(t.nextFinalFirmware)}getLanguagePackages(t,r){const n={deviceId:t.id,currentFinalFirmwareId:r.id};return this.dataSource.getLanguagePackages(n)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(t){const r={hashes:t};return He(async({fromPromise:n,throwE:o})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(a){return a instanceof xd?o(a):o(new xd(a))}})}getProvider(){return this.dataSource.getProvider()}};C1=i8([Qe(),o8(0,Oe(jl.ManagerApiDataSource))],C1);var s8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},gm=(e,t)=>(r,n)=>t(r,n,e);let k1=class{constructor(t,r,n){this.sessionService=t,this.managerApiDataSource=r,this._logger=n("SetFirmwareDistributionSaltUseCase")}_logger;execute(t){if(t.trim()===""){this._logger.warn("Ignoring empty firmware distribution salt");return}const r=this.managerApiDataSource.getFirmwareDistributionSalt();if(t===r){this._logger.debug("Firmware distribution salt unchanged",{data:{salt:t}});return}this.managerApiDataSource.setFirmwareDistributionSalt(t);let n=0;for(const o of this.sessionService.getDeviceSessions()){const a=o.getDeviceSessionState();a.sessionStateType!==Ys.Connected&&a.firmwareUpdateContext!==void 0&&(o.setDeviceSessionState({...a,firmwareUpdateContext:void 0}),n++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:r,salt:t,invalidatedSessions:n}})}};k1=s8([Qe(),gm(0,Oe(dr.DeviceSessionService)),gm(1,Oe(jl.ManagerApiDataSource)),gm(2,Oe(Dt.LoggerPublisherServiceFactory))],k1);var a8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},R1=(e,t)=>(r,n)=>t(r,n,e);let _1=class{constructor(t,r){this.sessionService=t,this.managerApiDataSource=r}execute(t){for(const r of this.sessionService.getDeviceSessions()){const n=r.getDeviceSessionState();n.sessionStateType!==Ys.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};_1=a8([Qe(),R1(0,Oe(dr.DeviceSessionService)),R1(1,Oe(jl.ManagerApiDataSource))],_1);var l8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},c8=(e,t)=>(r,n)=>t(r,n,e);let $1=class{webSocketBaseUrl;constructor({webSocketUrl:t}){this.webSocketBaseUrl=t}setWebSocketUrl(t){this.webSocketBaseUrl===t||t.length===0||(this.webSocketBaseUrl=t)}getWebSocketUrl(){return this.webSocketBaseUrl}genuineCheck(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return Tt(new gF(t))}catch(r){return yt(new SF(r))}}};$1=l8([Qe(),c8(0,Oe(Kd.DmkConfig))],$1);var u8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},d8=(e,t)=>(r,n)=>t(r,n,e);let A1=class{constructor(t){this.dataSource=t}genuineCheck(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.genuineCheck(n)}installApp(t,r){const{perso:n,firmware:o,firmwareKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};return this.dataSource.installApp(u)}listInstalledApps(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.listInstalledApps(n)}uninstallApp(t,r){const{perso:n,delete:o,deleteKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};return this.dataSource.uninstallApp(u)}updateFirmware(t,r){const n={targetId:t.targetId.toString(),perso:r.perso,firmware:r.firmware,firmwareKey:r.firmwareKey};return this.dataSource.updateFirmware(n)}updateMcu(t,r){const n={targetId:t.targetId.toString(),version:r.version};return this.dataSource.updateMcu(n)}};A1=u8([Qe(),d8(0,Oe(Kd.SecureChannelDataSource))],A1);var f8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},p8=(e,t)=>(r,n)=>t(r,n,e);let T1=class{constructor(t){this.secureChannelDataSource=t}execute(t){this.secureChannelDataSource.setWebSocketUrl(t)}};T1=f8([Qe(),p8(0,Oe(Kd.SecureChannelDataSource))],T1);var h8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},L1=(e,t)=>(r,n)=>t(r,n,e);let I1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:o}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async a=>(await a.sendApdu(r,{abortTimeout:n,triggersDisconnection:o})).caseOf({Right:l=>l,Left:l=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:l}}),l}}),Left:a=>{throw this._logger.error("Error getting deviceSession",{data:{error:a}}),a}})}};I1=h8([Qe(),L1(0,Oe(dr.DeviceSessionService)),L1(1,Oe(Dt.LoggerPublisherServiceFactory))],I1);var m8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},ks=(e,t)=>(r,n)=>t(r,n,e);let O1=class{constructor(t,r,n,o,a,l){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=o,this._apduSenderServiceFactory=a,this._apduReceiverServiceFactory=l,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new mF("No transports provided, please check your configuration");for(const u of t){const d=this.addTransport(u);if(d.isLeft())throw d.extract()}}_transports=new Map;_logger;addTransport(t){const r=t({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(r)}addTransportInternal(t){return this.getTransport(t.getIdentifier()).isJust()?(this._logger.warn(`Transport ${t.getIdentifier()} already exists, please check your configuration`),yt(new hF(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),Tt(void 0))}getTransport(t){return Ar.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};O1=m8([Qe(),ks(0,Oe(Gi.TransportsInput)),ks(1,Oe(Gi.DmkConfig)),ks(2,Oe(Dt.LoggerPublisherServiceFactory)),ks(3,Oe(pB.DeviceModelDataSource)),ks(4,Oe(dr.ApduSenderServiceFactory)),ks(5,Oe(dr.ApduReceiverServiceFactory))],O1);const g8={ADD_LOG:"addLog"};function v8(e){return{startListeningCommand:()=>e.sendMessage(zi.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(zi.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(zi.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(zi.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(zi.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function y8(e){return{getProviderCommand:()=>e.sendMessage(zi.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(zi.SET_PROVIDER,JSON.stringify({provider:t}))}}let b8=0;function x8(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++b8}`,o=r.match(/.{1,2}/g)?.map(a=>parseInt(a,16))||[];return e.sendMessage(zi.SEND_APDU,JSON.stringify({sessionId:t,apdu:o,requestId:n})),n}}}const w8=e=>{try{const t=JSON.parse(e);return typeof t=="string"||t!==null&&typeof t=="object"?t:t===null?{}:JSON.stringify(t)}catch{return e}},S8=new Set(["debug","info","warning","error","fatal"]),E8=e=>{if(e===null||typeof e!="object")return!1;const{timestamp:t,tag:r,verbosity:n,message:o,payloadJSON:a}=e;return typeof t=="string"&&typeof r=="string"&&typeof o=="string"&&typeof n=="string"&&S8.has(n)&&(a===void 0||typeof a=="string")};function C8(e){let t;try{t=JSON.parse(e)}catch{return null}if(!E8(t))return null;const r=t.payloadJSON??"{}";return{timestamp:t.timestamp,tag:t.tag,verbosity:t.verbosity,message:t.message,payloadJSON:r,payload:w8(r)}}function k8(e,t){try{const{module:r}=JSON.parse(e);t(n=>new Set([...n,r]))}catch(r){console.error("Failed to parse moduleConnected payload",r)}}function R8(e,t){const r=C8(e);return r!==null?(t(r),!0):!1}function _8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function $8(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(o=>new Map(o).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function A8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function T8(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}const L8=e=>{try{const{protocol:t,host:r}=new URL(e);return(t==="http:"||t==="https:")&&r!==""}catch{return!1}};function I8(e){try{const t=JSON.parse(e);if(t===null)return null;if(typeof t!="object")return;const{url:r,sessionToken:n}=t;return typeof r!="string"||!L8(r)||n!==void 0&&typeof n!="string"?void 0:n===void 0?{url:r}:{url:r,sessionToken:n}}catch{return}}function O8(e,t){const r=I8(e);if(r===void 0){console.error("Ignored an invalid mockServerConfig payload");return}t(r)}function N8(e,t){try{const r=JSON.parse(e);t(n=>new Map(n).set(r.requestId,r))}catch(r){console.error("Failed to parse apduResponse payload",r)}}const P8=250;function D8(e){const[t,r]=x.useState([]),[n,o]=x.useState(new Set),[a,l]=x.useState([]),[u,d]=x.useState(new Map),[p,h]=x.useState([]),[m,y]=x.useState(!1),[w,E]=x.useState(!1),[S,C]=x.useState(null),[R,k]=x.useState(new Map),[$,A]=x.useState(null),D=x.useRef([]);x.useEffect(()=>{let H;const O=()=>{H=void 0;const U=D.current;D.current=[],U.length>0&&r(z=>[...z,...U].slice(-2e4))},{unsubscribe:L}=e.listenToMessages((U,z)=>{switch(H??=setTimeout(O,P8),U){case b5:k8(z,o);break;case Es.CONNECTED_DEVICES_UPDATE:_8(z,l);break;case Es.DEVICE_SESSION_STATE_UPDATE:$8(z,d);break;case Es.DISCOVERED_DEVICES_UPDATE:A8(z,h);break;case Es.PROVIDER_VALUE:T8(z,C);break;case Es.APDU_RESPONSE:N8(z,k);break;case Es.MOCK_SERVER_CONFIG:O8(z,A);break;case g8.ADD_LOG:R8(z,T=>D.current.push(T));break}});return()=>{L(),clearTimeout(H),D.current=[]}},[e]);const N=x.useMemo(()=>v8(e),[e]),P=x.useMemo(()=>y8(e),[e]),I=x.useMemo(()=>x8(e),[e]),re=x.useCallback(()=>{y(!0),h([]),N.startListeningCommand()},[N]),Z=x.useCallback(()=>{y(!1),h([]),N.stopListeningCommand()},[N]),ee=x.useCallback(()=>{E(!0),h([]),N.startDiscoveringCommand()},[N]),ne=x.useCallback(()=>{E(!1),h([]),N.stopDiscoveringCommand()},[N]),X=x.useCallback(()=>{D.current=[],r([])},[]),F=n.has(mw.LOGGER),V=n.has(mw.DMK_INSPECTOR);return{logs:t,connectedModules:n,connectedDevices:a,sessionStates:u,discoveredDevices:p,isListening:m,isActivelyDiscovering:w,isLoggerConnected:F,isInspectorConnected:V,providerValue:S,apduResponses:R,mockServer:$,sendMessage:e.sendMessage,clearLogs:X,startListening:re,stopListening:Z,startDiscovering:ee,stopDiscovering:ne,connectDevice:N.connectDeviceCommand,getProvider:P.getProviderCommand,setProvider:P.setProviderCommand,sendApdu:I.sendApduCommand}}const _g=e=>`devtools-panel-width-${e}`,j8=e=>{try{const t=Number(localStorage.getItem(_g(e)));return t>0?t:null}catch{return null}},vm=(e,t)=>{try{t===null?localStorage.removeItem(_g(e)):localStorage.setItem(_g(e),String(t))}catch{}},Dv=({name:e,defaultWidth:t,minWidth:r,maxWidth:n,edge:o,className:a="",children:l})=>{const[u,d]=x.useState(()=>j8(e)??t),p=y=>{y.preventDefault();const w=y.clientX,E=u;let S=E;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const C=k=>{const $=k.clientX-w;S=Math.min(n,Math.max(r,E+(o==="right"?$:-$))),d(S)},R=()=>{document.body.style.cursor="",document.body.style.userSelect="",vm(e,S),window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",R)};window.addEventListener("mousemove",C),window.addEventListener("mouseup",R)},h=y=>{const w=y.key==="ArrowRight"?16:y.key==="ArrowLeft"?-16:0;if(w===0)return;y.preventDefault();const E=Math.min(n,Math.max(r,u+(o==="right"?w:-w)));d(E),vm(e,E)},m=()=>{d(t),vm(e,null)};return v.jsxs("div",{className:`relative flex flex-col ${a}`,style:{flex:`0 1 ${u}px`,minWidth:r},children:[l,v.jsx("span",{role:"separator","aria-orientation":"vertical","aria-label":"Resize the panel","aria-valuenow":u,"aria-valuemin":r,"aria-valuemax":n,tabIndex:0,title:"Drag or use the arrow keys to resize, double-click to reset",onMouseDown:p,onKeyDown:h,onDoubleClick:m,className:`absolute inset-y-0 z-10 w-6 cursor-col-resize border-transparent hover:border-active focus-visible:border-active focus-visible:outline-none ${o==="right"?"-right-3 border-r-2":"-left-3 border-l-2"}`})]})},c_="relative w-320 min-w-160 shrink",Ml="flex h-32 items-center gap-6 overflow-hidden rounded-sm border border-muted-subtle bg-surface px-8 transition-colors hover:border-muted focus-within:border-active",zl="min-w-0 flex-1 bg-transparent font-mono! body-3 text-base outline-none placeholder:text-muted",Lo="flex size-24 shrink-0 cursor-pointer items-center justify-center rounded-xs text-muted transition-colors hover:bg-base-transparent-hover hover:text-base disabled:cursor-default disabled:text-disabled disabled:hover:bg-transparent",u_=/Mac|iPhone|iPad/.test(navigator.userAgent)?"⌘":"Ctrl+",d_="rounded-xs border border-muted px-4 font-mono! body-4 text-muted",M8="body-4-semi-bold text-muted uppercase",z8=e=>{const t=[{title:null,blocks:[]}],r=e.split(`
40
40
  `);let n=0;const o=()=>t[t.length-1];for(;n<r.length;){const a=r[n],l=a.match(/^```(\w*)/);if(l){const d=[];for(n++;n<r.length&&!r[n].startsWith("```");)d.push(r[n]),n++;n++,o().blocks.push(l[1]==="sequence"?{kind:"sequence",lines:d.filter(p=>p.trim())}:{kind:"code",text:d.join(`
41
41
  `)});continue}const u=a.match(/^#{1,4}\s+(.*)/);if(u)t.push({title:u[1].trim(),blocks:[]});else if(/^\s*[-*]\s+/.test(a)){const d=[];for(;n<r.length&&/^\s*[-*]\s+/.test(r[n]);)d.push(r[n].replace(/^\s*[-*]\s+/,"")),n++;o().blocks.push({kind:"list",items:d});continue}else if(a.trim()){const d=[a];for(;n+1<r.length&&r[n+1].trim()&&!/^(#|```|\s*[-*]\s)/.test(r[n+1]);)n++,d.push(r[n]);o().blocks.push({kind:"paragraph",text:d.join(" ")})}n++}return t.filter(a=>a.title!==null||a.blocks.length>0)},N1=({text:e})=>v.jsx(v.Fragment,{children:e.split(/(\*\*[^*]+\*\*|`[^`]+`|https?:\/\/[^\s)]+)/).map((t,r)=>t.startsWith("http")?v.jsx("a",{href:t,target:"_blank",rel:"noreferrer",className:"text-active underline",children:t},r):t.startsWith("**")&&t.endsWith("**")?v.jsx("strong",{children:t.slice(2,-2)},r):t.startsWith("`")&&t.endsWith("`")?v.jsx("code",{className:"font-mono! body-4",children:t.slice(1,-1)},r):t)}),F8=/\b(?!9000\b)[5-6][0-9a-f]{3}\b/i,B8=({line:e})=>{const t=e.match(/^\s*(App|Device)\s*->\s*(?:App|Device)\s*:\s*(.*)$/i),r=t?.[1]?.toLowerCase()==="app",n=t?.[2]??e;return v.jsxs("li",{className:`flex gap-8 font-mono! body-4 ${r?"":"pl-24"} ${F8.test(n)&&!r?"text-error":""}`,children:[v.jsx("span",{className:"shrink-0 text-muted",children:r?"App →":"← Device"}),v.jsx("span",{className:"min-w-0 break-words",children:n})]})},U8=({block:e})=>{switch(e.kind){case"paragraph":return v.jsx("p",{className:"body-3",children:v.jsx(N1,{text:e.text})});case"list":return v.jsx("ul",{className:"flex list-disc flex-col gap-4 pl-16 body-3",children:e.items.map((t,r)=>v.jsx("li",{children:v.jsx(N1,{text:t})},r))});case"sequence":return v.jsx("ol",{className:"flex flex-col gap-4 rounded-sm bg-muted px-12 py-8",children:e.lines.map((t,r)=>v.jsx(B8,{line:t},r))});case"code":return v.jsx("pre",{className:"overflow-x-auto rounded-sm bg-muted px-12 py-8 font-mono! body-4",children:e.text})}},V8=({markdown:e})=>v.jsx("div",{className:"flex flex-col gap-16",children:z8(e).map((t,r)=>{const n=t.blocks[0]?.kind==="paragraph"?t.blocks[0].text:"",o=t.title?.toLowerCase()==="result",a=/^\**failed/i.test(n);return v.jsxs("section",{className:`flex flex-col gap-8 ${o?"rounded-sm bg-muted px-12 py-10":""}`,children:[t.title&&v.jsxs("h3",{className:`flex items-center gap-8 ${M8}`,children:[o&&v.jsx("span",{className:`size-8 rounded-full ${a?"bg-(--color-light-red-500)":"bg-(--color-light-green-500)"}`}),t.title]}),t.blocks.map((l,u)=>v.jsx(U8,{block:l},u))]},r)})}),Ts="<redacted>",f_=String.raw`\b([A-Za-z0-9_-]*(?:token|secret|password|passphrase|api[_-]?key|private[_-]?key|seed|mnemonic)[A-Za-z0-9_-]*|authorization)`,W8=new RegExp(String.raw`${f_}(\\?["']?\s*[:=]\s*)(\\?["'])`,"gi"),H8=(e,t,r)=>{for(let n=t;n<e.length;n++){if(e.startsWith(r,n))return n;e[n]==="\\"&&n++}return-1},q8=e=>{let t="",r=0;for(const n of e.matchAll(W8)){const o=n.index+n[0].length;if(n.index<r)continue;const a=H8(e,o,n[3]);a<0||(t+=e.slice(r,o)+Ts,r=a)}return t+e.slice(r)},P1=(e,t)=>q8(t.reduce((r,n)=>r.replaceAll(n,Ts),e)).replace(/\b(authorization\s*:\s*)(?!<redacted>)[^\r\n"']+/gi,`$1${Ts}`).replace(/\b(bearer\s+)(?!<redacted>)[^\s"',;\\]+/gi,`$1${Ts}`).replace(/\b(basic\s+)(?!<redacted>)[A-Za-z0-9+/]{8,}={0,2}/gi,`$1${Ts}`).replace(new RegExp(String.raw`${f_}(["']?\s*[:=]\s*)(?!<redacted>|\\?["'])[^\s"',;&\\]+`,"gi"),`$1$2${Ts}`),G8=(e,t)=>{switch(e.kind){case"explain":return{...e,context:P1(e.context,t)};case"followUp":return{...e,question:P1(e.question,t)};case"createTicket":return e}},X8="body-4-semi-bold text-muted uppercase",ym="cursor-pointer rounded-sm bg-muted-transparent px-12 py-6 body-3-semi-bold hover:bg-muted-transparent-hover",Lu="cursor-pointer rounded-sm bg-accent px-12 py-6 body-3-semi-bold text-on-accent hover:bg-accent-hover",D1=({selected:e,disabled:t,onClick:r,children:n})=>v.jsx("button",{type:"button","aria-pressed":e,disabled:t,onClick:r,className:`cursor-pointer rounded-sm px-10 py-4 body-4 disabled:cursor-default disabled:opacity-50 ${e?"bg-active-subtle body-4-semi-bold text-active":"bg-muted-transparent text-muted hover:bg-muted-transparent-hover"}`,children:n}),bm=({title:e,children:t})=>v.jsxs("div",{className:"flex flex-col gap-12 p-16",children:[v.jsx("h3",{className:"heading-5-semi-bold",children:e}),t]}),Y8=({turn:e,running:t})=>v.jsxs("div",{className:"flex flex-col gap-12",children:[e.question&&v.jsx("p",{className:"self-end rounded-sm bg-muted px-12 py-8 body-3",children:e.question}),e.steps.length>0&&v.jsx("ul",{className:"flex flex-col gap-4 body-4 text-muted",children:e.steps.map((r,n)=>v.jsxs("li",{className:"flex items-center gap-8",children:[t&&n===e.steps.length-1?v.jsx(yl,{size:12}):v.jsx(Pd,{size:12}),r]},n))}),e.answer!==null?v.jsx(V8,{markdown:e.answer}):e.text&&v.jsx("p",{className:"body-3 whitespace-pre-wrap",children:e.text}),t&&e.steps.length===0&&!e.text&&v.jsxs("p",{className:"flex items-center gap-8 body-3 text-muted",children:[v.jsx(yl,{size:16}),"Starting Claude Code…"]}),e.error&&v.jsxs("div",{className:"flex flex-col gap-4 rounded-sm bg-muted px-12 py-10",children:[v.jsx("span",{className:"body-3-semi-bold text-error",children:"Claude stopped before finishing"}),v.jsx("span",{className:"font-mono! body-4 break-words text-muted",children:e.error})]})]}),K8=({ai:e,request:t,secrets:r})=>{const[n,o]=x.useState(null),[a,l]=x.useState(!1),[u,d]=x.useState([]),[p,h]=x.useState(null),[m,y]=x.useState(!1),[w,E]=x.useState(""),S=x.useRef(null),C=x.useRef(null),R=x.useCallback((O=!1)=>{e&&(o(null),e.status(O).then(o).catch(L=>o({ready:!1,error:String(L)})))},[e]);x.useEffect(()=>R(),[R]);const k=()=>{e?.status(!0).then(o).catch(()=>{})};x.useEffect(()=>()=>S.current?.(),[]);const $=O=>d(L=>[...L.slice(0,-1),O(L.at(-1))]),A=x.useCallback((O,L,U)=>{if(!e)return;S.current?.();const z={question:L,steps:[],text:"",answer:null,verdict:void 0,ticket:void 0,createsTicket:!1,error:null};d(T=>U?[z]:[...T,z]),U&&h(null),y(!0),C.current={aiRequest:O,turnQuestion:L},S.current=e.analyze(G8(O,r),T=>{switch(T.type){case"step":$(M=>({...M,steps:[...M.steps,T.text],createsTicket:M.createsTicket||T.createsTicket===!0}));break;case"text":$(M=>({...M,text:M.text+T.text}));break;case"done":$(M=>({...M,answer:T.answer,verdict:T.verdict,ticket:T.ticket})),h(T.sessionId),y(!1),S.current=null;break;case"error":$(M=>({...M,error:T.message})),y(!1),S.current=null;break}})},[e,r]),D=x.useRef(null),N=x.useCallback(O=>{D.current=O,A({kind:"explain",context:O.context,summary:O.summary,readCode:a},null,!0)},[A,a]),P=n?.ready===!0;x.useEffect(()=>{t&&P&&D.current?.id!==t.id&&N(t)},[t,P,N]);const I=()=>{const O=C.current;if(!O||O.aiRequest.kind==="explain"){N(D.current);return}d(L=>L.slice(0,-1)),A(O.aiRequest,O.turnQuestion,!1)},re=()=>{S.current?.(),S.current=null,y(!1),$(O=>({...O,error:O.answer===null?"Stopped.":null}))},Z=[...u].reverse().find(O=>O.verdict)?.verdict==="bug",ee=u.find(O=>O.ticket)?.ticket,ne=u.some((O,L)=>O.createsTicket&&O.answer===null&&!(m&&L===u.length-1)),X=n?.ready===!0&&n.canCreateTickets,F=()=>{p&&A({kind:"createTicket",sessionId:p},"Create a Jira ticket",!1)},V=()=>{const O=w.trim();!O||!p||(E(""),A({kind:"followUp",sessionId:p,question:O,readCode:a},O,!1))},H=e?n===null?v.jsxs("p",{className:"flex items-center gap-8 p-16 body-3 text-muted",children:[v.jsx(yl,{size:16}),"Checking Claude Code…"]}):n.ready?u.length===0?v.jsxs(bm,{title:"Select logs or APDUs, then press Explain with AI",children:[v.jsx("p",{className:"body-3 text-muted",children:"Claude explains what happened and why, step by step, and draws the exchange between the app and the device."}),v.jsx("span",{className:X8,children:"Skills it uses"}),v.jsx("div",{className:"flex flex-wrap gap-6",children:n.skills.map(O=>v.jsx("span",{className:"rounded-sm bg-muted-transparent px-8 py-2 font-mono! body-4 text-muted",children:O},O))})]}):v.jsxs("div",{className:"flex flex-col gap-20 p-16",children:[u.map((O,L)=>v.jsx(Y8,{turn:O,running:m&&L===u.length-1},L)),!m&&u.at(-1)?.error&&D.current&&v.jsx("button",{type:"button",className:`self-start ${Lu}`,onClick:I,children:"Retry"})]}):v.jsxs(bm,{title:"Sign in to Claude Code to use AI debugging",children:[v.jsx("p",{className:"body-3 text-muted",children:"The DevTools uses the Claude Code login on this computer. Nothing is sent until you press Explain with AI."}),v.jsx("span",{className:"body-3",children:"1. Install Claude Code"}),v.jsx("code",{className:"rounded-sm bg-muted px-10 py-6 font-mono! body-4",children:"npm install -g @anthropic-ai/claude-code"}),v.jsx("span",{className:"body-3",children:"2. Run it once to sign in"}),v.jsx("code",{className:"rounded-sm bg-muted px-10 py-6 font-mono! body-4",children:"claude"}),v.jsx("span",{className:"font-mono! body-4 break-words text-muted",children:n.error}),v.jsx("button",{type:"button",className:`self-start ${Lu}`,onClick:()=>R(!0),children:"Check again"})]}):v.jsx(bm,{title:"AI debugging needs the DevTools desktop app",children:v.jsx("p",{className:"body-3 text-muted",children:"It runs Claude Code on your computer, which this panel cannot do. Open the same session in the desktop DevTools."})});return v.jsx(Dv,{name:"ai",defaultWidth:400,minWidth:320,maxWidth:800,edge:"left",className:"border-l border-muted-subtle bg-surface",children:v.jsxs("aside",{className:"flex min-h-0 flex-1 flex-col",children:[v.jsxs("div",{className:"flex items-center gap-8 border-b border-muted-subtle px-16 py-12",children:[v.jsx(hv,{size:16,className:"text-active"}),v.jsx("h2",{className:"body-2-semi-bold",children:"AI debugging"}),D.current&&v.jsxs("span",{className:"truncate body-4 text-muted",children:["· ",D.current.summary]}),v.jsx("span",{className:"flex-1"}),m&&v.jsx("button",{type:"button",className:ym,onClick:re,children:"Stop"})]}),P&&v.jsxs("div",{className:"flex items-center gap-6 px-16 pt-12",children:[v.jsx(D1,{selected:!a,disabled:m,onClick:()=>l(!1),children:"Quick"}),n.canReadCode&&v.jsx(vt,{label:"Let Claude read DMK's source code to confirm the cause. Slower.",children:v.jsx(D1,{selected:a,disabled:m,onClick:()=>l(!0),children:"Read the code"})}),v.jsx("span",{className:"flex-1"}),v.jsx("span",{className:"body-4 text-muted",children:n.model})]}),v.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:H}),P&&p&&v.jsxs("div",{className:"flex items-center gap-8 border-t border-muted-subtle px-16 py-12",children:[v.jsx("div",{className:`flex-1 ${Ml}`,children:v.jsx("input",{className:zl,type:"text",placeholder:"Ask a follow-up…","aria-label":"Ask a follow-up question",value:w,disabled:m,onChange:O=>E(O.target.value),onKeyDown:O=>O.key==="Enter"&&V()})}),v.jsx(vt,{label:"Ask",children:v.jsx(sr,{"aria-label":"Ask",icon:uR,size:"xs",appearance:"transparent",className:"rounded-sm [&>svg]:text-active",disabled:m||!w.trim(),onClick:V})}),ee?v.jsxs("a",{href:ee.url,target:"_blank",rel:"noreferrer",className:`whitespace-nowrap ${ym}`,children:[ee.key," ↗"]}):Z?ne?v.jsx("span",{className:"body-4 text-muted",children:"The ticket may already exist: check Jira"}):X?v.jsx("button",{type:"button",className:`whitespace-nowrap ${Lu} disabled:cursor-default disabled:opacity-50`,disabled:m,onClick:F,children:"Create Jira ticket"}):v.jsxs(v.Fragment,{children:[v.jsx(vt,{label:"Connect Atlassian in Claude (claude.ai › Settings › Connectors) to create tickets",children:v.jsx("button",{type:"button",disabled:!0,className:`cursor-default whitespace-nowrap opacity-50 ${Lu}`,children:"Create Jira ticket"})}),v.jsx("button",{type:"button",className:`whitespace-nowrap ${ym}`,onClick:k,children:"Check again"})]}):null]})]})})},p_=({title:e,description:t,codeExample:r})=>v.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-16 overflow-auto p-24",children:[v.jsx(KD,{appearance:"muted",icon:g5,size:56}),v.jsx("h3",{className:"heading-4-semi-bold",children:e}),v.jsx("p",{className:"max-w-480 text-center body-2 text-muted",children:t}),v.jsx("pre",{className:"max-w-full overflow-auto rounded-md bg-muted p-16 font-mono! body-3",children:r})]}),Q8={b001:"getAppAndVersion",b006:"loadCertificate",b010:"editExternalAddressIdentifier / editExternalAddressScope / provideContact / registerIdentity",b0a7:"closeApp"},J8={e001:"getOsVersion",e010:"getBatteryStatus",e02e:"renameContact",e033:"deleteLanguagePack",e034:"listLanguagePack",e060:"createBackgroundImage",e061:"uploadBackgroundImageChunk",e062:"commitBackgroundImage",e063:"deleteBackgroundImage",e064:"getBackgroundImageSize",e065:"fetchBackgroundImageChunk",e066:"getBackgroundImageHash",e06a:"GetAppStorageInfo",e06b:"BackupAppStorage",e06c:"InitRestoreAppStorage",e06d:"RestoreAppStorage",e06e:"CommitRestoreAppStorage",e06f:"RequestMasterConsent",e0d8:"openApp",e0de:"listApps",e0df:"listApps"},Z8={Aleo:{e003:"GetAppConfig",e005:"getAddress",e006:"signFeeIntent / signNestedCall / signRootIntent",e007:"getViewKey",e008:"getTvk"},Bitcoin:{e100:"getExtendedPublicKey",e102:"registerWalletAddress",e103:"getWalletAddress",e104:"signPsbt",e105:"getMasterFingerprint",e110:"signMessage",f801:"continue"},"Bitcoin Cash":{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},"Bitcoin Gold":{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Concordium:{e000:"VerifyAddress",e001:"GetPublicKey",e002:"SignTransfer",e004:"SignCredentialDeployment",e022:"SetTrustedName",e023:"GetChallenge",e027:"SignPlt",e032:"SignTransferWithMemo",e040:"GetAppConfig"},Cosmos:{5500:"GetAppConfig",5502:"SignTransaction",5504:"GetAddress"},Dogecoin:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Ethereum:{e002:"getAddress",e004:"signTransaction / startTransaction / storeTransaction",e006:"getAppConfiguration",e008:"signPersonalMessage",e00a:"provideTokenInformation",e00c:"signEIP712",e012:"setExternalPlugin",e014:"provideNFTInformation",e016:"setPlugin",e01a:"sendEIP712StructDefinition",e01c:"sendEIP712StructImplem",e01e:"sendEIP712Filtering",e020:"getChallenge",e022:"provideTrustedName",e024:"provideEnum",e026:"provideTransactionInformation",e028:"provideTransactionFieldDescription",e02a:"provideProxyInfo",e030:"provideNetworkConfiguration",e032:"provideWeb3Check / web3CheckOptIn",e034:"signEIP7702Authorization",e036:"provideSafeAccount",e038:"provideGatedSigning"},Horizen:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Hyperliquid:{e002:"sendMetadata",e003:"sendAction",e004:"signActions"},InternetComputer:{1100:"GetVersion",1101:"GetAddress",1102:"SignTransaction",1103:"SignUpdateCall"},"Ledger Sync":{e003:"getAppName / getVersion",e005:"getSeedId",e006:"init",e007:"signBlockSignature / signBlockSingle",e008:"parseBlockSignature / parseSingle",e009:"setTrustedMember"},Litecoin:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Polkadot:{f901:"GetAddress",f902:"SignTransaction"},Solana:{e004:"getAppConfiguration",e005:"getPubKey",e006:"signTransaction",e007:"signOffChainMessage",e008:"signTransactionPreview",e009:"delayedSignTransaction",e00a:"signMessageGenericPreview",e00b:"promptUiDisplay",e00c:"finalizeGenericClearSign",e016:"ProvideInstructionDescriptor",e020:"getChallenge",e021:"provideTLVDescriptor",e022:"ProvideTLVTransactionInstructionDescriptor",e023:"provideTransactionCheck / transactionCheckOptIn",e024:"provideInstructionInfo",e025:"provideInstructionSubstructure",e026:"provideEnumVariant",e027:"provideTokenAccountState",e028:"provideAltResolution",e029:"provideTrustedName"},Tron:{e002:"GetAddress",e004:"signTransaction",e005:"signTransactionHash",e006:"GetAppConfiguration",e008:"signPersonalMessage",e00a:"GetECDHSecret"},XRP:{e002:"GetAddress",e004:"SignTransaction",e006:"GetAppConfig"},Zcash:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction / ZcashSaplingOutputCommit",e04a:"HashOutputFull / ProvideOutputFullChangePath",e050:"GetFullViewingKey",e051:"GetShieldedAddress",e052:"PcztHeader",e053:"PcztTransparentInput",e054:"PcztTransparentOutput",e055:"SignPcztTransparent",e056:"PcztOrchardAction",e057:"SignPcztOrchard",e058:"PcztIronwoodAction",e059:"SignPcztIronwood",e0c4:"getAppConfig"}},eU={9e3:"OK",5501:"Refused",5502:"PIN not set",5515:"Locked",6807:"App not found",6985:"Refused","6d00":"INS not supported","6e00":"CLA not supported"},jv=e=>eU[e]??"",j1=e=>e.toLowerCase().match(/.{1,2}/g)??[],h_="OS",M1=e=>String.fromCharCode(...e.map(t=>parseInt(t,16))),tU=(e,t)=>{if(t.startsWith("b0"))return Q8[t];if(e!==void 0)return Iv(e)?J8[t]:Z8[e]?.[t]},rU=(e,t)=>t.startsWith("b0")||e!==void 0&&Iv(e)?h_:e,nU=(e,t,r,n)=>t==="b001"&&n[0]==="01"?M1(n.slice(2,2+parseInt(n[1]??"0",16))):t==="b0a7"?"BOLOS":t==="e0d8"&&(e===void 0||Iv(e))?M1(r.slice(5)):e,iU=e=>typeof e=="object"&&e!==null&&e.type==="apdu-exchange"&&typeof e.sessionId=="string"&&typeof e.apdu=="string"&&typeof e.response=="string",z1=new WeakMap;let oU=0;const sU=e=>{const t=new Map;return e.flatMap(r=>{if(!iU(r.payload))return[];const n=z1.get(r);if(n)return t.set(n.exchange.sessionId,n.openApp),[n.exchange];const{sessionId:o}=r.payload,a=j1(r.payload.apdu),l=j1(r.payload.response),u=l.slice(-2).join(""),d=a.slice(0,2).join(""),p=t.get(o),h=u==="9000"?nU(p,d,a,l.slice(0,-2)):p;t.set(o,h);const m={id:String(oU++),timestamp:r.timestamp,sessionId:o,layer:rU(p,d),command:tU(p,d)??a.slice(0,2).join(" "),sent:a,received:l,statusWord:u};return z1.set(r,{exchange:m,openApp:h}),[m]})},m_=(e,t,r,n,o)=>{const a=x.useRef(null),l=x.useRef(!1),u=x.useRef(e);u.current=e;const d=x.useRef(t);d.current=t;const p=x.useRef(r);p.current=r;const h=x.useRef(n);h.current=n;const m=x.useRef(o);m.current=o,x.useEffect(()=>{const E=()=>{const C=a.current;C?.moved&&(document.body.style.userSelect="",l.current=!0,m.current(C.last)),a.current=null},S=C=>{l.current&&(l.current=!1,C.stopPropagation(),C.preventDefault())};return window.addEventListener("mouseup",E),window.addEventListener("click",S,!0),()=>{window.removeEventListener("mouseup",E),window.removeEventListener("click",S,!0)}},[]);const y=x.useCallback((E,S)=>{const C=u.current(E);S.button!==0||S.shiftKey||C===void 0||(l.current=!1,a.current={anchor:C,last:C,adding:!p.current.has(C),base:new Set(p.current),moved:!1})},[]),w=x.useCallback(E=>{const S=a.current,C=u.current(E);if(!S||C===void 0||C===S.anchor&&!S.moved)return;const R=d.current(S.anchor);if(R<0)return;S.last=C,S.moved||(S.moved=!0,window.getSelection()?.removeAllRanges(),document.body.style.userSelect="none");const k=new Set(S.base);for(let $=Math.min(R,E);$<=Math.max(R,E);$++){const A=u.current($);A!==void 0&&(S.adding?k.add(A):k.delete(A))}h.current(k)},[]);return{onRowMouseDown:y,onRowMouseEnter:w}};function Mv(e){const t=e.trim();if(!t)return[];const r=[],n=/(-?)\/([^/]+)\/|(\S+)/g;let o;for(;(o=n.exec(t))!==null;)if(o[2]!==void 0){const a=o[1]==="-",l=o[2];try{const u=new RegExp(l,"i");r.push({type:"regex",pattern:u,exclude:a})}catch{const u=o[0],d=u.startsWith("-"),p=d?u.slice(1):u;p&&r.push({type:"keyword",value:p.toLowerCase(),exclude:d})}}else if(o[3]!==void 0){const a=o[3],l=a.startsWith("-"),u=l?a.slice(1):a;u&&r.push({type:"keyword",value:u.toLowerCase(),exclude:l})}return r}function aU(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function lU(e){return[e.tag,e.message,aU(e.payload)].join(" ")}function F1(e,t){return e.type==="keyword"?t.toLowerCase().includes(e.value):e.pattern.test(t)}function g_(e,t){if(t.length===0)return!0;const r=lU(e),n=t.filter(a=>!a.exclude),o=t.filter(a=>a.exclude);for(const a of n)if(!F1(a,r))return!1;for(const a of o)if(F1(a,r))return!1;return!0}const v_=({onClick:e,enabled:t,up:r=!1})=>v.jsx(vt,{label:"Scroll to latest logs",side:"left",className:`absolute right-16 bottom-16 transition-[opacity,visibility] duration-300 ${t?"invisible opacity-0":"visible opacity-100"}`,children:v.jsx(sr,{"aria-label":"Scroll to latest logs",icon:r?uR:u5,appearance:"accent",size:"sm",onClick:e,className:"shadow-md"})}),cU=4,y_=e=>{const t=x.useRef(null),r=x.useRef(null),[n,o]=x.useState(!0),a=x.useRef(!0),l=x.useCallback(p=>{a.current=p,o(p)},[]),u=x.useCallback(()=>{const p=t.current;p&&(p.scrollTop=p.scrollHeight)},[]);x.useLayoutEffect(()=>{e&&u()},[e,u]);const d=x.useCallback(()=>{const p=t.current;if(!p)return;const h=p.scrollHeight-p.clientHeight-p.scrollTop<=cU;h!==a.current&&l(h)},[l]);return x.useEffect(()=>{const p=r.current;if(!p||!e)return;const h=new MutationObserver(()=>{a.current&&u()});return h.observe(p,{childList:!0}),()=>h.disconnect()},[e,u]),{containerRef:t,contentRef:r,onScroll:d,atBottom:n,setAtBottom:l,scrollToBottom:u}},b_=({d:e,size:t=16,className:r})=>v.jsx("svg",{width:t,height:t,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",className:r,"aria-hidden":"true",children:v.jsx("path",{d:e})}),uU=e=>v.jsx(b_,{...e,d:"M5.667 3v10m4.666-10v10"}),dU=e=>v.jsx(b_,{...e,d:"M4.667 2.667v10.666L13 8z"}),x_=({paused:e,onToggle:t})=>v.jsx(vt,{label:e?"Resume incoming logs":"Pause incoming logs",side:"bottom",children:v.jsx(sr,{"aria-label":e?"Resume incoming logs":"Pause incoming logs",icon:e?dU:uU,size:"xs",appearance:"transparent",className:`rounded-sm ${e?"bg-active-subtle hover:bg-active-subtle-hover [&>svg]:text-active":""}`,onClick:t})});function B1(e,t){return e.type==="keyword"?t.toLowerCase().includes(e.value):e.pattern.test(t)}function fU(e,t){if(t.length===0)return!0;const r=t.filter(o=>!o.exclude),n=t.filter(o=>o.exclude);for(const o of r)if(!B1(o,e))return!1;for(const o of n)if(B1(o,e))return!1;return!0}const U1=({text:e,label:t})=>{const[r,n]=x.useState(!1);return v.jsx(vt,{label:t,children:v.jsx(sr,{"aria-label":t,icon:r?Pd:dR,size:"xs",appearance:"no-background",onClick:()=>{navigator.clipboard.writeText(e).then(()=>{n(!0),setTimeout(()=>n(!1),1500)})}})})},V1=5,$g=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,hour12:!1}),pU=e=>e==="9000"?{bar:"bg-(--color-light-green-500)",text:"text-success"}:e==="5515"?{bar:"bg-(--color-light-yellow-500)",text:"text-warning"}:{bar:"bg-(--color-light-red-500)",text:"text-error"},hU=e=>[e.command,e.layer,e.sent.join(" "),e.sent.join(""),e.received.join(" "),e.received.join(""),jv(e.statusWord)].join(" "),mU=e=>`[${e.timestamp}] [${e.layer??"unknown app"}] ${e.command} | => ${e.sent.join("")} | <= ${e.received.join("")}`,gU=({exchange:e,index:t,open:r,onToggle:n,selected:o,onSelect:a,onRowMouseDown:l,onRowMouseEnter:u})=>{const d=pU(e.statusWord);return v.jsxs("div",{className:`flex gap-8 px-8 py-2 ${o?"bg-active-subtle":""}`,onMouseDown:p=>l(t,p),onMouseEnter:()=>u(t),children:[v.jsx("div",{className:"flex shrink-0 pt-4",children:v.jsx(Qg,{"aria-label":"Select this APDU",checked:o,className:"size-16",onClick:p=>a(t,p.shiftKey)})}),v.jsx("span",{className:`w-4 shrink-0 rounded-full ${d.bar}`}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>n(e.id),className:"flex w-full cursor-pointer items-center gap-12 rounded-xs px-8 py-2 text-left font-mono! body-3 text-base hover:bg-base-transparent-hover",children:[v.jsx(Nd,{size:12,className:`shrink-0 text-muted transition-transform ${r?"rotate-90":""}`}),v.jsx("span",{className:"text-muted",children:$g(e.timestamp)}),v.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-8",children:[v.jsx(yg,{size:"sm",appearance:e.layer===h_?"accent-subtle":"gray",label:e.layer??"Unknown",className:"max-w-128 shrink-0"}),v.jsx("span",{className:"truncate",children:e.command})]}),v.jsxs("span",{className:"body-4 whitespace-nowrap text-muted",children:[e.sent.length," B → ",e.received.length," B"]}),v.jsxs("span",{className:`w-128 truncate ${d.text}`,children:[e.statusWord," ",jv(e.statusWord)]})]}),r&&v.jsxs("div",{className:"my-4 flex flex-col gap-8 rounded-sm bg-muted px-12 py-8 font-mono! body-3",children:[v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsxs("span",{className:"body-4-semi-bold text-muted uppercase",children:["Sent · ",e.sent.length," B"]}),v.jsx("span",{className:"flex-1"}),v.jsx(U1,{text:e.sent.join(""),label:"Copy sent bytes"})]}),v.jsxs("p",{className:"break-all",children:[e.sent.slice(0,V1).join(" ")," ",v.jsx("span",{className:"text-muted",children:e.sent.slice(V1).join(" ")})]}),v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsxs("span",{className:"body-4-semi-bold text-muted uppercase",children:["Received · ",e.received.length," B"]}),v.jsx("span",{className:"flex-1"}),v.jsx(U1,{text:e.received.join(""),label:"Copy received bytes"})]}),v.jsx("p",{className:"break-all",children:e.received.join(" ")})]})]})]})},vU=Ee.memo(gU,(e,t)=>e.exchange.id===t.exchange.id&&e.index===t.index&&e.open===t.open&&e.onToggle===t.onToggle&&e.selected===t.selected&&e.onSelect===t.onSelect&&e.onRowMouseDown===t.onRowMouseDown&&e.onRowMouseEnter===t.onRowMouseEnter),yU=({exchanges:e,clearedUpTo:t,onClear:r,onExplain:n})=>{const[o,a]=x.useState(""),[l,u]=x.useState(null),[d,p]=x.useState(new Set),h=x.useMemo(()=>{const O=l??e;return t===void 0?O:O.filter(L=>Number(L.id)>t)},[l,e,t]),m=x.useMemo(()=>{const O=Mv(o);return O.length===0?h:h.filter(L=>fU(hU(L),O))},[h,o]),[y,w]=x.useState(new Set),E=x.useRef(m);E.current=m;const S=x.useRef(null),C=x.useCallback((O,L)=>{const U=E.current,z=U[O];if(!z)return;const T=U.findIndex(({id:M})=>M===S.current);S.current=z.id,w(M=>{const te=new Set(M);if(L&&T>=0)for(let le=Math.min(T,O);le<=Math.max(T,O);le++)te.add(U[le].id);else te.delete(z.id)||te.add(z.id);return te})},[]),{onRowMouseDown:R,onRowMouseEnter:k}=m_(O=>E.current[O]?.id,O=>E.current.findIndex(L=>L.id===O),y,w,O=>{S.current=O}),$=()=>{w(new Set),S.current=null},A=h.filter(({id:O})=>y.has(O)),D=()=>{const O=e.at(-1);O&&r(Number(O.id)),u(L=>L&&[])},N=()=>{const O=new Blob([JSON.stringify(m,null,2)],{type:"application/json"}),L=URL.createObjectURL(O),U=document.createElement("a");U.href=L,U.download=`apdu-${new Date().toISOString()}.json`,U.click(),URL.revokeObjectURL(L)},P=l!==null,{containerRef:I,contentRef:re,onScroll:Z,atBottom:ee,setAtBottom:ne,scrollToBottom:X}=y_(!P),F=x.useCallback(O=>{ne(!1),p(L=>{const U=new Set(L);return U.delete(O)||U.add(O),U})},[ne]),V=()=>{ne(!0),X()},H=h.length-m.length;return v.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-8",children:[v.jsxs("div",{className:"flex flex-wrap items-center gap-x-12 gap-y-8",children:[v.jsx("div",{className:c_,children:v.jsx("div",{className:Ml,children:v.jsx("input",{className:zl,type:"text",placeholder:"Filter","aria-label":"Filter APDUs",value:o,onChange:O=>a(O.target.value)})})}),v.jsx("span",{className:"flex-1"}),v.jsxs("span",{className:"font-mono! body-4 whitespace-nowrap text-muted",children:[P&&v.jsx("span",{className:"text-warning",children:"paused · "}),h.length," ",h.length===1?"exchange":"exchanges",H>0&&` · ${H} filtered out`]}),v.jsxs("div",{className:"flex gap-6",children:[v.jsx(x_,{paused:P,onToggle:()=>u(P?null:e)}),v.jsx(vt,{label:"Clear APDUs",side:"bottom",children:v.jsx(sr,{"aria-label":"Clear APDUs",icon:gR,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:D})}),v.jsx(vt,{label:"Export APDUs",side:"bottom",children:v.jsx(sr,{"aria-label":"Export APDUs",icon:fR,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:N})})]})]}),v.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[v.jsx("div",{ref:I,className:"min-h-0 flex-1 overflow-auto",onScroll:Z,children:v.jsxs("div",{ref:re,children:[m.length===0?v.jsx("p",{className:"p-24 text-center body-2 text-muted",children:"No APDU exchanged yet"}):m.map((O,L)=>v.jsx(vU,{exchange:O,index:L,open:d.has(O.id),onToggle:F,selected:y.has(O.id),onSelect:C,onRowMouseDown:R,onRowMouseEnter:k},O.id)),!P&&m.length>0&&v.jsx("div",{className:`flex h-24 items-center justify-center gap-4 ${ee?"":"invisible"}`,"aria-label":ee?"Following new APDUs":void 0,children:["","[animation-delay:200ms]","[animation-delay:400ms]"].map(O=>v.jsx("span",{className:`size-4 animate-pulse rounded-full bg-muted-strong ${O}`},O))})]})}),v.jsx(v_,{enabled:ee,onClick:V})]}),A.length>0&&v.jsx(xR,{label:`${A.length} ${A.length===1?"APDU":"APDUs"} selected`,detail:`${$g(A[0].timestamp)} → ${$g(A.at(-1).timestamp)} · shift-click to extend`,onClear:$,onExplain:()=>n({context:A.map(mU).join(`
42
42
  `),summary:`${A.length} ${A.length===1?"APDU":"APDUs"}`})})]})},Iu=(e=[])=>e.map(t=>t.toString(16).padStart(2,"0")).join(""),bU=[{label:"Get app & version",apdu:"B001000000"},{label:"Get OS version",apdu:"E001000000"}],xU=({sessionId:e,onSend:t,responses:r})=>{const[n,o]=x.useState(""),[a,l]=x.useState(null),[u,d]=x.useState(null),p=y=>{const w=y.replace(/\s/g,"").toUpperCase();if(!/^[0-9A-F]*$/.test(w)||w.length%2!==0){l("Invalid hex string (e.g., E0C4000000)");return}d(t(e,w))},h=u?r.get(u):null,m=a??(h&&!h.success?h.error:null);return v.jsxs("div",{className:"flex flex-col gap-8",children:[v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsx("span",{className:"flex-1 body-4-semi-bold text-muted uppercase",children:"APDU"}),bU.map(y=>v.jsx("button",{type:"button",onClick:()=>{o(y.apdu),l(null),p(y.apdu)},className:"cursor-pointer rounded-full bg-muted-transparent px-8 py-2 body-4 text-base hover:bg-muted-transparent-hover",children:y.label},y.apdu))]}),v.jsxs("div",{className:"flex gap-8",children:[v.jsx("div",{className:`flex-1 ${Ml}`,children:v.jsx("input",{className:zl,type:"text",placeholder:"APDU hex (e.g., E0C4000000)","aria-label":"APDU to send",value:n,onChange:y=>{o(y.target.value),l(null)},onKeyDown:y=>y.key==="Enter"&&n.trim()&&p(n)})}),v.jsx(vt,{label:"Send APDU",children:v.jsx(sr,{"aria-label":"Send APDU",icon:h5,size:"xs",appearance:"transparent",className:"rounded-sm [&>svg]:text-active",onClick:()=>p(n),disabled:!n.trim()})})]}),m&&v.jsx("p",{className:"body-3 text-error",children:m}),!m&&h?.success&&v.jsxs("p",{className:"flex flex-wrap items-baseline gap-x-8 font-mono! body-3",children:[v.jsxs("span",{className:Iu(h.statusCode)==="9000"?"text-success":"text-error",children:[Iu(h.statusCode)," ",jv(Iu(h.statusCode))]}),h.data&&h.data.length>0&&v.jsx("span",{className:"break-all text-muted",children:Iu(h.data)})]})]})},wU={nanoS:Vu,nanoSP:Vu,nanoX:Vu,stax:mR,flex:pR,apexp:hR},zv=({modelId:e,className:t=""})=>{const r=wU[e]??d5;return v.jsx(r,{size:20,className:`shrink-0 text-muted ${t}`})},Fv="MOCKSERVER",SU=800,w_=e=>e===Fv?"Mock server":e,S_=e=>!e||e.deviceStatus!=="NOT CONNECTED",E_=e=>{const[t,r]=x.useState(e);return x.useEffect(()=>{if(e!=="BUSY"){r(e);return}const n=setTimeout(()=>r(e),SU);return()=>clearTimeout(n)},[e]),t},EU={CONNECTED:"bg-(--color-light-green-500)",LOCKED:"bg-(--color-light-yellow-500)",BUSY:"bg-(--color-light-decorative-blue-500)","NOT CONNECTED":"bg-muted-strong"},CU={CONNECTED:"success",LOCKED:"warning",BUSY:"accent-subtle","NOT CONNECTED":"error"},kU=({device:e,state:t,exchanges:r,onSendApdu:n,apduResponses:o,clearedUpTo:a,onClear:l,onExplain:u})=>{const d=t&&"currentApp"in t?t:void 0,p=E_(t?.deviceStatus??"");return v.jsxs("div",{className:"flex min-w-320 flex-1 flex-col gap-16 p-16",children:[v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsx(zv,{modelId:e.modelId}),v.jsx("h4",{className:"heading-5-semi-bold",children:e.name||e.modelId}),p&&v.jsx(yg,{size:"sm",appearance:CU[p]??"gray",label:p}),v.jsx(yg,{size:"sm",appearance:"gray",label:w_(e.transport)})]}),v.jsxs("dl",{className:"grid grid-cols-[120px_1fr] gap-x-12 gap-y-6 body-3",children:[v.jsx("dt",{className:"text-muted",children:"Session ID"}),v.jsx("dd",{className:"truncate font-mono!",children:e.sessionId}),v.jsx("dt",{className:"text-muted",children:"Model"}),v.jsx("dd",{children:e.modelId}),d?.currentApp&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{className:"text-muted",children:"Current app"}),v.jsxs("dd",{children:[d.currentApp.name," ",v.jsx("span",{className:"font-mono! text-muted",children:d.currentApp.version})]})]}),d?.firmwareVersion&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{className:"text-muted",children:"Firmware"}),v.jsx("dd",{className:"font-mono!",children:d.firmwareVersion.os})]}),d?.batteryStatus&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{className:"text-muted",children:"Battery"}),v.jsxs("dd",{children:[d.batteryStatus.level," %"]})]})]}),S_(t)&&v.jsx(xU,{sessionId:e.sessionId,onSend:n,responses:o},`sender-${e.sessionId}`),v.jsx(yU,{exchanges:r,clearedUpTo:a,onClear:l,onExplain:u},`list-${e.sessionId}`)]})},RU=({device:e,onConnect:t})=>v.jsxs("div",{className:"flex items-center gap-10 rounded-sm px-12 py-8 hover:bg-base-transparent-hover",children:[v.jsx(zv,{modelId:e.deviceModel.model}),v.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[v.jsx("span",{className:"truncate body-3-semi-bold",children:e.name||e.deviceModel.name}),v.jsxs("span",{className:"truncate font-mono! body-4 text-muted",children:[e.transport,e.rssi!==void 0&&e.rssi!==null&&` · ${e.rssi} dBm`]})]}),v.jsx("button",{type:"button",onClick:t,className:"cursor-pointer rounded-sm bg-muted-transparent px-8 py-4 body-4-semi-bold hover:bg-muted-transparent-hover",children:"Connect"})]}),xm="body-4-semi-bold text-muted uppercase",W1="cursor-pointer rounded-sm bg-muted-transparent px-8 py-4 body-4-semi-bold hover:bg-muted-transparent-hover disabled:cursor-default disabled:text-disabled",_U=({device:e,state:t,selected:r,onSelect:n})=>{const o=E_(t?.deviceStatus??"CONNECTED"),a=t&&"currentApp"in t?t.currentApp?.name:void 0;return v.jsxs("button",{type:"button",onClick:n,className:`flex cursor-pointer items-center gap-10 rounded-sm px-12 py-8 text-left ${r?"bg-active-subtle":"hover:bg-base-transparent-hover"} ${S_(t)?"":"opacity-60"}`,children:[v.jsx(zv,{modelId:e.modelId}),v.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[v.jsx("span",{className:"truncate body-3-semi-bold",children:e.name||e.modelId}),v.jsxs("span",{className:"truncate font-mono! body-4 text-muted",children:[w_(e.transport),a&&` · ${a}`]})]}),v.jsx("span",{title:o,className:`size-8 shrink-0 rounded-full ${EU[o]??"bg-muted-strong"}`})]})},$U=({devices:e,sessionStates:t,selectedSessionId:r,onSelect:n,discoveredDevices:o,isListening:a,isActivelyDiscovering:l,startListening:u,stopListening:d,startDiscovering:p,stopDiscovering:h,connectDevice:m,mockServer:y})=>{const w=e.some(E=>E.transport===Fv);return v.jsx(Dv,{name:"sessions",defaultWidth:288,minWidth:200,maxWidth:480,edge:"right",className:"border-r border-muted-subtle",children:v.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-16 overflow-auto p-12",children:[v.jsxs("section",{className:"flex flex-col gap-4",children:[v.jsxs("span",{className:`px-4 pb-4 ${xm}`,children:["Sessions · ",e.length]}),e.length===0&&v.jsx("p",{className:"px-4 body-3 text-muted",children:"No device connected yet."}),e.map(E=>v.jsx(_U,{device:E,state:t.get(E.sessionId),selected:E.sessionId===r,onSelect:()=>n(E.sessionId)},E.sessionId))]}),v.jsxs("section",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex items-center gap-6 px-4 pb-4",children:[v.jsx("span",{className:`flex-1 ${xm}`,children:"Discovered"}),v.jsx("button",{type:"button",className:W1,onClick:a?d:u,disabled:l,children:a?"Stop":"Listen"}),v.jsx("button",{type:"button",className:W1,onClick:l?h:p,disabled:a,children:l?"Stop":"Discover"})]}),(a||l)&&o.length===0&&v.jsxs("p",{className:"flex items-center gap-8 px-4 body-3 text-muted",children:[v.jsx(yl,{size:16}),a?"Listening…":"Discovering…"]}),o.map(E=>v.jsx(RU,{device:E,onConnect:()=>m(E.id)},E.id))]}),w&&v.jsxs("section",{className:"mt-auto flex flex-col gap-6 border-t border-muted-subtle px-4 pt-12",children:[v.jsx("span",{className:xm,children:"Mock server"}),y?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"truncate font-mono! body-3",children:y.url}),v.jsx("span",{className:"truncate font-mono! body-4 text-muted",children:y.sessionToken?`Session ${y.sessionToken.slice(0,8)}…`:"No session token shared"})]}):v.jsxs("p",{className:"body-3 text-muted",children:["Pass ",v.jsx("code",{children:"mockServer"})," to"," ",v.jsx("code",{children:"DevToolsDmkInspector"})," to see the device screens."]})]})]})})},Xu=(e,t)=>({label:e,touch:!1,speculos:!0,screenWidth:128,screenHeight:t,lightScreen:!1}),AU={nanoS:{...Xu("Nano S",32),speculos:!1},nanoSP:Xu("Nano S Plus",64),nanoX:Xu("Nano X",64),stax:{label:"Stax",touch:!0,speculos:!0,screenWidth:400,screenHeight:672,lightScreen:!0},flex:{label:"Flex",touch:!0,speculos:!0,screenWidth:480,screenHeight:600,lightScreen:!0},apexp:{label:"Apex",touch:!0,speculos:!0,screenWidth:300,screenHeight:400,lightScreen:!0}},TU=Xu("Device",64),LU=e=>AU[e]??TU,IU=e=>e?.status===409,OU=(e,t)=>({screenshot:async()=>{try{return await e.getScreenshot(t)}catch(r){if(IU(r))return null;throw r}},idle:async()=>({kind:"os-info",device:await e.getDevice(t)}),pressButton:(r,n)=>e.pressButton(t,r,n),touch:(r,n,o)=>e.touchScreen(t,r,n,o),openApp:async r=>{const n=new TextEncoder().encode(r);if(n.length>255)throw new Error(`App name too long to open: ${r}`);const{response:o}=await e.sendApdu(t,Uint8Array.from([224,216,0,0,n.length,...n])),a=o.slice(-4);if(a!=="9000")throw new Error(`Could not open ${r} (${a})`)}}),NU=150;function C_(e){const t=x.useRef(null),r=x.useRef(null),n=x.useRef(e);n.current=e;const o=x.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),a=x.useCallback(u=>{if(!n.current||t.current)return!1;const d={target:u,pressed:!1};return t.current=d,r.current=setTimeout(()=>{d.pressed=!0,n.current?.(u,"press")},NU),!0},[]),l=x.useCallback(()=>{const u=t.current;return u?(t.current=null,o(),n.current?.(u.target,u.pressed?"release":"press-and-release"),!0):!1},[o]);return x.useEffect(()=>()=>{const u=t.current;t.current=null,o(),u?.pressed&&n.current?.(u.target,"release")},[o]),x.useMemo(()=>({hold:a,release:l}),[a,l])}const PU=e=>C_(e),DU=2e3;function jU(e,t){const[r,n]=x.useState();return x.useEffect(()=>{let o=!1,a;if(n(void 0),!t)return;const l=()=>{e.getDevice(t).then(u=>{o||n(u)},()=>{o||(n(null),a=setTimeout(l,DU))})};return l(),()=>{o=!0,clearTimeout(a)}},[e,t]),r}const MU="BOLOS",zU=1e4,FU=e=>(e.apps??[]).filter(({name:t})=>t!==MU),BU=e=>`https://cdn.live.ledger.com/icons/${e.toLowerCase().replaceAll(" ","_")}.png`;function UU(e){const[t,r]=x.useState(),[n,o]=x.useState(),a=x.useRef(void 0);x.useEffect(()=>()=>clearTimeout(a.current),[]);const l=x.useCallback(u=>{!e||t||(r(u),o(void 0),e(u).then(()=>{a.current=setTimeout(()=>{r(void 0),o(`${u} opened but its screen never showed up`)},zU)},d=>{r(void 0),o(d instanceof Error?d.message:String(d))}))},[e,t]);return{opening:t,error:n,open:l}}const VU=500,WU=2e3,HU=3,qU=e=>e instanceof Error?e.message:String(e);function GU(e,t,r){const[n,o]=x.useState({kind:"loading"}),a=x.useRef(null),l=x.useRef(!1),u=x.useRef(!1);u.current=n.kind==="image";const d=x.useRef(0),p=x.useRef(0),h=x.useCallback(S=>{u.current&&++d.current<=HU||o({kind:"error",message:qU(S)})},[]),m=x.useCallback(()=>{a.current&&(r.releaseImageSource?.(a.current),a.current=null)},[r]),y=x.useRef(()=>{}),w=x.useMemo(()=>{const S=C=>{C.then(()=>y.current()).catch(h)};return{pressButton:(C,R)=>S(e.pressButton(C,R)),touch:(C,R,k)=>S(e.touch(C,R,k))}},[e,h]),E=x.useCallback(async()=>{if(l.current)return;l.current=!0;const S=p.current,C=()=>S!==p.current;try{const R=await e.screenshot();if(C())return;if(d.current=0,R){const k=await r.toImageSource(R);if(C()){r.releaseImageSource?.(k);return}k!==a.current&&(m(),a.current=k),o($=>$.kind==="image"&&$.src===k&&$.input===w?$:{kind:"image",src:k,input:w})}else{const k=await e.idle?.();if(C())return;m(),o(k??{kind:"error",message:"No screen to capture"})}}catch(R){C()||h(R)}finally{l.current=!1}},[e,r,w,h,m]);return y.current=()=>{E()},x.useEffect(()=>{if(!t){m(),o({kind:"loading"});return}let S,C=!1;const R=async()=>{r.isHidden()||await E(),!C&&(S=setTimeout(()=>{R()},u.current?VU:WU))};return R(),()=>{C=!0,clearTimeout(S),p.current++}},[t,r,E,m]),x.useEffect(()=>m,[m]),n}const XU=(e,t,r,n)=>{if(!r.width||!r.height||!n.width||!n.height)return null;const o=(a,l)=>Math.min(Math.max(Math.round(a),0),l-1);return{x:o(e/r.width*n.width,n.width),y:o(t/r.height*n.height,n.height)}};function YU(e){const t=x.useMemo(()=>e&&((r,n)=>e(r.x,r.y,n)),[e]);return C_(t)}const KU={stax:mR,flex:pR,apexp:hR},QU=e=>({...LU(e),icon:KU[e]??Vu}),Bv=({children:e})=>Ee.createElement("div",{className:"border-muted @container relative overflow-hidden rounded-md border"},e),JU="[&::-webkit-scrollbar]:size-[6px] [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full",H1=({name:e})=>{const[t,r]=x.useState(!1);return t?Ee.createElement("span",{className:"text-muted bg-muted flex size-[12.5cqw] items-center justify-center rounded-full text-[length:6cqw] font-semibold"},e.charAt(0)):Ee.createElement("img",{src:BU(e),alt:"",draggable:!1,className:"size-[12.5cqw] rounded-full",onError:()=>r(!0)})},ZU=({device:e,model:t,onOpenApp:r})=>{const n=FU(e),{opening:o,error:a,open:l}=UU(r),u=t.lightScreen?{background:"bg-white",text:"text-black",scrollbar:"[&::-webkit-scrollbar-thumb]:bg-black/30",overlay:"bg-white/70"}:{background:"bg-black",text:"text-white",scrollbar:"[&::-webkit-scrollbar-thumb]:bg-white/30",overlay:"bg-black/70"},d=t.touch?{scroll:"overflow-y-auto",list:"grid grid-cols-3 gap-[1.5cqw]",tile:"min-w-0 py-[3cqw]",opening:"flex-col"}:{scroll:"flex items-center overflow-x-auto",list:"flex gap-[2.5cqw]",tile:"w-[28cqw] shrink-0 py-[1.5cqw]",opening:"flex-row"};return Ee.createElement("div",{className:"flex flex-col gap-8","data-testid":"container_device-os-info"},Ee.createElement(Bv,null,Ee.createElement("div",{className:`${u.background} ${d.scroll} ${JU} ${u.scrollbar} p-[3cqw]`,style:{aspectRatio:t.screenWidth/t.screenHeight},"data-testid":"list_device-apps"},n.length===0?Ee.createElement("p",{className:`text-[length:5.5cqw] ${u.text} flex h-full w-full items-center justify-center opacity-60`},"No apps installed"):Ee.createElement("div",{className:d.list},n.map(p=>Ee.createElement("button",{key:p.name,type:"button",title:`${p.name} ${p.version}`,disabled:!r||o!==void 0,onClick:()=>l(p.name),className:`${u.text} ${d.tile} flex flex-col items-center gap-[1.5cqw] border-0 bg-transparent px-[1.5cqw] disabled:cursor-default enabled:cursor-pointer`,"data-testid":`button_open-app-${p.name}`},Ee.createElement(H1,{name:p.name}),Ee.createElement("span",{className:"w-full truncate text-center text-[length:4.7cqw] leading-[1.3]"},p.name))))),o!==void 0?Ee.createElement("div",{className:`${u.text} ${u.overlay} ${d.opening} pointer-events-none absolute inset-0 flex items-center justify-center gap-[3cqw] backdrop-blur-[1cqw]`,"data-testid":"spinner_opening-app-screen"},Ee.createElement("div",{className:"relative flex size-[18cqw] shrink-0 items-center justify-center"},Ee.createElement("span",{className:"absolute inset-0 rounded-full border-[0.8cqw] border-current opacity-15"}),Ee.createElement("span",{className:"absolute inset-0 animate-spin rounded-full border-[0.8cqw] border-transparent border-t-current"}),Ee.createElement(H1,{name:o})),Ee.createElement("span",{className:"animate-pulse text-[length:4.7cqw] font-semibold"},"Opening ",o)):null),a?Ee.createElement("p",{className:"body-4 text-error text-center"},a):null)},e7=[{button:"left",label:"Left"},{button:"both",label:"Both"},{button:"right",label:"Right"}],q1=e=>e===" "||e==="Enter",t7=({onPress:e})=>{const{hold:t,release:r}=PU(e);return Ee.createElement("div",{className:"flex gap-8"},e7.map(({button:n,label:o})=>Ee.createElement("button",{key:n,type:"button","aria-label":`${o} button`,onPointerDown:a=>{a.button===0&&(a.currentTarget.setPointerCapture(a.pointerId),t(n))},onPointerUp:r,onPointerCancel:r,onKeyDown:a=>{q1(a.key)&&(a.preventDefault(),t(n))},onKeyUp:a=>q1(a.key)&&r(),className:"border-muted body-3 text-base bg-muted hover:bg-muted-pressed active:bg-active flex-1 rounded-md border py-8 select-none",style:{touchAction:"none"},"data-testid":`button_device-screen-${n}`},o)))},r7=({src:e,onTouch:t})=>{const r=x.useRef(null),[n,o]=x.useState(!1),a=YU(t);x.useEffect(()=>o(!1),[e]);const l=p=>{const h=r.current;if(!t||!h||p.button!==0)return;const m=h.getBoundingClientRect(),y=XU(p.clientX-m.left,p.clientY-m.top,m,{width:h.naturalWidth,height:h.naturalHeight});y&&a.hold(y)&&h.setPointerCapture(p.pointerId)},u=p=>{a.release()&&r.current?.releasePointerCapture(p.pointerId)},d=x.useCallback(()=>o(!0),[]);return n?Ee.createElement("p",{className:"body-4 text-error text-center","data-testid":"text_device-screen-undecodable"},"Screenshot could not be decoded"):Ee.createElement(Bv,null,Ee.createElement("img",{ref:r,src:e,alt:"Device screen",draggable:!1,onError:d,onPointerDown:l,onPointerUp:u,onPointerCancel:u,className:`block w-full bg-black select-none ${t?"cursor-pointer":""}`,style:{imageRendering:"pixelated",touchAction:"none"},"data-testid":"image_device-screen"}))},n7={toImageSource:e=>Promise.resolve(URL.createObjectURL(e)),releaseImageSource:e=>URL.revokeObjectURL(e),isHidden:()=>document.hidden},wm=16,i7=224,o7=200,G1=(e,t,r)=>{const n=(o,a)=>Math.min(Math.max(o,0),Math.max(a,0));return{left:n(e,window.innerWidth-r.width),top:n(t,window.innerHeight-r.height)}},s7=(e,t)=>t?`${e} - ${t}`:e,a7=({api:e,deviceType:t,firmwareVersion:r,floating:n=!1,defaultCollapsed:o=!1})=>{const a=QU(t),[l,u]=x.useState(o),d=GU(e,!n||!l,n7);return n?Ee.createElement(l7,{title:s7(a.label,r),model:a,collapsed:l,onToggle:()=>u(p=>!p)},X1(d,a,e)):Ee.createElement("div",{className:"mx-auto flex w-full max-w-[420px] flex-col gap-8","data-testid":"container_device-screen"},X1(d,a,e))},l7=({title:e,model:t,collapsed:r,onToggle:n,children:o})=>{const a=x.useRef(null),[l,u]=x.useState(),[d,p]=x.useState(i7),h=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const k=()=>{const $=a.current?.getBoundingClientRect();$&&u(A=>A&&G1(A.left,A.top,$))};return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const y=k=>{const $=a.current?.getBoundingClientRect();!$||k.button!==0||k.target.closest("button")||(k.currentTarget.setPointerCapture(k.pointerId),h.current={dx:k.clientX-$.left,dy:k.clientY-$.top})},w=k=>{const $=a.current?.getBoundingClientRect();!h.current||!$||u(G1(k.clientX-h.current.dx,k.clientY-h.current.dy,$))},E=()=>{h.current=null},S=k=>{const $=a.current?.getBoundingClientRect();!$||k.button!==0||(k.currentTarget.setPointerCapture(k.pointerId),u({left:$.left,top:$.top}),m.current={x:k.clientX,width:$.width})},C=k=>{const $=a.current?.getBoundingClientRect();if(!m.current||!$)return;const A=m.current.width+k.clientX-m.current.x,D=window.innerWidth-$.left-wm;p(Math.max(o7,Math.min(A,D)))},R=()=>{m.current=null};return Ee.createElement("div",{ref:a,className:"bg-base border-muted fixed flex max-w-[calc(100vw-32px)] flex-col rounded-lg border shadow-lg",style:{zIndex:1e3,width:d,...l??{right:wm,bottom:wm}},"data-testid":"container_device-screen"},Ee.createElement("div",{className:"flex cursor-move items-center gap-8 px-12 py-8 select-none",style:{touchAction:"none"},onPointerDown:y,onPointerMove:w,onPointerUp:E,onPointerCancel:E},Ee.createElement(t.icon,{size:16}),Ee.createElement("span",{className:"body-3-semi-bold text-base flex-1"},e),Ee.createElement(sr,{appearance:"no-background",size:"xs",icon:r?Od:zs,"aria-label":r?"Expand device screen":"Collapse device screen",onClick:n,"data-testid":"button_toggle-device-screen"})),r?null:Ee.createElement(Ee.Fragment,null,Ee.createElement("div",{className:"flex flex-col gap-8 px-12 pb-12"},o),Ee.createElement("div",{className:"group absolute top-0 right-[-6px] bottom-0 flex w-[12px] cursor-ew-resize items-center justify-center",style:{touchAction:"none"},onPointerDown:S,onPointerMove:C,onPointerUp:R,onPointerCancel:R,"aria-hidden":!0,"data-testid":"handle_resize-device-screen"},Ee.createElement("span",{className:"border-muted bg-base group-hover:bg-muted group-active:bg-muted h-40 w-[6px] rounded-full border transition-colors"}))))};function X1(e,t,r){switch(e.kind){case"loading":return Ee.createElement(Bv,null,Ee.createElement("div",{className:`${t.lightScreen?"bg-white text-black":"bg-black text-white"} flex items-center justify-center`,style:{aspectRatio:t.screenWidth/t.screenHeight},"data-testid":"placeholder_device-screen-loading"},Ee.createElement("span",{className:"animate-pulse opacity-60"},Ee.createElement(t.icon,{size:32}))));case"error":return Ee.createElement(ng,{appearance:"error",title:"Screen unavailable",description:e.message});case"os-info":return Ee.createElement(Ee.Fragment,null,Ee.createElement(ZU,{device:e.device,model:t,onOpenApp:t.speculos?r.openApp:void 0}),t.speculos?null:Ee.createElement(ng,{appearance:"info",title:"No screen to capture",description:`Speculos has no emulator for the ${t.label}, so this device is mocked all the way through and has no screen.`,"data-testid":"banner_device-screen-no-emulator"}));case"image":return Ee.createElement(Ee.Fragment,null,Ee.createElement(r7,{src:e.src,onTouch:t.touch?e.input.touch:void 0}),t.touch?null:Ee.createElement(t7,{onPress:e.input.pressButton}))}}const Sm=Ft.interface({id:ut,prefix:ut,responses:Yr(ut)}),c7=Ft.interface({prefix:ut,response:Yt(ut),responses:Yt(Yr(ut))}),k_=Ft.interface({name:ut,version:ut,hash:Yt(ut)}),u7=Ft.interface({hash:ut,name:ut,version:ut}),Is=Ft.interface({id:ut,name:ut,device_type:ut,connectivity_type:ut,firmware_version:Yt(ut),apps:Yt(Yr(k_)),masks:Yt(Yr(Mo)),connected:Yt(vd),onboarded:Yt(vd),language:Yt(ut)}),d7=Ft.interface({name:Yt(ut),device_type:Yt(ut),connectivity_type:Yt(ut),firmware_version:Yt(ut),apps:Yt(Yr(k_)),masks:Yt(Yr(Mo)),mocks:Yt(Yr(c7)),catalog:Yt(Yr(u7)),onboarded:Yt(vd),language:Yt(ut)}),f7=Ft.interface({token:ut,expires_at:Mo}),p7=Ft.interface({device:Is,connected:vd}),h7=Ft.interface({response:ut}),m7=Ft.interface({status:ut,sessions:Mo}),g7=Ft.interface({id:ut,created_at:Mo,expires_at:Mo,devices:Yr(Is)}),Y1=Ft.interface({devices:Yr(d7)}),v7=Ft.interface({run_id:ut,speculos_url:ut,model:ut});let y7=class{client;timeoutMs;token;authPromise;constructor(t,r={}){this.client=r.httpClient??new l_({baseUrl:this.normalizeUrl(t)}),this.token=r.token,this.timeoutMs=r.timeoutMs}async getHealth(){const t=await this.client.get("health",this.requestConfig());return this.decode(m7,t)}async authenticate(){const t=await this.client.post("auth",{},this.requestConfig()),r=this.decode(f7,t).token;return this.token=r,r}getToken(){return this.token}async listDevices(){const t=await this.client.get("devices",await this.authRequestConfig());return this.decode(Yr(Is),t)}async addDevice(t={}){const r=await this.client.post("devices",t,await this.authRequestConfig());return this.decode(Is,r)}async getDevice(t){const r=await this.client.get(`devices/${t}`,await this.authRequestConfig());return this.decode(Is,r)}async editDevice(t,r){const n=await this.client.patch(`devices/${t}`,r,await this.authRequestConfig());return this.decode(Is,n)}async deleteDevice(t){return await this.client.delete(`devices/${t}`,await this.authRequestConfig()),!0}async connect(t){const r=await this.client.post(`devices/${t}/connect`,{},await this.authRequestConfig());return this.decode(p7,r)}async disconnect(t){return await this.client.post(`devices/${t}/disconnect`,{},await this.authRequestConfig()),!0}async disconnectAll(){const t=await this.listDevices();return await Promise.all(t.filter(r=>r.connected).map(r=>this.disconnect(r.id))),!0}async sendApdu(t,r){const n=typeof r=="string"?r:si(r,!1),o=await this.client.post(`devices/${t}/apdu`,{apdu:n},await this.authRequestConfig());return this.decode(h7,o)}async listMocks(t){const r=await this.client.get(`devices/${t}/mocks`,await this.authRequestConfig());return this.decode(Yr(Sm),r)}async addMock(t,r){const n=await this.client.post(`devices/${t}/mocks`,r,await this.authRequestConfig());return this.decode(Sm,n)}async editMock(t,r,n){const o=await this.client.patch(`devices/${t}/mocks/${r}`,n,await this.authRequestConfig());return this.decode(Sm,o)}async deleteMock(t,r){return await this.client.delete(`devices/${t}/mocks/${r}`,await this.authRequestConfig()),!0}async clearMocks(t){return await this.client.delete(`devices/${t}/mocks`,await this.authRequestConfig()),!0}async getSpeculos(t){const r=await this.client.get(`devices/${t}/speculos`,await this.authRequestConfig());return this.decode(v7,r)}async getScreenshot(t){return await this.client.get(`devices/${t}/speculos/screenshot`,{...await this.authRequestConfig(),responseType:"blob"})}async pressButton(t,r,n="press-and-release"){await this.client.post(`devices/${t}/speculos/button/${r}`,{action:n},await this.authRequestConfig())}async touchScreen(t,r,n,o="press-and-release"){await this.client.post(`devices/${t}/speculos/finger`,{action:o,x:r,y:n},await this.authRequestConfig())}async getSession(){const t=await this.client.get("sessions/current",await this.authRequestConfig());return this.decode(g7,t)}async setSeed(t){await this.client.put("sessions/current/seed",{seed:t},await this.authRequestConfig())}async disposeSession(){return await this.client.delete("sessions/current",await this.authRequestConfig()),this.token=void 0,this.authPromise=void 0,!0}async exportSession(){const t=await this.client.get("export",await this.authRequestConfig());return this.decode(Y1,t)}async importSession(t){const r=await this.client.post("import",t,await this.authRequestConfig());return this.decode(Y1,r)}decode(t,r){return t.decode(r).caseOf({Left:n=>{throw new Error(`MockClient: invalid server response (${n})`)},Right:n=>n})}requestConfig(){return{timeoutMs:this.timeoutMs}}async authRequestConfig(){const t=await this.ensureToken();return{...this.requestConfig(),headers:{Authorization:`Bearer ${t}`}}}ensureToken(){return this.token?Promise.resolve(this.token):(this.authPromise||(this.authPromise=this.authenticate()),this.authPromise)}normalizeUrl(t){return t.endsWith("/")?t:`${t}/`}};const b7=({url:e,token:t,deviceId:r,...n})=>{const o=x.useMemo(()=>new y7(e,{token:t}),[e,t]),a=x.useMemo(()=>OU(o,r),[o,r]),l=jU(o,r);return l===void 0?null:Ee.createElement(a7,{api:a,deviceType:l?.device_type??"",firmwareVersion:l?.firmware_version,...n})},x7=({mockServer:e,rewriteUrl:t,deviceId:r})=>v.jsx(Dv,{name:"live-screen",defaultWidth:320,minWidth:240,maxWidth:640,edge:"left",className:"border-l border-muted-subtle bg-surface",children:v.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-16 overflow-auto p-16",children:[v.jsx("span",{className:"body-4-semi-bold text-muted uppercase",children:"Live screen"}),e?.sessionToken?v.jsx(b7,{url:t?t(e.url):e.url,token:e.sessionToken,deviceId:r}):v.jsx("p",{className:"rounded-lg border border-dashed border-muted-subtle p-24 text-center body-3 text-muted",children:e?"The app shares its mock server without a session token, so the device screen cannot be reached.":"Pass mockServer to DevToolsDmkInspector to see the device screen."})]})}),w7=`import { DevToolsDmkInspector } from "@ledgerhq/device-management-kit-devtools-core";