@ledgerhq/device-management-kit-devtools-rozenite 0.0.0-develop-20260707003031 → 0.0.0-develop-20260708131309

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
@@ -450,7 +450,7 @@ Error generating stack: `+E.message+`
450
450
  height: 100%;
451
451
  min-height: 0;
452
452
  min-width: 0;
453
- `,wE=({direction:e,first:t,second:r,defaultFirstSize:n="50%",minFirstSize:i="20%",minSecondSize:o="20%"})=>k.jsx(eN,{children:k.jsxs(x$,{orientation:e==="horizontal"?"vertical":"horizontal",style:{flex:1},children:[k.jsx(j0,{defaultSize:n,minSize:i,children:k.jsx(SE,{children:t})}),k.jsx(Z6,{$direction:e}),k.jsx(j0,{minSize:o,children:k.jsx(SE,{children:r})})]})}),Eu={CONNECTED_DEVICES_UPDATE:"connectedDevicesUpdate",DEVICE_SESSION_STATE_UPDATE:"deviceSessionStateUpdate",PROVIDER_VALUE:"providerValue",APDU_RESPONSE:"apduResponse",DISCOVERED_DEVICES_UPDATE:"discoveredDevicesUpdate"},Qo={DISCONNECT:"disconnect",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"},xE={LOGGER:"logger",DMK_INSPECTOR:"dmk-inspector"},tN="moduleConnected";var EE;(function(e){(function(t){var r=typeof globalThis=="object"?globalThis:typeof self=="object"||typeof self=="object"?self:typeof this=="object"?this:u(),n=i(e);typeof r.Reflect<"u"&&(n=i(r.Reflect,n)),t(n,r),typeof r.Reflect>"u"&&(r.Reflect=e);function i(c,f){return function(p,g){Object.defineProperty(c,p,{configurable:!0,writable:!0,value:g}),f&&f(p,g)}}function o(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function u(){return o()||s()}})(function(t,r){var n=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",o=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",u=typeof Object.create=="function",c={__proto__:[]}instanceof Array,f=!u&&!c,p={create:u?function(){return Dt(Object.create(null))}:c?function(){return Dt({__proto__:null})}:function(){return Dt({})},has:f?function(re,ie){return n.call(re,ie)}:function(re,ie){return ie in re},get:f?function(re,ie){return n.call(re,ie)?re[ie]:void 0}:function(re,ie){return re[ie]}},g=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Mt(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:ht(),y=typeof WeakMap=="function"?WeakMap:Kt(),b=i?Symbol.for("@reflect-metadata:registry"):void 0,S=Ve(),_=ye(S);function C(re,ie,ue,V){if(A(ue)){if(!Me(re))throw new TypeError;if(!je(ie))throw new TypeError;return Y(re,ie)}else{if(!Me(re))throw new TypeError;if(!ne(ie))throw new TypeError;if(!ne(V)&&!A(V)&&!J(V))throw new TypeError;return J(V)&&(V=void 0),ue=we(ue),N(re,ie,ue,V)}}t("decorate",C);function O(re,ie){function ue(V,pe){if(!ne(V))throw new TypeError;if(!A(pe)&&!Ae(pe))throw new TypeError;M(re,ie,V,pe)}return ue}t("metadata",O);function R(re,ie,ue,V){if(!ne(ue))throw new TypeError;return A(V)||(V=we(V)),M(re,ie,ue,V)}t("defineMetadata",R);function T(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),j(re,ie,ue)}t("hasMetadata",T);function $(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),F(re,ie,ue)}t("hasOwnMetadata",$);function P(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),q(re,ie,ue)}t("getMetadata",P);function L(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),U(re,ie,ue)}t("getOwnMetadata",L);function z(re,ie){if(!ne(re))throw new TypeError;return A(ie)||(ie=we(ie)),G(re,ie)}t("getMetadataKeys",z);function B(re,ie){if(!ne(re))throw new TypeError;return A(ie)||(ie=we(ie)),K(re,ie)}t("getOwnMetadataKeys",B);function X(re,ie,ue){if(!ne(ie))throw new TypeError;if(A(ue)||(ue=we(ue)),!ne(ie))throw new TypeError;A(ue)||(ue=we(ue));var V=ct(ie,ue,!1);return A(V)?!1:V.OrdinaryDeleteMetadata(re,ie,ue)}t("deleteMetadata",X);function Y(re,ie){for(var ue=re.length-1;ue>=0;--ue){var V=re[ue],pe=V(ie);if(!A(pe)&&!J(pe)){if(!je(pe))throw new TypeError;ie=pe}}return ie}function N(re,ie,ue,V){for(var pe=re.length-1;pe>=0;--pe){var _e=re[pe],De=_e(ie,ue,V);if(!A(De)&&!J(De)){if(!ne(De))throw new TypeError;V=De}}return V}function j(re,ie,ue){var V=F(re,ie,ue);if(V)return!0;var pe=Ue(ie);return J(pe)?!1:j(re,pe,ue)}function F(re,ie,ue){var V=ct(ie,ue,!1);return A(V)?!1:se(V.OrdinaryHasOwnMetadata(re,ie,ue))}function q(re,ie,ue){var V=F(re,ie,ue);if(V)return U(re,ie,ue);var pe=Ue(ie);if(!J(pe))return q(re,pe,ue)}function U(re,ie,ue){var V=ct(ie,ue,!1);if(!A(V))return V.OrdinaryGetOwnMetadata(re,ie,ue)}function M(re,ie,ue,V){var pe=ct(ue,V,!0);pe.OrdinaryDefineOwnMetadata(re,ie,ue,V)}function G(re,ie){var ue=K(re,ie),V=Ue(re);if(V===null)return ue;var pe=G(V,ie);if(pe.length<=0)return ue;if(ue.length<=0)return pe;for(var _e=new m,De=[],fe=0,he=ue;fe<he.length;fe++){var me=he[fe],Ce=_e.has(me);Ce||(_e.add(me),De.push(me))}for(var $e=0,Xe=pe;$e<Xe.length;$e++){var me=Xe[$e],Ce=_e.has(me);Ce||(_e.add(me),De.push(me))}return De}function K(re,ie){var ue=ct(re,ie,!1);return ue?ue.OrdinaryOwnMetadataKeys(re,ie):[]}function D(re){if(re===null)return 1;switch(typeof re){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return re===null?1:6;default:return 6}}function A(re){return re===void 0}function J(re){return re===null}function Z(re){return typeof re=="symbol"}function ne(re){return typeof re=="object"?re!==null:typeof re=="function"}function W(re,ie){switch(D(re)){case 0:return re;case 1:return re;case 2:return re;case 3:return re;case 4:return re;case 5:return re}var ue="string",V=Ne(re,o);if(V!==void 0){var pe=V.call(re,ue);if(ne(pe))throw new TypeError;return pe}return ve(re)}function ve(re,ie){var ue,V,pe;{var _e=re.toString;if(Oe(_e)){var V=_e.call(re);if(!ne(V))return V}var ue=re.valueOf;if(Oe(ue)){var V=ue.call(re);if(!ne(V))return V}}throw new TypeError}function se(re){return!!re}function Ee(re){return""+re}function we(re){var ie=W(re);return Z(ie)?ie:Ee(ie)}function Me(re){return Array.isArray?Array.isArray(re):re instanceof Object?re instanceof Array:Object.prototype.toString.call(re)==="[object Array]"}function Oe(re){return typeof re=="function"}function je(re){return typeof re=="function"}function Ae(re){switch(D(re)){case 3:return!0;case 4:return!0;default:return!1}}function Te(re,ie){return re===ie||re!==re&&ie!==ie}function Ne(re,ie){var ue=re[ie];if(ue!=null){if(!Oe(ue))throw new TypeError;return ue}}function Ie(re){var ie=Ne(re,s);if(!Oe(ie))throw new TypeError;var ue=ie.call(re);if(!ne(ue))throw new TypeError;return ue}function Ke(re){return re.value}function nt(re){var ie=re.next();return ie.done?!1:ie}function ze(re){var ie=re.return;ie&&ie.call(re)}function Ue(re){var ie=Object.getPrototypeOf(re);if(typeof re!="function"||re===g||ie!==g)return ie;var ue=re.prototype,V=ue&&Object.getPrototypeOf(ue);if(V==null||V===Object.prototype)return ie;var pe=V.constructor;return typeof pe!="function"||pe===re?ie:pe}function Qe(){var re;!A(b)&&typeof r.Reflect<"u"&&!(b in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(re=Ge(r.Reflect));var ie,ue,V,pe=new y,_e={registerProvider:De,getProvider:he,setProvider:Ce};return _e;function De($e){if(!Object.isExtensible(_e))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case re===$e:break;case A(ie):ie=$e;break;case ie===$e:break;case A(ue):ue=$e;break;case ue===$e:break;default:V===void 0&&(V=new m),V.add($e);break}}function fe($e,Xe){if(!A(ie)){if(ie.isProviderFor($e,Xe))return ie;if(!A(ue)){if(ue.isProviderFor($e,Xe))return ie;if(!A(V))for(var it=Ie(V);;){var Je=nt(it);if(!Je)return;var ot=Ke(Je);if(ot.isProviderFor($e,Xe))return ze(it),ot}}}if(!A(re)&&re.isProviderFor($e,Xe))return re}function he($e,Xe){var it=pe.get($e),Je;return A(it)||(Je=it.get(Xe)),A(Je)&&(Je=fe($e,Xe),A(Je)||(A(it)&&(it=new h,pe.set($e,it)),it.set(Xe,Je))),Je}function me($e){if(A($e))throw new TypeError;return ie===$e||ue===$e||!A(V)&&V.has($e)}function Ce($e,Xe,it){if(!me(it))throw new Error("Metadata provider not registered.");var Je=he($e,Xe);if(Je!==it){if(!A(Je))return!1;var ot=pe.get($e);A(ot)&&(ot=new h,pe.set($e,ot)),ot.set(Xe,it)}return!0}}function Ve(){var re;return!A(b)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&(re=r.Reflect[b]),A(re)&&(re=Qe()),!A(b)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,b,{enumerable:!1,configurable:!1,writable:!1,value:re}),re}function ye(re){var ie=new y,ue={isProviderFor:function(me,Ce){var $e=ie.get(me);return A($e)?!1:$e.has(Ce)},OrdinaryDefineOwnMetadata:De,OrdinaryHasOwnMetadata:pe,OrdinaryGetOwnMetadata:_e,OrdinaryOwnMetadataKeys:fe,OrdinaryDeleteMetadata:he};return S.registerProvider(ue),ue;function V(me,Ce,$e){var Xe=ie.get(me),it=!1;if(A(Xe)){if(!$e)return;Xe=new h,ie.set(me,Xe),it=!0}var Je=Xe.get(Ce);if(A(Je)){if(!$e)return;if(Je=new h,Xe.set(Ce,Je),!re.setProvider(me,Ce,ue))throw Xe.delete(Ce),it&&ie.delete(me),new Error("Wrong provider for target.")}return Je}function pe(me,Ce,$e){var Xe=V(Ce,$e,!1);return A(Xe)?!1:se(Xe.has(me))}function _e(me,Ce,$e){var Xe=V(Ce,$e,!1);if(!A(Xe))return Xe.get(me)}function De(me,Ce,$e,Xe){var it=V($e,Xe,!0);it.set(me,Ce)}function fe(me,Ce){var $e=[],Xe=V(me,Ce,!1);if(A(Xe))return $e;for(var it=Xe.keys(),Je=Ie(it),ot=0;;){var Fr=nt(Je);if(!Fr)return $e.length=ot,$e;var ft=Ke(Fr);try{$e[ot]=ft}catch(dt){try{ze(Je)}finally{throw dt}}ot++}}function he(me,Ce,$e){var Xe=V(Ce,$e,!1);if(A(Xe)||!Xe.delete(me))return!1;if(Xe.size===0){var it=ie.get(Ce);A(it)||(it.delete($e),it.size===0&&ie.delete(it))}return!0}}function Ge(re){var ie=re.defineMetadata,ue=re.hasOwnMetadata,V=re.getOwnMetadata,pe=re.getOwnMetadataKeys,_e=re.deleteMetadata,De=new y,fe={isProviderFor:function(he,me){var Ce=De.get(he);return!A(Ce)&&Ce.has(me)?!0:pe(he,me).length?(A(Ce)&&(Ce=new m,De.set(he,Ce)),Ce.add(me),!0):!1},OrdinaryDefineOwnMetadata:ie,OrdinaryHasOwnMetadata:ue,OrdinaryGetOwnMetadata:V,OrdinaryOwnMetadataKeys:pe,OrdinaryDeleteMetadata:_e};return fe}function ct(re,ie,ue){var V=S.getProvider(re,ie);if(!A(V))return V;if(ue){if(S.setProvider(re,ie,_))return _;throw new Error("Illegal state.")}}function Mt(){var re={},ie=[],ue=(function(){function fe(he,me,Ce){this._index=0,this._keys=he,this._values=me,this._selector=Ce}return fe.prototype["@@iterator"]=function(){return this},fe.prototype[s]=function(){return this},fe.prototype.next=function(){var he=this._index;if(he>=0&&he<this._keys.length){var me=this._selector(this._keys[he],this._values[he]);return he+1>=this._keys.length?(this._index=-1,this._keys=ie,this._values=ie):this._index++,{value:me,done:!1}}return{value:void 0,done:!0}},fe.prototype.throw=function(he){throw this._index>=0&&(this._index=-1,this._keys=ie,this._values=ie),he},fe.prototype.return=function(he){return this._index>=0&&(this._index=-1,this._keys=ie,this._values=ie),{value:he,done:!0}},fe})(),V=(function(){function fe(){this._keys=[],this._values=[],this._cacheKey=re,this._cacheIndex=-2}return Object.defineProperty(fe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),fe.prototype.has=function(he){return this._find(he,!1)>=0},fe.prototype.get=function(he){var me=this._find(he,!1);return me>=0?this._values[me]:void 0},fe.prototype.set=function(he,me){var Ce=this._find(he,!0);return this._values[Ce]=me,this},fe.prototype.delete=function(he){var me=this._find(he,!1);if(me>=0){for(var Ce=this._keys.length,$e=me+1;$e<Ce;$e++)this._keys[$e-1]=this._keys[$e],this._values[$e-1]=this._values[$e];return this._keys.length--,this._values.length--,Te(he,this._cacheKey)&&(this._cacheKey=re,this._cacheIndex=-2),!0}return!1},fe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=re,this._cacheIndex=-2},fe.prototype.keys=function(){return new ue(this._keys,this._values,pe)},fe.prototype.values=function(){return new ue(this._keys,this._values,_e)},fe.prototype.entries=function(){return new ue(this._keys,this._values,De)},fe.prototype["@@iterator"]=function(){return this.entries()},fe.prototype[s]=function(){return this.entries()},fe.prototype._find=function(he,me){if(!Te(this._cacheKey,he)){this._cacheIndex=-1;for(var Ce=0;Ce<this._keys.length;Ce++)if(Te(this._keys[Ce],he)){this._cacheIndex=Ce;break}}return this._cacheIndex<0&&me&&(this._cacheIndex=this._keys.length,this._keys.push(he),this._values.push(void 0)),this._cacheIndex},fe})();return V;function pe(fe,he){return fe}function _e(fe,he){return he}function De(fe,he){return[fe,he]}}function ht(){var re=(function(){function ie(){this._map=new h}return Object.defineProperty(ie.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),ie.prototype.has=function(ue){return this._map.has(ue)},ie.prototype.add=function(ue){return this._map.set(ue,ue),this},ie.prototype.delete=function(ue){return this._map.delete(ue)},ie.prototype.clear=function(){this._map.clear()},ie.prototype.keys=function(){return this._map.keys()},ie.prototype.values=function(){return this._map.keys()},ie.prototype.entries=function(){return this._map.entries()},ie.prototype["@@iterator"]=function(){return this.keys()},ie.prototype[s]=function(){return this.keys()},ie})();return re}function Kt(){var re=16,ie=p.create(),ue=V();return(function(){function he(){this._key=V()}return he.prototype.has=function(me){var Ce=pe(me,!1);return Ce!==void 0?p.has(Ce,this._key):!1},he.prototype.get=function(me){var Ce=pe(me,!1);return Ce!==void 0?p.get(Ce,this._key):void 0},he.prototype.set=function(me,Ce){var $e=pe(me,!0);return $e[this._key]=Ce,this},he.prototype.delete=function(me){var Ce=pe(me,!1);return Ce!==void 0?delete Ce[this._key]:!1},he.prototype.clear=function(){this._key=V()},he})();function V(){var he;do he="@@WeakMap@@"+fe();while(p.has(ie,he));return ie[he]=!0,he}function pe(he,me){if(!n.call(he,ue)){if(!me)return;Object.defineProperty(he,ue,{value:p.create()})}return he[ue]}function _e(he,me){for(var Ce=0;Ce<me;++Ce)he[Ce]=Math.random()*255|0;return he}function De(he){if(typeof Uint8Array=="function"){var me=new Uint8Array(he);return typeof crypto<"u"?crypto.getRandomValues(me):typeof msCrypto<"u"?msCrypto.getRandomValues(me):_e(me,he),me}return _e(new Array(he),he)}function fe(){var he=De(re);he[6]=he[6]&79|64,he[8]=he[8]&191|128;for(var me="",Ce=0;Ce<re;++Ce){var $e=he[Ce];(Ce===4||Ce===6||Ce===8)&&(me+="-"),$e<16&&(me+="0"),me+=$e.toString(16).toLowerCase()}return me}}function Dt(re){return re.__=void 0,delete re.__,re}})})(EE||(EE={}));let rN=class{cla;ins;p1;p2;data;constructor(t,r,n,i,o){this.cla=t,this.ins=r,this.p1=n,this.p2=i,this.data=o??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 CE(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 Jo(e,t=!0){return`${t?"0x":""}${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`}let cv=class{_tag="ValueOverflow";originalError;message;constructor(t,r=C$){this.message=`Value overflow for ${t}, max is ${r}`}},nd=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}`}},_E=class{_tag="HexaString";message;originalError;constructor(t){this.message=`Invalid encoded hexa string or length is null: ${t}`}};const nN=4294967295;let iN=class{constructor(t=nN){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 nd(t.toString())),this);addHexaStringToData=t=>{const r=CE(t);return r===null||r.length===0?(this.errors.push(new _E(t)),this):(this.addBufferToData(r),this)};addAsciiStringToData=t=>{const r=new TextEncoder().encode(t);return this.addBufferToData(r),this};encodeInLVFromHexa=t=>{const r=CE(t);return r===null||r.length===0?(this.errors.push(new _E(t)),this):this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addBufferToData(r),this):(this.errors.push(new nd(t)),this)};encodeInLVFromBuffer=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addBufferToData(t),this):(this.errors.push(new nd(t.toString())),this);encodeInLVFromAscii=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addAsciiStringToData(t),this):(this.errors.push(new nd(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,i){let o=this.checkBoundsAndConvert(t,r,n);if(o===void 0)return this;const s=Number(r)/8,u=new Uint8Array(s);if(i)for(let c=s-1;c>=0;c--)u[c]=Number(o&0xffn),o>>=8n;else for(let c=0;c<s;c++)u[c]=Number(o&0xffn),o>>=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 cv(t.toString()));return}t=BigInt(t)}if(n){const i=1n<<r-1n;if(t>=i||t<-i){this.errors.push(new cv(t.toString(),i-1n));return}if(t<0n){const o=(1n<<r)-1n;t=-t,t=(~t&o)+1n}}else{const i=1n<<r;if(t<0||t>=i){this.errors.push(new cv(t.toString(),i-1n));return}}return t}};const C$=255;let _$=class{_ins;_cla;_p1;p2;data=new iN(C$);constructor({ins:t,cla:r,p1:n,p2:i}){this._cla=r&255,this._ins=t&255,this._p1=n&255,this.p2=i&255}build=()=>new rN(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()},oN=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 i=this.index;return{tag:r,value:n,tlv:this.buffer.slice(t,i)}}encodeToHexaString(t,r=!1){if(t===void 0||t.length===0)return"";const n=Jo(t);return r?n:n.slice(2)}encodeToString(t){let r="",n=0;if(!t)return r;for(;n<=t.length;){const i=t[n];i&&(r+=String.fromCharCode(i)),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 i=Number(t)/8;if(this.outOfRange(i))return;let o=0n;if(n)for(let s=0;s<i;s++)o=o<<8n|BigInt(this.buffer[s+this.index]);else for(let s=i-1;s>=0;s--)o=o<<8n|BigInt(this.buffer[s+this.index]);if(r){const s=1n<<t-1n;o&s&&(o-=s<<1n)}return this.index+=i,o}},g1=class{parser;constructor(t){this.parser=new oN(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()},aN=class{_tag="InvalidStatusWordError";originalError;constructor(t){this.originalError=new Error(t??"Invalid status word.")}},sN=class{_tag="InvalidResponseFormatError";originalError;constructor(t){this.originalError=new Error(t??"Invalid response format.")}};var lN=(e=>(e.Error="ERROR",e.Success="SUCCESS",e))(lN||{});function uN(e){return"error"in e&&e.error!==void 0}function RE(e){return uN(e)?{status:"ERROR",error:e.error}:{status:"SUCCESS",data:e.data}}function cN(e){return e.status==="SUCCESS"}function ls({data:e,error:t}){return RE(t!==void 0?{error:t}:{data:e})}function fN(e){return cN(e)}const dN=(e,t)=>Object.keys(t).includes(e);let v1=class ll{static isValidStatusCode(t){return t.length===2}static isSuccessResponse({statusCode:t}){return ll.isValidStatusCode(t)?t[0]===144&&t[1]===0:!1}static isLockedDeviceResponse({statusCode:t}){return ll.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 ll.isValidStatusCode(t)?t[0]===85&&t[1]===1||t[0]===105&&t[1]===133:!1}static isAppAlreadyInstalled({statusCode:t}){return ll.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 ll.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 i=0;i<4;i++)if(n[i]!==t[i])return!1;return!0})}},pN=class{_tag;originalError;errorCode;message;constructor({tag:t,errorCode:r,originalError:n,message:i}){this._tag=t,this.originalError=n,this.errorCode=r,this.message=i??"An error occured during device exchange."}},hN=class{_tag="UnknownDeviceExchangeError";originalError;message;constructor(t){this.originalError=t,this.message="Unexpected device exchange error happened."}},gN=class extends pN{constructor(t){super({tag:"GlobalCommandError",...t})}};const OE={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 R$=class{static handle(t){const r=new g1(t).encodeToHexaString(t.statusCode);return dN(r,OE)?new gN({...OE[r],errorCode:r}):new hN({message:"UnknownError",errorCode:r})}},TE=class{name="getAppAndVersion";args=void 0;getApdu(){const t={cla:176,ins:1,p1:0,p2:0};return new _$(t).build()}parseResponse(t){if(!v1.isSuccessResponse(t))return ls({error:R$.handle(t)});const r=new g1(t);if(r.extract8BitUInt()!==1)return ls({error:new sN("getAppAndVersion: format not supported")});const n=r.encodeToString(r.extractFieldLVEncoded()),i=r.encodeToString(r.extractFieldLVEncoded());if(r.getUnparsedRemainingLength()===0)return ls({data:{name:n,version:i}});const o=r.extractFieldLVEncoded();return ls({data:{name:n,version:i,flags:o}})}};var vN=(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))(vN||{}),mN=(e=>(e[e.NONE=0]="NONE",e[e.USB=1]="USB",e[e.QI=2]="QI",e))(mN||{}),id={exports:{}},fv,$E;function Ip(){if($E)return fv;$E=1;const e="2.0.0",t=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,i=t-6;return fv={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:e,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},fv}var dv,IE;function Ap(){if(IE)return dv;IE=1;var e={};return dv=typeof process=="object"&&e&&e.NODE_DEBUG&&/\bsemver\b/i.test(e.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},dv}var AE;function _c(){return AE||(AE=1,(function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:i}=Ip(),o=Ap();t=e.exports={};const s=t.re=[],u=t.safeRe=[],c=t.src=[],f=t.safeSrc=[],p=t.t={};let g=0;const h="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",i],[h,n]],y=S=>{for(const[_,C]of m)S=S.split(`${_}*`).join(`${_}{0,${C}}`).split(`${_}+`).join(`${_}{1,${C}}`);return S},b=(S,_,C)=>{const O=y(_),R=g++;o(S,R,_),p[S]=R,c[R]=_,f[R]=O,s[R]=new RegExp(_,C?"g":void 0),u[R]=new RegExp(O,C?"g":void 0)};b("NUMERICIDENTIFIER","0|[1-9]\\d*"),b("NUMERICIDENTIFIERLOOSE","\\d+"),b("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),b("MAINVERSION",`(${c[p.NUMERICIDENTIFIER]})\\.(${c[p.NUMERICIDENTIFIER]})\\.(${c[p.NUMERICIDENTIFIER]})`),b("MAINVERSIONLOOSE",`(${c[p.NUMERICIDENTIFIERLOOSE]})\\.(${c[p.NUMERICIDENTIFIERLOOSE]})\\.(${c[p.NUMERICIDENTIFIERLOOSE]})`),b("PRERELEASEIDENTIFIER",`(?:${c[p.NONNUMERICIDENTIFIER]}|${c[p.NUMERICIDENTIFIER]})`),b("PRERELEASEIDENTIFIERLOOSE",`(?:${c[p.NONNUMERICIDENTIFIER]}|${c[p.NUMERICIDENTIFIERLOOSE]})`),b("PRERELEASE",`(?:-(${c[p.PRERELEASEIDENTIFIER]}(?:\\.${c[p.PRERELEASEIDENTIFIER]})*))`),b("PRERELEASELOOSE",`(?:-?(${c[p.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[p.PRERELEASEIDENTIFIERLOOSE]})*))`),b("BUILDIDENTIFIER",`${h}+`),b("BUILD",`(?:\\+(${c[p.BUILDIDENTIFIER]}(?:\\.${c[p.BUILDIDENTIFIER]})*))`),b("FULLPLAIN",`v?${c[p.MAINVERSION]}${c[p.PRERELEASE]}?${c[p.BUILD]}?`),b("FULL",`^${c[p.FULLPLAIN]}$`),b("LOOSEPLAIN",`[v=\\s]*${c[p.MAINVERSIONLOOSE]}${c[p.PRERELEASELOOSE]}?${c[p.BUILD]}?`),b("LOOSE",`^${c[p.LOOSEPLAIN]}$`),b("GTLT","((?:<|>)?=?)"),b("XRANGEIDENTIFIERLOOSE",`${c[p.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),b("XRANGEIDENTIFIER",`${c[p.NUMERICIDENTIFIER]}|x|X|\\*`),b("XRANGEPLAIN",`[v=\\s]*(${c[p.XRANGEIDENTIFIER]})(?:\\.(${c[p.XRANGEIDENTIFIER]})(?:\\.(${c[p.XRANGEIDENTIFIER]})(?:${c[p.PRERELEASE]})?${c[p.BUILD]}?)?)?`),b("XRANGEPLAINLOOSE",`[v=\\s]*(${c[p.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[p.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[p.XRANGEIDENTIFIERLOOSE]})(?:${c[p.PRERELEASELOOSE]})?${c[p.BUILD]}?)?)?`),b("XRANGE",`^${c[p.GTLT]}\\s*${c[p.XRANGEPLAIN]}$`),b("XRANGELOOSE",`^${c[p.GTLT]}\\s*${c[p.XRANGEPLAINLOOSE]}$`),b("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),b("COERCE",`${c[p.COERCEPLAIN]}(?:$|[^\\d])`),b("COERCEFULL",c[p.COERCEPLAIN]+`(?:${c[p.PRERELEASE]})?(?:${c[p.BUILD]})?(?:$|[^\\d])`),b("COERCERTL",c[p.COERCE],!0),b("COERCERTLFULL",c[p.COERCEFULL],!0),b("LONETILDE","(?:~>?)"),b("TILDETRIM",`(\\s*)${c[p.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",b("TILDE",`^${c[p.LONETILDE]}${c[p.XRANGEPLAIN]}$`),b("TILDELOOSE",`^${c[p.LONETILDE]}${c[p.XRANGEPLAINLOOSE]}$`),b("LONECARET","(?:\\^)"),b("CARETTRIM",`(\\s*)${c[p.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",b("CARET",`^${c[p.LONECARET]}${c[p.XRANGEPLAIN]}$`),b("CARETLOOSE",`^${c[p.LONECARET]}${c[p.XRANGEPLAINLOOSE]}$`),b("COMPARATORLOOSE",`^${c[p.GTLT]}\\s*(${c[p.LOOSEPLAIN]})$|^$`),b("COMPARATOR",`^${c[p.GTLT]}\\s*(${c[p.FULLPLAIN]})$|^$`),b("COMPARATORTRIM",`(\\s*)${c[p.GTLT]}\\s*(${c[p.LOOSEPLAIN]}|${c[p.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",b("HYPHENRANGE",`^\\s*(${c[p.XRANGEPLAIN]})\\s+-\\s+(${c[p.XRANGEPLAIN]})\\s*$`),b("HYPHENRANGELOOSE",`^\\s*(${c[p.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[p.XRANGEPLAINLOOSE]})\\s*$`),b("STAR","(<|>)?=?\\s*\\*"),b("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),b("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(id,id.exports)),id.exports}var pv,kE;function m1(){if(kE)return pv;kE=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return pv=n=>n?typeof n!="object"?e:n:t,pv}var hv,PE;function O$(){if(PE)return hv;PE=1;const e=/^[0-9]+$/,t=(n,i)=>{const o=e.test(n),s=e.test(i);return o&&s&&(n=+n,i=+i),n===i?0:o&&!s?-1:s&&!o?1:n<i?-1:1};return hv={compareIdentifiers:t,rcompareIdentifiers:(n,i)=>t(i,n)},hv}var gv,ME;function fn(){if(ME)return gv;ME=1;const e=Ap(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Ip(),{safeRe:n,t:i}=_c(),o=m1(),{compareIdentifiers:s}=O$();class u{constructor(f,p){if(p=o(p),f instanceof u){if(f.loose===!!p.loose&&f.includePrerelease===!!p.includePrerelease)return f;f=f.version}else if(typeof f!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof f}".`);if(f.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",f,p),this.options=p,this.loose=!!p.loose,this.includePrerelease=!!p.includePrerelease;const g=f.trim().match(p.loose?n[i.LOOSE]:n[i.FULL]);if(!g)throw new TypeError(`Invalid Version: ${f}`);if(this.raw=f,this.major=+g[1],this.minor=+g[2],this.patch=+g[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");g[4]?this.prerelease=g[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const m=+h;if(m>=0&&m<r)return m}return h}):this.prerelease=[],this.build=g[5]?g[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(f){if(e("SemVer.compare",this.version,this.options,f),!(f instanceof u)){if(typeof f=="string"&&f===this.version)return 0;f=new u(f,this.options)}return f.version===this.version?0:this.compareMain(f)||this.comparePre(f)}compareMain(f){return f instanceof u||(f=new u(f,this.options)),s(this.major,f.major)||s(this.minor,f.minor)||s(this.patch,f.patch)}comparePre(f){if(f instanceof u||(f=new u(f,this.options)),this.prerelease.length&&!f.prerelease.length)return-1;if(!this.prerelease.length&&f.prerelease.length)return 1;if(!this.prerelease.length&&!f.prerelease.length)return 0;let p=0;do{const g=this.prerelease[p],h=f.prerelease[p];if(e("prerelease compare",p,g,h),g===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(g===void 0)return-1;if(g===h)continue;return s(g,h)}while(++p)}compareBuild(f){f instanceof u||(f=new u(f,this.options));let p=0;do{const g=this.build[p],h=f.build[p];if(e("build compare",p,g,h),g===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(g===void 0)return-1;if(g===h)continue;return s(g,h)}while(++p)}inc(f,p,g){if(f.startsWith("pre")){if(!p&&g===!1)throw new Error("invalid increment argument: identifier is empty");if(p){const h=`-${p}`.match(this.options.loose?n[i.PRERELEASELOOSE]:n[i.PRERELEASE]);if(!h||h[1]!==p)throw new Error(`invalid identifier: ${p}`)}}switch(f){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",p,g);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",p,g);break;case"prepatch":this.prerelease.length=0,this.inc("patch",p,g),this.inc("pre",p,g);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",p,g),this.inc("pre",p,g);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 h=Number(g)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let m=this.prerelease.length;for(;--m>=0;)typeof this.prerelease[m]=="number"&&(this.prerelease[m]++,m=-2);if(m===-1){if(p===this.prerelease.join(".")&&g===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(p){let m=[p,h];g===!1&&(m=[p]),s(this.prerelease[0],p)===0?isNaN(this.prerelease[1])&&(this.prerelease=m):this.prerelease=m}break}default:throw new Error(`invalid increment argument: ${f}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return gv=u,gv}var vv,DE;function Vl(){if(DE)return vv;DE=1;const e=fn();return vv=(r,n,i=!1)=>{if(r instanceof e)return r;try{return new e(r,n)}catch(o){if(!i)return null;throw o}},vv}var mv,LE;function yN(){if(LE)return mv;LE=1;const e=Vl();return mv=(r,n)=>{const i=e(r,n);return i?i.version:null},mv}var yv,FE;function bN(){if(FE)return yv;FE=1;const e=Vl();return yv=(r,n)=>{const i=e(r.trim().replace(/^[=v]+/,""),n);return i?i.version:null},yv}var bv,NE;function SN(){if(NE)return bv;NE=1;const e=fn();return bv=(r,n,i,o,s)=>{typeof i=="string"&&(s=o,o=i,i=void 0);try{return new e(r instanceof e?r.version:r,i).inc(n,o,s).version}catch{return null}},bv}var Sv,jE;function wN(){if(jE)return Sv;jE=1;const e=Vl();return Sv=(r,n)=>{const i=e(r,null,!0),o=e(n,null,!0),s=i.compare(o);if(s===0)return null;const u=s>0,c=u?i:o,f=u?o:i,p=!!c.prerelease.length;if(!!f.prerelease.length&&!p){if(!f.patch&&!f.minor)return"major";if(f.compareMain(c)===0)return f.minor&&!f.patch?"minor":"patch"}const h=p?"pre":"";return i.major!==o.major?h+"major":i.minor!==o.minor?h+"minor":i.patch!==o.patch?h+"patch":"prerelease"},Sv}var wv,zE;function xN(){if(zE)return wv;zE=1;const e=fn();return wv=(r,n)=>new e(r,n).major,wv}var xv,BE;function EN(){if(BE)return xv;BE=1;const e=fn();return xv=(r,n)=>new e(r,n).minor,xv}var Ev,VE;function CN(){if(VE)return Ev;VE=1;const e=fn();return Ev=(r,n)=>new e(r,n).patch,Ev}var Cv,HE;function _N(){if(HE)return Cv;HE=1;const e=Vl();return Cv=(r,n)=>{const i=e(r,n);return i&&i.prerelease.length?i.prerelease:null},Cv}var _v,UE;function eo(){if(UE)return _v;UE=1;const e=fn();return _v=(r,n,i)=>new e(r,i).compare(new e(n,i)),_v}var Rv,WE;function RN(){if(WE)return Rv;WE=1;const e=eo();return Rv=(r,n,i)=>e(n,r,i),Rv}var Ov,GE;function ON(){if(GE)return Ov;GE=1;const e=eo();return Ov=(r,n)=>e(r,n,!0),Ov}var Tv,qE;function y1(){if(qE)return Tv;qE=1;const e=fn();return Tv=(r,n,i)=>{const o=new e(r,i),s=new e(n,i);return o.compare(s)||o.compareBuild(s)},Tv}var $v,XE;function TN(){if(XE)return $v;XE=1;const e=y1();return $v=(r,n)=>r.sort((i,o)=>e(i,o,n)),$v}var Iv,KE;function $N(){if(KE)return Iv;KE=1;const e=y1();return Iv=(r,n)=>r.sort((i,o)=>e(o,i,n)),Iv}var Av,YE;function kp(){if(YE)return Av;YE=1;const e=eo();return Av=(r,n,i)=>e(r,n,i)>0,Av}var kv,QE;function b1(){if(QE)return kv;QE=1;const e=eo();return kv=(r,n,i)=>e(r,n,i)<0,kv}var Pv,JE;function T$(){if(JE)return Pv;JE=1;const e=eo();return Pv=(r,n,i)=>e(r,n,i)===0,Pv}var Mv,ZE;function $$(){if(ZE)return Mv;ZE=1;const e=eo();return Mv=(r,n,i)=>e(r,n,i)!==0,Mv}var Dv,eC;function S1(){if(eC)return Dv;eC=1;const e=eo();return Dv=(r,n,i)=>e(r,n,i)>=0,Dv}var Lv,tC;function w1(){if(tC)return Lv;tC=1;const e=eo();return Lv=(r,n,i)=>e(r,n,i)<=0,Lv}var Fv,rC;function I$(){if(rC)return Fv;rC=1;const e=T$(),t=$$(),r=kp(),n=S1(),i=b1(),o=w1();return Fv=(u,c,f,p)=>{switch(c){case"===":return typeof u=="object"&&(u=u.version),typeof f=="object"&&(f=f.version),u===f;case"!==":return typeof u=="object"&&(u=u.version),typeof f=="object"&&(f=f.version),u!==f;case"":case"=":case"==":return e(u,f,p);case"!=":return t(u,f,p);case">":return r(u,f,p);case">=":return n(u,f,p);case"<":return i(u,f,p);case"<=":return o(u,f,p);default:throw new TypeError(`Invalid operator: ${c}`)}},Fv}var Nv,nC;function IN(){if(nC)return Nv;nC=1;const e=fn(),t=Vl(),{safeRe:r,t:n}=_c();return Nv=(o,s)=>{if(o instanceof e)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;s=s||{};let u=null;if(!s.rtl)u=o.match(s.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const m=s.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let y;for(;(y=m.exec(o))&&(!u||u.index+u[0].length!==o.length);)(!u||y.index+y[0].length!==u.index+u[0].length)&&(u=y),m.lastIndex=y.index+y[1].length+y[2].length;m.lastIndex=-1}if(u===null)return null;const c=u[2],f=u[3]||"0",p=u[4]||"0",g=s.includePrerelease&&u[5]?`-${u[5]}`:"",h=s.includePrerelease&&u[6]?`+${u[6]}`:"";return t(`${c}.${f}.${p}${g}${h}`,s)},Nv}var jv,iC;function AN(){if(iC)return jv;iC=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 o=this.map.keys().next().value;this.delete(o)}this.map.set(r,n)}return this}}return jv=e,jv}var zv,oC;function to(){if(oC)return zv;oC=1;const e=/\s+/g;class t{constructor(F,q){if(q=i(q),F instanceof t)return F.loose===!!q.loose&&F.includePrerelease===!!q.includePrerelease?F:new t(F.raw,q);if(F instanceof o)return this.raw=F.value,this.set=[[F]],this.formatted=void 0,this;if(this.options=q,this.loose=!!q.loose,this.includePrerelease=!!q.includePrerelease,this.raw=F.trim().replace(e," "),this.set=this.raw.split("||").map(U=>this.parseRange(U.trim())).filter(U=>U.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const U=this.set[0];if(this.set=this.set.filter(M=>!b(M[0])),this.set.length===0)this.set=[U];else if(this.set.length>1){for(const M of this.set)if(M.length===1&&S(M[0])){this.set=[M];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let F=0;F<this.set.length;F++){F>0&&(this.formatted+="||");const q=this.set[F];for(let U=0;U<q.length;U++)U>0&&(this.formatted+=" "),this.formatted+=q[U].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(F){const U=((this.options.includePrerelease&&m)|(this.options.loose&&y))+":"+F,M=n.get(U);if(M)return M;const G=this.options.loose,K=G?c[f.HYPHENRANGELOOSE]:c[f.HYPHENRANGE];F=F.replace(K,Y(this.options.includePrerelease)),s("hyphen replace",F),F=F.replace(c[f.COMPARATORTRIM],p),s("comparator trim",F),F=F.replace(c[f.TILDETRIM],g),s("tilde trim",F),F=F.replace(c[f.CARETTRIM],h),s("caret trim",F);let D=F.split(" ").map(ne=>C(ne,this.options)).join(" ").split(/\s+/).map(ne=>X(ne,this.options));G&&(D=D.filter(ne=>(s("loose invalid filter",ne,this.options),!!ne.match(c[f.COMPARATORLOOSE])))),s("range list",D);const A=new Map,J=D.map(ne=>new o(ne,this.options));for(const ne of J){if(b(ne))return[ne];A.set(ne.value,ne)}A.size>1&&A.has("")&&A.delete("");const Z=[...A.values()];return n.set(U,Z),Z}intersects(F,q){if(!(F instanceof t))throw new TypeError("a Range is required");return this.set.some(U=>_(U,q)&&F.set.some(M=>_(M,q)&&U.every(G=>M.every(K=>G.intersects(K,q)))))}test(F){if(!F)return!1;if(typeof F=="string")try{F=new u(F,this.options)}catch{return!1}for(let q=0;q<this.set.length;q++)if(N(this.set[q],F,this.options))return!0;return!1}}zv=t;const r=AN(),n=new r,i=m1(),o=Pp(),s=Ap(),u=fn(),{safeRe:c,t:f,comparatorTrimReplace:p,tildeTrimReplace:g,caretTrimReplace:h}=_c(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:y}=Ip(),b=j=>j.value==="<0.0.0-0",S=j=>j.value==="",_=(j,F)=>{let q=!0;const U=j.slice();let M=U.pop();for(;q&&U.length;)q=U.every(G=>M.intersects(G,F)),M=U.pop();return q},C=(j,F)=>(s("comp",j,F),j=$(j,F),s("caret",j),j=R(j,F),s("tildes",j),j=L(j,F),s("xrange",j),j=B(j,F),s("stars",j),j),O=j=>!j||j.toLowerCase()==="x"||j==="*",R=(j,F)=>j.trim().split(/\s+/).map(q=>T(q,F)).join(" "),T=(j,F)=>{const q=F.loose?c[f.TILDELOOSE]:c[f.TILDE];return j.replace(q,(U,M,G,K,D)=>{s("tilde",j,U,M,G,K,D);let A;return O(M)?A="":O(G)?A=`>=${M}.0.0 <${+M+1}.0.0-0`:O(K)?A=`>=${M}.${G}.0 <${M}.${+G+1}.0-0`:D?(s("replaceTilde pr",D),A=`>=${M}.${G}.${K}-${D} <${M}.${+G+1}.0-0`):A=`>=${M}.${G}.${K} <${M}.${+G+1}.0-0`,s("tilde return",A),A})},$=(j,F)=>j.trim().split(/\s+/).map(q=>P(q,F)).join(" "),P=(j,F)=>{s("caret",j,F);const q=F.loose?c[f.CARETLOOSE]:c[f.CARET],U=F.includePrerelease?"-0":"";return j.replace(q,(M,G,K,D,A)=>{s("caret",j,M,G,K,D,A);let J;return O(G)?J="":O(K)?J=`>=${G}.0.0${U} <${+G+1}.0.0-0`:O(D)?G==="0"?J=`>=${G}.${K}.0${U} <${G}.${+K+1}.0-0`:J=`>=${G}.${K}.0${U} <${+G+1}.0.0-0`:A?(s("replaceCaret pr",A),G==="0"?K==="0"?J=`>=${G}.${K}.${D}-${A} <${G}.${K}.${+D+1}-0`:J=`>=${G}.${K}.${D}-${A} <${G}.${+K+1}.0-0`:J=`>=${G}.${K}.${D}-${A} <${+G+1}.0.0-0`):(s("no pr"),G==="0"?K==="0"?J=`>=${G}.${K}.${D}${U} <${G}.${K}.${+D+1}-0`:J=`>=${G}.${K}.${D}${U} <${G}.${+K+1}.0-0`:J=`>=${G}.${K}.${D} <${+G+1}.0.0-0`),s("caret return",J),J})},L=(j,F)=>(s("replaceXRanges",j,F),j.split(/\s+/).map(q=>z(q,F)).join(" ")),z=(j,F)=>{j=j.trim();const q=F.loose?c[f.XRANGELOOSE]:c[f.XRANGE];return j.replace(q,(U,M,G,K,D,A)=>{s("xRange",j,U,M,G,K,D,A);const J=O(G),Z=J||O(K),ne=Z||O(D),W=ne;return M==="="&&W&&(M=""),A=F.includePrerelease?"-0":"",J?M===">"||M==="<"?U="<0.0.0-0":U="*":M&&W?(Z&&(K=0),D=0,M===">"?(M=">=",Z?(G=+G+1,K=0,D=0):(K=+K+1,D=0)):M==="<="&&(M="<",Z?G=+G+1:K=+K+1),M==="<"&&(A="-0"),U=`${M+G}.${K}.${D}${A}`):Z?U=`>=${G}.0.0${A} <${+G+1}.0.0-0`:ne&&(U=`>=${G}.${K}.0${A} <${G}.${+K+1}.0-0`),s("xRange return",U),U})},B=(j,F)=>(s("replaceStars",j,F),j.trim().replace(c[f.STAR],"")),X=(j,F)=>(s("replaceGTE0",j,F),j.trim().replace(c[F.includePrerelease?f.GTE0PRE:f.GTE0],"")),Y=j=>(F,q,U,M,G,K,D,A,J,Z,ne,W)=>(O(U)?q="":O(M)?q=`>=${U}.0.0${j?"-0":""}`:O(G)?q=`>=${U}.${M}.0${j?"-0":""}`:K?q=`>=${q}`:q=`>=${q}${j?"-0":""}`,O(J)?A="":O(Z)?A=`<${+J+1}.0.0-0`:O(ne)?A=`<${J}.${+Z+1}.0-0`:W?A=`<=${J}.${Z}.${ne}-${W}`:j?A=`<${J}.${Z}.${+ne+1}-0`:A=`<=${A}`,`${q} ${A}`.trim()),N=(j,F,q)=>{for(let U=0;U<j.length;U++)if(!j[U].test(F))return!1;if(F.prerelease.length&&!q.includePrerelease){for(let U=0;U<j.length;U++)if(s(j[U].semver),j[U].semver!==o.ANY&&j[U].semver.prerelease.length>0){const M=j[U].semver;if(M.major===F.major&&M.minor===F.minor&&M.patch===F.patch)return!0}return!1}return!0};return zv}var Bv,aC;function Pp(){if(aC)return Bv;aC=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(p,g){if(g=r(g),p instanceof t){if(p.loose===!!g.loose)return p;p=p.value}p=p.trim().split(/\s+/).join(" "),s("comparator",p,g),this.options=g,this.loose=!!g.loose,this.parse(p),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(p){const g=this.options.loose?n[i.COMPARATORLOOSE]:n[i.COMPARATOR],h=p.match(g);if(!h)throw new TypeError(`Invalid comparator: ${p}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new u(h[2],this.options.loose):this.semver=e}toString(){return this.value}test(p){if(s("Comparator.test",p,this.options.loose),this.semver===e||p===e)return!0;if(typeof p=="string")try{p=new u(p,this.options)}catch{return!1}return o(p,this.operator,this.semver,this.options)}intersects(p,g){if(!(p instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(p.value,g).test(this.value):p.operator===""?p.value===""?!0:new c(this.value,g).test(p.semver):(g=r(g),g.includePrerelease&&(this.value==="<0.0.0-0"||p.value==="<0.0.0-0")||!g.includePrerelease&&(this.value.startsWith("<0.0.0")||p.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&p.operator.startsWith(">")||this.operator.startsWith("<")&&p.operator.startsWith("<")||this.semver.version===p.semver.version&&this.operator.includes("=")&&p.operator.includes("=")||o(this.semver,"<",p.semver,g)&&this.operator.startsWith(">")&&p.operator.startsWith("<")||o(this.semver,">",p.semver,g)&&this.operator.startsWith("<")&&p.operator.startsWith(">")))}}Bv=t;const r=m1(),{safeRe:n,t:i}=_c(),o=I$(),s=Ap(),u=fn(),c=to();return Bv}var Vv,sC;function Mp(){if(sC)return Vv;sC=1;const e=to();return Vv=(r,n,i)=>{try{n=new e(n,i)}catch{return!1}return n.test(r)},Vv}var Hv,lC;function kN(){if(lC)return Hv;lC=1;const e=to();return Hv=(r,n)=>new e(r,n).set.map(i=>i.map(o=>o.value).join(" ").trim().split(" ")),Hv}var Uv,uC;function PN(){if(uC)return Uv;uC=1;const e=fn(),t=to();return Uv=(n,i,o)=>{let s=null,u=null,c=null;try{c=new t(i,o)}catch{return null}return n.forEach(f=>{c.test(f)&&(!s||u.compare(f)===-1)&&(s=f,u=new e(s,o))}),s},Uv}var Wv,cC;function MN(){if(cC)return Wv;cC=1;const e=fn(),t=to();return Wv=(n,i,o)=>{let s=null,u=null,c=null;try{c=new t(i,o)}catch{return null}return n.forEach(f=>{c.test(f)&&(!s||u.compare(f)===1)&&(s=f,u=new e(s,o))}),s},Wv}var Gv,fC;function DN(){if(fC)return Gv;fC=1;const e=fn(),t=to(),r=kp();return Gv=(i,o)=>{i=new t(i,o);let s=new e("0.0.0");if(i.test(s)||(s=new e("0.0.0-0"),i.test(s)))return s;s=null;for(let u=0;u<i.set.length;++u){const c=i.set[u];let f=null;c.forEach(p=>{const g=new e(p.semver.version);switch(p.operator){case">":g.prerelease.length===0?g.patch++:g.prerelease.push(0),g.raw=g.format();case"":case">=":(!f||r(g,f))&&(f=g);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${p.operator}`)}}),f&&(!s||r(s,f))&&(s=f)}return s&&i.test(s)?s:null},Gv}var qv,dC;function LN(){if(dC)return qv;dC=1;const e=to();return qv=(r,n)=>{try{return new e(r,n).range||"*"}catch{return null}},qv}var Xv,pC;function x1(){if(pC)return Xv;pC=1;const e=fn(),t=Pp(),{ANY:r}=t,n=to(),i=Mp(),o=kp(),s=b1(),u=w1(),c=S1();return Xv=(p,g,h,m)=>{p=new e(p,m),g=new n(g,m);let y,b,S,_,C;switch(h){case">":y=o,b=u,S=s,_=">",C=">=";break;case"<":y=s,b=c,S=o,_="<",C="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i(p,g,m))return!1;for(let O=0;O<g.set.length;++O){const R=g.set[O];let T=null,$=null;if(R.forEach(P=>{P.semver===r&&(P=new t(">=0.0.0")),T=T||P,$=$||P,y(P.semver,T.semver,m)?T=P:S(P.semver,$.semver,m)&&($=P)}),T.operator===_||T.operator===C||(!$.operator||$.operator===_)&&b(p,$.semver))return!1;if($.operator===C&&S(p,$.semver))return!1}return!0},Xv}var Kv,hC;function FN(){if(hC)return Kv;hC=1;const e=x1();return Kv=(r,n,i)=>e(r,n,">",i),Kv}var Yv,gC;function NN(){if(gC)return Yv;gC=1;const e=x1();return Yv=(r,n,i)=>e(r,n,"<",i),Yv}var Qv,vC;function jN(){if(vC)return Qv;vC=1;const e=to();return Qv=(r,n,i)=>(r=new e(r,i),n=new e(n,i),r.intersects(n,i)),Qv}var Jv,mC;function zN(){if(mC)return Jv;mC=1;const e=Mp(),t=eo();return Jv=(r,n,i)=>{const o=[];let s=null,u=null;const c=r.sort((h,m)=>t(h,m,i));for(const h of c)e(h,n,i)?(u=h,s||(s=h)):(u&&o.push([s,u]),u=null,s=null);s&&o.push([s,null]);const f=[];for(const[h,m]of o)h===m?f.push(h):!m&&h===c[0]?f.push("*"):m?h===c[0]?f.push(`<=${m}`):f.push(`${h} - ${m}`):f.push(`>=${h}`);const p=f.join(" || "),g=typeof n.raw=="string"?n.raw:String(n);return p.length<g.length?p:n},Jv}var Zv,yC;function BN(){if(yC)return Zv;yC=1;const e=to(),t=Pp(),{ANY:r}=t,n=Mp(),i=eo(),o=(g,h,m={})=>{if(g===h)return!0;g=new e(g,m),h=new e(h,m);let y=!1;e:for(const b of g.set){for(const S of h.set){const _=c(b,S,m);if(y=y||_!==null,_)continue e}if(y)return!1}return!0},s=[new t(">=0.0.0-0")],u=[new t(">=0.0.0")],c=(g,h,m)=>{if(g===h)return!0;if(g.length===1&&g[0].semver===r){if(h.length===1&&h[0].semver===r)return!0;m.includePrerelease?g=s:g=u}if(h.length===1&&h[0].semver===r){if(m.includePrerelease)return!0;h=u}const y=new Set;let b,S;for(const L of g)L.operator===">"||L.operator===">="?b=f(b,L,m):L.operator==="<"||L.operator==="<="?S=p(S,L,m):y.add(L.semver);if(y.size>1)return null;let _;if(b&&S){if(_=i(b.semver,S.semver,m),_>0)return null;if(_===0&&(b.operator!==">="||S.operator!=="<="))return null}for(const L of y){if(b&&!n(L,String(b),m)||S&&!n(L,String(S),m))return null;for(const z of h)if(!n(L,String(z),m))return!1;return!0}let C,O,R,T,$=S&&!m.includePrerelease&&S.semver.prerelease.length?S.semver:!1,P=b&&!m.includePrerelease&&b.semver.prerelease.length?b.semver:!1;$&&$.prerelease.length===1&&S.operator==="<"&&$.prerelease[0]===0&&($=!1);for(const L of h){if(T=T||L.operator===">"||L.operator===">=",R=R||L.operator==="<"||L.operator==="<=",b){if(P&&L.semver.prerelease&&L.semver.prerelease.length&&L.semver.major===P.major&&L.semver.minor===P.minor&&L.semver.patch===P.patch&&(P=!1),L.operator===">"||L.operator===">="){if(C=f(b,L,m),C===L&&C!==b)return!1}else if(b.operator===">="&&!n(b.semver,String(L),m))return!1}if(S){if($&&L.semver.prerelease&&L.semver.prerelease.length&&L.semver.major===$.major&&L.semver.minor===$.minor&&L.semver.patch===$.patch&&($=!1),L.operator==="<"||L.operator==="<="){if(O=p(S,L,m),O===L&&O!==S)return!1}else if(S.operator==="<="&&!n(S.semver,String(L),m))return!1}if(!L.operator&&(S||b)&&_!==0)return!1}return!(b&&R&&!S&&_!==0||S&&T&&!b&&_!==0||P||$)},f=(g,h,m)=>{if(!g)return h;const y=i(g.semver,h.semver,m);return y>0?g:y<0||h.operator===">"&&g.operator===">="?h:g},p=(g,h,m)=>{if(!g)return h;const y=i(g.semver,h.semver,m);return y<0?g:y>0||h.operator==="<"&&g.operator==="<="?h:g};return Zv=o,Zv}var em,bC;function VN(){if(bC)return em;bC=1;const e=_c(),t=Ip(),r=fn(),n=O$(),i=Vl(),o=yN(),s=bN(),u=SN(),c=wN(),f=xN(),p=EN(),g=CN(),h=_N(),m=eo(),y=RN(),b=ON(),S=y1(),_=TN(),C=$N(),O=kp(),R=b1(),T=T$(),$=$$(),P=S1(),L=w1(),z=I$(),B=IN(),X=Pp(),Y=to(),N=Mp(),j=kN(),F=PN(),q=MN(),U=DN(),M=LN(),G=x1(),K=FN(),D=NN(),A=jN(),J=zN(),Z=BN();return em={parse:i,valid:o,clean:s,inc:u,diff:c,major:f,minor:p,patch:g,prerelease:h,compare:m,rcompare:y,compareLoose:b,compareBuild:S,sort:_,rsort:C,gt:O,lt:R,eq:T,neq:$,gte:P,lte:L,cmp:z,coerce:B,Comparator:X,Range:Y,satisfies:N,toComparators:j,maxSatisfying:F,minSatisfying:q,minVersion:U,validRange:M,outside:G,gtr:K,ltr:D,intersects:A,simplifyRange:J,subset:Z,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},em}var Vn=VN();const SC=Dr(Vn);var Xt=(e=>(e.NANO_S="nanoS",e.NANO_SP="nanoSP",e.NANO_X="nanoX",e.STAX="stax",e.FLEX="flex",e.APEX="apexp",e))(Xt||{});let A$=class{id;model;name;constructor({id:t,model:r,name:n}){this.id=t,this.model=r,this.name=n}},HN=class{constructor(t){if(this.seFlags=t,this.seFlags.length!==4)throw new Error("Invalid secure element flags 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(){throw new Error("Not implemented")}wordsInformation(){throw new Error("Not implemented")}onboardingStatus(){throw new Error("Not implemented")}_checkNthBitInByte(t,r){return(t>>8-r&1)===1}},UN=class{name="getOsVersion";args=void 0;getApdu(){const t={cla:224,ins:1,p1:0,p2:0};return new _$(t).build()}parseResponse(t,r){if(!v1.isSuccessResponse(t))return ls({error:R$.handle(t)});const n=new g1(t),i=n.extract32BitUInt();if(i===void 0)return ls({error:new aN("Missing target ID in OS version")});let o=n.encodeToString(n.extractFieldLVEncoded()),s=n.extractFieldLVEncoded()??new Uint8Array(0);const u={...new HN(s).generalDeviceState()};o||(o="0.0.0",s=new Uint8Array);const c=(i&4026531840)!==805306368,f=o.includes("-osu");let p="",g="",h="",m="",y,b,S,_;if(c){h=o,y=i;const C=n.extractFieldLVEncoded();C&&(C.length>=5?(p=n.encodeToString(C),b=parseInt(n.encodeToHexaString(n.extractFieldLVEncoded()),16)):b=parseInt(n.encodeToHexaString(C),16))}else{if(p=o,b=i,g=n.encodeToString(n.extractFieldLVEncoded()),this.isBootloaderVersionSupported(p,r)&&(h=n.encodeToString(n.extractFieldLVEncoded())),this.isHardwareVersionSupported(p,r)?m=n.encodeToHexaString(n.extractFieldLVEncoded()):m="00",this.isLocalizationSupported(p,r)){const C=n.extractFieldLVEncoded();C!==void 0&&(S=parseInt(n.encodeToHexaString(C),16))}if(this.isRecoverSupported(p,r)){const C=n.extractFieldLVEncoded();C!==void 0&&(_=parseInt(n.encodeToHexaString(C),16))}}return ls({data:{isBootloader:c,isOsu:f,targetId:i,seTargetId:b,mcuTargetId:y,seVersion:p,seFlags:s,mcuSephVersion:g,mcuBootloaderVersion:h,hwVersion:m,langId:S,recoverState:_,secureElementFlags:u}})}isBootloaderVersionSupported(t,r){const n=Vn.coerce(t)??"";switch(r){case Xt.NANO_S:case Xt.NANO_X:return Vn.gte(n,"2.0.0");default:return!0}}isHardwareVersionSupported(t,r){const n=Vn.coerce(t)??"";return r===Xt.NANO_X?Vn.gte(n,"2.0.0"):!1}isLocalizationSupported(t,r){const n=Vn.coerce(t)??"";switch(r){case Xt.NANO_S:return!1;case Xt.NANO_SP:return Vn.gte(n,"1.1.0");case Xt.NANO_X:return Vn.gte(n,"2.1.0");default:return!0}}isRecoverSupported(t,r){const n=Vn.coerce(t)??"";switch(r){case Xt.NANO_S:return!1;case Xt.NANO_SP:return Vn.gte(n,"1.1.2");case Xt.NANO_X:return Vn.gte(n,"2.2.3");case Xt.STAX:return Vn.gte(n,"1.4.0");case Xt.FLEX:return Vn.gte(n,"1.0.1");default:return!0}}};var po=(e=>(e.LOCKED="LOCKED",e.BUSY="BUSY",e.CONNECTED="CONNECTED",e.NOT_CONNECTED="NOT CONNECTED",e))(po||{}),WN=(e=>(e.NotStarted="not-started",e.Pending="pending",e.Stopped="stopped",e.Completed="completed",e.Error="error",e))(WN||{}),GN=(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))(GN||{});const Cn={of(e){return Qr(e)},empty(){return jt},zero(){return jt},fromNullable(e){return e==null?jt:Qr(e)},fromFalsy(e){return e?Qr(e):jt},fromPredicate(e,t){return arguments.length===1?r=>Cn.fromPredicate(e,r):e(t)?Qr(t):jt},mapMaybe(e,t){return arguments.length===1?r=>Cn.mapMaybe(e,r):Cn.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 Qr(e())}catch{return jt}},isMaybe(e){return e instanceof E1||e instanceof C1},sequence(e){let t=[];for(const r of e)if(r.isJust())t.push(r.extract());else return jt;return Qr(t)},"fantasy-land/of"(e){return this.of(e)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};class E1{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 Qr(t(this.__value))}ap(t){return t.isJust()?this.map(t.extract()):jt}alt(t){return this}altLazy(t){return this}chain(t){return t(this.__value)}chainNullable(t){return Cn.fromNullable(t(this.__value))}join(){return this.__value}reduce(t,r){return t(r,this.__value)}extend(t){return Qr(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 nr(this.__value)}ifJust(t){return t(this.__value),this}ifNothing(t){return this}filter(t){return t(this.__value)?Qr(this.__value):jt}}E1.prototype.constructor=Cn;class C1{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 jt}ap(t){return jt}alt(t){return t}altLazy(t){return t()}chain(t){return jt}chainNullable(t){return jt}join(){return jt}reduce(t,r){return r}extend(t){return jt}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 Wt(t)}ifJust(t){return this}ifNothing(t){return t(),this}filter(t){return jt}}C1.prototype.constructor=Cn;const Qr=e=>new E1(e),jt=new C1,_n={of(e){return nr(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 nr(e())}catch(t){return Wt(t)}},sequence(e){let t=[];for(const r of e){if(r.isLeft())return r;t.push(r.extract())}return nr(t)},isEither(e){return e instanceof R1||e instanceof _1},"fantasy-land/of"(e){return _n.of(e)}};class _1{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 nr(r(this.__value))}map(t){return nr(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 nr(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 Qr(this.__value)}leftToMaybe(){return jt}extract(){return this.__value}swap(){return Wt(this.__value)}}_1.prototype.constructor=_n;class R1{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 Wt(t(this.__value))}map(t){return this}mapLeft(t){return Wt(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 jt}leftToMaybe(){return Qr(this.__value)}extract(){return this.__value}swap(){return nr(this.__value)}}R1.prototype.constructor=_n;const Wt=e=>new R1(e),nr=e=>new _1(e),Rc=e=>e,qN=e=>e,tm=Object.assign(qN,{fromArray:e=>tm.isNonEmpty(e)?Qr(e):jt,unsafeCoerce:e=>{if(tm.isNonEmpty(e))return e;throw new Error("NonEmptyList#unsafeCoerce was ran on an empty array")},fromTuple:e=>tm(e.toArray()),head:e=>e[0],last:e=>e[e.length-1],isNonEmpty:e=>e.length>0,tail:e=>e.slice(1)}),jd=(e,t)=>typeof t=="bigint"?t.toString():t,XN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xs=(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,jd):"an object with value "+JSON.stringify(t,jd);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,jd)}`,`Expected ${e}, but received ${r}`},KN=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),YN=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),k$(e)}return e},k$=e=>(YN(e),KN(e),e),Sr={interface(e){const t=Object.keys(e),r=i=>{if(!XN(i))return Wt(xs("an object",i));const o={};for(const s of t){if(!i.hasOwnProperty(s)&&!e[s]._isOptional)return Wt(`Problem with property "${s}": it does not exist in received object ${JSON.stringify(i,jd)}`);const u=e[s].decode(i[s]);if(u.isLeft())return Wt(`Problem with the value of property "${s}": ${u.extract()}`);const c=u.extract();c!==void 0&&(o[s]=c)}return nr(o)};return{decode:r,encode:i=>{const o={};for(const s of t)o[s]=e[s].encode(i[s]);return o},unsafeDecode:i=>r(i).mapLeft(Error).unsafeCoerce(),schema:()=>t.reduce((i,o)=>(e[o]._isOptional||i.required.push(o),i.properties[o]=k$(e[o].schema()),i),{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??(()=>({}))}}},zt=Sr.custom({decode:e=>typeof e=="string"?nr(e):Wt(xs("a string",e)),encode:Rc,schema:()=>({type:"string"})}),Cl=Sr.custom({decode:e=>typeof e=="number"?nr(e):Wt(xs("a number",e)),encode:Rc,schema:()=>({type:"number"})}),QN=Sr.custom({decode:e=>e===void 0?nr(e):Wt(xs("an undefined",e)),encode:Rc}),sn=e=>({...JN([e,QN]),schema:e.schema,_isOptional:!0}),P$=Sr.custom({decode:e=>typeof e=="boolean"?nr(e):Wt(xs("a boolean",e)),encode:Rc,schema:()=>({type:"boolean"})}),JN=e=>Sr.custom({decode:t=>{let r=[];for(const n of e){const i=n.decode(t);if(i.isRight())return i;r.push(i.extract())}return Wt(`One of the following problems occured: ${r.map((n,i)=>`(${i}) ${n}`).join(", ")}`)},encode:t=>{for(const r of e)if(_n.encase(()=>r.encode(t)).mapLeft(i=>"").chain(r.decode).isRight())return r.encode(t);return t},schema:()=>({oneOf:e.map(t=>t.schema())})}),bi=e=>Sr.custom({decode:t=>{if(Array.isArray(t)){const r=[];for(let n=0;n<t.length;n++){const i=e.decode(t[n]);if(i.isRight())r.push(i.extract());else return Wt(`Problem with the value at index ${n}: ${i.extract()}`)}return nr(r)}else return Wt(xs("an array",t))},encode:t=>t.map(e.encode),schema:()=>({type:"array",items:e.schema()})});Sr.custom({decode:e=>zt.decode(e).chain(t=>isFinite(+t)?nr(t):Wt(xs("a number",e))),encode:Rc,schema:Cl.schema});var M$;const D$={liftEither(e){if(e.isRight())return Promise.resolve(e.extract());throw e.extract()},fromPromise(e){return e.then(D$.liftEither)},throwE(e){throw e}};class L${constructor(t){this.runPromise=t,this[M$]="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 pt(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 pt(async r=>{const n=await t;if(n.isRight()){const i=await this.run();return i.isRight()?n.extract()(i.extract()):r.liftEither(i)}return r.liftEither(n)})}alt(t){return pt(async r=>{const n=await this.run();if(n.isRight())return n.extract();{const i=await t;return r.liftEither(i)}})}extend(t){return pt(async r=>{const n=await this.run();if(n.isRight()){const i=pt.liftEither(n);return r.liftEither(nr(t(i)))}return r.liftEither(n)})}async run(){try{return nr(await this.runPromise(D$))}catch(t){return Wt(t)}}bimap(t,r){return pt(async n=>{const i=await this.run();try{return await n.liftEither(i.bimap(t,r))}catch(o){throw await o}})}map(t){return pt(r=>this.runPromise(r).then(t))}mapLeft(t){return pt(async r=>{try{return await this.runPromise(r)}catch(n){throw await t(n)}})}chain(t){return pt(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}chainLeft(t){return pt(async r=>{try{return await this.runPromise(r)}catch(n){return r.fromPromise(t(n))}})}toMaybeAsync(){return on(async({liftMaybe:t})=>{const r=await this.run();return t(r.toMaybe())})}swap(){return pt(async t=>{const r=await this.run();return r.isRight()&&t.throwE(r.extract()),t.liftEither(nr(r.extract()))})}ifLeft(t){return pt(async r=>{const n=await this.run();return n.ifLeft(t),r.liftEither(n)})}ifRight(t){return pt(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 pt(({fromPromise:r})=>r(this.run().finally(t)))}}M$=Symbol.toStringTag;const pt=Object.assign(e=>new L$(e),{fromPromise:e=>pt(({fromPromise:t})=>t(e())),liftEither:e=>pt(({liftEither:t})=>t(e)),lefts:e=>Promise.all(e.map(t=>t.run())).then(_n.lefts),rights:e=>Promise.all(e.map(t=>t.run())).then(_n.rights),sequence:e=>pt(async t=>{let r=[];for await(const n of e){if(n.isLeft())return t.liftEither(n);r.push(n.extract())}return t.liftEither(nr(r))}),all:e=>pt.fromPromise(async()=>Promise.all(e).then(_n.sequence))});L$.prototype.constructor=pt;var F$;const N$={liftMaybe(e){if(e.isJust())return Promise.resolve(e.extract());throw jt},fromPromise(e){return e.then(N$.liftMaybe)}};class j${constructor(t){this.runPromise=t,this[F$]="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 on(async t=>{const r=await this.run();if(r.isJust()){const n=await r.extract();return t.liftMaybe(n)}return t.liftMaybe(jt)})}ap(t){return on(async r=>{const n=await t;if(n.isJust()){const i=await this.run();return i.isJust()?n.extract()(i.extract()):r.liftMaybe(jt)}return r.liftMaybe(jt)})}alt(t){return on(async r=>{const n=await this.run();if(n.isJust())return n.extract();{const i=await t;return r.liftMaybe(i)}})}extend(t){return on(async r=>{const n=await this.run();if(n.isJust()){const i=on.liftMaybe(n);return r.liftMaybe(Qr(t(i)))}return r.liftMaybe(jt)})}filter(t){return on(async r=>{const n=await this.run();return r.liftMaybe(n.filter(t))})}async run(){try{return Qr(await this.runPromise(N$))}catch{return jt}}map(t){return on(r=>this.runPromise(r).then(t))}chain(t){return on(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}toEitherAsync(t){return pt(async({liftEither:r})=>{const n=await this.run();return r(n.toEither(t))})}ifJust(t){return on(async r=>{const n=await this.run();return n.ifJust(t),r.liftMaybe(n)})}ifNothing(t){return on(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 on(({fromPromise:r})=>r(this.run().finally(t)))}then(t,r){return this.run().then(t,r)}}F$=Symbol.toStringTag;const on=Object.assign(e=>new j$(e),{catMaybes:e=>Promise.all(e).then(Cn.catMaybes),fromPromise:e=>on(({fromPromise:t})=>t(e())),liftMaybe:e=>on(({liftMaybe:t})=>t(e))});j$.prototype.constructor=on;var z0=function(e,t){return z0=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},z0(e,t)};function xo(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");z0(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function ZN(e,t,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function u(p){try{f(n.next(p))}catch(g){s(g)}}function c(p){try{f(n.throw(p))}catch(g){s(g)}}function f(p){p.done?o(p.value):i(p.value).then(u,c)}f((n=n.apply(e,t||[])).next())})}function z$(e,t){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=u(0),s.throw=u(1),s.return=u(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(f){return function(p){return c([f,p])}}function c(f){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,f[0]&&(r=0)),r;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){r.label=f[1];break}if(f[0]===6&&r.label<o[1]){r.label=o[1],o=f;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(f);break}o[2]&&r.ops.pop(),r.trys.pop();continue}f=t.call(e,r)}catch(p){f=[6,p],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function _l(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rl(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),i,o=[],s;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function Ol(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,o;n<i;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))}function bl(e){return this instanceof bl?(this.v=e,this):new bl(e)}function e3(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(e,t||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(m){return function(y){return Promise.resolve(y).then(m,g)}}function u(m,y){n[m]&&(i[m]=function(b){return new Promise(function(S,_){o.push([m,b,S,_])>1||c(m,b)})},y&&(i[m]=y(i[m])))}function c(m,y){try{f(n[m](y))}catch(b){h(o[0][3],b)}}function f(m){m.value instanceof bl?Promise.resolve(m.value.v).then(p,g):h(o[0][2],m)}function p(m){c("next",m)}function g(m){c("throw",m)}function h(m,y){m(y),o.shift(),o.length&&c(o[0][0],o[0][1])}}function t3(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof _l=="function"?_l(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=e[o]&&function(s){return new Promise(function(u,c){s=e[o](s),i(u,c,s.done,s.value)})}}function i(o,s,u,c){Promise.resolve(c).then(function(f){o({value:f,done:u})},s)}}function cr(e){return typeof e=="function"}function Dp(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 rm=Dp(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription:
453
+ `,wE=({direction:e,first:t,second:r,defaultFirstSize:n="50%",minFirstSize:i="20%",minSecondSize:o="20%"})=>k.jsx(eN,{children:k.jsxs(x$,{orientation:e==="horizontal"?"vertical":"horizontal",style:{flex:1},children:[k.jsx(j0,{defaultSize:n,minSize:i,children:k.jsx(SE,{children:t})}),k.jsx(Z6,{$direction:e}),k.jsx(j0,{minSize:o,children:k.jsx(SE,{children:r})})]})}),Eu={CONNECTED_DEVICES_UPDATE:"connectedDevicesUpdate",DEVICE_SESSION_STATE_UPDATE:"deviceSessionStateUpdate",PROVIDER_VALUE:"providerValue",APDU_RESPONSE:"apduResponse",DISCOVERED_DEVICES_UPDATE:"discoveredDevicesUpdate"},Qo={DISCONNECT:"disconnect",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"},xE={LOGGER:"logger",DMK_INSPECTOR:"dmk-inspector"},tN="moduleConnected";var EE;(function(e){(function(t){var r=typeof globalThis=="object"?globalThis:typeof self=="object"||typeof self=="object"?self:typeof this=="object"?this:u(),n=i(e);typeof r.Reflect<"u"&&(n=i(r.Reflect,n)),t(n,r),typeof r.Reflect>"u"&&(r.Reflect=e);function i(c,f){return function(p,g){Object.defineProperty(c,p,{configurable:!0,writable:!0,value:g}),f&&f(p,g)}}function o(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function u(){return o()||s()}})(function(t,r){var n=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",o=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",u=typeof Object.create=="function",c={__proto__:[]}instanceof Array,f=!u&&!c,p={create:u?function(){return Dt(Object.create(null))}:c?function(){return Dt({__proto__:null})}:function(){return Dt({})},has:f?function(re,ie){return n.call(re,ie)}:function(re,ie){return ie in re},get:f?function(re,ie){return n.call(re,ie)?re[ie]:void 0}:function(re,ie){return re[ie]}},g=Object.getPrototypeOf(Function),h=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Mt(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:ht(),y=typeof WeakMap=="function"?WeakMap:Kt(),b=i?Symbol.for("@reflect-metadata:registry"):void 0,S=Ve(),_=ye(S);function C(re,ie,ue,V){if(A(ue)){if(!Me(re))throw new TypeError;if(!je(ie))throw new TypeError;return Y(re,ie)}else{if(!Me(re))throw new TypeError;if(!ne(ie))throw new TypeError;if(!ne(V)&&!A(V)&&!J(V))throw new TypeError;return J(V)&&(V=void 0),ue=we(ue),N(re,ie,ue,V)}}t("decorate",C);function O(re,ie){function ue(V,pe){if(!ne(V))throw new TypeError;if(!A(pe)&&!Ae(pe))throw new TypeError;M(re,ie,V,pe)}return ue}t("metadata",O);function R(re,ie,ue,V){if(!ne(ue))throw new TypeError;return A(V)||(V=we(V)),M(re,ie,ue,V)}t("defineMetadata",R);function T(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),j(re,ie,ue)}t("hasMetadata",T);function $(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),F(re,ie,ue)}t("hasOwnMetadata",$);function P(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),q(re,ie,ue)}t("getMetadata",P);function L(re,ie,ue){if(!ne(ie))throw new TypeError;return A(ue)||(ue=we(ue)),U(re,ie,ue)}t("getOwnMetadata",L);function z(re,ie){if(!ne(re))throw new TypeError;return A(ie)||(ie=we(ie)),G(re,ie)}t("getMetadataKeys",z);function B(re,ie){if(!ne(re))throw new TypeError;return A(ie)||(ie=we(ie)),K(re,ie)}t("getOwnMetadataKeys",B);function X(re,ie,ue){if(!ne(ie))throw new TypeError;if(A(ue)||(ue=we(ue)),!ne(ie))throw new TypeError;A(ue)||(ue=we(ue));var V=ct(ie,ue,!1);return A(V)?!1:V.OrdinaryDeleteMetadata(re,ie,ue)}t("deleteMetadata",X);function Y(re,ie){for(var ue=re.length-1;ue>=0;--ue){var V=re[ue],pe=V(ie);if(!A(pe)&&!J(pe)){if(!je(pe))throw new TypeError;ie=pe}}return ie}function N(re,ie,ue,V){for(var pe=re.length-1;pe>=0;--pe){var _e=re[pe],De=_e(ie,ue,V);if(!A(De)&&!J(De)){if(!ne(De))throw new TypeError;V=De}}return V}function j(re,ie,ue){var V=F(re,ie,ue);if(V)return!0;var pe=Ue(ie);return J(pe)?!1:j(re,pe,ue)}function F(re,ie,ue){var V=ct(ie,ue,!1);return A(V)?!1:se(V.OrdinaryHasOwnMetadata(re,ie,ue))}function q(re,ie,ue){var V=F(re,ie,ue);if(V)return U(re,ie,ue);var pe=Ue(ie);if(!J(pe))return q(re,pe,ue)}function U(re,ie,ue){var V=ct(ie,ue,!1);if(!A(V))return V.OrdinaryGetOwnMetadata(re,ie,ue)}function M(re,ie,ue,V){var pe=ct(ue,V,!0);pe.OrdinaryDefineOwnMetadata(re,ie,ue,V)}function G(re,ie){var ue=K(re,ie),V=Ue(re);if(V===null)return ue;var pe=G(V,ie);if(pe.length<=0)return ue;if(ue.length<=0)return pe;for(var _e=new m,De=[],fe=0,he=ue;fe<he.length;fe++){var me=he[fe],Ce=_e.has(me);Ce||(_e.add(me),De.push(me))}for(var $e=0,Xe=pe;$e<Xe.length;$e++){var me=Xe[$e],Ce=_e.has(me);Ce||(_e.add(me),De.push(me))}return De}function K(re,ie){var ue=ct(re,ie,!1);return ue?ue.OrdinaryOwnMetadataKeys(re,ie):[]}function D(re){if(re===null)return 1;switch(typeof re){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return re===null?1:6;default:return 6}}function A(re){return re===void 0}function J(re){return re===null}function Z(re){return typeof re=="symbol"}function ne(re){return typeof re=="object"?re!==null:typeof re=="function"}function W(re,ie){switch(D(re)){case 0:return re;case 1:return re;case 2:return re;case 3:return re;case 4:return re;case 5:return re}var ue="string",V=Ne(re,o);if(V!==void 0){var pe=V.call(re,ue);if(ne(pe))throw new TypeError;return pe}return ve(re)}function ve(re,ie){var ue,V,pe;{var _e=re.toString;if(Oe(_e)){var V=_e.call(re);if(!ne(V))return V}var ue=re.valueOf;if(Oe(ue)){var V=ue.call(re);if(!ne(V))return V}}throw new TypeError}function se(re){return!!re}function Ee(re){return""+re}function we(re){var ie=W(re);return Z(ie)?ie:Ee(ie)}function Me(re){return Array.isArray?Array.isArray(re):re instanceof Object?re instanceof Array:Object.prototype.toString.call(re)==="[object Array]"}function Oe(re){return typeof re=="function"}function je(re){return typeof re=="function"}function Ae(re){switch(D(re)){case 3:return!0;case 4:return!0;default:return!1}}function Te(re,ie){return re===ie||re!==re&&ie!==ie}function Ne(re,ie){var ue=re[ie];if(ue!=null){if(!Oe(ue))throw new TypeError;return ue}}function Ie(re){var ie=Ne(re,s);if(!Oe(ie))throw new TypeError;var ue=ie.call(re);if(!ne(ue))throw new TypeError;return ue}function Ke(re){return re.value}function nt(re){var ie=re.next();return ie.done?!1:ie}function ze(re){var ie=re.return;ie&&ie.call(re)}function Ue(re){var ie=Object.getPrototypeOf(re);if(typeof re!="function"||re===g||ie!==g)return ie;var ue=re.prototype,V=ue&&Object.getPrototypeOf(ue);if(V==null||V===Object.prototype)return ie;var pe=V.constructor;return typeof pe!="function"||pe===re?ie:pe}function Qe(){var re;!A(b)&&typeof r.Reflect<"u"&&!(b in r.Reflect)&&typeof r.Reflect.defineMetadata=="function"&&(re=Ge(r.Reflect));var ie,ue,V,pe=new y,_e={registerProvider:De,getProvider:he,setProvider:Ce};return _e;function De($e){if(!Object.isExtensible(_e))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case re===$e:break;case A(ie):ie=$e;break;case ie===$e:break;case A(ue):ue=$e;break;case ue===$e:break;default:V===void 0&&(V=new m),V.add($e);break}}function fe($e,Xe){if(!A(ie)){if(ie.isProviderFor($e,Xe))return ie;if(!A(ue)){if(ue.isProviderFor($e,Xe))return ie;if(!A(V))for(var it=Ie(V);;){var Je=nt(it);if(!Je)return;var ot=Ke(Je);if(ot.isProviderFor($e,Xe))return ze(it),ot}}}if(!A(re)&&re.isProviderFor($e,Xe))return re}function he($e,Xe){var it=pe.get($e),Je;return A(it)||(Je=it.get(Xe)),A(Je)&&(Je=fe($e,Xe),A(Je)||(A(it)&&(it=new h,pe.set($e,it)),it.set(Xe,Je))),Je}function me($e){if(A($e))throw new TypeError;return ie===$e||ue===$e||!A(V)&&V.has($e)}function Ce($e,Xe,it){if(!me(it))throw new Error("Metadata provider not registered.");var Je=he($e,Xe);if(Je!==it){if(!A(Je))return!1;var ot=pe.get($e);A(ot)&&(ot=new h,pe.set($e,ot)),ot.set(Xe,it)}return!0}}function Ve(){var re;return!A(b)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&(re=r.Reflect[b]),A(re)&&(re=Qe()),!A(b)&&ne(r.Reflect)&&Object.isExtensible(r.Reflect)&&Object.defineProperty(r.Reflect,b,{enumerable:!1,configurable:!1,writable:!1,value:re}),re}function ye(re){var ie=new y,ue={isProviderFor:function(me,Ce){var $e=ie.get(me);return A($e)?!1:$e.has(Ce)},OrdinaryDefineOwnMetadata:De,OrdinaryHasOwnMetadata:pe,OrdinaryGetOwnMetadata:_e,OrdinaryOwnMetadataKeys:fe,OrdinaryDeleteMetadata:he};return S.registerProvider(ue),ue;function V(me,Ce,$e){var Xe=ie.get(me),it=!1;if(A(Xe)){if(!$e)return;Xe=new h,ie.set(me,Xe),it=!0}var Je=Xe.get(Ce);if(A(Je)){if(!$e)return;if(Je=new h,Xe.set(Ce,Je),!re.setProvider(me,Ce,ue))throw Xe.delete(Ce),it&&ie.delete(me),new Error("Wrong provider for target.")}return Je}function pe(me,Ce,$e){var Xe=V(Ce,$e,!1);return A(Xe)?!1:se(Xe.has(me))}function _e(me,Ce,$e){var Xe=V(Ce,$e,!1);if(!A(Xe))return Xe.get(me)}function De(me,Ce,$e,Xe){var it=V($e,Xe,!0);it.set(me,Ce)}function fe(me,Ce){var $e=[],Xe=V(me,Ce,!1);if(A(Xe))return $e;for(var it=Xe.keys(),Je=Ie(it),ot=0;;){var Fr=nt(Je);if(!Fr)return $e.length=ot,$e;var ft=Ke(Fr);try{$e[ot]=ft}catch(dt){try{ze(Je)}finally{throw dt}}ot++}}function he(me,Ce,$e){var Xe=V(Ce,$e,!1);if(A(Xe)||!Xe.delete(me))return!1;if(Xe.size===0){var it=ie.get(Ce);A(it)||(it.delete($e),it.size===0&&ie.delete(it))}return!0}}function Ge(re){var ie=re.defineMetadata,ue=re.hasOwnMetadata,V=re.getOwnMetadata,pe=re.getOwnMetadataKeys,_e=re.deleteMetadata,De=new y,fe={isProviderFor:function(he,me){var Ce=De.get(he);return!A(Ce)&&Ce.has(me)?!0:pe(he,me).length?(A(Ce)&&(Ce=new m,De.set(he,Ce)),Ce.add(me),!0):!1},OrdinaryDefineOwnMetadata:ie,OrdinaryHasOwnMetadata:ue,OrdinaryGetOwnMetadata:V,OrdinaryOwnMetadataKeys:pe,OrdinaryDeleteMetadata:_e};return fe}function ct(re,ie,ue){var V=S.getProvider(re,ie);if(!A(V))return V;if(ue){if(S.setProvider(re,ie,_))return _;throw new Error("Illegal state.")}}function Mt(){var re={},ie=[],ue=(function(){function fe(he,me,Ce){this._index=0,this._keys=he,this._values=me,this._selector=Ce}return fe.prototype["@@iterator"]=function(){return this},fe.prototype[s]=function(){return this},fe.prototype.next=function(){var he=this._index;if(he>=0&&he<this._keys.length){var me=this._selector(this._keys[he],this._values[he]);return he+1>=this._keys.length?(this._index=-1,this._keys=ie,this._values=ie):this._index++,{value:me,done:!1}}return{value:void 0,done:!0}},fe.prototype.throw=function(he){throw this._index>=0&&(this._index=-1,this._keys=ie,this._values=ie),he},fe.prototype.return=function(he){return this._index>=0&&(this._index=-1,this._keys=ie,this._values=ie),{value:he,done:!0}},fe})(),V=(function(){function fe(){this._keys=[],this._values=[],this._cacheKey=re,this._cacheIndex=-2}return Object.defineProperty(fe.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),fe.prototype.has=function(he){return this._find(he,!1)>=0},fe.prototype.get=function(he){var me=this._find(he,!1);return me>=0?this._values[me]:void 0},fe.prototype.set=function(he,me){var Ce=this._find(he,!0);return this._values[Ce]=me,this},fe.prototype.delete=function(he){var me=this._find(he,!1);if(me>=0){for(var Ce=this._keys.length,$e=me+1;$e<Ce;$e++)this._keys[$e-1]=this._keys[$e],this._values[$e-1]=this._values[$e];return this._keys.length--,this._values.length--,Te(he,this._cacheKey)&&(this._cacheKey=re,this._cacheIndex=-2),!0}return!1},fe.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=re,this._cacheIndex=-2},fe.prototype.keys=function(){return new ue(this._keys,this._values,pe)},fe.prototype.values=function(){return new ue(this._keys,this._values,_e)},fe.prototype.entries=function(){return new ue(this._keys,this._values,De)},fe.prototype["@@iterator"]=function(){return this.entries()},fe.prototype[s]=function(){return this.entries()},fe.prototype._find=function(he,me){if(!Te(this._cacheKey,he)){this._cacheIndex=-1;for(var Ce=0;Ce<this._keys.length;Ce++)if(Te(this._keys[Ce],he)){this._cacheIndex=Ce;break}}return this._cacheIndex<0&&me&&(this._cacheIndex=this._keys.length,this._keys.push(he),this._values.push(void 0)),this._cacheIndex},fe})();return V;function pe(fe,he){return fe}function _e(fe,he){return he}function De(fe,he){return[fe,he]}}function ht(){var re=(function(){function ie(){this._map=new h}return Object.defineProperty(ie.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),ie.prototype.has=function(ue){return this._map.has(ue)},ie.prototype.add=function(ue){return this._map.set(ue,ue),this},ie.prototype.delete=function(ue){return this._map.delete(ue)},ie.prototype.clear=function(){this._map.clear()},ie.prototype.keys=function(){return this._map.keys()},ie.prototype.values=function(){return this._map.keys()},ie.prototype.entries=function(){return this._map.entries()},ie.prototype["@@iterator"]=function(){return this.keys()},ie.prototype[s]=function(){return this.keys()},ie})();return re}function Kt(){var re=16,ie=p.create(),ue=V();return(function(){function he(){this._key=V()}return he.prototype.has=function(me){var Ce=pe(me,!1);return Ce!==void 0?p.has(Ce,this._key):!1},he.prototype.get=function(me){var Ce=pe(me,!1);return Ce!==void 0?p.get(Ce,this._key):void 0},he.prototype.set=function(me,Ce){var $e=pe(me,!0);return $e[this._key]=Ce,this},he.prototype.delete=function(me){var Ce=pe(me,!1);return Ce!==void 0?delete Ce[this._key]:!1},he.prototype.clear=function(){this._key=V()},he})();function V(){var he;do he="@@WeakMap@@"+fe();while(p.has(ie,he));return ie[he]=!0,he}function pe(he,me){if(!n.call(he,ue)){if(!me)return;Object.defineProperty(he,ue,{value:p.create()})}return he[ue]}function _e(he,me){for(var Ce=0;Ce<me;++Ce)he[Ce]=Math.random()*255|0;return he}function De(he){if(typeof Uint8Array=="function"){var me=new Uint8Array(he);return typeof crypto<"u"?crypto.getRandomValues(me):typeof msCrypto<"u"?msCrypto.getRandomValues(me):_e(me,he),me}return _e(new Array(he),he)}function fe(){var he=De(re);he[6]=he[6]&79|64,he[8]=he[8]&191|128;for(var me="",Ce=0;Ce<re;++Ce){var $e=he[Ce];(Ce===4||Ce===6||Ce===8)&&(me+="-"),$e<16&&(me+="0"),me+=$e.toString(16).toLowerCase()}return me}}function Dt(re){return re.__=void 0,delete re.__,re}})})(EE||(EE={}));let rN=class{cla;ins;p1;p2;data;constructor(t,r,n,i,o){this.cla=t,this.ins=r,this.p1=n,this.p2=i,this.data=o??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 CE(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 Jo(e,t=!0){return`${t?"0x":""}${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`}let cv=class{_tag="ValueOverflow";originalError;message;constructor(t,r=C$){this.message=`Value overflow for ${t}, max is ${r}`}},nd=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}`}},_E=class{_tag="HexaString";message;originalError;constructor(t){this.message=`Invalid encoded hexa string or length is null: ${t}`}};const nN=4294967295;let iN=class{constructor(t=nN){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 nd(t.toString())),this);addHexaStringToData=t=>{const r=CE(t);return r===null||r.length===0?(this.errors.push(new _E(t)),this):(this.addBufferToData(r),this)};addAsciiStringToData=t=>{const r=new TextEncoder().encode(t);return this.addBufferToData(r),this};encodeInLVFromHexa=t=>{const r=CE(t);return r===null||r.length===0?(this.errors.push(new _E(t)),this):this.hasEnoughLengthRemaining(r,!0)?(this.add8BitUIntToData(r.length),this.addBufferToData(r),this):(this.errors.push(new nd(t)),this)};encodeInLVFromBuffer=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addBufferToData(t),this):(this.errors.push(new nd(t.toString())),this);encodeInLVFromAscii=t=>this.hasEnoughLengthRemaining(t,!0)?(this.add8BitUIntToData(t.length),this.addAsciiStringToData(t),this):(this.errors.push(new nd(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,i){let o=this.checkBoundsAndConvert(t,r,n);if(o===void 0)return this;const s=Number(r)/8,u=new Uint8Array(s);if(i)for(let c=s-1;c>=0;c--)u[c]=Number(o&0xffn),o>>=8n;else for(let c=0;c<s;c++)u[c]=Number(o&0xffn),o>>=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 cv(t.toString()));return}t=BigInt(t)}if(n){const i=1n<<r-1n;if(t>=i||t<-i){this.errors.push(new cv(t.toString(),i-1n));return}if(t<0n){const o=(1n<<r)-1n;t=-t,t=(~t&o)+1n}}else{const i=1n<<r;if(t<0||t>=i){this.errors.push(new cv(t.toString(),i-1n));return}}return t}};const C$=255;let _$=class{_ins;_cla;_p1;p2;data=new iN(C$);constructor({ins:t,cla:r,p1:n,p2:i}){this._cla=r&255,this._ins=t&255,this._p1=n&255,this.p2=i&255}build=()=>new rN(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()},oN=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 i=this.index;return{tag:r,value:n,tlv:this.buffer.slice(t,i)}}encodeToHexaString(t,r=!1){if(t===void 0||t.length===0)return"";const n=Jo(t);return r?n:n.slice(2)}encodeToString(t){let r="",n=0;if(!t)return r;for(;n<=t.length;){const i=t[n];i&&(r+=String.fromCharCode(i)),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 i=Number(t)/8;if(this.outOfRange(i))return;let o=0n;if(n)for(let s=0;s<i;s++)o=o<<8n|BigInt(this.buffer[s+this.index]);else for(let s=i-1;s>=0;s--)o=o<<8n|BigInt(this.buffer[s+this.index]);if(r){const s=1n<<t-1n;o&s&&(o-=s<<1n)}return this.index+=i,o}},g1=class{parser;constructor(t){this.parser=new oN(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()},aN=class{_tag="InvalidStatusWordError";originalError;constructor(t){this.originalError=new Error(t??"Invalid status word.")}},sN=class{_tag="InvalidResponseFormatError";originalError;constructor(t){this.originalError=new Error(t??"Invalid response format.")}};var lN=(e=>(e.Error="ERROR",e.Success="SUCCESS",e))(lN||{});function uN(e){return"error"in e&&e.error!==void 0}function RE(e){return uN(e)?{status:"ERROR",error:e.error}:{status:"SUCCESS",data:e.data}}function cN(e){return e.status==="SUCCESS"}function ls({data:e,error:t}){return RE(t!==void 0?{error:t}:{data:e})}function fN(e){return cN(e)}let v1=class ll{static isValidStatusCode(t){return t.length===2}static isSuccessResponse({statusCode:t}){return ll.isValidStatusCode(t)?t[0]===144&&t[1]===0:!1}static isLockedDeviceResponse({statusCode:t}){return ll.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 ll.isValidStatusCode(t)?t[0]===85&&t[1]===1||t[0]===105&&t[1]===133:!1}static isAppAlreadyInstalled({statusCode:t}){return ll.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 ll.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 i=0;i<4;i++)if(n[i]!==t[i])return!1;return!0})}},dN=class{_tag;originalError;errorCode;message;constructor({tag:t,errorCode:r,originalError:n,message:i}){this._tag=t,this.originalError=n,this.errorCode=r,this.message=i??"An error occured during device exchange."}},pN=class{_tag="UnknownDeviceExchangeError";originalError;message;constructor(t){this.originalError=t,this.message="Unexpected device exchange error happened."}};const hN=(e,t)=>Object.keys(t).includes(e);let gN=class extends dN{constructor(t){super({tag:"GlobalCommandError",...t})}};const OE={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 R$=class{static handle(t){const r=new g1(t).encodeToHexaString(t.statusCode);return hN(r,OE)?new gN({...OE[r],errorCode:r}):new pN({message:"UnknownError",errorCode:r})}},TE=class{name="getAppAndVersion";args=void 0;getApdu(){const t={cla:176,ins:1,p1:0,p2:0};return new _$(t).build()}parseResponse(t){if(!v1.isSuccessResponse(t))return ls({error:R$.handle(t)});const r=new g1(t);if(r.extract8BitUInt()!==1)return ls({error:new sN("getAppAndVersion: format not supported")});const n=r.encodeToString(r.extractFieldLVEncoded()),i=r.encodeToString(r.extractFieldLVEncoded());if(r.getUnparsedRemainingLength()===0)return ls({data:{name:n,version:i}});const o=r.extractFieldLVEncoded();return ls({data:{name:n,version:i,flags:o}})}};var vN=(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))(vN||{}),mN=(e=>(e[e.NONE=0]="NONE",e[e.USB=1]="USB",e[e.QI=2]="QI",e))(mN||{}),id={exports:{}},fv,$E;function Ip(){if($E)return fv;$E=1;const e="2.0.0",t=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,i=t-6;return fv={MAX_LENGTH:t,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:i,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:e,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},fv}var dv,IE;function Ap(){if(IE)return dv;IE=1;var e={};return dv=typeof process=="object"&&e&&e.NODE_DEBUG&&/\bsemver\b/i.test(e.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},dv}var AE;function _c(){return AE||(AE=1,(function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:i}=Ip(),o=Ap();t=e.exports={};const s=t.re=[],u=t.safeRe=[],c=t.src=[],f=t.safeSrc=[],p=t.t={};let g=0;const h="[a-zA-Z0-9-]",m=[["\\s",1],["\\d",i],[h,n]],y=S=>{for(const[_,C]of m)S=S.split(`${_}*`).join(`${_}{0,${C}}`).split(`${_}+`).join(`${_}{1,${C}}`);return S},b=(S,_,C)=>{const O=y(_),R=g++;o(S,R,_),p[S]=R,c[R]=_,f[R]=O,s[R]=new RegExp(_,C?"g":void 0),u[R]=new RegExp(O,C?"g":void 0)};b("NUMERICIDENTIFIER","0|[1-9]\\d*"),b("NUMERICIDENTIFIERLOOSE","\\d+"),b("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),b("MAINVERSION",`(${c[p.NUMERICIDENTIFIER]})\\.(${c[p.NUMERICIDENTIFIER]})\\.(${c[p.NUMERICIDENTIFIER]})`),b("MAINVERSIONLOOSE",`(${c[p.NUMERICIDENTIFIERLOOSE]})\\.(${c[p.NUMERICIDENTIFIERLOOSE]})\\.(${c[p.NUMERICIDENTIFIERLOOSE]})`),b("PRERELEASEIDENTIFIER",`(?:${c[p.NONNUMERICIDENTIFIER]}|${c[p.NUMERICIDENTIFIER]})`),b("PRERELEASEIDENTIFIERLOOSE",`(?:${c[p.NONNUMERICIDENTIFIER]}|${c[p.NUMERICIDENTIFIERLOOSE]})`),b("PRERELEASE",`(?:-(${c[p.PRERELEASEIDENTIFIER]}(?:\\.${c[p.PRERELEASEIDENTIFIER]})*))`),b("PRERELEASELOOSE",`(?:-?(${c[p.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[p.PRERELEASEIDENTIFIERLOOSE]})*))`),b("BUILDIDENTIFIER",`${h}+`),b("BUILD",`(?:\\+(${c[p.BUILDIDENTIFIER]}(?:\\.${c[p.BUILDIDENTIFIER]})*))`),b("FULLPLAIN",`v?${c[p.MAINVERSION]}${c[p.PRERELEASE]}?${c[p.BUILD]}?`),b("FULL",`^${c[p.FULLPLAIN]}$`),b("LOOSEPLAIN",`[v=\\s]*${c[p.MAINVERSIONLOOSE]}${c[p.PRERELEASELOOSE]}?${c[p.BUILD]}?`),b("LOOSE",`^${c[p.LOOSEPLAIN]}$`),b("GTLT","((?:<|>)?=?)"),b("XRANGEIDENTIFIERLOOSE",`${c[p.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),b("XRANGEIDENTIFIER",`${c[p.NUMERICIDENTIFIER]}|x|X|\\*`),b("XRANGEPLAIN",`[v=\\s]*(${c[p.XRANGEIDENTIFIER]})(?:\\.(${c[p.XRANGEIDENTIFIER]})(?:\\.(${c[p.XRANGEIDENTIFIER]})(?:${c[p.PRERELEASE]})?${c[p.BUILD]}?)?)?`),b("XRANGEPLAINLOOSE",`[v=\\s]*(${c[p.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[p.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[p.XRANGEIDENTIFIERLOOSE]})(?:${c[p.PRERELEASELOOSE]})?${c[p.BUILD]}?)?)?`),b("XRANGE",`^${c[p.GTLT]}\\s*${c[p.XRANGEPLAIN]}$`),b("XRANGELOOSE",`^${c[p.GTLT]}\\s*${c[p.XRANGEPLAINLOOSE]}$`),b("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),b("COERCE",`${c[p.COERCEPLAIN]}(?:$|[^\\d])`),b("COERCEFULL",c[p.COERCEPLAIN]+`(?:${c[p.PRERELEASE]})?(?:${c[p.BUILD]})?(?:$|[^\\d])`),b("COERCERTL",c[p.COERCE],!0),b("COERCERTLFULL",c[p.COERCEFULL],!0),b("LONETILDE","(?:~>?)"),b("TILDETRIM",`(\\s*)${c[p.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",b("TILDE",`^${c[p.LONETILDE]}${c[p.XRANGEPLAIN]}$`),b("TILDELOOSE",`^${c[p.LONETILDE]}${c[p.XRANGEPLAINLOOSE]}$`),b("LONECARET","(?:\\^)"),b("CARETTRIM",`(\\s*)${c[p.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",b("CARET",`^${c[p.LONECARET]}${c[p.XRANGEPLAIN]}$`),b("CARETLOOSE",`^${c[p.LONECARET]}${c[p.XRANGEPLAINLOOSE]}$`),b("COMPARATORLOOSE",`^${c[p.GTLT]}\\s*(${c[p.LOOSEPLAIN]})$|^$`),b("COMPARATOR",`^${c[p.GTLT]}\\s*(${c[p.FULLPLAIN]})$|^$`),b("COMPARATORTRIM",`(\\s*)${c[p.GTLT]}\\s*(${c[p.LOOSEPLAIN]}|${c[p.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",b("HYPHENRANGE",`^\\s*(${c[p.XRANGEPLAIN]})\\s+-\\s+(${c[p.XRANGEPLAIN]})\\s*$`),b("HYPHENRANGELOOSE",`^\\s*(${c[p.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[p.XRANGEPLAINLOOSE]})\\s*$`),b("STAR","(<|>)?=?\\s*\\*"),b("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),b("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(id,id.exports)),id.exports}var pv,kE;function m1(){if(kE)return pv;kE=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return pv=n=>n?typeof n!="object"?e:n:t,pv}var hv,PE;function O$(){if(PE)return hv;PE=1;const e=/^[0-9]+$/,t=(n,i)=>{const o=e.test(n),s=e.test(i);return o&&s&&(n=+n,i=+i),n===i?0:o&&!s?-1:s&&!o?1:n<i?-1:1};return hv={compareIdentifiers:t,rcompareIdentifiers:(n,i)=>t(i,n)},hv}var gv,ME;function fn(){if(ME)return gv;ME=1;const e=Ap(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:r}=Ip(),{safeRe:n,t:i}=_c(),o=m1(),{compareIdentifiers:s}=O$();class u{constructor(f,p){if(p=o(p),f instanceof u){if(f.loose===!!p.loose&&f.includePrerelease===!!p.includePrerelease)return f;f=f.version}else if(typeof f!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof f}".`);if(f.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",f,p),this.options=p,this.loose=!!p.loose,this.includePrerelease=!!p.includePrerelease;const g=f.trim().match(p.loose?n[i.LOOSE]:n[i.FULL]);if(!g)throw new TypeError(`Invalid Version: ${f}`);if(this.raw=f,this.major=+g[1],this.minor=+g[2],this.patch=+g[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");g[4]?this.prerelease=g[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const m=+h;if(m>=0&&m<r)return m}return h}):this.prerelease=[],this.build=g[5]?g[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(f){if(e("SemVer.compare",this.version,this.options,f),!(f instanceof u)){if(typeof f=="string"&&f===this.version)return 0;f=new u(f,this.options)}return f.version===this.version?0:this.compareMain(f)||this.comparePre(f)}compareMain(f){return f instanceof u||(f=new u(f,this.options)),s(this.major,f.major)||s(this.minor,f.minor)||s(this.patch,f.patch)}comparePre(f){if(f instanceof u||(f=new u(f,this.options)),this.prerelease.length&&!f.prerelease.length)return-1;if(!this.prerelease.length&&f.prerelease.length)return 1;if(!this.prerelease.length&&!f.prerelease.length)return 0;let p=0;do{const g=this.prerelease[p],h=f.prerelease[p];if(e("prerelease compare",p,g,h),g===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(g===void 0)return-1;if(g===h)continue;return s(g,h)}while(++p)}compareBuild(f){f instanceof u||(f=new u(f,this.options));let p=0;do{const g=this.build[p],h=f.build[p];if(e("build compare",p,g,h),g===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(g===void 0)return-1;if(g===h)continue;return s(g,h)}while(++p)}inc(f,p,g){if(f.startsWith("pre")){if(!p&&g===!1)throw new Error("invalid increment argument: identifier is empty");if(p){const h=`-${p}`.match(this.options.loose?n[i.PRERELEASELOOSE]:n[i.PRERELEASE]);if(!h||h[1]!==p)throw new Error(`invalid identifier: ${p}`)}}switch(f){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",p,g);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",p,g);break;case"prepatch":this.prerelease.length=0,this.inc("patch",p,g),this.inc("pre",p,g);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",p,g),this.inc("pre",p,g);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 h=Number(g)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let m=this.prerelease.length;for(;--m>=0;)typeof this.prerelease[m]=="number"&&(this.prerelease[m]++,m=-2);if(m===-1){if(p===this.prerelease.join(".")&&g===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(p){let m=[p,h];g===!1&&(m=[p]),s(this.prerelease[0],p)===0?isNaN(this.prerelease[1])&&(this.prerelease=m):this.prerelease=m}break}default:throw new Error(`invalid increment argument: ${f}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return gv=u,gv}var vv,DE;function Vl(){if(DE)return vv;DE=1;const e=fn();return vv=(r,n,i=!1)=>{if(r instanceof e)return r;try{return new e(r,n)}catch(o){if(!i)return null;throw o}},vv}var mv,LE;function yN(){if(LE)return mv;LE=1;const e=Vl();return mv=(r,n)=>{const i=e(r,n);return i?i.version:null},mv}var yv,FE;function bN(){if(FE)return yv;FE=1;const e=Vl();return yv=(r,n)=>{const i=e(r.trim().replace(/^[=v]+/,""),n);return i?i.version:null},yv}var bv,NE;function SN(){if(NE)return bv;NE=1;const e=fn();return bv=(r,n,i,o,s)=>{typeof i=="string"&&(s=o,o=i,i=void 0);try{return new e(r instanceof e?r.version:r,i).inc(n,o,s).version}catch{return null}},bv}var Sv,jE;function wN(){if(jE)return Sv;jE=1;const e=Vl();return Sv=(r,n)=>{const i=e(r,null,!0),o=e(n,null,!0),s=i.compare(o);if(s===0)return null;const u=s>0,c=u?i:o,f=u?o:i,p=!!c.prerelease.length;if(!!f.prerelease.length&&!p){if(!f.patch&&!f.minor)return"major";if(f.compareMain(c)===0)return f.minor&&!f.patch?"minor":"patch"}const h=p?"pre":"";return i.major!==o.major?h+"major":i.minor!==o.minor?h+"minor":i.patch!==o.patch?h+"patch":"prerelease"},Sv}var wv,zE;function xN(){if(zE)return wv;zE=1;const e=fn();return wv=(r,n)=>new e(r,n).major,wv}var xv,BE;function EN(){if(BE)return xv;BE=1;const e=fn();return xv=(r,n)=>new e(r,n).minor,xv}var Ev,VE;function CN(){if(VE)return Ev;VE=1;const e=fn();return Ev=(r,n)=>new e(r,n).patch,Ev}var Cv,HE;function _N(){if(HE)return Cv;HE=1;const e=Vl();return Cv=(r,n)=>{const i=e(r,n);return i&&i.prerelease.length?i.prerelease:null},Cv}var _v,UE;function eo(){if(UE)return _v;UE=1;const e=fn();return _v=(r,n,i)=>new e(r,i).compare(new e(n,i)),_v}var Rv,WE;function RN(){if(WE)return Rv;WE=1;const e=eo();return Rv=(r,n,i)=>e(n,r,i),Rv}var Ov,GE;function ON(){if(GE)return Ov;GE=1;const e=eo();return Ov=(r,n)=>e(r,n,!0),Ov}var Tv,qE;function y1(){if(qE)return Tv;qE=1;const e=fn();return Tv=(r,n,i)=>{const o=new e(r,i),s=new e(n,i);return o.compare(s)||o.compareBuild(s)},Tv}var $v,XE;function TN(){if(XE)return $v;XE=1;const e=y1();return $v=(r,n)=>r.sort((i,o)=>e(i,o,n)),$v}var Iv,KE;function $N(){if(KE)return Iv;KE=1;const e=y1();return Iv=(r,n)=>r.sort((i,o)=>e(o,i,n)),Iv}var Av,YE;function kp(){if(YE)return Av;YE=1;const e=eo();return Av=(r,n,i)=>e(r,n,i)>0,Av}var kv,QE;function b1(){if(QE)return kv;QE=1;const e=eo();return kv=(r,n,i)=>e(r,n,i)<0,kv}var Pv,JE;function T$(){if(JE)return Pv;JE=1;const e=eo();return Pv=(r,n,i)=>e(r,n,i)===0,Pv}var Mv,ZE;function $$(){if(ZE)return Mv;ZE=1;const e=eo();return Mv=(r,n,i)=>e(r,n,i)!==0,Mv}var Dv,eC;function S1(){if(eC)return Dv;eC=1;const e=eo();return Dv=(r,n,i)=>e(r,n,i)>=0,Dv}var Lv,tC;function w1(){if(tC)return Lv;tC=1;const e=eo();return Lv=(r,n,i)=>e(r,n,i)<=0,Lv}var Fv,rC;function I$(){if(rC)return Fv;rC=1;const e=T$(),t=$$(),r=kp(),n=S1(),i=b1(),o=w1();return Fv=(u,c,f,p)=>{switch(c){case"===":return typeof u=="object"&&(u=u.version),typeof f=="object"&&(f=f.version),u===f;case"!==":return typeof u=="object"&&(u=u.version),typeof f=="object"&&(f=f.version),u!==f;case"":case"=":case"==":return e(u,f,p);case"!=":return t(u,f,p);case">":return r(u,f,p);case">=":return n(u,f,p);case"<":return i(u,f,p);case"<=":return o(u,f,p);default:throw new TypeError(`Invalid operator: ${c}`)}},Fv}var Nv,nC;function IN(){if(nC)return Nv;nC=1;const e=fn(),t=Vl(),{safeRe:r,t:n}=_c();return Nv=(o,s)=>{if(o instanceof e)return o;if(typeof o=="number"&&(o=String(o)),typeof o!="string")return null;s=s||{};let u=null;if(!s.rtl)u=o.match(s.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const m=s.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let y;for(;(y=m.exec(o))&&(!u||u.index+u[0].length!==o.length);)(!u||y.index+y[0].length!==u.index+u[0].length)&&(u=y),m.lastIndex=y.index+y[1].length+y[2].length;m.lastIndex=-1}if(u===null)return null;const c=u[2],f=u[3]||"0",p=u[4]||"0",g=s.includePrerelease&&u[5]?`-${u[5]}`:"",h=s.includePrerelease&&u[6]?`+${u[6]}`:"";return t(`${c}.${f}.${p}${g}${h}`,s)},Nv}var jv,iC;function AN(){if(iC)return jv;iC=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 o=this.map.keys().next().value;this.delete(o)}this.map.set(r,n)}return this}}return jv=e,jv}var zv,oC;function to(){if(oC)return zv;oC=1;const e=/\s+/g;class t{constructor(F,q){if(q=i(q),F instanceof t)return F.loose===!!q.loose&&F.includePrerelease===!!q.includePrerelease?F:new t(F.raw,q);if(F instanceof o)return this.raw=F.value,this.set=[[F]],this.formatted=void 0,this;if(this.options=q,this.loose=!!q.loose,this.includePrerelease=!!q.includePrerelease,this.raw=F.trim().replace(e," "),this.set=this.raw.split("||").map(U=>this.parseRange(U.trim())).filter(U=>U.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const U=this.set[0];if(this.set=this.set.filter(M=>!b(M[0])),this.set.length===0)this.set=[U];else if(this.set.length>1){for(const M of this.set)if(M.length===1&&S(M[0])){this.set=[M];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let F=0;F<this.set.length;F++){F>0&&(this.formatted+="||");const q=this.set[F];for(let U=0;U<q.length;U++)U>0&&(this.formatted+=" "),this.formatted+=q[U].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(F){const U=((this.options.includePrerelease&&m)|(this.options.loose&&y))+":"+F,M=n.get(U);if(M)return M;const G=this.options.loose,K=G?c[f.HYPHENRANGELOOSE]:c[f.HYPHENRANGE];F=F.replace(K,Y(this.options.includePrerelease)),s("hyphen replace",F),F=F.replace(c[f.COMPARATORTRIM],p),s("comparator trim",F),F=F.replace(c[f.TILDETRIM],g),s("tilde trim",F),F=F.replace(c[f.CARETTRIM],h),s("caret trim",F);let D=F.split(" ").map(ne=>C(ne,this.options)).join(" ").split(/\s+/).map(ne=>X(ne,this.options));G&&(D=D.filter(ne=>(s("loose invalid filter",ne,this.options),!!ne.match(c[f.COMPARATORLOOSE])))),s("range list",D);const A=new Map,J=D.map(ne=>new o(ne,this.options));for(const ne of J){if(b(ne))return[ne];A.set(ne.value,ne)}A.size>1&&A.has("")&&A.delete("");const Z=[...A.values()];return n.set(U,Z),Z}intersects(F,q){if(!(F instanceof t))throw new TypeError("a Range is required");return this.set.some(U=>_(U,q)&&F.set.some(M=>_(M,q)&&U.every(G=>M.every(K=>G.intersects(K,q)))))}test(F){if(!F)return!1;if(typeof F=="string")try{F=new u(F,this.options)}catch{return!1}for(let q=0;q<this.set.length;q++)if(N(this.set[q],F,this.options))return!0;return!1}}zv=t;const r=AN(),n=new r,i=m1(),o=Pp(),s=Ap(),u=fn(),{safeRe:c,t:f,comparatorTrimReplace:p,tildeTrimReplace:g,caretTrimReplace:h}=_c(),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:y}=Ip(),b=j=>j.value==="<0.0.0-0",S=j=>j.value==="",_=(j,F)=>{let q=!0;const U=j.slice();let M=U.pop();for(;q&&U.length;)q=U.every(G=>M.intersects(G,F)),M=U.pop();return q},C=(j,F)=>(s("comp",j,F),j=$(j,F),s("caret",j),j=R(j,F),s("tildes",j),j=L(j,F),s("xrange",j),j=B(j,F),s("stars",j),j),O=j=>!j||j.toLowerCase()==="x"||j==="*",R=(j,F)=>j.trim().split(/\s+/).map(q=>T(q,F)).join(" "),T=(j,F)=>{const q=F.loose?c[f.TILDELOOSE]:c[f.TILDE];return j.replace(q,(U,M,G,K,D)=>{s("tilde",j,U,M,G,K,D);let A;return O(M)?A="":O(G)?A=`>=${M}.0.0 <${+M+1}.0.0-0`:O(K)?A=`>=${M}.${G}.0 <${M}.${+G+1}.0-0`:D?(s("replaceTilde pr",D),A=`>=${M}.${G}.${K}-${D} <${M}.${+G+1}.0-0`):A=`>=${M}.${G}.${K} <${M}.${+G+1}.0-0`,s("tilde return",A),A})},$=(j,F)=>j.trim().split(/\s+/).map(q=>P(q,F)).join(" "),P=(j,F)=>{s("caret",j,F);const q=F.loose?c[f.CARETLOOSE]:c[f.CARET],U=F.includePrerelease?"-0":"";return j.replace(q,(M,G,K,D,A)=>{s("caret",j,M,G,K,D,A);let J;return O(G)?J="":O(K)?J=`>=${G}.0.0${U} <${+G+1}.0.0-0`:O(D)?G==="0"?J=`>=${G}.${K}.0${U} <${G}.${+K+1}.0-0`:J=`>=${G}.${K}.0${U} <${+G+1}.0.0-0`:A?(s("replaceCaret pr",A),G==="0"?K==="0"?J=`>=${G}.${K}.${D}-${A} <${G}.${K}.${+D+1}-0`:J=`>=${G}.${K}.${D}-${A} <${G}.${+K+1}.0-0`:J=`>=${G}.${K}.${D}-${A} <${+G+1}.0.0-0`):(s("no pr"),G==="0"?K==="0"?J=`>=${G}.${K}.${D}${U} <${G}.${K}.${+D+1}-0`:J=`>=${G}.${K}.${D}${U} <${G}.${+K+1}.0-0`:J=`>=${G}.${K}.${D} <${+G+1}.0.0-0`),s("caret return",J),J})},L=(j,F)=>(s("replaceXRanges",j,F),j.split(/\s+/).map(q=>z(q,F)).join(" ")),z=(j,F)=>{j=j.trim();const q=F.loose?c[f.XRANGELOOSE]:c[f.XRANGE];return j.replace(q,(U,M,G,K,D,A)=>{s("xRange",j,U,M,G,K,D,A);const J=O(G),Z=J||O(K),ne=Z||O(D),W=ne;return M==="="&&W&&(M=""),A=F.includePrerelease?"-0":"",J?M===">"||M==="<"?U="<0.0.0-0":U="*":M&&W?(Z&&(K=0),D=0,M===">"?(M=">=",Z?(G=+G+1,K=0,D=0):(K=+K+1,D=0)):M==="<="&&(M="<",Z?G=+G+1:K=+K+1),M==="<"&&(A="-0"),U=`${M+G}.${K}.${D}${A}`):Z?U=`>=${G}.0.0${A} <${+G+1}.0.0-0`:ne&&(U=`>=${G}.${K}.0${A} <${G}.${+K+1}.0-0`),s("xRange return",U),U})},B=(j,F)=>(s("replaceStars",j,F),j.trim().replace(c[f.STAR],"")),X=(j,F)=>(s("replaceGTE0",j,F),j.trim().replace(c[F.includePrerelease?f.GTE0PRE:f.GTE0],"")),Y=j=>(F,q,U,M,G,K,D,A,J,Z,ne,W)=>(O(U)?q="":O(M)?q=`>=${U}.0.0${j?"-0":""}`:O(G)?q=`>=${U}.${M}.0${j?"-0":""}`:K?q=`>=${q}`:q=`>=${q}${j?"-0":""}`,O(J)?A="":O(Z)?A=`<${+J+1}.0.0-0`:O(ne)?A=`<${J}.${+Z+1}.0-0`:W?A=`<=${J}.${Z}.${ne}-${W}`:j?A=`<${J}.${Z}.${+ne+1}-0`:A=`<=${A}`,`${q} ${A}`.trim()),N=(j,F,q)=>{for(let U=0;U<j.length;U++)if(!j[U].test(F))return!1;if(F.prerelease.length&&!q.includePrerelease){for(let U=0;U<j.length;U++)if(s(j[U].semver),j[U].semver!==o.ANY&&j[U].semver.prerelease.length>0){const M=j[U].semver;if(M.major===F.major&&M.minor===F.minor&&M.patch===F.patch)return!0}return!1}return!0};return zv}var Bv,aC;function Pp(){if(aC)return Bv;aC=1;const e=Symbol("SemVer ANY");class t{static get ANY(){return e}constructor(p,g){if(g=r(g),p instanceof t){if(p.loose===!!g.loose)return p;p=p.value}p=p.trim().split(/\s+/).join(" "),s("comparator",p,g),this.options=g,this.loose=!!g.loose,this.parse(p),this.semver===e?this.value="":this.value=this.operator+this.semver.version,s("comp",this)}parse(p){const g=this.options.loose?n[i.COMPARATORLOOSE]:n[i.COMPARATOR],h=p.match(g);if(!h)throw new TypeError(`Invalid comparator: ${p}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new u(h[2],this.options.loose):this.semver=e}toString(){return this.value}test(p){if(s("Comparator.test",p,this.options.loose),this.semver===e||p===e)return!0;if(typeof p=="string")try{p=new u(p,this.options)}catch{return!1}return o(p,this.operator,this.semver,this.options)}intersects(p,g){if(!(p instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(p.value,g).test(this.value):p.operator===""?p.value===""?!0:new c(this.value,g).test(p.semver):(g=r(g),g.includePrerelease&&(this.value==="<0.0.0-0"||p.value==="<0.0.0-0")||!g.includePrerelease&&(this.value.startsWith("<0.0.0")||p.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&p.operator.startsWith(">")||this.operator.startsWith("<")&&p.operator.startsWith("<")||this.semver.version===p.semver.version&&this.operator.includes("=")&&p.operator.includes("=")||o(this.semver,"<",p.semver,g)&&this.operator.startsWith(">")&&p.operator.startsWith("<")||o(this.semver,">",p.semver,g)&&this.operator.startsWith("<")&&p.operator.startsWith(">")))}}Bv=t;const r=m1(),{safeRe:n,t:i}=_c(),o=I$(),s=Ap(),u=fn(),c=to();return Bv}var Vv,sC;function Mp(){if(sC)return Vv;sC=1;const e=to();return Vv=(r,n,i)=>{try{n=new e(n,i)}catch{return!1}return n.test(r)},Vv}var Hv,lC;function kN(){if(lC)return Hv;lC=1;const e=to();return Hv=(r,n)=>new e(r,n).set.map(i=>i.map(o=>o.value).join(" ").trim().split(" ")),Hv}var Uv,uC;function PN(){if(uC)return Uv;uC=1;const e=fn(),t=to();return Uv=(n,i,o)=>{let s=null,u=null,c=null;try{c=new t(i,o)}catch{return null}return n.forEach(f=>{c.test(f)&&(!s||u.compare(f)===-1)&&(s=f,u=new e(s,o))}),s},Uv}var Wv,cC;function MN(){if(cC)return Wv;cC=1;const e=fn(),t=to();return Wv=(n,i,o)=>{let s=null,u=null,c=null;try{c=new t(i,o)}catch{return null}return n.forEach(f=>{c.test(f)&&(!s||u.compare(f)===1)&&(s=f,u=new e(s,o))}),s},Wv}var Gv,fC;function DN(){if(fC)return Gv;fC=1;const e=fn(),t=to(),r=kp();return Gv=(i,o)=>{i=new t(i,o);let s=new e("0.0.0");if(i.test(s)||(s=new e("0.0.0-0"),i.test(s)))return s;s=null;for(let u=0;u<i.set.length;++u){const c=i.set[u];let f=null;c.forEach(p=>{const g=new e(p.semver.version);switch(p.operator){case">":g.prerelease.length===0?g.patch++:g.prerelease.push(0),g.raw=g.format();case"":case">=":(!f||r(g,f))&&(f=g);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${p.operator}`)}}),f&&(!s||r(s,f))&&(s=f)}return s&&i.test(s)?s:null},Gv}var qv,dC;function LN(){if(dC)return qv;dC=1;const e=to();return qv=(r,n)=>{try{return new e(r,n).range||"*"}catch{return null}},qv}var Xv,pC;function x1(){if(pC)return Xv;pC=1;const e=fn(),t=Pp(),{ANY:r}=t,n=to(),i=Mp(),o=kp(),s=b1(),u=w1(),c=S1();return Xv=(p,g,h,m)=>{p=new e(p,m),g=new n(g,m);let y,b,S,_,C;switch(h){case">":y=o,b=u,S=s,_=">",C=">=";break;case"<":y=s,b=c,S=o,_="<",C="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(i(p,g,m))return!1;for(let O=0;O<g.set.length;++O){const R=g.set[O];let T=null,$=null;if(R.forEach(P=>{P.semver===r&&(P=new t(">=0.0.0")),T=T||P,$=$||P,y(P.semver,T.semver,m)?T=P:S(P.semver,$.semver,m)&&($=P)}),T.operator===_||T.operator===C||(!$.operator||$.operator===_)&&b(p,$.semver))return!1;if($.operator===C&&S(p,$.semver))return!1}return!0},Xv}var Kv,hC;function FN(){if(hC)return Kv;hC=1;const e=x1();return Kv=(r,n,i)=>e(r,n,">",i),Kv}var Yv,gC;function NN(){if(gC)return Yv;gC=1;const e=x1();return Yv=(r,n,i)=>e(r,n,"<",i),Yv}var Qv,vC;function jN(){if(vC)return Qv;vC=1;const e=to();return Qv=(r,n,i)=>(r=new e(r,i),n=new e(n,i),r.intersects(n,i)),Qv}var Jv,mC;function zN(){if(mC)return Jv;mC=1;const e=Mp(),t=eo();return Jv=(r,n,i)=>{const o=[];let s=null,u=null;const c=r.sort((h,m)=>t(h,m,i));for(const h of c)e(h,n,i)?(u=h,s||(s=h)):(u&&o.push([s,u]),u=null,s=null);s&&o.push([s,null]);const f=[];for(const[h,m]of o)h===m?f.push(h):!m&&h===c[0]?f.push("*"):m?h===c[0]?f.push(`<=${m}`):f.push(`${h} - ${m}`):f.push(`>=${h}`);const p=f.join(" || "),g=typeof n.raw=="string"?n.raw:String(n);return p.length<g.length?p:n},Jv}var Zv,yC;function BN(){if(yC)return Zv;yC=1;const e=to(),t=Pp(),{ANY:r}=t,n=Mp(),i=eo(),o=(g,h,m={})=>{if(g===h)return!0;g=new e(g,m),h=new e(h,m);let y=!1;e:for(const b of g.set){for(const S of h.set){const _=c(b,S,m);if(y=y||_!==null,_)continue e}if(y)return!1}return!0},s=[new t(">=0.0.0-0")],u=[new t(">=0.0.0")],c=(g,h,m)=>{if(g===h)return!0;if(g.length===1&&g[0].semver===r){if(h.length===1&&h[0].semver===r)return!0;m.includePrerelease?g=s:g=u}if(h.length===1&&h[0].semver===r){if(m.includePrerelease)return!0;h=u}const y=new Set;let b,S;for(const L of g)L.operator===">"||L.operator===">="?b=f(b,L,m):L.operator==="<"||L.operator==="<="?S=p(S,L,m):y.add(L.semver);if(y.size>1)return null;let _;if(b&&S){if(_=i(b.semver,S.semver,m),_>0)return null;if(_===0&&(b.operator!==">="||S.operator!=="<="))return null}for(const L of y){if(b&&!n(L,String(b),m)||S&&!n(L,String(S),m))return null;for(const z of h)if(!n(L,String(z),m))return!1;return!0}let C,O,R,T,$=S&&!m.includePrerelease&&S.semver.prerelease.length?S.semver:!1,P=b&&!m.includePrerelease&&b.semver.prerelease.length?b.semver:!1;$&&$.prerelease.length===1&&S.operator==="<"&&$.prerelease[0]===0&&($=!1);for(const L of h){if(T=T||L.operator===">"||L.operator===">=",R=R||L.operator==="<"||L.operator==="<=",b){if(P&&L.semver.prerelease&&L.semver.prerelease.length&&L.semver.major===P.major&&L.semver.minor===P.minor&&L.semver.patch===P.patch&&(P=!1),L.operator===">"||L.operator===">="){if(C=f(b,L,m),C===L&&C!==b)return!1}else if(b.operator===">="&&!n(b.semver,String(L),m))return!1}if(S){if($&&L.semver.prerelease&&L.semver.prerelease.length&&L.semver.major===$.major&&L.semver.minor===$.minor&&L.semver.patch===$.patch&&($=!1),L.operator==="<"||L.operator==="<="){if(O=p(S,L,m),O===L&&O!==S)return!1}else if(S.operator==="<="&&!n(S.semver,String(L),m))return!1}if(!L.operator&&(S||b)&&_!==0)return!1}return!(b&&R&&!S&&_!==0||S&&T&&!b&&_!==0||P||$)},f=(g,h,m)=>{if(!g)return h;const y=i(g.semver,h.semver,m);return y>0?g:y<0||h.operator===">"&&g.operator===">="?h:g},p=(g,h,m)=>{if(!g)return h;const y=i(g.semver,h.semver,m);return y<0?g:y>0||h.operator==="<"&&g.operator==="<="?h:g};return Zv=o,Zv}var em,bC;function VN(){if(bC)return em;bC=1;const e=_c(),t=Ip(),r=fn(),n=O$(),i=Vl(),o=yN(),s=bN(),u=SN(),c=wN(),f=xN(),p=EN(),g=CN(),h=_N(),m=eo(),y=RN(),b=ON(),S=y1(),_=TN(),C=$N(),O=kp(),R=b1(),T=T$(),$=$$(),P=S1(),L=w1(),z=I$(),B=IN(),X=Pp(),Y=to(),N=Mp(),j=kN(),F=PN(),q=MN(),U=DN(),M=LN(),G=x1(),K=FN(),D=NN(),A=jN(),J=zN(),Z=BN();return em={parse:i,valid:o,clean:s,inc:u,diff:c,major:f,minor:p,patch:g,prerelease:h,compare:m,rcompare:y,compareLoose:b,compareBuild:S,sort:_,rsort:C,gt:O,lt:R,eq:T,neq:$,gte:P,lte:L,cmp:z,coerce:B,Comparator:X,Range:Y,satisfies:N,toComparators:j,maxSatisfying:F,minSatisfying:q,minVersion:U,validRange:M,outside:G,gtr:K,ltr:D,intersects:A,simplifyRange:J,subset:Z,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},em}var Vn=VN();const SC=Dr(Vn);var Xt=(e=>(e.NANO_S="nanoS",e.NANO_SP="nanoSP",e.NANO_X="nanoX",e.STAX="stax",e.FLEX="flex",e.APEX="apexp",e))(Xt||{});let A$=class{id;model;name;constructor({id:t,model:r,name:n}){this.id=t,this.model=r,this.name=n}},HN=class{constructor(t){if(this.seFlags=t,this.seFlags.length!==4)throw new Error("Invalid secure element flags 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(){throw new Error("Not implemented")}wordsInformation(){throw new Error("Not implemented")}onboardingStatus(){throw new Error("Not implemented")}_checkNthBitInByte(t,r){return(t>>8-r&1)===1}},UN=class{name="getOsVersion";args=void 0;getApdu(){const t={cla:224,ins:1,p1:0,p2:0};return new _$(t).build()}parseResponse(t,r){if(!v1.isSuccessResponse(t))return ls({error:R$.handle(t)});const n=new g1(t),i=n.extract32BitUInt();if(i===void 0)return ls({error:new aN("Missing target ID in OS version")});let o=n.encodeToString(n.extractFieldLVEncoded()),s=n.extractFieldLVEncoded()??new Uint8Array(0);const u={...new HN(s).generalDeviceState()};o||(o="0.0.0",s=new Uint8Array);const c=(i&4026531840)!==805306368,f=o.includes("-osu");let p="",g="",h="",m="",y,b,S,_;if(c){h=o,y=i;const C=n.extractFieldLVEncoded();C&&(C.length>=5?(p=n.encodeToString(C),b=parseInt(n.encodeToHexaString(n.extractFieldLVEncoded()),16)):b=parseInt(n.encodeToHexaString(C),16))}else{if(p=o,b=i,g=n.encodeToString(n.extractFieldLVEncoded()),this.isBootloaderVersionSupported(p,r)&&(h=n.encodeToString(n.extractFieldLVEncoded())),this.isHardwareVersionSupported(p,r)?m=n.encodeToHexaString(n.extractFieldLVEncoded()):m="00",this.isLocalizationSupported(p,r)){const C=n.extractFieldLVEncoded();C!==void 0&&(S=parseInt(n.encodeToHexaString(C),16))}if(this.isRecoverSupported(p,r)){const C=n.extractFieldLVEncoded();C!==void 0&&(_=parseInt(n.encodeToHexaString(C),16))}}return ls({data:{isBootloader:c,isOsu:f,targetId:i,seTargetId:b,mcuTargetId:y,seVersion:p,seFlags:s,mcuSephVersion:g,mcuBootloaderVersion:h,hwVersion:m,langId:S,recoverState:_,secureElementFlags:u}})}isBootloaderVersionSupported(t,r){const n=Vn.coerce(t)??"";switch(r){case Xt.NANO_S:case Xt.NANO_X:return Vn.gte(n,"2.0.0");default:return!0}}isHardwareVersionSupported(t,r){const n=Vn.coerce(t)??"";return r===Xt.NANO_X?Vn.gte(n,"2.0.0"):!1}isLocalizationSupported(t,r){const n=Vn.coerce(t)??"";switch(r){case Xt.NANO_S:return!1;case Xt.NANO_SP:return Vn.gte(n,"1.1.0");case Xt.NANO_X:return Vn.gte(n,"2.1.0");default:return!0}}isRecoverSupported(t,r){const n=Vn.coerce(t)??"";switch(r){case Xt.NANO_S:return!1;case Xt.NANO_SP:return Vn.gte(n,"1.1.2");case Xt.NANO_X:return Vn.gte(n,"2.2.3");case Xt.STAX:return Vn.gte(n,"1.4.0");case Xt.FLEX:return Vn.gte(n,"1.0.1");default:return!0}}};var po=(e=>(e.LOCKED="LOCKED",e.BUSY="BUSY",e.CONNECTED="CONNECTED",e.NOT_CONNECTED="NOT CONNECTED",e))(po||{}),WN=(e=>(e.NotStarted="not-started",e.Pending="pending",e.Stopped="stopped",e.Completed="completed",e.Error="error",e))(WN||{}),GN=(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))(GN||{});const Cn={of(e){return Qr(e)},empty(){return jt},zero(){return jt},fromNullable(e){return e==null?jt:Qr(e)},fromFalsy(e){return e?Qr(e):jt},fromPredicate(e,t){return arguments.length===1?r=>Cn.fromPredicate(e,r):e(t)?Qr(t):jt},mapMaybe(e,t){return arguments.length===1?r=>Cn.mapMaybe(e,r):Cn.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 Qr(e())}catch{return jt}},isMaybe(e){return e instanceof E1||e instanceof C1},sequence(e){let t=[];for(const r of e)if(r.isJust())t.push(r.extract());else return jt;return Qr(t)},"fantasy-land/of"(e){return this.of(e)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};class E1{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 Qr(t(this.__value))}ap(t){return t.isJust()?this.map(t.extract()):jt}alt(t){return this}altLazy(t){return this}chain(t){return t(this.__value)}chainNullable(t){return Cn.fromNullable(t(this.__value))}join(){return this.__value}reduce(t,r){return t(r,this.__value)}extend(t){return Qr(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 nr(this.__value)}ifJust(t){return t(this.__value),this}ifNothing(t){return this}filter(t){return t(this.__value)?Qr(this.__value):jt}}E1.prototype.constructor=Cn;class C1{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 jt}ap(t){return jt}alt(t){return t}altLazy(t){return t()}chain(t){return jt}chainNullable(t){return jt}join(){return jt}reduce(t,r){return r}extend(t){return jt}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 Wt(t)}ifJust(t){return this}ifNothing(t){return t(),this}filter(t){return jt}}C1.prototype.constructor=Cn;const Qr=e=>new E1(e),jt=new C1,_n={of(e){return nr(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 nr(e())}catch(t){return Wt(t)}},sequence(e){let t=[];for(const r of e){if(r.isLeft())return r;t.push(r.extract())}return nr(t)},isEither(e){return e instanceof R1||e instanceof _1},"fantasy-land/of"(e){return _n.of(e)}};class _1{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 nr(r(this.__value))}map(t){return nr(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 nr(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 Qr(this.__value)}leftToMaybe(){return jt}extract(){return this.__value}swap(){return Wt(this.__value)}}_1.prototype.constructor=_n;class R1{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 Wt(t(this.__value))}map(t){return this}mapLeft(t){return Wt(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 jt}leftToMaybe(){return Qr(this.__value)}extract(){return this.__value}swap(){return nr(this.__value)}}R1.prototype.constructor=_n;const Wt=e=>new R1(e),nr=e=>new _1(e),Rc=e=>e,qN=e=>e,tm=Object.assign(qN,{fromArray:e=>tm.isNonEmpty(e)?Qr(e):jt,unsafeCoerce:e=>{if(tm.isNonEmpty(e))return e;throw new Error("NonEmptyList#unsafeCoerce was ran on an empty array")},fromTuple:e=>tm(e.toArray()),head:e=>e[0],last:e=>e[e.length-1],isNonEmpty:e=>e.length>0,tail:e=>e.slice(1)}),jd=(e,t)=>typeof t=="bigint"?t.toString():t,XN=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xs=(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,jd):"an object with value "+JSON.stringify(t,jd);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,jd)}`,`Expected ${e}, but received ${r}`},KN=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),YN=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),k$(e)}return e},k$=e=>(YN(e),KN(e),e),Sr={interface(e){const t=Object.keys(e),r=i=>{if(!XN(i))return Wt(xs("an object",i));const o={};for(const s of t){if(!i.hasOwnProperty(s)&&!e[s]._isOptional)return Wt(`Problem with property "${s}": it does not exist in received object ${JSON.stringify(i,jd)}`);const u=e[s].decode(i[s]);if(u.isLeft())return Wt(`Problem with the value of property "${s}": ${u.extract()}`);const c=u.extract();c!==void 0&&(o[s]=c)}return nr(o)};return{decode:r,encode:i=>{const o={};for(const s of t)o[s]=e[s].encode(i[s]);return o},unsafeDecode:i=>r(i).mapLeft(Error).unsafeCoerce(),schema:()=>t.reduce((i,o)=>(e[o]._isOptional||i.required.push(o),i.properties[o]=k$(e[o].schema()),i),{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??(()=>({}))}}},zt=Sr.custom({decode:e=>typeof e=="string"?nr(e):Wt(xs("a string",e)),encode:Rc,schema:()=>({type:"string"})}),Cl=Sr.custom({decode:e=>typeof e=="number"?nr(e):Wt(xs("a number",e)),encode:Rc,schema:()=>({type:"number"})}),QN=Sr.custom({decode:e=>e===void 0?nr(e):Wt(xs("an undefined",e)),encode:Rc}),sn=e=>({...JN([e,QN]),schema:e.schema,_isOptional:!0}),P$=Sr.custom({decode:e=>typeof e=="boolean"?nr(e):Wt(xs("a boolean",e)),encode:Rc,schema:()=>({type:"boolean"})}),JN=e=>Sr.custom({decode:t=>{let r=[];for(const n of e){const i=n.decode(t);if(i.isRight())return i;r.push(i.extract())}return Wt(`One of the following problems occured: ${r.map((n,i)=>`(${i}) ${n}`).join(", ")}`)},encode:t=>{for(const r of e)if(_n.encase(()=>r.encode(t)).mapLeft(i=>"").chain(r.decode).isRight())return r.encode(t);return t},schema:()=>({oneOf:e.map(t=>t.schema())})}),bi=e=>Sr.custom({decode:t=>{if(Array.isArray(t)){const r=[];for(let n=0;n<t.length;n++){const i=e.decode(t[n]);if(i.isRight())r.push(i.extract());else return Wt(`Problem with the value at index ${n}: ${i.extract()}`)}return nr(r)}else return Wt(xs("an array",t))},encode:t=>t.map(e.encode),schema:()=>({type:"array",items:e.schema()})});Sr.custom({decode:e=>zt.decode(e).chain(t=>isFinite(+t)?nr(t):Wt(xs("a number",e))),encode:Rc,schema:Cl.schema});var M$;const D$={liftEither(e){if(e.isRight())return Promise.resolve(e.extract());throw e.extract()},fromPromise(e){return e.then(D$.liftEither)},throwE(e){throw e}};class L${constructor(t){this.runPromise=t,this[M$]="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 pt(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 pt(async r=>{const n=await t;if(n.isRight()){const i=await this.run();return i.isRight()?n.extract()(i.extract()):r.liftEither(i)}return r.liftEither(n)})}alt(t){return pt(async r=>{const n=await this.run();if(n.isRight())return n.extract();{const i=await t;return r.liftEither(i)}})}extend(t){return pt(async r=>{const n=await this.run();if(n.isRight()){const i=pt.liftEither(n);return r.liftEither(nr(t(i)))}return r.liftEither(n)})}async run(){try{return nr(await this.runPromise(D$))}catch(t){return Wt(t)}}bimap(t,r){return pt(async n=>{const i=await this.run();try{return await n.liftEither(i.bimap(t,r))}catch(o){throw await o}})}map(t){return pt(r=>this.runPromise(r).then(t))}mapLeft(t){return pt(async r=>{try{return await this.runPromise(r)}catch(n){throw await t(n)}})}chain(t){return pt(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}chainLeft(t){return pt(async r=>{try{return await this.runPromise(r)}catch(n){return r.fromPromise(t(n))}})}toMaybeAsync(){return on(async({liftMaybe:t})=>{const r=await this.run();return t(r.toMaybe())})}swap(){return pt(async t=>{const r=await this.run();return r.isRight()&&t.throwE(r.extract()),t.liftEither(nr(r.extract()))})}ifLeft(t){return pt(async r=>{const n=await this.run();return n.ifLeft(t),r.liftEither(n)})}ifRight(t){return pt(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 pt(({fromPromise:r})=>r(this.run().finally(t)))}}M$=Symbol.toStringTag;const pt=Object.assign(e=>new L$(e),{fromPromise:e=>pt(({fromPromise:t})=>t(e())),liftEither:e=>pt(({liftEither:t})=>t(e)),lefts:e=>Promise.all(e.map(t=>t.run())).then(_n.lefts),rights:e=>Promise.all(e.map(t=>t.run())).then(_n.rights),sequence:e=>pt(async t=>{let r=[];for await(const n of e){if(n.isLeft())return t.liftEither(n);r.push(n.extract())}return t.liftEither(nr(r))}),all:e=>pt.fromPromise(async()=>Promise.all(e).then(_n.sequence))});L$.prototype.constructor=pt;var F$;const N$={liftMaybe(e){if(e.isJust())return Promise.resolve(e.extract());throw jt},fromPromise(e){return e.then(N$.liftMaybe)}};class j${constructor(t){this.runPromise=t,this[F$]="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 on(async t=>{const r=await this.run();if(r.isJust()){const n=await r.extract();return t.liftMaybe(n)}return t.liftMaybe(jt)})}ap(t){return on(async r=>{const n=await t;if(n.isJust()){const i=await this.run();return i.isJust()?n.extract()(i.extract()):r.liftMaybe(jt)}return r.liftMaybe(jt)})}alt(t){return on(async r=>{const n=await this.run();if(n.isJust())return n.extract();{const i=await t;return r.liftMaybe(i)}})}extend(t){return on(async r=>{const n=await this.run();if(n.isJust()){const i=on.liftMaybe(n);return r.liftMaybe(Qr(t(i)))}return r.liftMaybe(jt)})}filter(t){return on(async r=>{const n=await this.run();return r.liftMaybe(n.filter(t))})}async run(){try{return Qr(await this.runPromise(N$))}catch{return jt}}map(t){return on(r=>this.runPromise(r).then(t))}chain(t){return on(async r=>{const n=await this.runPromise(r);return r.fromPromise(t(n))})}toEitherAsync(t){return pt(async({liftEither:r})=>{const n=await this.run();return r(n.toEither(t))})}ifJust(t){return on(async r=>{const n=await this.run();return n.ifJust(t),r.liftMaybe(n)})}ifNothing(t){return on(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 on(({fromPromise:r})=>r(this.run().finally(t)))}then(t,r){return this.run().then(t,r)}}F$=Symbol.toStringTag;const on=Object.assign(e=>new j$(e),{catMaybes:e=>Promise.all(e).then(Cn.catMaybes),fromPromise:e=>on(({fromPromise:t})=>t(e())),liftMaybe:e=>on(({liftMaybe:t})=>t(e))});j$.prototype.constructor=on;var z0=function(e,t){return z0=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},z0(e,t)};function xo(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");z0(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function ZN(e,t,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function u(p){try{f(n.next(p))}catch(g){s(g)}}function c(p){try{f(n.throw(p))}catch(g){s(g)}}function f(p){p.done?o(p.value):i(p.value).then(u,c)}f((n=n.apply(e,t||[])).next())})}function z$(e,t){var r={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=u(0),s.throw=u(1),s.return=u(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(f){return function(p){return c([f,p])}}function c(f){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,f[0]&&(r=0)),r;)try{if(n=1,i&&(o=f[0]&2?i.return:f[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,f[1])).done)return o;switch(i=0,o&&(f=[f[0]&2,o.value]),f[0]){case 0:case 1:o=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(o=r.trys,!(o=o.length>0&&o[o.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!o||f[1]>o[0]&&f[1]<o[3])){r.label=f[1];break}if(f[0]===6&&r.label<o[1]){r.label=o[1],o=f;break}if(o&&r.label<o[2]){r.label=o[2],r.ops.push(f);break}o[2]&&r.ops.pop(),r.trys.pop();continue}f=t.call(e,r)}catch(p){f=[6,p],i=0}finally{n=o=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function _l(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rl(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),i,o=[],s;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return o}function Ol(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,o;n<i;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))}function bl(e){return this instanceof bl?(this.v=e,this):new bl(e)}function e3(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(e,t||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(m){return function(y){return Promise.resolve(y).then(m,g)}}function u(m,y){n[m]&&(i[m]=function(b){return new Promise(function(S,_){o.push([m,b,S,_])>1||c(m,b)})},y&&(i[m]=y(i[m])))}function c(m,y){try{f(n[m](y))}catch(b){h(o[0][3],b)}}function f(m){m.value instanceof bl?Promise.resolve(m.value.v).then(p,g):h(o[0][2],m)}function p(m){c("next",m)}function g(m){c("throw",m)}function h(m,y){m(y),o.shift(),o.length&&c(o[0][0],o[0][1])}}function t3(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof _l=="function"?_l(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=e[o]&&function(s){return new Promise(function(u,c){s=e[o](s),i(u,c,s.done,s.value)})}}function i(o,s,u,c){Promise.resolve(c).then(function(f){o({value:f,done:u})},s)}}function cr(e){return typeof e=="function"}function Dp(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 rm=Dp(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription:
454
454
  `+r.map(function(n,i){return i+1+") "+n.toString()}).join(`
455
455
  `):"",this.name="UnsubscriptionError",this.errors=r}});function ap(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Oc=(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,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var u=_l(s),c=u.next();!c.done;c=u.next()){var f=c.value;f.remove(this)}}catch(b){t={error:b}}finally{try{c&&!c.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}else s.remove(this);var p=this.initialTeardown;if(cr(p))try{p()}catch(b){o=b instanceof rm?b.errors:[b]}var g=this._finalizers;if(g){this._finalizers=null;try{for(var h=_l(g),m=h.next();!m.done;m=h.next()){var y=m.value;try{wC(y)}catch(b){o=o??[],b instanceof rm?o=Ol(Ol([],Rl(o)),Rl(b.errors)):o.push(b)}}}catch(b){n={error:b}}finally{try{m&&!m.done&&(i=h.return)&&i.call(h)}finally{if(n)throw n.error}}}if(o)throw new rm(o)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)wC(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)&&ap(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&ap(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),B$=Oc.EMPTY;function V$(e){return e instanceof Oc||e&&"closed"in e&&cr(e.remove)&&cr(e.add)&&cr(e.unsubscribe)}function wC(e){cr(e)?e():e.unsubscribe()}var r3={Promise:void 0},n3={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,Ol([e,t],Rl(r)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function H$(e){n3.setTimeout(function(){throw e})}function B0(){}function zd(e){e()}var O1=(function(e){xo(t,e);function t(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,V$(r)&&r.add(n)):n.destination=a3,n}return t.create=function(r,n,i){return new V0(r,n,i)},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})(Oc),i3=(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){od(n)}},e.prototype.error=function(t){var r=this.partialObserver;if(r.error)try{r.error(t)}catch(n){od(n)}else od(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(r){od(r)}},e})(),V0=(function(e){xo(t,e);function t(r,n,i){var o=e.call(this)||this,s;return cr(r)||!r?s={next:r??void 0,error:n??void 0,complete:i??void 0}:s=r,o.destination=new i3(s),o}return t})(O1);function od(e){H$(e)}function o3(e){throw e}var a3={closed:!0,next:B0,error:o3,complete:B0},T1=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Tc(e){return e}function s3(e){return e.length===0?Tc:e.length===1?e[0]:function(r){return e.reduce(function(n,i){return i(n)},r)}}var Kn=(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 i=this,o=u3(t)?t:new V0(t,r,n);return zd(function(){var s=i,u=s.operator,c=s.source;o.add(u?u.call(o,c):c?i._subscribe(o):i._trySubscribe(o))}),o},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=xC(r),new r(function(i,o){var s=new V0({next:function(u){try{t(u)}catch(c){o(c),s.unsubscribe()}},error:o,complete:i});n.subscribe(s)})},e.prototype._subscribe=function(t){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(t)},e.prototype[T1]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return s3(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=xC(t),new t(function(n,i){var o;r.subscribe(function(s){return o=s},function(s){return i(s)},function(){return n(o)})})},e.create=function(t){return new e(t)},e})();function xC(e){var t;return(t=e??r3.Promise)!==null&&t!==void 0?t:Promise}function l3(e){return e&&cr(e.next)&&cr(e.error)&&cr(e.complete)}function u3(e){return e&&e instanceof O1||l3(e)&&V$(e)}function c3(e){return cr(e?.lift)}function Ti(e){return function(t){if(c3(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 Zi(e,t,r,n,i){return new f3(e,t,r,n,i)}var f3=(function(e){xo(t,e);function t(r,n,i,o,s,u){var c=e.call(this,r)||this;return c.onFinalize=s,c.shouldUnsubscribe=u,c._next=n?function(f){try{n(f)}catch(p){r.error(p)}}:e.prototype._next,c._error=o?function(f){try{o(f)}catch(p){r.error(p)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=i?function(){try{i()}catch(f){r.error(f)}finally{this.unsubscribe()}}:e.prototype._complete,c}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})(O1),d3=Dp(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Hl=(function(e){xo(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 EC(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new d3},t.prototype.next=function(r){var n=this;zd(function(){var i,o;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var s=_l(n.currentObservers),u=s.next();!u.done;u=s.next()){var c=u.value;c.next(r)}}catch(f){i={error:f}}finally{try{u&&!u.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}}})},t.prototype.error=function(r){var n=this;zd(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var i=n.observers;i.length;)i.shift().error(r)}})},t.prototype.complete=function(){var r=this;zd(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,i=this,o=i.hasError,s=i.isStopped,u=i.observers;return o||s?B$:(this.currentObservers=null,u.push(r),new Oc(function(){n.currentObservers=null,ap(u,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,i=n.hasError,o=n.thrownError,s=n.isStopped;i?r.error(o):s&&r.complete()},t.prototype.asObservable=function(){var r=new Kn;return r.source=this,r},t.create=function(r,n){return new EC(r,n)},t})(Kn),EC=(function(e){xo(t,e);function t(r,n){var i=e.call(this)||this;return i.destination=r,i.source=n,i}return t.prototype.next=function(r){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,r)},t.prototype.error=function(r){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.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,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&i!==void 0?i:B$},t})(Hl),p3=(function(e){xo(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,i=r.thrownError,o=r._value;if(n)throw i;return this._throwIfClosed(),o},t.prototype.next=function(r){e.prototype.next.call(this,this._value=r)},t})(Hl),$1={now:function(){return($1.delegate||Date).now()},delegate:void 0},U$=(function(e){xo(t,e);function t(r,n,i){r===void 0&&(r=1/0),n===void 0&&(n=1/0),i===void 0&&(i=$1);var o=e.call(this)||this;return o._bufferSize=r,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,r),o._windowTime=Math.max(1,n),o}return t.prototype.next=function(r){var n=this,i=n.isStopped,o=n._buffer,s=n._infiniteTimeWindow,u=n._timestampProvider,c=n._windowTime;i||(o.push(r),!s&&o.push(u.now()+c)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),i=this,o=i._infiniteTimeWindow,s=i._buffer,u=s.slice(),c=0;c<u.length&&!r.closed;c+=o?1:2)r.next(u[c]);return this._checkFinalizedStatuses(r),n},t.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,i=r._timestampProvider,o=r._buffer,s=r._infiniteTimeWindow,u=(s?1:2)*n;if(n<1/0&&u<o.length&&o.splice(0,o.length-u),!s){for(var c=i.now(),f=0,p=1;p<o.length&&o[p]<=c;p+=2)f=p;f&&o.splice(0,f+1)}},t})(Hl),h3=(function(e){xo(t,e);function t(r,n){return e.call(this)||this}return t.prototype.schedule=function(r,n){return this},t})(Oc),CC={setInterval:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setInterval.apply(void 0,Ol([e,t],Rl(r)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},g3=(function(e){xo(t,e);function t(r,n){var i=e.call(this,r,n)||this;return i.scheduler=r,i.work=n,i.pending=!1,i}return t.prototype.schedule=function(r,n){var i;if(n===void 0&&(n=0),this.closed)return this;this.state=r;var o=this.id,s=this.scheduler;return o!=null&&(this.id=this.recycleAsyncId(s,o,n)),this.pending=!0,this.delay=n,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(s,this.id,n),this},t.prototype.requestAsyncId=function(r,n,i){return i===void 0&&(i=0),CC.setInterval(r.flush.bind(r,this),i)},t.prototype.recycleAsyncId=function(r,n,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return n;n!=null&&CC.clearInterval(n)},t.prototype.execute=function(r,n){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(r,n);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(r,n){var i=!1,o;try{this.work(r)}catch(s){i=!0,o=s||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),o},t.prototype.unsubscribe=function(){if(!this.closed){var r=this,n=r.id,i=r.scheduler,o=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ap(o,this),n!=null&&(this.id=this.recycleAsyncId(i,n,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t})(h3),_C=(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=$1.now,e})(),v3=(function(e){xo(t,e);function t(r,n){n===void 0&&(n=_C.now);var i=e.call(this,r,n)||this;return i.actions=[],i._active=!1,i}return t.prototype.flush=function(r){var n=this.actions;if(this._active){n.push(r);return}var i;this._active=!0;do if(i=r.execute(r.state,r.delay))break;while(r=n.shift());if(this._active=!1,i){for(;r=n.shift();)r.unsubscribe();throw i}},t})(_C),W$=new v3(g3),m3=W$,y3=new Kn(function(e){return e.complete()});function G$(e){return e&&cr(e.schedule)}function I1(e){return e[e.length-1]}function b3(e){return cr(I1(e))?e.pop():void 0}function Lp(e){return G$(I1(e))?e.pop():void 0}function S3(e,t){return typeof I1(e)=="number"?e.pop():t}var q$=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function X$(e){return cr(e?.then)}function K$(e){return cr(e[T1])}function Y$(e){return Symbol.asyncIterator&&cr(e?.[Symbol.asyncIterator])}function Q$(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 w3(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var J$=w3();function Z$(e){return cr(e?.[J$])}function e2(e){return e3(this,arguments,function(){var r,n,i,o;return z$(this,function(s){switch(s.label){case 0:r=e.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,bl(r.read())];case 3:return n=s.sent(),i=n.value,o=n.done,o?[4,bl(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,bl(i)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function t2(e){return cr(e?.getReader)}function za(e){if(e instanceof Kn)return e;if(e!=null){if(K$(e))return x3(e);if(q$(e))return E3(e);if(X$(e))return C3(e);if(Y$(e))return r2(e);if(Z$(e))return _3(e);if(t2(e))return R3(e)}throw Q$(e)}function x3(e){return new Kn(function(t){var r=e[T1]();if(cr(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function E3(e){return new Kn(function(t){for(var r=0;r<e.length&&!t.closed;r++)t.next(e[r]);t.complete()})}function C3(e){return new Kn(function(t){e.then(function(r){t.closed||(t.next(r),t.complete())},function(r){return t.error(r)}).then(null,H$)})}function _3(e){return new Kn(function(t){var r,n;try{for(var i=_l(e),o=i.next();!o.done;o=i.next()){var s=o.value;if(t.next(s),t.closed)return}}catch(u){r={error:u}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}t.complete()})}function r2(e){return new Kn(function(t){O3(e,t).catch(function(r){return t.error(r)})})}function R3(e){return r2(e2(e))}function O3(e,t){var r,n,i,o;return ZN(this,void 0,void 0,function(){var s,u;return z$(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),r=t3(e),c.label=1;case 1:return[4,r.next()];case 2:if(n=c.sent(),!!n.done)return[3,4];if(s=n.value,t.next(s),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=c.sent(),i={error:u},[3,11];case 6:return c.trys.push([6,,9,10]),n&&!n.done&&(o=r.return)?[4,o.call(r)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Ma(e,t,r,n,i){n===void 0&&(n=0),i===void 0&&(i=!1);var o=t.schedule(function(){r(),i?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(o),!i)return o}function n2(e,t){return t===void 0&&(t=0),Ti(function(r,n){r.subscribe(Zi(n,function(i){return Ma(n,e,function(){return n.next(i)},t)},function(){return Ma(n,e,function(){return n.complete()},t)},function(i){return Ma(n,e,function(){return n.error(i)},t)}))})}function i2(e,t){return t===void 0&&(t=0),Ti(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}function T3(e,t){return za(e).pipe(i2(t),n2(t))}function $3(e,t){return za(e).pipe(i2(t),n2(t))}function I3(e,t){return new Kn(function(r){var n=0;return t.schedule(function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())})})}function A3(e,t){return new Kn(function(r){var n;return Ma(r,t,function(){n=e[J$](),Ma(r,t,function(){var i,o,s;try{i=n.next(),o=i.value,s=i.done}catch(u){r.error(u);return}s?r.complete():r.next(o)},0,!0)}),function(){return cr(n?.return)&&n.return()}})}function o2(e,t){if(!e)throw new Error("Iterable cannot be null");return new Kn(function(r){Ma(r,t,function(){var n=e[Symbol.asyncIterator]();Ma(r,t,function(){n.next().then(function(i){i.done?r.complete():r.next(i.value)})},0,!0)})})}function k3(e,t){return o2(e2(e),t)}function P3(e,t){if(e!=null){if(K$(e))return T3(e,t);if(q$(e))return I3(e,t);if(X$(e))return $3(e,t);if(Y$(e))return o2(e,t);if(Z$(e))return A3(e,t);if(t2(e))return k3(e,t)}throw Q$(e)}function Tl(e,t){return t?P3(e,t):za(e)}function a2(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Lp(e);return Tl(e,r)}var M3=Dp(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function RC(e,t){return new Promise(function(r,n){var i=!1,o;e.subscribe({next:function(s){o=s,i=!0},error:n,complete:function(){i?r(o):n(new M3)}})})}function s2(e){return e instanceof Date&&!isNaN(e)}var D3=Dp(function(e){return function(r){r===void 0&&(r=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=r}});function OC(e,t){var r=s2(e)?{first:e}:typeof e=="number"?{each:e}:e,n=r.first,i=r.each,o=r.with,s=o===void 0?L3:o,u=r.scheduler,c=u===void 0?W$:u,f=r.meta,p=f===void 0?null:f;if(n==null&&i==null)throw new TypeError("No timeout provided.");return Ti(function(g,h){var m,y,b=null,S=0,_=function(C){y=Ma(h,c,function(){try{m.unsubscribe(),za(s({meta:p,lastValue:b,seen:S})).subscribe(h)}catch(O){h.error(O)}},C)};m=g.subscribe(Zi(h,function(C){y?.unsubscribe(),S++,h.next(b=C),i>0&&_(i)},void 0,void 0,function(){y?.closed||y?.unsubscribe(),b=null})),!S&&_(n!=null?typeof n=="number"?n:+n-c.now():i)})}function L3(e){throw new D3(e)}function Da(e,t){return Ti(function(r,n){var i=0;r.subscribe(Zi(n,function(o){n.next(e.call(t,o,i++))}))})}function F3(e,t,r,n,i,o,s,u){var c=[],f=0,p=0,g=!1,h=function(){g&&!c.length&&!f&&t.complete()},m=function(b){return f<n?y(b):c.push(b)},y=function(b){f++;var S=!1;za(r(b,p++)).subscribe(Zi(t,function(_){t.next(_)},function(){S=!0},void 0,function(){if(S)try{f--;for(var _=function(){var C=c.shift();s||y(C)};c.length&&f<n;)_();h()}catch(C){t.error(C)}}))};return e.subscribe(Zi(t,m,function(){g=!0,h()})),function(){}}function A1(e,t,r){return r===void 0&&(r=1/0),cr(t)?A1(function(n,i){return Da(function(o,s){return t(n,o,i,s)})(za(e(n,i)))},r):(typeof t=="number"&&(r=t),Ti(function(n,i){return F3(n,i,e,r)}))}function l2(e){return e===void 0&&(e=1/0),A1(Tc,e)}function N3(){return l2(1)}function TC(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return N3()(Tl(e,Lp(e)))}function j3(e,t,r){r===void 0&&(r=m3);var n=-1;return t!=null&&(G$(t)?r=t:n=t),new Kn(function(i){var o=s2(e)?+e-r.now():e;o<0&&(o=0);var s=0;return r.schedule(function(){i.closed||(i.next(s++),0<=n?this.schedule(void 0,n):i.complete())},o)})}function z3(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Lp(e),n=S3(e,1/0),i=e;return i.length?i.length===1?za(i[0]):l2(n)(Tl(i,r)):y3}function $C(e,t){return Ti(function(r,n){var i=0;r.subscribe(Zi(n,function(o){return e.call(t,o,i++)&&n.next(o)}))})}function B3(e,t,r,n,i){return function(o,s){var u=r,c=t,f=0;o.subscribe(Zi(s,function(p){var g=f++;c=u?e(c,p,g):(u=!0,p),s.next(c)},i))}}function V3(e,t){return t===void 0&&(t=Tc),e=e??H3,Ti(function(r,n){var i,o=!0;r.subscribe(Zi(n,function(s){var u=t(s);(o||!e(i,u))&&(o=!1,i=u,n.next(s))}))})}function H3(e,t){return e===t}function U3(e){return Ti(function(t,r){try{t.subscribe(r)}finally{r.add(e)}})}function W3(e,t){return Ti(B3(e,t,arguments.length>=2,!0))}function G3(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Lp(e);return Ti(function(n,i){(r?TC(e,n,r):TC(e,n)).subscribe(i)})}function IC(e,t,r){var n=cr(e)||t||r?{next:e,error:t,complete:r}:e;return n?Ti(function(i,o){var s;(s=n.subscribe)===null||s===void 0||s.call(n);var u=!0;i.subscribe(Zi(o,function(c){var f;(f=n.next)===null||f===void 0||f.call(n,c),o.next(c)},function(){var c;u=!1,(c=n.complete)===null||c===void 0||c.call(n),o.complete()},function(c){var f;u=!1,(f=n.error)===null||f===void 0||f.call(n,c),o.error(c)},function(){var c,f;u&&((c=n.unsubscribe)===null||c===void 0||c.call(n)),(f=n.finalize)===null||f===void 0||f.call(n)}))}):Tc}function q3(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=b3(e);return Ti(function(n,i){for(var o=e.length,s=new Array(o),u=e.map(function(){return!1}),c=!1,f=function(g){za(e[g]).subscribe(Zi(i,function(h){s[g]=h,!c&&!u[g]&&(u[g]=!0,(c=u.every(Tc))&&(u=null))},B0))},p=0;p<o;p++)f(p);n.subscribe(Zi(i,function(g){if(c){var h=Ol([g],Rl(s));i.next(r?r.apply(void 0,Ol([],Rl(h))):h)}}))})}var $l=(e=>(e[e.Connected=0]="Connected",e[e.ReadyWithoutSecureChannel=1]="ReadyWithoutSecureChannel",e[e.ReadyWithSecureChannel=2]="ReadyWithSecureChannel",e))($l||{});let $c=class{_tag="GeneralDmkError";originalError;constructor(t){t instanceof Error?this.originalError=t:t!==void 0&&(this.originalError=new Error(String(t)))}},k1=class extends $c{constructor(t){super(t),this.err=t}_tag="TransportNotSupportedError"},X3=class extends $c{constructor(t){super(t),this.err=t}_tag="SendApduTimeoutError"},K3=class extends $c{constructor(t){super(t),this.err=t}_tag="SendCommandTimeoutError"},Y3=class extends $c{constructor(t){super(t),this.err=t}_tag="TransportAlreadyExistsError"},Q3=class extends $c{constructor(t){super(t),this.err=t}_tag="NoTransportProvidedError"};var ul=null;typeof WebSocket<"u"?ul=WebSocket:typeof MozWebSocket<"u"?ul=MozWebSocket:typeof self<"u"?ul=self.WebSocket||self.MozWebSocket:typeof window<"u"?ul=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(ul=self.WebSocket||self.MozWebSocket);const J3=ul;var Z3=(e=>(e.GenuineCheck="GenuineCheck",e.ListInstalledApps="ListInstalledApps",e.UpdateMcu="UpdateMcu",e.UpdateFirmware="UpdateFirmware",e.InstallApp="InstallApp",e.UninstallApp="UninstallApp",e))(Z3||{}),e4=(e=>(e.EXCHANGE="exchange",e.BULK="bulk",e.ERROR="error",e.WARNING="warning",e.SUCCESS="success",e))(e4||{}),t4=(e=>(e.SUCCESS="success",e.ERROR="error",e))(t4||{}),r4=(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))(r4||{}),n4=(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))(n4||{});let i4=class{constructor(t){this.error=t,this.originalError=t}_tag="WebSocketConnectionError";originalError};function P1(e,t){return Reflect.getOwnMetadata(t,e)}function o4(e,t,r){Reflect.defineMetadata(t,r,e)}function Hu(e,t,r,n){const i=n(P1(e,t)??r());Reflect.defineMetadata(t,i,e)}var AC,kC,PC;(function(e){e.moduleId="moduleId",e.serviceId="serviceId"})(AC||(AC={}));(function(e){e.id="id",e.moduleId="moduleId",e.serviceId="serviceId"})(kC||(kC={}));(function(e){e.moduleId="moduleId",e.serviceId="serviceId"})(PC||(PC={}));const Bd="@inversifyjs/core/classMetadataReflectKey";function Vd(){return{constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}const a4="@inversifyjs/core/pendingClassMetadataCountReflectKey",nm=Symbol.for("@inversifyjs/core/InversifyCoreError");let La=class u2 extends Error{[nm];kind;constructor(t,r,n){super(r,n),this[nm]=!0,this.kind=t}static is(t){return typeof t=="object"&&t!==null&&t[nm]===!0}static isErrorOfKind(t,r){return u2.is(t)&&t.kind===r}};var bo,sp,oc;function s4(){return 0}function l4(e){return t=>{t!==void 0&&t.kind===sp.unknown&&Hu(e,a4,s4,(r=>r-1))}}function u4(e,t){return(...r)=>n=>{if(n===void 0)return e(...r);if(n.kind===oc.unmanaged)throw new La(bo.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return t(n,...r)}}function c4(e){if(e.kind!==sp.unknown&&e.isFromTypescriptParamType!==!0)throw new La(bo.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"})(bo||(bo={})),(function(e){e[e.unknown=32]="unknown"})(sp||(sp={})),(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection",e[e.unmanaged=2]="unmanaged"})(oc||(oc={}));const f4=u4((function(e,t){return{kind:e,name:void 0,optional:!1,tags:new Map,value:t}}),(function(e,t,r){return c4(e),{...e,kind:t,value:r}}));function MC(e,t){return r=>{const n=r.properties.get(t);return r.properties.set(t,e(n)),r}}var Ra;function d4(e,t,r,n){if(La.isErrorOfKind(n,bo.injectionDecoratorConflict)){const i=(function(o,s,u){if(u===void 0){if(s===void 0)throw new La(bo.unknown,"Unexpected undefined property and index values");return{kind:Ra.property,property:s,targetClass:o.constructor}}return typeof u=="number"?{index:u,kind:Ra.parameter,targetClass:o}:{kind:Ra.method,method:s,targetClass:o}})(e,t,r);throw new La(bo.injectionDecoratorConflict,`Unexpected injection error.
456
456
 
@@ -462,7 +462,7 @@ Details
462
462
 
463
463
  ${(function(o){switch(o.kind){case Ra.method:return`[class: "${o.targetClass.name}", method: "${o.method.toString()}"]`;case Ra.parameter:return`[class: "${o.targetClass.name}", index: "${o.index.toString()}"]`;case Ra.property:return`[class: "${o.targetClass.name}", property: "${o.property.toString()}"]`}})(i)}`,{cause:n})}throw n}function p4(e,t){return(r,n,i)=>{try{i===void 0?(function(o,s){const u=im(o,s);return(c,f)=>{Hu(c.constructor,Bd,Vd,MC(u(c),f))}})(e,t)(r,n):typeof i=="number"?(function(o,s){const u=im(o,s);return(c,f,p)=>{if(!(function(g,h){return typeof g=="function"&&h===void 0})(c,f))throw new La(bo.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
464
464
  Found @inject decorator at method "${f?.toString()??""}" at class "${c.constructor.name}"`);Hu(c,Bd,Vd,(function(g,h){return m=>{const y=m.constructorArguments[h];return m.constructorArguments[h]=g(y),m}})(u(c),p))}})(e,t)(r,n,i):(function(o,s){const u=im(o,s);return(c,f,p)=>{if(!(function(g){return g.set!==void 0})(p))throw new La(bo.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
465
- Found @inject decorator at method "${f.toString()}" at class "${c.constructor.name}"`);Hu(c.constructor,Bd,Vd,MC(u(c),f))}})(e,t)(r,n,i)}catch(o){d4(r,n,i,o)}}}function im(e,t){return r=>{const n=t(r);return i=>(n(i),e(i))}}function Ye(e){return p4(f4(oc.singleInjection,e),l4)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(Ra||(Ra={}));const DC="@inversifyjs/core/classIsInjectableFlagReflectKey",h4=[Array,BigInt,Boolean,Function,Number,Object,String];function g4(e){const t=P1(e,"design:paramtypes");t!==void 0&&Hu(e,Bd,Vd,(function(r){return n=>(r.forEach(((i,o)=>{var s;n.constructorArguments[o]!==void 0||(s=i,h4.includes(s))||(n.constructorArguments[o]=(function(u){return{isFromTypescriptParamType:!0,kind:oc.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(i))})),n)})(t))}function Et(e){return t=>{(function(r){if(P1(r,DC)!==void 0)throw new La(bo.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);o4(r,DC,!0)})(t),g4(t)}}var LC;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(LC||(LC={}));var FC;(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"})(FC||(FC={}));let v4=class{constructor(t,r,n,i,o){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=i,this.notifyUuid=o}},Qs=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 m4=Object.defineProperty,y4=(e,t,r)=>t in e?m4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},S4=(e,t,r)=>y4(e,t+"",r);let Oa=class{getAllDeviceModels(){return Object.values(Oa.deviceModelByIds)}getDeviceModel(t){return Oa.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,i])=>r[n]===i))}getBluetoothServicesInfos(){return Object.values(Oa.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((i,o)=>({...i,[o.serviceUuid]:new v4(r,o.serviceUuid,o.writeUuid,o.writeCmdUuid,o.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values(Oa.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};S4(Oa,"deviceModelByIds",{[Xt.NANO_S]:new Qs({id:Xt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>SC.lt(SC.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[Xt.NANO_SP]:new Qs({id:Xt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[Xt.NANO_X]:new Qs({id:Xt.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"}]}),[Xt.STAX]:new Qs({id:Xt.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"}]}),[Xt.FLEX]:new Qs({id:Xt.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"}]}),[Xt.APEX]:new Qs({id:Xt.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"}]})}),Oa=b4([Et()],Oa);let w4=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const x4=5,is=1,H0=2,pl=2,U0=2,Pr=[];for(let e=0;e<256;++e)Pr.push((e+256).toString(16).slice(1));function E4(e,t=0){return(Pr[e[t+0]]+Pr[e[t+1]]+Pr[e[t+2]]+Pr[e[t+3]]+"-"+Pr[e[t+4]]+Pr[e[t+5]]+"-"+Pr[e[t+6]]+Pr[e[t+7]]+"-"+Pr[e[t+8]]+Pr[e[t+9]]+"-"+Pr[e[t+10]]+Pr[e[t+11]]+Pr[e[t+12]]+Pr[e[t+13]]+Pr[e[t+14]]+Pr[e[t+15]]).toLowerCase()}let om;const C4=new Uint8Array(16);function _4(){if(!om){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");om=crypto.getRandomValues.bind(crypto)}return om(C4)}const R4=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),NC={randomUUID:R4};function Fp(e,t,r){if(NC.randomUUID&&!e)return NC.randomUUID();e=e||{};const n=e.random||(e.rng||_4)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,E4(n)}const ds={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)}},jC=2,am=800;let zC=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},O4=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},BC=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},VC=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},c2=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:Jo(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}},f2=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:i,length:o,channel:s}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=i,this._length=o,this._channel=s}getDataLength(){return this._dataLength.map(t=>ds.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 wr={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var T4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},$4=(e,t)=>(r,n)=>t(r,n,e);let HC=class{_channel;_logger;_pendingFrames;constructor({channel:t=Cn.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 jt;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"),jt;const n=ds.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),i=ds.getFirstBytesFrom(n,n.length-jC),o=ds.getLastBytesFrom(n,jC);return this._pendingFrames=[],Qr(new w4({data:i,statusCode:o}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>H0,Nothing:()=>0}),n=t.slice(r,r+is),i=t.slice(r+is,r+is+pl),o=i.reduce((h,m)=>h+m,0)===0;if(!o&&this._pendingFrames.length===0)return Wt(new BC);const s=r+is+pl,u=o?U0:0;if(t.length<r+is+pl+u)return Wt(new BC("Unable to parse header from apdu"));const c=o?Qr(t.slice(s,s+u)):jt,f=s+u,p=t.slice(f),g=new c2({header:new f2({uuid:Fp(),channel:this._channel,dataSize:c,headTag:n,index:i,length:r+is+pl+u}),data:p});return nr(g)}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))}};HC=T4([Et(),$4(1,Ye(wr.LoggerPublisherServiceFactory))],HC);var I4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},A4=(e,t)=>(r,n)=>t(r,n,e);let UC=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=Cn.zero(),padding:n=!1},i){this._frameSize=t,this._channel=r,this._padding=n,this._logger=i("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,i=this.getFrameAtIndex(t,n);for(;i.isRight();)r.push(i.extract()),n+=1,i=this.getFrameAtIndex(t,n).mapLeft(o=>(o instanceof zC||this._logger.error("Error while parsing frame",{data:{error:o}}),o));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),i=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(i>=t.length)return Wt(new zC);if(n.getLength()>this._frameSize)return Wt(new O4);const o=this._frameSize-n.getLength(),s=t.slice(i,i+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(o).fill(0):new Uint8Array(s.length<o?s.length:o);u.set(s,0);const c=new c2({header:n,data:u});return nr(c)}getFrameHeaderFrom(t,r){const n=new f2({uuid:Fp(),channel:this._channel.map(i=>ds.getLastBytesFrom(i,H0)),headTag:new Uint8Array([x4]),index:ds.numberToByteArray(t,pl),length:this.getFrameHeaderSizeFromIndex(t),dataSize:Cn.zero()});return t===0&&n.setDataSize(Cn.of(ds.numberToByteArray(r,U0))),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:()=>H0,Nothing:()=>0})+pl+is+(t===0?U0:0)}};UC=I4([Et(),A4(1,Ye(wr.LoggerPublisherServiceFactory))],UC);const W0={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},cn={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},WC={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},Np={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Fa={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var k4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},GC=(e,t)=>(r,n)=>t(r,n,e);let qC=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 i=>await i.sendCommand(r,n),Left:i=>{throw this._logger.error("Error getting session",{data:{error:i}}),i}})}};qC=k4([Et(),GC(0,Ye(cn.DeviceSessionService)),GC(1,Ye(wr.LoggerPublisherServiceFactory))],qC);var P4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let XC=class{execute=vi.fn(()=>"stub")};XC=P4([Et()],XC);var M4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},KC=(e,t)=>(r,n)=>t(r,n,e);let YC=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}})}};YC=M4([Et(),KC(0,Ye(cn.DeviceSessionService)),KC(1,Ye(wr.LoggerPublisherServiceFactory))],YC);function D4(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let QC=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},L4=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},d2=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},F4=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const N4="@ledgerhq/device-management-kit",j4="0.0.0-develop-20260707003031",JC={name:N4,version:j4};var z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};const B4={name:JC.name,version:JC.version},V4=()=>JSON.stringify(B4);let ZC=class{getConfig(){return _n.encase(()=>V4()).mapLeft(t=>new F4(t)).chain(t=>_n.encase(()=>{const r=JSON.parse(t);if(D4(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new d2(r)))}};ZC=z4([Et()],ZC);var H4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let e_=class{getConfig(){return _n.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};e_=H4([Et()],e_);var U4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let t_=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return Wt(new QC(t.extract()));if(!t.extract().ok)return Wt(new QC(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?Wt(new d2):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?Wt(new L4):_n.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(_n.of({ok:!0,json:async()=>new Promise(r=>{r(_n.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};t_=U4([Et()],t_);var W4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let r_=class{async getConfig(){return new Promise(t=>t(_n.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};r_=W4([Et()],r_);var G4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},sm=(e,t)=>(r,n)=>t(r,n,e);let n_=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())}};n_=G4([Et(),sm(0,Ye(W0.LocalConfigDataSource)),sm(1,Ye(W0.RemoteConfigDataSource)),sm(2,Ye(wr.LoggerPublisherServiceFactory))],n_);var q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},X4=(e,t)=>(r,n)=>t(r,n,e);let i_=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};i_=q4([Et(),X4(0,Ye(W0.ConfigService))],i_);const K4={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var Y4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},o_=(e,t)=>(r,n)=>t(r,n,e);let a_=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)})}};a_=Y4([Et(),o_(0,Ye(cn.DeviceSessionService)),o_(1,Ye(wr.LoggerPublisherServiceFactory))],a_);var Q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},J4=(e,t)=>(r,n)=>t(r,n,e);let s_=class{_sessions;_sessionsSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new U$,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 Cn.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new VC)}getDeviceSessionsByDeviceId(t){return Cn.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new VC)}getDeviceSessions(){return this._sessions}};s_=Q4([Et(),J4(0,Ye(wr.LoggerPublisherServiceFactory))],s_);var Z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},l_=(e,t)=>(r,n)=>t(r,n,e);let u_=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)}};u_=Z4([Et(),l_(0,Ye(cn.DeviceSessionService)),l_(1,Ye(Fa.TransportService))],u_);var ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},c_=(e,t)=>(r,n)=>t(r,n,e);let f_=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})}};f_=ej([Et(),c_(0,Ye(cn.DeviceSessionService)),c_(1,Ye(wr.LoggerPublisherServiceFactory))],f_);var tj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},d_=(e,t)=>(r,n)=>t(r,n,e);let p_=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)}})}};p_=tj([Et(),d_(0,Ye(cn.DeviceSessionService)),d_(1,Ye(wr.LoggerPublisherServiceFactory))],p_);function rj(e){return`[will send APDU] ~...> ${Jo(e,!1)}`}function nj(e){return`[exchange] <= ${Jo(e.data,!1)}${Jo(e.statusCode,!1)}`}const ij="apdu-exchange";function oj(e,t,r){const n=Jo(t,!1),i=`${Jo(r.data,!1)}${Jo(r.statusCode,!1)}`;return{message:nj(r),data:{type:ij,sessionId:e,apdu:n,response:i}}}const G0=1e3,lm=1e3,aj={isRefresherDisabled:!1,pollingInterval:1e3};var ur=(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))(ur||{});let sj=class{_eventEmitter=new Hl;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},lj=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 Hl,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const i=()=>{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(U3(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:i}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:ur.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:ur.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()}},uj=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${Fp()}`;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()}},cj=class{constructor(t,r,n,i){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=i,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async o=>await this.mapEventAction(o))}_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===ur.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===Xt.NANO_S){const r=async()=>{const o=await this._sendCommandFunction(new TE,am);return this._sendCommandFunction(new UN,am),o},n=new Promise(o=>{setTimeout(()=>o(null),G0*2+100)}),i=await Promise.race([r(),n]);return i?this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:i}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}),i}else{const r=await this._sendCommandFunction(new TE,am);return this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},fj=class{constructor(t,r,n,i){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=i.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($C(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY||n.eventName===ur.NEW_STATE),Da(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY),G3(!1),V3());this._refresherSubscription=j3(0,t).pipe(q3(r),IC(([n,i])=>{i&&this._logger.debug("Refresh skipped: device is busy")}),$C(([n,i])=>!i),IC(()=>this._sessionEventDispatcher.dispatch({eventName:ur.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===Xt.NANO_S){const i=G0*2;return n!==void 0&&n<i?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${i}`),i):n??i}else return n!==void 0&&n<lm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${lm}`),lm):n??G0}},dj=class{constructor(t,r,n,i,o){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=i,this.setDeviceSessionState=o,this._subscription=this._sessionEventDispatcher.listen().subscribe(s=>this.mapEventAction(s)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=po.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:i,currentApp:o}=r,s=this._deviceState.getValue();s.sessionStateType===$l.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...s,sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case ur.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case ur.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:po.BUSY});case ur.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=po.LOCKED;return;case ur.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=po.CONNECTED;return;case ur.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=po.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case ur.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:po.BUSY});case ur.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return fN(t)?{sessionStateType:$l.ReadyWithoutSecureChannel,deviceStatus:po.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()}},pj=class{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new sj;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=Fp()},n,i,o,s,u=c=>new lj(n,c)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=i,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=o,this._refresherOptions={...aj,...s},this._deviceState=new p3({sessionStateType:$l.Connected,deviceStatus:po.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new cj(n,t,this._sessionEventDispatcher,(c,f)=>this.sendCommand(c,f)),this._deviceSessionRefresher=new fj(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new dj(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,c=>this.setDeviceSessionState(c)),this._refresherService=new uj(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,i=Date.now(),{observable:o,cancel:s}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Tl((async()=>{const c=Date.now()-i;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-c:void 0})})())}),u=n?o.pipe(OC({each:n,with:()=>{throw s(),new X3}})):o;return RC(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(rj(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:i,data:o}=oj(this._id,t,n);this._logger.debug(i,{data:o}),v1.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:ur.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:i,cancel:o}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Tl((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),s=r?i.pipe(OC({each:r,with:()=>{throw o(),new K3}})):i;return RC(s)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:i=>{throw this._logger.error("[sendCommand] error",{data:{err:i}}),i},Right:i=>{const o=t.parseResponse(i,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:o}}),o}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:i}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:o,cancel:s}=this._unsafeInternalExecuteDeviceAction(t);return r=s,o}});return{observable:n,cancel:()=>{r?.(),i()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async i=>this._unsafeInternalSendApdu(i),sendCommand:async i=>this._unsafeInternalSendCommand(i),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:i=>(this.setDeviceSessionState(i),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(po.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})}};const M1={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")};var hj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Cu=(e,t)=>(r,n)=>t(r,n,e);let h_=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,i,o){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=i,this._secureChannel=o}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),i="sessionId"in t?t.sessionId:void 0;return pt.liftEither(n.toEither(new k1(new Error("Unknown transport")))).chain(async o=>o.connect({deviceId:t.id,onDisconnect:s=>this.handleDeviceDisconnect(s)})).ifLeft(o=>{this._logger.error("Error connecting to device")}).map(async o=>{const s=new pj({connectedDevice:o,id:i},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(s),await s.initialiseSession(),s.id}).caseOf({Left:o=>{throw o},Right:o=>o})}};h_=hj([Et(),Cu(0,Ye(Fa.TransportService)),Cu(1,Ye(cn.DeviceSessionService)),Cu(2,Ye(wr.LoggerPublisherServiceFactory)),Cu(3,Ye(Np.ManagerApiService)),Cu(4,Ye(M1.SecureChannelService))],h_);var gj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},um=(e,t)=>(r,n)=>t(r,n,e);let g_=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)}}),pt(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(s=>{this._logger.error("Device session not found",{data:{sessionId:t,error:s}})})),i=n.connectedDevice.transport,o=await r(this._transportService.getTransport(i).toEither(new k1(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await o.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};g_=gj([Et(),um(0,Ye(Fa.TransportService)),um(1,Ye(cn.DeviceSessionService)),um(2,Ye(wr.LoggerPublisherServiceFactory))],g_);let D1=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:i,transport:o,name:s},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=s??n,this.type=i,this.transport=o}};var vj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},v_=(e,t)=>(r,n)=>t(r,n,e);let m_=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 D1({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};m_=vj([Et(),v_(0,Ye(cn.DeviceSessionService)),v_(1,Ye(wr.LoggerPublisherServiceFactory))],m_);var mj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},y_=(e,t)=>(r,n)=>t(r,n,e);let b_=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 D1({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};b_=mj([Et(),y_(0,Ye(cn.DeviceSessionService)),y_(1,Ye(wr.LoggerPublisherServiceFactory))],b_);var yj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},S_=(e,t)=>(r,n)=>t(r,n,e);let w_=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new A$({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"),Tl([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,i)=>n.listenToAvailableDevices().pipe(Da(o=>({index:i,arr:o}))));return z3(...r).pipe(W3((n,{index:i,arr:o})=>(n[i]=o,n),{}),Da(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`),a2([])),Just:r=>r.listenToAvailableDevices().pipe(Da(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};w_=yj([Et(),S_(0,Ye(Fa.TransportService)),S_(1,Ye(wr.LoggerPublisherServiceFactory))],w_);var bj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},x_=(e,t)=>(r,n)=>t(r,n,e);let E_=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(Da(t=>new D1({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};E_=bj([Et(),x_(0,Ye(cn.DeviceSessionService)),x_(1,Ye(wr.LoggerPublisherServiceFactory))],E_);var Sj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},cm=(e,t)=>(r,n)=>t(r,n,e);let C_=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})}};C_=Sj([Et(),cm(0,Ye(WC.ConnectUseCase)),cm(1,Ye(WC.DisconnectUseCase)),cm(2,Ye(wr.LoggerPublisherServiceFactory))],C_);var wj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},xj=(e,t)=>(r,n)=>t(r,n,e);let __=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new A$({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 a2(...r).pipe(A1(n=>n.startDiscovering().pipe(Da(i=>this.mapDiscoveredDevice(i)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(Da(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new k1(new Error("Unknown transport"))}})}};__=wj([Et(),xj(0,Ye(Fa.TransportService))],__);var Ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},R_=(e,t)=>(r,n)=>t(r,n,e);let O_=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()}};O_=Ej([Et(),R_(0,Ye(Fa.TransportService)),R_(1,Ye(wr.LoggerPublisherServiceFactory))],O_);var Mu=(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))(Mu||{});let Cj=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function q0(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>q0(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=q0(i,t);return r}return e}function _j(e){const t=new WeakSet;t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=q0(i,t);return r}var Rj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let T_=class{subscribers;tag;tagFormatter;constructor(t,r,n=new Cj){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const i=n?.data?_j(n.data):void 0,o=n?.tag??this.tag,s=this.tagFormatter.format(o);this.subscribers.forEach(u=>{const c={timestamp:n?.timestamp??Date.now(),tag:s,data:i};u.log(t,r,c)})}info(t,r){this._log(Mu.Info,t,r)}warn(t,r){this._log(Mu.Warning,t,r)}debug(t,r){this._log(Mu.Debug,t,r)}error(t,r){this._log(Mu.Error,t,r)}};T_=Rj([Et()],T_);let ac=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 Oj="application/json";function Tj(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function $j(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function os(e){const{url:t,params:r,baseUrl:n}=e,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?Tj(n,t):t,o=r?$j(r):"";if(o.length===0)return i;const s=i.includes("?")?"&":"?";return`${i}${s}${o}`}function Ij(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function Aj(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 kj(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:i}=e,o={...n,...i};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:o}:Aj(r)?{body:r,headers:o}:(Ij(o,"content-type")||(o["Content-Type"]=Oj),{body:JSON.stringify(r),headers:o})}function Pj(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 Mj(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 ac({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function Dj(e){try{return await e.text()}catch{return}}function Lj(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const i=t.name==="TimeoutError"||n;return new ac({message:i?"Request timed out":"Request aborted",isTimeout:i,cause:t})}return new ac({message:t instanceof Error?t.message:"Network request failed",cause:t})}let p2=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(i=>i.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(i=>i.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(i=>i.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=os({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:i}=kj({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:o,cleanup:s}=Pj({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,c=t.responseType??"json";try{let f;try{f=await this.getFetch()(r,{method:t.method,headers:i,body:n,signal:o})}catch(p){throw Lj({cause:p,timeoutMs:t.timeoutMs})}if(!f.ok&&u){const p=await Dj(f);throw new ac({message:`HTTP error ${f.status} ${f.statusText}`.trim(),status:f.status,statusText:f.statusText,responseBody:p})}return{data:await Mj(f,c),status:f.status,statusText:f.statusText,headers:f.headers,ok:f.ok}}finally{s()}}};var Du=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Du||{});const Fj=1,Nj="0";let lp=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var Lu=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Lu||{}),jj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},zj=(e,t)=>(r,n)=>t(r,n,e);const Go=e=>e instanceof ac&&e.cause!==void 0?new lp(e.cause):new lp(e);let $_=class{http;_provider=Fj;_firmwareDistributionSalt=Nj;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n}){this.http=new p2({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n}setProvider(t){this._provider===t||t<1||(this._provider=t)}getProvider(){return this._provider}getAppList(t){const{targetId:r,firmwareVersionName:n}=t;return pt(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(i=>this.mapApplicationDtoToApplication(i)).mapLeft(Go)}getMcuList(){return pt(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(Go)}getDeviceVersion(t){const{targetId:r}=t;return pt(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(Go)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return pt(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapFinalFirmwareDto(i)).mapLeft(Go)}getFirmwareVersionById(t){return pt(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(Go)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return pt(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapOsuFirmwareDto(i)).mapLeft(Go)}getLatestFirmwareVersion(t){const r="34.27.0",{currentFinalFirmwareId:n,deviceId:i}=t;return pt(()=>this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:n,device_version:i,provider:this._provider,salt:this._firmwareDistributionSalt,livecommonversion:r}})).chain(o=>this.mapLatestFirmwareDto(o)).mapLeft(Go)}getAppsByHash(t){const{hashes:r}=t;return pt(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(Go)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return pt(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(i=>this.mapLanguagesDtoToLanguages(i)).mapLeft(Go)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case Lu.currency:return Du.currency;case Lu.plugin:return Du.plugin;case Lu.tool:return Du.tool;case Lu.swap:return Du.swap}}mapApplicationDtoToApplication(t){return pt(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return pt(()=>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:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,...f}=t;return{...f,hash:n,perso:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return pt(()=>Promise.resolve(t.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name}})))}mapDeviceVersionDto(t){return pt(()=>{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 pt(()=>{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 pt(()=>{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=>this.mapOsuFirmwareDto(r))}mapOsuFirmwareDto(t){return pt(()=>{if(typeof t!="object"||typeof t.id!="number"||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,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 pt(()=>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}}};$_=jj([Et(),zj(0,Ye(Np.DmkConfig))],$_);var Bj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Vj=(e,t)=>(r,n)=>t(r,n,e);let I_=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 pt(async({fromPromise:n,throwE:i})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(o){return o instanceof lp?i(o):i(new lp(o))}})}};I_=Bj([Et(),Vj(0,Ye(Np.ManagerApiDataSource))],I_);var Hj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},A_=(e,t)=>(r,n)=>t(r,n,e);let k_=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!==$l.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};k_=Hj([Et(),A_(0,Ye(cn.DeviceSessionService)),A_(1,Ye(Np.ManagerApiDataSource))],k_);var Uj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Wj=(e,t)=>(r,n)=>t(r,n,e);let P_=class{webSocketBaseUrl;constructor({webSocketUrl:t}){this.webSocketBaseUrl=t}genuineCheck(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return nr(new J3(t))}catch(r){return Wt(new i4(r))}}};P_=Uj([Et(),Wj(0,Ye(M1.DmkConfig))],P_);var Gj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},qj=(e,t)=>(r,n)=>t(r,n,e);let M_=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:i,firmwareKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};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:i,deleteKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};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)}};M_=Gj([Et(),qj(0,Ye(M1.SecureChannelDataSource))],M_);var Xj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},D_=(e,t)=>(r,n)=>t(r,n,e);let L_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:i}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async o=>(await o.sendApdu(r,{abortTimeout:n,triggersDisconnection:i})).caseOf({Right:s=>s,Left:s=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:s}}),s}}),Left:o=>{throw this._logger.error("Error getting deviceSession",{data:{error:o}}),o}})}};L_=Xj([Et(),D_(0,Ye(cn.DeviceSessionService)),D_(1,Ye(wr.LoggerPublisherServiceFactory))],L_);var Kj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Js=(e,t)=>(r,n)=>t(r,n,e);let F_=class{constructor(t,r,n,i,o,s){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=i,this._apduSenderServiceFactory=o,this._apduReceiverServiceFactory=s,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new Q3("No transports provided, please check your configuration");for(const u of t){const c=this.addTransport(u);if(c.isLeft())throw c.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`),Wt(new Y3(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),nr(void 0))}getTransport(t){return Cn.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};F_=Kj([Et(),Js(0,Ye(Fa.TransportsInput)),Js(1,Ye(Fa.DmkConfig)),Js(2,Ye(wr.LoggerPublisherServiceFactory)),Js(3,Ye(K4.DeviceModelDataSource)),Js(4,Ye(cn.ApduSenderServiceFactory)),Js(5,Ye(cn.ApduReceiverServiceFactory))],F_);const Yj={ADD_LOG:"addLog"};function Qj(e){return{startListeningCommand:()=>e.sendMessage(Qo.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(Qo.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(Qo.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(Qo.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(Qo.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function Jj(e){return{getProviderCommand:()=>e.sendMessage(Qo.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(Qo.SET_PROVIDER,JSON.stringify({provider:t}))}}let Zj=0;function ez(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++Zj}`,i=r.match(/.{1,2}/g)?.map(o=>parseInt(o,16))||[];return e.sendMessage(Qo.SEND_APDU,JSON.stringify({sessionId:t,apdu:i,requestId:n})),n}}}function tz(e){const{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o}=JSON.parse(e);return{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o,payload:JSON.parse(o)}}const rz="apdu-exchange";function nz(e){const t=e.payload;return typeof t!="object"||t===null||Array.isArray(t)||t.type!==rz||typeof t.apdu!="string"||typeof t.response!="string"?null:{sessionId:typeof t.sessionId=="string"?t.sessionId:void 0,apdu:t.apdu,response:t.response,timestamp:e.timestamp}}function iz(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 oz(e,t,r,n){const i=tz(e);if(i!==null){if(t(o=>[...o,i]),n){const o=nz(i);o!==null&&r(s=>[...s,o])}return!0}return!1}function az(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function sz(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(i=>new Map(i).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function lz(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function uz(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}function cz(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)}}function fz(e){const[t,r]=x.useState([]),[n,i]=x.useState([]),[o,s]=x.useState([]),[u,c]=x.useState(new Set),[f,p]=x.useState([]),[g,h]=x.useState(new Map),[m,y]=x.useState([]),[b,S]=x.useState(!1),[_,C]=x.useState(!1),[O,R]=x.useState(null),[T,$]=x.useState(new Map),[P,L]=x.useState([]),[z,B]=x.useState(!1),X=x.useRef(!1),Y=x.useMemo(()=>({...e,sendMessage:(W,ve)=>{e.sendMessage(W,ve),i(se=>[...se,{type:W,payload:ve}])}}),[e]);x.useEffect(()=>{const{unsubscribe:W}=e.listenToMessages((ve,se)=>{switch(r(Ee=>[...Ee,{type:ve,payload:se}]),ve){case tN:iz(se,c);break;case Eu.CONNECTED_DEVICES_UPDATE:az(se,p);break;case Eu.DEVICE_SESSION_STATE_UPDATE:sz(se,h);break;case Eu.DISCOVERED_DEVICES_UPDATE:lz(se,y);break;case Eu.PROVIDER_VALUE:uz(se,R);break;case Eu.APDU_RESPONSE:cz(se,$);break;case Yj.ADD_LOG:oz(se,s,L,X.current);break}});return W},[e]);const N=x.useMemo(()=>Qj(Y),[Y]),j=x.useMemo(()=>Jj(Y),[Y]),F=x.useMemo(()=>ez(Y),[Y]),q=x.useCallback(()=>{S(!0),y([]),N.startListeningCommand()},[N]),U=x.useCallback(()=>{S(!1),y([]),N.stopListeningCommand()},[N]),M=x.useCallback(()=>{C(!0),y([]),N.startDiscoveringCommand()},[N]),G=x.useCallback(()=>{C(!1),y([]),N.stopDiscoveringCommand()},[N]),K=x.useCallback(()=>{s([])},[]),D=x.useCallback(()=>{X.current=!0,B(!0)},[]),A=x.useCallback(()=>{X.current=!1,B(!1)},[]),J=x.useCallback(()=>{L([])},[]),Z=u.has(xE.LOGGER),ne=u.has(xE.DMK_INSPECTOR);return{receivedMessages:t,sentMessages:n,logs:o,connectedModules:u,connectedDevices:f,sessionStates:g,discoveredDevices:m,isListening:b,isActivelyDiscovering:_,isLoggerConnected:Z,isInspectorConnected:ne,providerValue:O,apduResponses:T,apduExchanges:P,isRecordingExchanges:z,sendMessage:Y.sendMessage,clearLogs:K,startRecordingExchanges:D,stopRecordingExchanges:A,clearRecordedExchanges:J,startListening:q,stopListening:U,startDiscovering:M,stopDiscovering:G,connectDevice:N.connectDeviceCommand,getProvider:j.getProviderCommand,setProvider:j.setProviderCommand,sendApdu:F.sendApduCommand}}const dz=ge.div`
465
+ Found @inject decorator at method "${f.toString()}" at class "${c.constructor.name}"`);Hu(c.constructor,Bd,Vd,MC(u(c),f))}})(e,t)(r,n,i)}catch(o){d4(r,n,i,o)}}}function im(e,t){return r=>{const n=t(r);return i=>(n(i),e(i))}}function Ye(e){return p4(f4(oc.singleInjection,e),l4)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(Ra||(Ra={}));const DC="@inversifyjs/core/classIsInjectableFlagReflectKey",h4=[Array,BigInt,Boolean,Function,Number,Object,String];function g4(e){const t=P1(e,"design:paramtypes");t!==void 0&&Hu(e,Bd,Vd,(function(r){return n=>(r.forEach(((i,o)=>{var s;n.constructorArguments[o]!==void 0||(s=i,h4.includes(s))||(n.constructorArguments[o]=(function(u){return{isFromTypescriptParamType:!0,kind:oc.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(i))})),n)})(t))}function Et(e){return t=>{(function(r){if(P1(r,DC)!==void 0)throw new La(bo.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);o4(r,DC,!0)})(t),g4(t)}}var LC;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(LC||(LC={}));var FC;(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"})(FC||(FC={}));let v4=class{constructor(t,r,n,i,o){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=i,this.notifyUuid=o}},Qs=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 m4=Object.defineProperty,y4=(e,t,r)=>t in e?m4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,b4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},S4=(e,t,r)=>y4(e,t+"",r);let Oa=class{getAllDeviceModels(){return Object.values(Oa.deviceModelByIds)}getDeviceModel(t){return Oa.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,i])=>r[n]===i))}getBluetoothServicesInfos(){return Object.values(Oa.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((i,o)=>({...i,[o.serviceUuid]:new v4(r,o.serviceUuid,o.writeUuid,o.writeCmdUuid,o.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values(Oa.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};S4(Oa,"deviceModelByIds",{[Xt.NANO_S]:new Qs({id:Xt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>SC.lt(SC.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[Xt.NANO_SP]:new Qs({id:Xt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[Xt.NANO_X]:new Qs({id:Xt.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"}]}),[Xt.STAX]:new Qs({id:Xt.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"}]}),[Xt.FLEX]:new Qs({id:Xt.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"}]}),[Xt.APEX]:new Qs({id:Xt.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"}]})}),Oa=b4([Et()],Oa);let w4=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const x4=5,is=1,H0=2,pl=2,U0=2,Pr=[];for(let e=0;e<256;++e)Pr.push((e+256).toString(16).slice(1));function E4(e,t=0){return(Pr[e[t+0]]+Pr[e[t+1]]+Pr[e[t+2]]+Pr[e[t+3]]+"-"+Pr[e[t+4]]+Pr[e[t+5]]+"-"+Pr[e[t+6]]+Pr[e[t+7]]+"-"+Pr[e[t+8]]+Pr[e[t+9]]+"-"+Pr[e[t+10]]+Pr[e[t+11]]+Pr[e[t+12]]+Pr[e[t+13]]+Pr[e[t+14]]+Pr[e[t+15]]).toLowerCase()}let om;const C4=new Uint8Array(16);function _4(){if(!om){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");om=crypto.getRandomValues.bind(crypto)}return om(C4)}const R4=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),NC={randomUUID:R4};function Fp(e,t,r){if(NC.randomUUID&&!e)return NC.randomUUID();e=e||{};const n=e.random||(e.rng||_4)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,E4(n)}const ds={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)}},jC=2,am=800;let zC=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},O4=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},BC=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},VC=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},c2=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:Jo(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}},f2=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:i,length:o,channel:s}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=i,this._length=o,this._channel=s}getDataLength(){return this._dataLength.map(t=>ds.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 wr={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var T4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},$4=(e,t)=>(r,n)=>t(r,n,e);let HC=class{_channel;_logger;_pendingFrames;constructor({channel:t=Cn.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 jt;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"),jt;const n=ds.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),i=ds.getFirstBytesFrom(n,n.length-jC),o=ds.getLastBytesFrom(n,jC);return this._pendingFrames=[],Qr(new w4({data:i,statusCode:o}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>H0,Nothing:()=>0}),n=t.slice(r,r+is),i=t.slice(r+is,r+is+pl),o=i.reduce((h,m)=>h+m,0)===0;if(!o&&this._pendingFrames.length===0)return Wt(new BC);const s=r+is+pl,u=o?U0:0;if(t.length<r+is+pl+u)return Wt(new BC("Unable to parse header from apdu"));const c=o?Qr(t.slice(s,s+u)):jt,f=s+u,p=t.slice(f),g=new c2({header:new f2({uuid:Fp(),channel:this._channel,dataSize:c,headTag:n,index:i,length:r+is+pl+u}),data:p});return nr(g)}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))}};HC=T4([Et(),$4(1,Ye(wr.LoggerPublisherServiceFactory))],HC);var I4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},A4=(e,t)=>(r,n)=>t(r,n,e);let UC=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=Cn.zero(),padding:n=!1},i){this._frameSize=t,this._channel=r,this._padding=n,this._logger=i("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,i=this.getFrameAtIndex(t,n);for(;i.isRight();)r.push(i.extract()),n+=1,i=this.getFrameAtIndex(t,n).mapLeft(o=>(o instanceof zC||this._logger.error("Error while parsing frame",{data:{error:o}}),o));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),i=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(i>=t.length)return Wt(new zC);if(n.getLength()>this._frameSize)return Wt(new O4);const o=this._frameSize-n.getLength(),s=t.slice(i,i+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(o).fill(0):new Uint8Array(s.length<o?s.length:o);u.set(s,0);const c=new c2({header:n,data:u});return nr(c)}getFrameHeaderFrom(t,r){const n=new f2({uuid:Fp(),channel:this._channel.map(i=>ds.getLastBytesFrom(i,H0)),headTag:new Uint8Array([x4]),index:ds.numberToByteArray(t,pl),length:this.getFrameHeaderSizeFromIndex(t),dataSize:Cn.zero()});return t===0&&n.setDataSize(Cn.of(ds.numberToByteArray(r,U0))),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:()=>H0,Nothing:()=>0})+pl+is+(t===0?U0:0)}};UC=I4([Et(),A4(1,Ye(wr.LoggerPublisherServiceFactory))],UC);const W0={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},cn={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},WC={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},Np={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Fa={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var k4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},GC=(e,t)=>(r,n)=>t(r,n,e);let qC=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 i=>await i.sendCommand(r,n),Left:i=>{throw this._logger.error("Error getting session",{data:{error:i}}),i}})}};qC=k4([Et(),GC(0,Ye(cn.DeviceSessionService)),GC(1,Ye(wr.LoggerPublisherServiceFactory))],qC);var P4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let XC=class{execute=vi.fn(()=>"stub")};XC=P4([Et()],XC);var M4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},KC=(e,t)=>(r,n)=>t(r,n,e);let YC=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}})}};YC=M4([Et(),KC(0,Ye(cn.DeviceSessionService)),KC(1,Ye(wr.LoggerPublisherServiceFactory))],YC);function D4(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let QC=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},L4=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},d2=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},F4=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const N4="@ledgerhq/device-management-kit",j4="0.0.0-develop-20260708131309",JC={name:N4,version:j4};var z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};const B4={name:JC.name,version:JC.version},V4=()=>JSON.stringify(B4);let ZC=class{getConfig(){return _n.encase(()=>V4()).mapLeft(t=>new F4(t)).chain(t=>_n.encase(()=>{const r=JSON.parse(t);if(D4(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new d2(r)))}};ZC=z4([Et()],ZC);var H4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let e_=class{getConfig(){return _n.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};e_=H4([Et()],e_);var U4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let t_=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return Wt(new QC(t.extract()));if(!t.extract().ok)return Wt(new QC(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?Wt(new d2):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?Wt(new L4):_n.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(_n.of({ok:!0,json:async()=>new Promise(r=>{r(_n.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};t_=U4([Et()],t_);var W4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let r_=class{async getConfig(){return new Promise(t=>t(_n.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};r_=W4([Et()],r_);var G4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},sm=(e,t)=>(r,n)=>t(r,n,e);let n_=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())}};n_=G4([Et(),sm(0,Ye(W0.LocalConfigDataSource)),sm(1,Ye(W0.RemoteConfigDataSource)),sm(2,Ye(wr.LoggerPublisherServiceFactory))],n_);var q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},X4=(e,t)=>(r,n)=>t(r,n,e);let i_=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};i_=q4([Et(),X4(0,Ye(W0.ConfigService))],i_);const K4={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var Y4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},o_=(e,t)=>(r,n)=>t(r,n,e);let a_=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)})}};a_=Y4([Et(),o_(0,Ye(cn.DeviceSessionService)),o_(1,Ye(wr.LoggerPublisherServiceFactory))],a_);var Q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},J4=(e,t)=>(r,n)=>t(r,n,e);let s_=class{_sessions;_sessionsSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new U$,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 Cn.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new VC)}getDeviceSessionsByDeviceId(t){return Cn.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new VC)}getDeviceSessions(){return this._sessions}};s_=Q4([Et(),J4(0,Ye(wr.LoggerPublisherServiceFactory))],s_);var Z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},l_=(e,t)=>(r,n)=>t(r,n,e);let u_=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)}};u_=Z4([Et(),l_(0,Ye(cn.DeviceSessionService)),l_(1,Ye(Fa.TransportService))],u_);var ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},c_=(e,t)=>(r,n)=>t(r,n,e);let f_=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})}};f_=ej([Et(),c_(0,Ye(cn.DeviceSessionService)),c_(1,Ye(wr.LoggerPublisherServiceFactory))],f_);var tj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},d_=(e,t)=>(r,n)=>t(r,n,e);let p_=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)}})}};p_=tj([Et(),d_(0,Ye(cn.DeviceSessionService)),d_(1,Ye(wr.LoggerPublisherServiceFactory))],p_);function rj(e){return`[will send APDU] ~...> ${Jo(e,!1)}`}function nj(e){return`[exchange] <= ${Jo(e.data,!1)}${Jo(e.statusCode,!1)}`}const ij="apdu-exchange";function oj(e,t,r){const n=Jo(t,!1),i=`${Jo(r.data,!1)}${Jo(r.statusCode,!1)}`;return{message:nj(r),data:{type:ij,sessionId:e,apdu:n,response:i}}}const G0=1e3,lm=1e3,aj={isRefresherDisabled:!1,pollingInterval:1e3};var ur=(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))(ur||{});let sj=class{_eventEmitter=new Hl;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},lj=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 Hl,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const i=()=>{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(U3(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:i}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:ur.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:ur.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()}},uj=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${Fp()}`;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()}},cj=class{constructor(t,r,n,i){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=i,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async o=>await this.mapEventAction(o))}_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===ur.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===Xt.NANO_S){const r=async()=>{const o=await this._sendCommandFunction(new TE,am);return this._sendCommandFunction(new UN,am),o},n=new Promise(o=>{setTimeout(()=>o(null),G0*2+100)}),i=await Promise.race([r(),n]);return i?this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:i}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}),i}else{const r=await this._sendCommandFunction(new TE,am);return this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},fj=class{constructor(t,r,n,i){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=i.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($C(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY||n.eventName===ur.NEW_STATE),Da(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY),G3(!1),V3());this._refresherSubscription=j3(0,t).pipe(q3(r),IC(([n,i])=>{i&&this._logger.debug("Refresh skipped: device is busy")}),$C(([n,i])=>!i),IC(()=>this._sessionEventDispatcher.dispatch({eventName:ur.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===Xt.NANO_S){const i=G0*2;return n!==void 0&&n<i?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${i}`),i):n??i}else return n!==void 0&&n<lm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${lm}`),lm):n??G0}},dj=class{constructor(t,r,n,i,o){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=i,this.setDeviceSessionState=o,this._subscription=this._sessionEventDispatcher.listen().subscribe(s=>this.mapEventAction(s)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=po.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:i,currentApp:o}=r,s=this._deviceState.getValue();s.sessionStateType===$l.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...s,sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case ur.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case ur.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:po.BUSY});case ur.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=po.LOCKED;return;case ur.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=po.CONNECTED;return;case ur.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=po.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case ur.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:po.BUSY});case ur.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return fN(t)?{sessionStateType:$l.ReadyWithoutSecureChannel,deviceStatus:po.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()}},pj=class{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new sj;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=Fp()},n,i,o,s,u=c=>new lj(n,c)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=i,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=o,this._refresherOptions={...aj,...s},this._deviceState=new p3({sessionStateType:$l.Connected,deviceStatus:po.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new cj(n,t,this._sessionEventDispatcher,(c,f)=>this.sendCommand(c,f)),this._deviceSessionRefresher=new fj(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new dj(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,c=>this.setDeviceSessionState(c)),this._refresherService=new uj(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,i=Date.now(),{observable:o,cancel:s}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Tl((async()=>{const c=Date.now()-i;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-c:void 0})})())}),u=n?o.pipe(OC({each:n,with:()=>{throw s(),new X3}})):o;return RC(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(rj(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:i,data:o}=oj(this._id,t,n);this._logger.debug(i,{data:o}),v1.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:ur.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:i,cancel:o}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Tl((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),s=r?i.pipe(OC({each:r,with:()=>{throw o(),new K3}})):i;return RC(s)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:i=>{throw this._logger.error("[sendCommand] error",{data:{err:i}}),i},Right:i=>{const o=t.parseResponse(i,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:o}}),o}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:i}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:o,cancel:s}=this._unsafeInternalExecuteDeviceAction(t);return r=s,o}});return{observable:n,cancel:()=>{r?.(),i()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async i=>this._unsafeInternalSendApdu(i),sendCommand:async i=>this._unsafeInternalSendCommand(i),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:i=>(this.setDeviceSessionState(i),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(po.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})}};const M1={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")};var hj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Cu=(e,t)=>(r,n)=>t(r,n,e);let h_=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,i,o){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=i,this._secureChannel=o}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),i="sessionId"in t?t.sessionId:void 0;return pt.liftEither(n.toEither(new k1(new Error("Unknown transport")))).chain(async o=>o.connect({deviceId:t.id,onDisconnect:s=>this.handleDeviceDisconnect(s)})).ifLeft(o=>{this._logger.error("Error connecting to device")}).map(async o=>{const s=new pj({connectedDevice:o,id:i},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(s),await s.initialiseSession(),s.id}).caseOf({Left:o=>{throw o},Right:o=>o})}};h_=hj([Et(),Cu(0,Ye(Fa.TransportService)),Cu(1,Ye(cn.DeviceSessionService)),Cu(2,Ye(wr.LoggerPublisherServiceFactory)),Cu(3,Ye(Np.ManagerApiService)),Cu(4,Ye(M1.SecureChannelService))],h_);var gj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},um=(e,t)=>(r,n)=>t(r,n,e);let g_=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)}}),pt(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(s=>{this._logger.error("Device session not found",{data:{sessionId:t,error:s}})})),i=n.connectedDevice.transport,o=await r(this._transportService.getTransport(i).toEither(new k1(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await o.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};g_=gj([Et(),um(0,Ye(Fa.TransportService)),um(1,Ye(cn.DeviceSessionService)),um(2,Ye(wr.LoggerPublisherServiceFactory))],g_);let D1=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:i,transport:o,name:s},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=s??n,this.type=i,this.transport=o}};var vj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},v_=(e,t)=>(r,n)=>t(r,n,e);let m_=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 D1({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};m_=vj([Et(),v_(0,Ye(cn.DeviceSessionService)),v_(1,Ye(wr.LoggerPublisherServiceFactory))],m_);var mj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},y_=(e,t)=>(r,n)=>t(r,n,e);let b_=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 D1({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};b_=mj([Et(),y_(0,Ye(cn.DeviceSessionService)),y_(1,Ye(wr.LoggerPublisherServiceFactory))],b_);var yj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},S_=(e,t)=>(r,n)=>t(r,n,e);let w_=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new A$({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"),Tl([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,i)=>n.listenToAvailableDevices().pipe(Da(o=>({index:i,arr:o}))));return z3(...r).pipe(W3((n,{index:i,arr:o})=>(n[i]=o,n),{}),Da(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`),a2([])),Just:r=>r.listenToAvailableDevices().pipe(Da(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};w_=yj([Et(),S_(0,Ye(Fa.TransportService)),S_(1,Ye(wr.LoggerPublisherServiceFactory))],w_);var bj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},x_=(e,t)=>(r,n)=>t(r,n,e);let E_=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(Da(t=>new D1({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};E_=bj([Et(),x_(0,Ye(cn.DeviceSessionService)),x_(1,Ye(wr.LoggerPublisherServiceFactory))],E_);var Sj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},cm=(e,t)=>(r,n)=>t(r,n,e);let C_=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})}};C_=Sj([Et(),cm(0,Ye(WC.ConnectUseCase)),cm(1,Ye(WC.DisconnectUseCase)),cm(2,Ye(wr.LoggerPublisherServiceFactory))],C_);var wj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},xj=(e,t)=>(r,n)=>t(r,n,e);let __=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new A$({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 a2(...r).pipe(A1(n=>n.startDiscovering().pipe(Da(i=>this.mapDiscoveredDevice(i)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(Da(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new k1(new Error("Unknown transport"))}})}};__=wj([Et(),xj(0,Ye(Fa.TransportService))],__);var Ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},R_=(e,t)=>(r,n)=>t(r,n,e);let O_=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()}};O_=Ej([Et(),R_(0,Ye(Fa.TransportService)),R_(1,Ye(wr.LoggerPublisherServiceFactory))],O_);var Mu=(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))(Mu||{});let Cj=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function q0(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>q0(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=q0(i,t);return r}return e}function _j(e){const t=new WeakSet;t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=q0(i,t);return r}var Rj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let T_=class{subscribers;tag;tagFormatter;constructor(t,r,n=new Cj){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const i=n?.data?_j(n.data):void 0,o=n?.tag??this.tag,s=this.tagFormatter.format(o);this.subscribers.forEach(u=>{const c={timestamp:n?.timestamp??Date.now(),tag:s,data:i};u.log(t,r,c)})}info(t,r){this._log(Mu.Info,t,r)}warn(t,r){this._log(Mu.Warning,t,r)}debug(t,r){this._log(Mu.Debug,t,r)}error(t,r){this._log(Mu.Error,t,r)}};T_=Rj([Et()],T_);let ac=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 Oj="application/json";function Tj(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function $j(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function os(e){const{url:t,params:r,baseUrl:n}=e,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?Tj(n,t):t,o=r?$j(r):"";if(o.length===0)return i;const s=i.includes("?")?"&":"?";return`${i}${s}${o}`}function Ij(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function Aj(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 kj(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:i}=e,o={...n,...i};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:o}:Aj(r)?{body:r,headers:o}:(Ij(o,"content-type")||(o["Content-Type"]=Oj),{body:JSON.stringify(r),headers:o})}function Pj(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 Mj(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 ac({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function Dj(e){try{return await e.text()}catch{return}}function Lj(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const i=t.name==="TimeoutError"||n;return new ac({message:i?"Request timed out":"Request aborted",isTimeout:i,cause:t})}return new ac({message:t instanceof Error?t.message:"Network request failed",cause:t})}let p2=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(i=>i.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(i=>i.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(i=>i.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=os({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:i}=kj({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:o,cleanup:s}=Pj({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,c=t.responseType??"json";try{let f;try{f=await this.getFetch()(r,{method:t.method,headers:i,body:n,signal:o})}catch(p){throw Lj({cause:p,timeoutMs:t.timeoutMs})}if(!f.ok&&u){const p=await Dj(f);throw new ac({message:`HTTP error ${f.status} ${f.statusText}`.trim(),status:f.status,statusText:f.statusText,responseBody:p})}return{data:await Mj(f,c),status:f.status,statusText:f.statusText,headers:f.headers,ok:f.ok}}finally{s()}}};var Du=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Du||{});const Fj=1,Nj="0";let lp=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var Lu=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Lu||{}),jj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},zj=(e,t)=>(r,n)=>t(r,n,e);const Go=e=>e instanceof ac&&e.cause!==void 0?new lp(e.cause):new lp(e);let $_=class{http;_provider=Fj;_firmwareDistributionSalt=Nj;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n}){this.http=new p2({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n}setProvider(t){this._provider===t||t<1||(this._provider=t)}getProvider(){return this._provider}getAppList(t){const{targetId:r,firmwareVersionName:n}=t;return pt(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(i=>this.mapApplicationDtoToApplication(i)).mapLeft(Go)}getMcuList(){return pt(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(Go)}getDeviceVersion(t){const{targetId:r}=t;return pt(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(Go)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return pt(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapFinalFirmwareDto(i)).mapLeft(Go)}getFirmwareVersionById(t){return pt(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(Go)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return pt(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapOsuFirmwareDto(i)).mapLeft(Go)}getLatestFirmwareVersion(t){const r="34.27.0",{currentFinalFirmwareId:n,deviceId:i}=t;return pt(()=>this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:n,device_version:i,provider:this._provider,salt:this._firmwareDistributionSalt,livecommonversion:r}})).chain(o=>this.mapLatestFirmwareDto(o)).mapLeft(Go)}getAppsByHash(t){const{hashes:r}=t;return pt(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(Go)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return pt(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(i=>this.mapLanguagesDtoToLanguages(i)).mapLeft(Go)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case Lu.currency:return Du.currency;case Lu.plugin:return Du.plugin;case Lu.tool:return Du.tool;case Lu.swap:return Du.swap}}mapApplicationDtoToApplication(t){return pt(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return pt(()=>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:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,...f}=t;return{...f,hash:n,perso:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return pt(()=>Promise.resolve(t.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name}})))}mapDeviceVersionDto(t){return pt(()=>{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 pt(()=>{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 pt(()=>{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=>this.mapOsuFirmwareDto(r))}mapOsuFirmwareDto(t){return pt(()=>{if(typeof t!="object"||typeof t.id!="number"||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,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 pt(()=>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}}};$_=jj([Et(),zj(0,Ye(Np.DmkConfig))],$_);var Bj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Vj=(e,t)=>(r,n)=>t(r,n,e);let I_=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 pt(async({fromPromise:n,throwE:i})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(o){return o instanceof lp?i(o):i(new lp(o))}})}};I_=Bj([Et(),Vj(0,Ye(Np.ManagerApiDataSource))],I_);var Hj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},A_=(e,t)=>(r,n)=>t(r,n,e);let k_=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!==$l.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};k_=Hj([Et(),A_(0,Ye(cn.DeviceSessionService)),A_(1,Ye(Np.ManagerApiDataSource))],k_);var Uj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Wj=(e,t)=>(r,n)=>t(r,n,e);let P_=class{webSocketBaseUrl;constructor({webSocketUrl:t}){this.webSocketBaseUrl=t}genuineCheck(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=os({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return nr(new J3(t))}catch(r){return Wt(new i4(r))}}};P_=Uj([Et(),Wj(0,Ye(M1.DmkConfig))],P_);var Gj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},qj=(e,t)=>(r,n)=>t(r,n,e);let M_=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:i,firmwareKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};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:i,deleteKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};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)}};M_=Gj([Et(),qj(0,Ye(M1.SecureChannelDataSource))],M_);var Xj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},D_=(e,t)=>(r,n)=>t(r,n,e);let L_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:i}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async o=>(await o.sendApdu(r,{abortTimeout:n,triggersDisconnection:i})).caseOf({Right:s=>s,Left:s=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:s}}),s}}),Left:o=>{throw this._logger.error("Error getting deviceSession",{data:{error:o}}),o}})}};L_=Xj([Et(),D_(0,Ye(cn.DeviceSessionService)),D_(1,Ye(wr.LoggerPublisherServiceFactory))],L_);var Kj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Js=(e,t)=>(r,n)=>t(r,n,e);let F_=class{constructor(t,r,n,i,o,s){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=i,this._apduSenderServiceFactory=o,this._apduReceiverServiceFactory=s,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new Q3("No transports provided, please check your configuration");for(const u of t){const c=this.addTransport(u);if(c.isLeft())throw c.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`),Wt(new Y3(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),nr(void 0))}getTransport(t){return Cn.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};F_=Kj([Et(),Js(0,Ye(Fa.TransportsInput)),Js(1,Ye(Fa.DmkConfig)),Js(2,Ye(wr.LoggerPublisherServiceFactory)),Js(3,Ye(K4.DeviceModelDataSource)),Js(4,Ye(cn.ApduSenderServiceFactory)),Js(5,Ye(cn.ApduReceiverServiceFactory))],F_);const Yj={ADD_LOG:"addLog"};function Qj(e){return{startListeningCommand:()=>e.sendMessage(Qo.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(Qo.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(Qo.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(Qo.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(Qo.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function Jj(e){return{getProviderCommand:()=>e.sendMessage(Qo.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(Qo.SET_PROVIDER,JSON.stringify({provider:t}))}}let Zj=0;function ez(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++Zj}`,i=r.match(/.{1,2}/g)?.map(o=>parseInt(o,16))||[];return e.sendMessage(Qo.SEND_APDU,JSON.stringify({sessionId:t,apdu:i,requestId:n})),n}}}function tz(e){const{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o}=JSON.parse(e);return{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o,payload:JSON.parse(o)}}const rz="apdu-exchange";function nz(e){const t=e.payload;return typeof t!="object"||t===null||Array.isArray(t)||t.type!==rz||typeof t.apdu!="string"||typeof t.response!="string"?null:{sessionId:typeof t.sessionId=="string"?t.sessionId:void 0,apdu:t.apdu,response:t.response,timestamp:e.timestamp}}function iz(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 oz(e,t,r,n){const i=tz(e);if(i!==null){if(t(o=>[...o,i]),n){const o=nz(i);o!==null&&r(s=>[...s,o])}return!0}return!1}function az(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function sz(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(i=>new Map(i).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function lz(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function uz(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}function cz(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)}}function fz(e){const[t,r]=x.useState([]),[n,i]=x.useState([]),[o,s]=x.useState([]),[u,c]=x.useState(new Set),[f,p]=x.useState([]),[g,h]=x.useState(new Map),[m,y]=x.useState([]),[b,S]=x.useState(!1),[_,C]=x.useState(!1),[O,R]=x.useState(null),[T,$]=x.useState(new Map),[P,L]=x.useState([]),[z,B]=x.useState(!1),X=x.useRef(!1),Y=x.useMemo(()=>({...e,sendMessage:(W,ve)=>{e.sendMessage(W,ve),i(se=>[...se,{type:W,payload:ve}])}}),[e]);x.useEffect(()=>{const{unsubscribe:W}=e.listenToMessages((ve,se)=>{switch(r(Ee=>[...Ee,{type:ve,payload:se}]),ve){case tN:iz(se,c);break;case Eu.CONNECTED_DEVICES_UPDATE:az(se,p);break;case Eu.DEVICE_SESSION_STATE_UPDATE:sz(se,h);break;case Eu.DISCOVERED_DEVICES_UPDATE:lz(se,y);break;case Eu.PROVIDER_VALUE:uz(se,R);break;case Eu.APDU_RESPONSE:cz(se,$);break;case Yj.ADD_LOG:oz(se,s,L,X.current);break}});return W},[e]);const N=x.useMemo(()=>Qj(Y),[Y]),j=x.useMemo(()=>Jj(Y),[Y]),F=x.useMemo(()=>ez(Y),[Y]),q=x.useCallback(()=>{S(!0),y([]),N.startListeningCommand()},[N]),U=x.useCallback(()=>{S(!1),y([]),N.stopListeningCommand()},[N]),M=x.useCallback(()=>{C(!0),y([]),N.startDiscoveringCommand()},[N]),G=x.useCallback(()=>{C(!1),y([]),N.stopDiscoveringCommand()},[N]),K=x.useCallback(()=>{s([])},[]),D=x.useCallback(()=>{X.current=!0,B(!0)},[]),A=x.useCallback(()=>{X.current=!1,B(!1)},[]),J=x.useCallback(()=>{L([])},[]),Z=u.has(xE.LOGGER),ne=u.has(xE.DMK_INSPECTOR);return{receivedMessages:t,sentMessages:n,logs:o,connectedModules:u,connectedDevices:f,sessionStates:g,discoveredDevices:m,isListening:b,isActivelyDiscovering:_,isLoggerConnected:Z,isInspectorConnected:ne,providerValue:O,apduResponses:T,apduExchanges:P,isRecordingExchanges:z,sendMessage:Y.sendMessage,clearLogs:K,startRecordingExchanges:D,stopRecordingExchanges:A,clearRecordedExchanges:J,startListening:q,stopListening:U,startDiscovering:M,stopDiscovering:G,connectDevice:N.connectDeviceCommand,getProvider:j.getProviderCommand,setProvider:j.setProviderCommand,sendApdu:F.sendApduCommand}}const dz=ge.div`
466
466
  display: flex;
467
467
  flex-direction: column;
468
468
  align-items: center;
@@ -1 +1 @@
1
- {"name":"@ledgerhq/device-management-kit-devtools-rozenite","version":"0.0.0-develop-20260707003031","description":"Inspect and debug your integration of the Device Management Kit","panels":[{"name":"DMK DevTools","source":"/index.html"}]}
1
+ {"name":"@ledgerhq/device-management-kit-devtools-rozenite","version":"0.0.0-develop-20260708131309","description":"Inspect and debug your integration of the Device Management Kit","panels":[{"name":"DMK DevTools","source":"/index.html"}]}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "dependencies": {
3
3
  "@rozenite/plugin-bridge": "1.1.0",
4
4
  "rxjs": "7.8.2",
5
- "@ledgerhq/device-management-kit-devtools-ui": "0.0.0-develop-20260707003031"
5
+ "@ledgerhq/device-management-kit-devtools-ui": "0.0.0-develop-20260708131309"
6
6
  },
7
7
  "description": "Inspect and debug your integration of the Device Management Kit",
8
8
  "devDependencies": {
@@ -15,7 +15,7 @@
15
15
  "rozenite": "1.1.0",
16
16
  "typescript": "5.9.2",
17
17
  "vite": "7.3.6",
18
- "@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20260707003031"
18
+ "@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20260708131309"
19
19
  },
20
20
  "files": [
21
21
  "./dist"
@@ -27,7 +27,7 @@
27
27
  "peerDependencies": {
28
28
  "react": "*",
29
29
  "react-native": "*",
30
- "@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20260707003031"
30
+ "@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20260708131309"
31
31
  },
32
32
  "private": false,
33
33
  "repository": {
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "type": "module",
38
38
  "types": "./dist/react-native.d.ts",
39
- "version": "0.0.0-develop-20260707003031",
39
+ "version": "0.0.0-develop-20260708131309",
40
40
  "scripts": {
41
41
  "build": "rozenite build",
42
42
  "dev": "rozenite dev"