@swapkit/wallet-hardware 5.0.1 → 6.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD_PARTY_LICENSES.md +2344 -0
- package/dist/chunk-09e51wma.js +4 -0
- package/dist/chunk-09e51wma.js.map +167 -0
- package/dist/chunk-0arpsm5f.js +4 -0
- package/dist/chunk-0arpsm5f.js.map +10 -0
- package/dist/chunk-1amf58aq.js +4 -0
- package/dist/{chunk-xkh15edk.js.map → chunk-1amf58aq.js.map} +2 -2
- package/dist/chunk-3t17wpjg.js +17 -0
- package/dist/chunk-3t17wpjg.js.map +29 -0
- package/dist/chunk-5c7b7z2d.js +4 -0
- package/dist/{chunk-20wx60bn.js.map → chunk-5c7b7z2d.js.map} +2 -2
- package/dist/chunk-5p3ttw6y.js +4 -0
- package/dist/{chunk-1jpcb30j.js.map → chunk-5p3ttw6y.js.map} +1 -1
- package/dist/chunk-dptbnkzm.js +64 -0
- package/dist/chunk-dptbnkzm.js.map +260 -0
- package/dist/chunk-ds2m83jp.js +5 -0
- package/dist/chunk-ds2m83jp.js.map +11 -0
- package/dist/chunk-eenx3cv6.js +4 -0
- package/dist/chunk-eenx3cv6.js.map +33 -0
- package/dist/chunk-gr3eswf1.js +4 -0
- package/dist/chunk-gr3eswf1.js.map +73 -0
- package/dist/{chunk-7fsaymh4.js → chunk-hg71hp4m.js} +3 -3
- package/dist/{chunk-7fsaymh4.js.map → chunk-hg71hp4m.js.map} +1 -1
- package/dist/chunk-jewm2ag3.js +5 -0
- package/dist/{chunk-4tbtxdxa.js.map → chunk-jewm2ag3.js.map} +2 -2
- package/dist/chunk-jzrytcrf.js +4 -0
- package/dist/chunk-jzrytcrf.js.map +12 -0
- package/dist/chunk-k3thje6a.js +4 -0
- package/dist/chunk-k3thje6a.js.map +9 -0
- package/dist/chunk-nhva847d.js +5 -0
- package/dist/chunk-nhva847d.js.map +9 -0
- package/dist/chunk-tm47brht.js +4 -0
- package/dist/chunk-tm47brht.js.map +140 -0
- package/dist/chunk-xmvg4cds.js +4 -0
- package/dist/chunk-xmvg4cds.js.map +127 -0
- package/dist/chunk-xx7cwpzq.js +4 -0
- package/dist/chunk-xx7cwpzq.js.map +9 -0
- package/dist/chunk-yrxe491r.js +20 -0
- package/dist/chunk-yrxe491r.js.map +17 -0
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/keepkey/index.cjs +2 -2
- package/dist/keepkey/index.cjs.map +2 -2
- package/dist/keepkey/index.js +2 -2
- package/dist/keepkey/index.js.map +2 -2
- package/dist/ledger/index.cjs +90 -2
- package/dist/ledger/index.cjs.map +830 -24
- package/dist/ledger/index.js +2 -2
- package/dist/ledger/index.js.map +21 -19
- package/dist/trezor/index.cjs +2 -2
- package/dist/trezor/index.cjs.map +5 -5
- package/dist/trezor/index.js +2 -2
- package/dist/trezor/index.js.map +3 -3
- package/dist/types/ledger/clients/bitcoin.d.ts +36 -0
- package/dist/types/ledger/clients/bitcoin.d.ts.map +1 -0
- package/dist/types/ledger/clients/cosmos.d.ts +38 -10
- package/dist/types/ledger/clients/cosmos.d.ts.map +1 -1
- package/dist/types/ledger/clients/evm.d.ts +37 -46
- package/dist/types/ledger/clients/evm.d.ts.map +1 -1
- package/dist/types/ledger/clients/near.d.ts +5 -2
- package/dist/types/ledger/clients/near.d.ts.map +1 -1
- package/dist/types/ledger/clients/sui.d.ts +8 -12
- package/dist/types/ledger/clients/sui.d.ts.map +1 -1
- package/dist/types/ledger/clients/thorchain/index.d.ts +34 -8
- package/dist/types/ledger/clients/thorchain/index.d.ts.map +1 -1
- package/dist/types/ledger/clients/thorchain/protocol.d.ts +58 -0
- package/dist/types/ledger/clients/thorchain/protocol.d.ts.map +1 -0
- package/dist/types/ledger/clients/tron.d.ts +11 -8
- package/dist/types/ledger/clients/tron.d.ts.map +1 -1
- package/dist/types/ledger/clients/utxo-legacy-adapter.d.ts +3 -2
- package/dist/types/ledger/clients/utxo-legacy-adapter.d.ts.map +1 -1
- package/dist/types/ledger/clients/utxo-legacy-outputs.d.ts +18 -0
- package/dist/types/ledger/clients/utxo-legacy-outputs.d.ts.map +1 -0
- package/dist/types/ledger/clients/utxo.d.ts +10 -13
- package/dist/types/ledger/clients/utxo.d.ts.map +1 -1
- package/dist/types/ledger/clients/xrp.d.ts +4 -1
- package/dist/types/ledger/clients/xrp.d.ts.map +1 -1
- package/dist/types/ledger/clients/zcash.d.ts +53 -0
- package/dist/types/ledger/clients/zcash.d.ts.map +1 -0
- package/dist/types/ledger/helpers/dmk.d.ts +24 -0
- package/dist/types/ledger/helpers/dmk.d.ts.map +1 -0
- package/dist/types/ledger/helpers/executeDeviceAction.d.ts +34 -0
- package/dist/types/ledger/helpers/executeDeviceAction.d.ts.map +1 -0
- package/dist/types/ledger/helpers/getLedgerAddress.d.ts +1 -1
- package/dist/types/ledger/helpers/getLedgerAddress.d.ts.map +1 -1
- package/dist/types/ledger/helpers/getLedgerClient.d.ts +10 -3
- package/dist/types/ledger/helpers/getLedgerClient.d.ts.map +1 -1
- package/dist/types/ledger/helpers/index.d.ts +2 -1
- package/dist/types/ledger/helpers/index.d.ts.map +1 -1
- package/dist/types/ledger/helpers/ledgerJsDmkBridge.d.ts +26 -0
- package/dist/types/ledger/helpers/ledgerJsDmkBridge.d.ts.map +1 -0
- package/dist/types/ledger/helpers/ledgerJsDmkTransport.d.ts +13 -0
- package/dist/types/ledger/helpers/ledgerJsDmkTransport.d.ts.map +1 -0
- package/dist/types/ledger/helpers/lowS.d.ts +6 -0
- package/dist/types/ledger/helpers/lowS.d.ts.map +1 -0
- package/dist/types/ledger/helpers/rawTx.d.ts +2 -0
- package/dist/types/ledger/helpers/rawTx.d.ts.map +1 -0
- package/dist/types/ledger/index.d.ts +19 -7
- package/dist/types/ledger/index.d.ts.map +1 -1
- package/dist/types/ledger/types.d.ts +6 -10
- package/dist/types/ledger/types.d.ts.map +1 -1
- package/dist/types/trezor/index.d.ts +2 -2
- package/dist/types/trezor/index.d.ts.map +1 -1
- package/package.json +36 -36
- package/src/ledger/clients/bitcoin.ts +575 -0
- package/src/ledger/clients/cosmos.ts +180 -51
- package/src/ledger/clients/evm.ts +238 -195
- package/src/ledger/clients/near.ts +43 -13
- package/src/ledger/clients/sui.ts +55 -68
- package/src/ledger/clients/thorchain/index.ts +210 -86
- package/src/ledger/clients/thorchain/protocol.ts +166 -0
- package/src/ledger/clients/tron.ts +49 -37
- package/src/ledger/clients/utxo-legacy-adapter.ts +35 -32
- package/src/ledger/clients/utxo-legacy-outputs.ts +122 -0
- package/src/ledger/clients/utxo.ts +108 -206
- package/src/ledger/clients/xrp.ts +39 -23
- package/src/ledger/clients/zcash.ts +440 -0
- package/src/ledger/helpers/dmk.ts +231 -0
- package/src/ledger/helpers/executeDeviceAction.ts +201 -0
- package/src/ledger/helpers/getLedgerClient.ts +101 -72
- package/src/ledger/helpers/index.ts +6 -1
- package/src/ledger/helpers/ledgerJsDmkBridge.ts +109 -0
- package/src/ledger/helpers/ledgerJsDmkTransport.ts +88 -0
- package/src/ledger/helpers/lowS.ts +30 -0
- package/src/ledger/helpers/rawTx.ts +12 -0
- package/src/ledger/index.ts +564 -369
- package/src/ledger/types.ts +15 -10
- package/src/trezor/index.ts +183 -68
- package/dist/chunk-1jpcb30j.js +0 -5
- package/dist/chunk-20wx60bn.js +0 -4
- package/dist/chunk-4tbtxdxa.js +0 -5
- package/dist/chunk-7v7cgm69.js +0 -4
- package/dist/chunk-7v7cgm69.js.map +0 -10
- package/dist/chunk-83g13ck6.js +0 -5
- package/dist/chunk-83g13ck6.js.map +0 -10
- package/dist/chunk-h2r568rz.js +0 -4
- package/dist/chunk-h2r568rz.js.map +0 -10
- package/dist/chunk-xkh15edk.js +0 -4
- package/dist/types/ledger/clients/thorchain/common.d.ts +0 -28
- package/dist/types/ledger/clients/thorchain/common.d.ts.map +0 -1
- package/dist/types/ledger/clients/thorchain/helpers.d.ts +0 -7
- package/dist/types/ledger/clients/thorchain/helpers.d.ts.map +0 -1
- package/dist/types/ledger/clients/thorchain/lib.d.ts +0 -22
- package/dist/types/ledger/clients/thorchain/lib.d.ts.map +0 -1
- package/dist/types/ledger/clients/thorchain/utils.d.ts +0 -2
- package/dist/types/ledger/clients/thorchain/utils.d.ts.map +0 -1
- package/dist/types/ledger/clients/utxo-psbt.d.ts +0 -18
- package/dist/types/ledger/clients/utxo-psbt.d.ts.map +0 -1
- package/dist/types/ledger/cosmosTypes.d.ts +0 -40
- package/dist/types/ledger/cosmosTypes.d.ts.map +0 -1
- package/dist/types/ledger/helpers/getLedgerTransport.d.ts +0 -3
- package/dist/types/ledger/helpers/getLedgerTransport.d.ts.map +0 -1
- package/dist/types/ledger/helpers/ledgerNetworkInfo.d.ts +0 -14
- package/dist/types/ledger/helpers/ledgerNetworkInfo.d.ts.map +0 -1
- package/dist/types/ledger/interfaces/CosmosLedgerInterface.d.ts +0 -14
- package/dist/types/ledger/interfaces/CosmosLedgerInterface.d.ts.map +0 -1
- package/src/ledger/clients/thorchain/common.ts +0 -93
- package/src/ledger/clients/thorchain/helpers.ts +0 -120
- package/src/ledger/clients/thorchain/lib.ts +0 -258
- package/src/ledger/clients/thorchain/utils.ts +0 -69
- package/src/ledger/clients/utxo-psbt.ts +0 -204
- package/src/ledger/cosmosTypes.ts +0 -98
- package/src/ledger/helpers/getLedgerTransport.ts +0 -102
- package/src/ledger/helpers/ledgerNetworkInfo.ts +0 -127
- package/src/ledger/interfaces/CosmosLedgerInterface.ts +0 -67
package/dist/ledger/index.cjs
CHANGED
|
@@ -1,4 +1,92 @@
|
|
|
1
|
-
var p0=Object.create;var{getPrototypeOf:s0,defineProperty:N_,getOwnPropertyNames:v_,getOwnPropertyDescriptor:r0}=Object,b_=Object.prototype.hasOwnProperty;function c_(_){return this[_]}var t0,a0,e0=(_,L,R)=>{var N=_!=null&&typeof _==="object";if(N){var G=L?t0??=new WeakMap:a0??=new WeakMap,O=G.get(_);if(O)return O}R=_!=null?p0(s0(_)):{};let B=L||!_||!_.__esModule?N_(R,"default",{value:_,enumerable:!0}):R;for(let w of v_(_))if(!b_.call(B,w))N_(B,w,{get:c_.bind(_,w),enumerable:!0});if(N)G.set(_,B);return B},_L=(_)=>{var L=(I_??=new WeakMap).get(_),R;if(L)return L;if(L=N_({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function"){for(var N of v_(_))if(!b_.call(L,N))N_(L,N,{get:c_.bind(_,N),enumerable:!(R=r0(_,N))||R.enumerable})}return I_.set(_,L),L},I_;var LL=(_)=>_;function RL(_,L){this[_]=LL.bind(null,L)}var Y_=(_,L)=>{for(var R in L)N_(_,R,{get:L[R],enumerable:!0,configurable:!0,set:RL.bind(L,R)})};var j_=(_,L)=>()=>(_&&(L=_(_=0)),L);var e,A_=()=>navigator?.usb,OL=async()=>{let _=A_();if(typeof _?.getDevices!=="function")return{};let{ledgerUSBVendorId:L}=await import("@ledgerhq/devices"),N=(await _?.getDevices()).filter((G)=>G.vendorId===L);if(N.length>0)return N[0];return _?.requestDevice({filters:[{vendorId:L}]})},H=async()=>{let _=await OL();if(!_)throw new e.SwapKitError("wallet_ledger_device_not_found");if(_.opened||await _.open(),_.configuration===null)await _.selectConfiguration(1);try{await _.reset()}catch{}let L=_.configuration??_.configurations?.[0],R=L?.interfaces.find(({alternates:$})=>$.some(({interfaceClass:f})=>f===255))||L?.interfaces.find(({alternates:$})=>$.some(({interfaceClass:f})=>f===3));if(!R)throw await _.close(),new e.SwapKitError("wallet_ledger_connection_error");let N=R.alternates?.find(({interfaceClass:$})=>$===3)?.interfaceClass,G=R.alternates?.find(({interfaceClass:$})=>$===255)?.interfaceClass;if(N&&!G){let $=(await import("@ledgerhq/hw-transport-webhid")).default;if(!await $.isSupported())throw await _.close(),new e.SwapKitError("wallet_ledger_webhid_not_supported");return await $.create()}try{await _.claimInterface(R.interfaceNumber)}catch($){throw await _.close(),new e.SwapKitError("wallet_ledger_connection_claimed",$)}let O=(await import("@ledgerhq/hw-transport-webusb")).default;if(!await O.isSupported())throw new e.SwapKitError("wallet_ledger_webusb_not_supported");let{DisconnectedDevice:w}=await import("@ledgerhq/errors"),T=new O(_,R.interfaceNumber),U=($)=>{if(_===$.device)A_()?.removeEventListener("disconnect",U),T._emitDisconnect(new w)};return A_()?.addEventListener("disconnect",U),T};var c=j_(()=>{e=require("@swapkit/helpers")});async function E0({chain:_,indexes:L,publicKey:R,tx:N}){let{getMissingSpendingMetadata:G,getNetworkForChain:O}=await import("@swapkit/toolboxes/utxo");for(let{index:B,...w}of G({chain:_,indexes:L,network:O(_),publicKey:R,tx:N}))N.updateInput(B,w)}var m0={};Y_(m0,{LitecoinPsbtLedger:()=>zL,BitcoinPsbtLedger:()=>AL});function QL(_){switch(_){case"bech32":return"wpkh(@0/**)";case"p2sh":return"sh(wpkh(@0/**))";case"legacy":return"pkh(@0/**)";default:return"wpkh(@0/**)"}}function FL(_){return typeof _==="string"?_:u.derivationPathToString(_)}function K0(_){return _.replace(/^m\//,"").replace(/^\/+/,"")}function qL(_){return _.replace(/^m\//,"").split("/").filter(Boolean).map((L)=>{let R=L.endsWith("'"),N=Number.parseInt(R?L.slice(0,-1):L,10);return R?(N|2147483648)>>>0:N})}function CL(_){for(let L=0;L<_.inputsLength;L++){let R=_.getInput(L);if(R.nonWitnessUtxo&&R.witnessUtxo)_.updateInput(L,{witnessUtxo:void 0})}}function HL(_,L){let R=_.getInput(L);return Boolean(R.bip32Derivation?.length)}var k0,S0,u,jL,V0=({chain:_})=>{return(L,R)=>{let N,G;async function O(){if(!N){let F=R??await H(),{AppClient:z}=await import("ledger-bitcoin");N=new z(F)}return N}async function B(){if(!G)G=await(await O()).getMasterFingerprint();return G}let w=K0(L?FL(L):"84'/0'/0'/0/0"),T=w.split("/").filter(Boolean),U=T.slice(0,3).join("/"),$=T.slice(3),f=Number($[0]??0),M=Number($[1]??0),W=u.getWalletFormatFor(`m/${w}`),q=QL(W),j,k;async function S(){let F=await O(),z=await B();if(!j)j=await F.getExtendedPubkey(`m/${U}`);let{DefaultWalletPolicy:D}=await import("ledger-bitcoin"),Z=new D(q,`[${z}/${U}]${j}`);return{app:F,fpr:z,policy:Z,xpub:j}}async function d(){if(!k){let{xpub:F}=await S(),D=S0.HDKey.fromExtendedKey(F).derive(`m/${f}/${M}`);if(!D.publicKey)throw new u.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot derive leaf pubkey for ${_}`});k=D.publicKey}return k}return{connect:async()=>{await O()},getAddress:async()=>{let{app:F,policy:z}=await S(),D=await F.getWalletAddress(z,null,f,M,!1);if(!D)throw new u.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${_} address from ledger derivation path: ${w}`});return D},getExtendedPublicKey:async(F=`m/${U}`)=>{return(await O()).getExtendedPubkey(`m/${K0(F)}`)},getPublicKey:d,signTransaction:async(F)=>{let{app:z,policy:D,fpr:Z}=await S(),C=Number.parseInt(Z,16)>>>0,A=qL(w),I=Array.from({length:F.inputsLength},(i,v)=>v).filter((i)=>!HL(F,i));if(I.length>0){let i=await d();for(let v of I)F.updateInput(v,{bip32Derivation:[[i,{fingerprint:C,path:A}]]})}if(W==="legacy")CL(F);if(W==="p2sh")await E0({chain:jL[_],publicKey:await d(),tx:F});let V=k0.base64.encode(F.toPSBT(0)),r=await z.signPsbt(V,D,null);for(let[i,v]of r)F.updateInput(i,{partialSig:[[new Uint8Array(v.pubkey),new Uint8Array(v.signature)]]});return F}}}},AL,zL;var P0=j_(()=>{c();k0=require("@scure/base"),S0=require("@scure/bip32"),u=require("@swapkit/helpers"),jL={bitcoin:u.Chain.Bitcoin,litecoin:u.Chain.Litecoin};AL=V0({chain:"bitcoin"}),zL=V0({chain:"litecoin"})});var c0={};Y_(c0,{signLegacyPsbtTransaction:()=>b0,extractInputsFromPsbt:()=>v0,createLegacyPsbtSigner:()=>EL});async function v0(_,L){let{RawTx:R}=await import("@swapkit/utxo-signer"),{getUtxoApi:N}=await import("@swapkit/toolboxes/utxo"),G=[];for(let O=0;O<_.inputsLength;O++){let B=_.getInput(O);if(!B.txid||B.index===void 0)throw Error(`PSBT input ${O} is missing txid/index`);let w=M_.hex.encode(B.txid),T=B.nonWitnessUtxo?M_.hex.encode(R.encode(B.nonWitnessUtxo)):await N(L).getRawTx(w);if(!T)throw new I0.SwapKitError("wallet_ledger_invalid_params",{chain:L,inputIndex:O,reason:"Unable to resolve previous transaction hex for Ledger signing",txid:w});let U=B.witnessUtxo?{script:B.witnessUtxo.script,value:Number(B.witnessUtxo.amount)}:void 0,$=B.index!==void 0?B.nonWitnessUtxo?.outputs?.[B.index]:void 0,f=U?.value??($?Number($.amount):0);G.push({hash:w,index:B.index,txHex:T,value:f,witnessUtxo:U})}return G}async function b0({legacyClient:_,chain:L,tx:R}){let N=await v0(R,L);return _.signTransaction(R,N)}function EL({legacyClient:_,chain:L,address:R}){return{getAddress:async()=>R,signTransaction:async(N)=>{let G=await b0({chain:L,legacyClient:_,tx:N}),{Transaction:O}=await import("@swapkit/utxo-signer");return O.fromRaw(M_.hex.decode(G))}}}var M_,I0;var l0=j_(()=>{M_=require("@scure/base"),I0=require("@swapkit/helpers")});var VL={};Y_(VL,{ledgerWallet:()=>g0,getLedgerExtendedPublicKey:()=>x0,LEDGER_SUPPORTED_CHAINS:()=>KL});module.exports=_L(VL);var y=require("@swapkit/helpers"),Q=require("@swapkit/toolboxes/utxo"),X_=require("@swapkit/wallet-core");var J=require("@swapkit/helpers"),o=async({chain:_,ledgerClient:L})=>{if(!L)return"";switch(_){case J.Chain.Cosmos:case J.Chain.THORChain:return L.connect();case J.Chain.Ethereum:case J.Chain.BinanceSmartChain:case J.Chain.Avalanche:case J.Chain.Polygon:case J.Chain.Arbitrum:case J.Chain.Arc:case J.Chain.Berachain:case J.Chain.Optimism:case J.Chain.Base:case J.Chain.Aurora:case J.Chain.Gnosis:case J.Chain.Monad:case J.Chain.XLayer:return L.getAddress();case J.Chain.Bitcoin:case J.Chain.BitcoinCash:case J.Chain.Dash:case J.Chain.Dogecoin:case J.Chain.Litecoin:case J.Chain.Zcash:{let R=L;await R.connect();let N=await R.getAddress();return _===J.Chain.BitcoinCash?N.replace("bitcoincash:",""):N}case J.Chain.Near:return await L.getAddress();case J.Chain.Ripple:return L.getAddress();case J.Chain.Tron:return L.getAddress();case J.Chain.Sui:return L.connect();default:throw new J.SwapKitError("wallet_chain_not_supported",{chain:_,wallet:J.WalletOption.LEDGER})}};var X=require("@swapkit/helpers");var s=require("@swapkit/helpers");var l=require("@swapkit/helpers");var H_=require("@swapkit/helpers");var t=85,Q_=250;var p={GET_ADDR_SECP256K1:4,GET_VERSION:0,INS_PUBLIC_KEY_SECP256K1:1,SIGN_SECP256K1:2},U_={ADD:1,INIT:0,LAST:2},F_={ONLY_RETRIEVE:0,SHOW_ADDRESS_IN_DEVICE:1},a={JSON:0},n={NoError:36864},l_={1:"U2F: Unknown",2:"U2F: Bad request",3:"U2F: Configuration unsupported",4:"U2F: Device Ineligible",5:"U2F: Timeout",14:"Timeout",25600:"Execution Error",26368:"Wrong Length",26626:"Error deriving keys",27010:"Empty Buffer",27011:"Output buffer too small",27012:"Data is invalid",27013:"Conditions not satisfied",27014:"Transaction rejected",27264:"Bad key handle",27392:"Invalid P1/P2",27904:"Instruction not supported",28160:"App does not seem to be open",28416:"Unknown error",28417:"Sign/verify error",36864:"No errors",36865:"Device is busy"};function b(_){if(_ in l_)return l_[_];return`Unknown Status Code: ${_}`}function NL(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)&&!(_ instanceof Date)}function m(_){if(_){if(NL(_)){if(Object.hasOwn(_,"statusCode"))return{error_message:b(_.statusCode),return_code:_.statusCode};if(Object.hasOwn(_,"return_code")&&Object.hasOwn(_,"error_message"))return _}return{error_message:_.toString(),return_code:65535}}return{error_message:_.toString(),return_code:65535}}function q_(_){return _.send(85,p.GET_VERSION,0,0).then((L)=>{let R=L.slice(-2),N=R[0]*256+R[1],G=0;if(L.length>=9)G=(L[5]<<24)+(L[6]<<16)+(L[7]<<8)+(L[8]<<0);return{device_locked:L[4]===1,error_message:b(N),major:L[1],minor:L[2],patch:L[3],return_code:N,target_id:G.toString(16),test_mode:L[0]!==0}},m)}var G_=require("@swapkit/helpers");function g_(_){if(_==null||_.length<3)throw new G_.SwapKitError("wallet_ledger_invalid_params",{reason:"Path too short"});if(_.length>10)throw new G_.SwapKitError("wallet_ledger_invalid_params",{reason:"Path too long"});let L=Buffer.alloc(1+4*_.length);L.writeUInt8(_.length,0);for(let R=0;R<_.length;R+=1){let N=_[R]||0;if(R<3)N|=2147483648;L.writeInt32LE(N,1+R*4)}return L}function C_(_,L,R,N,G=a.JSON){return _.transport.send(t,p.SIGN_SECP256K1,L,G,N,[n.NoError,27012,27264]).then((O)=>{let B=O.slice(-2),w=B[0]*256+B[1],T=b(w);if(w===27264||w===27012)T=`${T} : ${O.slice(0,O.length-2).toString("ascii")}`;let U=null;if(O.length>2)U=O.slice(0,O.length-2);return{error_message:T,return_code:w,signature:U}},m)}function GL(_){if(_.length!==65)throw new G_.SwapKitError("wallet_ledger_invalid_params",{reason:"decompressed public key length should be 65 bytes"});let L=_.slice(33,65),R=Buffer.from([2+(L[L.length-1]&1)]);return Buffer.concat([R,_.slice(1,33)])}function x_(_,L){return _.transport.send(t,p.INS_PUBLIC_KEY_SECP256K1,0,0,L,[n.NoError]).then((R)=>{let N=R.slice(-2),G=N[0]*256+N[1],O=Buffer.from(R.slice(0,65));return{compressed_pk:GL(O),error_message:b(G),pk:O,return_code:G}},m)}function h_(_){if(!_||_.length!==5)throw new G_.SwapKitError("wallet_ledger_invalid_params",{reason:"Path must be exactly 5 elements"});let L=Buffer.alloc(20);return L.writeUInt32LE(2147483648+_[0],0),L.writeUInt32LE(2147483648+_[1],4),L.writeUInt32LE(2147483648+_[2],8),L.writeUInt32LE(_[3],12),L.writeUInt32LE(_[4],16),L}function u_(_,L,R,N,G=a.JSON){let O=U_.ADD;if(L===1)O=U_.INIT;if(L===R)O=U_.LAST;return C_(_,O,0,N,G)}function d_(_,L){return _.transport.send(t,p.GET_ADDR_SECP256K1,0,0,L,[n.NoError]).then((R)=>{let N=R.slice(-2),G=N[0]*256+N[1];return{compressed_pk:Buffer.from(R.slice(0,33)),error_message:b(G),pk:"OBSOLETE PROPERTY",return_code:G}},m)}class O_{transport;versionResponse;constructor(_){if(!_)throw new H_.SwapKitError("wallet_ledger_transport_not_defined");this.transport=_}static serializeHRP(_){if(_==null||_.length<3||_.length>83)throw new H_.SwapKitError("wallet_ledger_invalid_params",{reason:"Invalid HRP"});let L=Buffer.alloc(1+_.length);return L.writeUInt8(_.length,0),L.write(_,1),L}async serializePath(_){if(this.versionResponse=await q_(this.transport),this.versionResponse.return_code!==n.NoError)throw this.versionResponse;switch(this.versionResponse.major){case 1:return g_(_);case 2:return h_(_);default:return Buffer.alloc(0)}}async signGetChunks(_,L){let R=await this.serializePath(_),N=[];N.push(R);for(let G=0;G<L.length;G+=Q_){let O=G+Q_;if(G>L.length)O=L.length;N.push(L.slice(G,O))}return N}async getVersion(){try{return this.versionResponse=await q_(this.transport),this.versionResponse}catch(_){return m(_)}}appInfo(){return this.transport.send(176,1,0,0).then((_)=>{let L=_.readUInt16BE(_.length-2),R="",N="",G=0,O=0;if(_[0]!==1)return{error_message:"response format ID not recognized",return_code:36865};let B=_[1];R=_.slice(2,2+B).toString("ascii");let w=2+B,T=_[w];w+=1,N=_.slice(w,w+T).toString("ascii"),w+=T;let U=_[w];return w+=1,G=U,O=_[w],{appName:R,appVersion:N,error_message:b(L),flag_onboarded:(O&4)!==0,flag_pin_validated:(O&128)!==0,flag_recovery:(O&1)!==0,flag_signed_mcu_code:(O&2)!==0,flagLen:G,flagsValue:O,return_code:L}},m)}deviceInfo(){return this.transport.send(224,1,0,0,Buffer.from([]),[n.NoError,28160]).then((_)=>{let L=_.slice(-2),R=L[0]*256+L[1];if(R===28160)return{error_message:"This command is only available in the Dashboard",return_code:R};let N=_.slice(0,4).toString("hex"),G=4,O=_[G];G+=1;let B=_.slice(G,G+O).toString();G+=O;let w=_[G];G+=1;let T=_.slice(G,G+w).toString("hex");G+=w;let U=_[G];G+=1;let $=_.slice(G,G+U);if($[U-1]===0)$=_.slice(G,G+U-1);let f=$.toString();return{error_message:b(R),flag:T,mcuVersion:f,return_code:R,seVersion:B,targetId:N}},m)}async publicKey(_){try{let L=await this.serializePath(_);switch(this.versionResponse.major){case 1:return x_(this,L);case 2:{let R=Buffer.concat([O_.serializeHRP("thor"),L]);return d_(this,R)}default:return{error_message:"App Version is not supported",return_code:25600}}}catch(L){return m(L)}}async getAddressAndPubKey(_,L,R=!1){try{let N=await this.serializePath(_),G=Buffer.concat([O_.serializeHRP(L),N]),O=await this.transport.send(t,p.GET_ADDR_SECP256K1,R?F_.SHOW_ADDRESS_IN_DEVICE:F_.ONLY_RETRIEVE,0,G,[n.NoError]),B=Buffer.from(O.slice(0,33)),w=Buffer.from(O.slice(33,-2)).toString(),T=O.readUInt16BE(O.length-2);return{bech32_address:w,compressed_pk:B,error_message:b(T),return_code:T}}catch(N){return m(N)}}showAddressAndPubKey(_,L){return this.getAddressAndPubKey(_,L,!0)}signSendChunk(_,L,R,N=a.JSON){switch(this.versionResponse.major){case 1:return C_(this,_,L,R,N);case 2:return u_(this,_,L,R,N);default:return{error_message:"App Version is not supported",return_code:25600}}}async sign(_,L,R=a.JSON){let N=Buffer.from(L),G=[],O;try{G=await this.signGetChunks(_,N),O=await this.signSendChunk(1,G.length,G[0],R)}catch(w){m(w)}let B={error_message:O.error_message,return_code:O.return_code,signature:null};for(let w=1;w<G.length;w+=1)if(B=await this.signSendChunk(1+w,G.length,G[w],R),B.return_code!==n.NoError)break;return{error_message:B.error_message,return_code:B.return_code,signature:B.signature}}}c();class y_{ledgerTimeout=50000;derivationPath=l.NetworkDerivationPath.GAIA;transport;ledgerApp;chain="thor";injectedTransport;constructor(_){if(this.injectedTransport=_,_)this.transport=_}checkOrCreateTransportAndLedger=async(_=!1)=>{if(!_&&this.transport&&this.ledgerApp)return;try{if(!this.transport||_&&!this.injectedTransport)this.transport=this.injectedTransport??await H();switch(this.chain){case"thor":{this.ledgerApp=_||!this.ledgerApp?new O_(this.transport):this.ledgerApp;break}case"cosmos":{let R=(await import("@ledgerhq/hw-app-cosmos")).default;this.ledgerApp=_||!this.ledgerApp?new R(this.transport):this.ledgerApp}}return this.ledgerApp}catch(L){throw new l.SwapKitError("wallet_ledger_connection_error",L)}};validateResponse=(_,L)=>{switch(_){case l.LedgerErrorCode.NoError:return;case l.LedgerErrorCode.LockedDevice:throw new l.SwapKitError("wallet_ledger_device_locked",{message:`Ledger is locked: ${L}`});case l.LedgerErrorCode.TC_NotFound:throw new l.SwapKitError("wallet_ledger_device_not_found");default:break}}}class z_ extends y_{pubKey=null;derivationPath;constructor(_=s.NetworkDerivationPath.GAIA,L){super(L);this.chain="cosmos",this.derivationPath=s.derivationPathToString(_)}connect=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{publicKey:_,address:L}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(_,"hex").toString("base64"),L};getAddressAndPubKey=async()=>{return await this.checkOrCreateTransportAndLedger(!0),await this.ledgerApp.getAddress(this.derivationPath,this.chain)};signTransaction=async(_,L="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:R,error_message:N,signature:G}=await this.ledgerApp.sign(this.derivationPath,_);if(!this.pubKey)throw new s.SwapKitError("wallet_ledger_pubkey_not_found");return this.validateResponse(R,N),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:L,signature:G}]};signAmino=async(_,L)=>{await this.checkOrCreateTransportAndLedger(!0);let R=await this.getAccounts();if(R.findIndex((M)=>M.address===_)===-1)throw new s.SwapKitError("wallet_ledger_address_not_found",{address:_});let G=await import("@cosmjs/amino"),O=G.encodeSecp256k1Signature??G.default?.encodeSecp256k1Signature,B=G.serializeSignDoc??G.default?.serializeSignDoc,w=await import("@cosmjs/crypto"),T=w.Secp256k1Signature??w.default?.Secp256k1Signature,U=B(L),$=await this.ledgerApp.sign(this.derivationPath,U);this.validateResponse($.return_code,$.error_message);let f=T.fromDer($.signature).toFixedLength();return{signature:O(R[0].pubkey,f),signed:L}};getAccounts=async()=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.getAddressAndPubKey();return[{address:_.address,algo:"secp256k1",pubkey:Buffer.from(_.publicKey,"hex")}]}}c();var Y=require("@swapkit/helpers"),a_=require("ethers");var o_={apex:"apexp",europa:"flex",nanoS:"nanos",nanoSP:"nanosp",nanoX:"nanox",stax:"stax"};async function n_(_,L=fetch){let R=o_[_];if(!R)return null;let N=`https://crypto-assets-service.api.ledger.com/v1/certificates?output=descriptor&public_key_usage=network&target_device=${R}`,G=await L(N);if(!G.ok)return null;let B=(await G.json())[0]?.descriptor,w=B?.signatures?.prod;if(!(B?.data&&w))return null;return`${B.data}${yL(w)}`}async function i_(_,L){await _.send(176,6,12,0,Buffer.from(L,"hex"))}async function p_(_,L,R=fetch){let N=o_[L];if(!N)return null;let G=`https://crypto-assets-service.api.ledger.com/v1/networks?chain_id=${_}&output=chain_id,descriptors,icons`,O=await R(G);if(!O.ok)return null;let w=(await O.json()).find(($)=>$.chain_id===_),T=w?.descriptors?.[N],U=T?.signatures?.prod;if(!(T?.data&&U))return null;return{data:T.data,icon:w?.icons?.[N],signature:U}}function yL(_){return s_(21,Buffer.from(_,"hex")).toString("hex")}function s_(_,L){return Buffer.concat([Buffer.from([_,L.length]),L])}function BL({data:_,signature:L}){let R=Buffer.concat([Buffer.from(_,"hex"),s_(21,Buffer.from(L,"hex"))]),N=Buffer.alloc(2);return N.writeUInt16BE(R.length,0),Buffer.concat([N,R])}async function E_(_,L,R){for(let N=0;N<R.length;N+=255){let G=N===0?1:0,O=R.subarray(N,N+255);await _.send(224,48,G,L,O)}}async function r_(_,L){let R=BL(L);if(await E_(_,0,R),!L.icon)return{iconAccepted:!1};try{return await E_(_,1,Buffer.from(L.icon,"hex")),{iconAccepted:!0}}catch{return await E_(_,0,R),{iconAccepted:!1}}}var wL=27264,t_=Number(Y.ChainId.Arc);function TL(_){return _ instanceof Error&&"statusCode"in _&&_.statusCode===wL}function $L(_){return Object.values(_??{}).some((L)=>Array.isArray(L)&&L.length)}function UL(_){if(typeof _==="number")return _;let L=_.startsWith("0x")?_.slice(2):_;return Number.parseInt(L||"0",16)}class E extends a_.AbstractSigner{chainId=Y.ChainId.Ethereum;derivationPath="";ledgerApp=null;ledgerTimeout=50000;transport;injectedTransport;arcNetworkRegistered=!1;constructor({provider:_,derivationPath:L=Y.NetworkDerivationPath.OP,chainId:R=Y.ChainId.Optimism,transport:N}){super(_);this.chainId=R||Y.ChainId.Ethereum,this.derivationPath=typeof L==="string"?L:Y.derivationPathToString(L),this.injectedTransport=N,Object.defineProperty(this,"provider",{enumerable:!0,value:_||null,writable:!1})}connect=(_)=>new E({chainId:this.chainId,derivationPath:this.derivationPath,provider:_,transport:this.transport??this.injectedTransport});checkOrCreateTransportAndLedger=async()=>{await this.createTransportAndLedger()};createTransportAndLedger=async()=>{if(this.ledgerApp)return;this.transport||=this.injectedTransport??await H();let _=(await import("@ledgerhq/hw-app-eth")).default;this.ledgerApp=new _(this.transport)};getAddress=async()=>{let _=await this.getAddressAndPubKey();if(!_)throw new Y.SwapKitError("wallet_ledger_failed_to_get_address");return _.address};getAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath)};showAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath,!0)};signMessage=async(_)=>{let{Signature:L}=await import("ethers");await this.createTransportAndLedger();let R=await this.ledgerApp?.signPersonalMessage(this.derivationPath,_);if(!R)throw new Y.SwapKitError("wallet_ledger_signing_error");return R.r=`0x${R.r}`,R.s=`0x${R.s}`,L.from(R).serialized};sendTransaction=async(_)=>{if(!this.provider)throw new Y.SwapKitError("wallet_ledger_no_provider");let L=await this.signTransaction(_);return await this.provider.broadcastTransaction(L)};signTypedData=async(_,L,R,N)=>{let{buildEIP712DomainType:G}=await import("@swapkit/toolboxes/evm"),{Signature:O,TypedDataEncoder:B}=await import("ethers");await this.createTransportAndLedger();let{EIP712Domain:w,...T}=L,U=N??B.from(T).primaryType,$;try{$=await this.ledgerApp?.signEIP712Message(this.derivationPath,{domain:_,message:R,primaryType:U,types:{EIP712Domain:G(_),...T}})}catch(f){let M=f instanceof Error&&"statusCode"in f;if(!M||M&&f.statusCode===27013)throw f;let W=B.hashDomain(_).slice(2),q=B.from(T).hash(R).slice(2);$=await this.ledgerApp?.signEIP712HashedMessage(this.derivationPath,W,q)}if(!$)throw new Y.SwapKitError("wallet_ledger_signing_error");return $.r=`0x${$.r}`,$.s=`0x${$.s}`,O.from($).serialized};signTransaction=async(_)=>{let{Transaction:L}=await import("ethers");await this.createTransportAndLedger();let R=_.nonce??void 0,N=R===void 0?await this.provider?.getTransactionCount(_.from||await this.getAddress()):void 0,G={chainId:_.chainId||this.chainId,data:_.data,gasLimit:_.gasLimit,..._.gasPrice&&{gasPrice:_.gasPrice},...!_.gasPrice&&_.maxFeePerGas&&{maxFeePerGas:_.maxFeePerGas,maxPriorityFeePerGas:_.maxPriorityFeePerGas},nonce:R!==void 0?Number(R.toString()):N,to:_.to?.toString(),type:_.type&&!Number.isNaN(_.type)?_.type:_.maxFeePerGas?2:0,value:_.value},O=L.from(G).unsignedSerialized.slice(2),{ledgerService:B}=await import("@ledgerhq/hw-app-eth"),w=Number(G.chainId),T=w===t_,U=await B.resolveTransaction(O,{},{erc20:!0,externalPlugins:!0}).catch((q)=>{if(!T)throw q;return console.warn("Ledger: could not fetch clear-signing metadata for Arc, signing blind"),null});if(T&&!this.arcNetworkRegistered)await this.registerNetworkOnDevice(w);let $=await this.signWithLedgerApp(O,U,w);if(!$)throw new Y.SwapKitError("wallet_ledger_signing_error");let{r:f,s:M,v:W}=$;return L.from({...G,signature:{r:`0x${f}`,s:`0x${M}`,v:UL(W)}}).serialized};signWithLedgerApp=async(_,L,R)=>{try{return await this.ledgerApp?.signTransaction(this.derivationPath,_,L)}catch(N){if(!(R===t_&&TL(N)&&$L(L)))throw N;return console.warn("Ledger: the app rejected the Arc metadata, signing blind"),await this.ledgerApp?.signTransaction(this.derivationPath,_,null)}};registerNetworkOnDevice=async(_)=>{let L=this.transport?.deviceModel?.id;if(!(this.transport&&L))return;try{let[R,N]=await Promise.all([p_(_,L),n_(L)]);if(!R)return;if(N)await i_(this.transport,N);await r_(this.transport,R),this.arcNetworkRegistered=!0}catch{}}}var e_=(_)=>new E({..._,chainId:Y.ChainId.Arbitrum}),_0=(_)=>new E({..._,chainId:Y.ChainId.Arc}),L0=(_)=>new E({..._,chainId:Y.ChainId.Aurora}),R0=(_)=>new E({..._,chainId:Y.ChainId.Avalanche}),N0=(_)=>new E({..._,chainId:Y.ChainId.Base}),G0=(_)=>new E({..._,chainId:Y.ChainId.Ethereum}),O0=(_)=>new E({..._,chainId:Y.ChainId.Gnosis}),y0=(_)=>new E({..._,chainId:Y.ChainId.Optimism}),B0=(_)=>new E({..._,chainId:Y.ChainId.Polygon}),w0=(_)=>new E({..._,chainId:Y.ChainId.BinanceSmartChain}),T0=(_)=>new E({..._,chainId:Y.ChainId.Monad}),$0=(_)=>new E({..._,chainId:Y.ChainId.XLayer}),U0=(_)=>new E({..._,chainId:Y.ChainId.Berachain});c();async function f0(_,L){let R=(await import("@ledgerhq/hw-app-near")).default,{Chain:N,NetworkDerivationPath:G,SwapKitError:O}=await import("@swapkit/helpers"),B=L??await H(),w=new R(B),T=(_||G[N.Near]).join("'/").concat("'"),{address:U,publicKey:$}=await w.getAddress(T);return{getAddress(){return Promise.resolve(U)},async getPublicKey(){let{PublicKey:M}=await import("@near-js/crypto");return M.fromString(`ed25519:${$}`)},signDelegateAction(M){return Promise.reject(new O("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(M,W,q,j,k){return Promise.reject(new O("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(M){let{Signature:W,SignedTransaction:q}=await import("@near-js/transactions");try{let j=await w.signTransaction(M.encode(),T);if(!j)throw Error("Signature undefined");let k=new W({data:j,keyType:0}),S=new q({signature:k,transaction:M});return[j,S]}catch(j){throw new O("wallet_ledger_signing_error",{error:j})}}}}c();var K=require("@swapkit/helpers");class D0{derivationPath;ledgerApp=null;address=null;publicKey=null;injectedTransport;constructor(_,L){this.derivationPath=typeof _==="string"?_:K.derivationPathToString(_||K.NetworkDerivationPath[K.Chain.Sui]),this.injectedTransport=L}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async createTransportAndLedger(){if(this.ledgerApp)return;let _=this.injectedTransport??await H(),L=(await import("@ledgerhq/hw-app-sui")).default;this.ledgerApp=new L(_)}async connect(){if(await this.createTransportAndLedger(),!this.ledgerApp)throw new K.SwapKitError("wallet_ledger_transport_error");let _=this.getLedgerPath(),L=await this.ledgerApp.getPublicKey(_);if(!L?.publicKey)throw new K.SwapKitError("wallet_ledger_failed_to_get_address");return this.publicKey=L.publicKey,this.address=`0x${Buffer.from(L.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new K.SwapKitError("wallet_ledger_failed_to_get_address");return this.address}async getAddress(){if(this.address)return this.address;return await this.connect()}async signTransaction(_){let L=_ instanceof Uint8Array?_:_.transaction;if(await this.createTransportAndLedger(),!this.ledgerApp)throw new K.SwapKitError("wallet_ledger_transport_error");if(!this.publicKey)throw new K.SwapKitError("wallet_ledger_failed_to_get_address");try{let R=this.getLedgerPath(),N=new Uint8Array(3+L.length);N[0]=0,N[1]=0,N[2]=0,N.set(L,3);let G=await this.ledgerApp.signTransaction(R,N);if(!G?.signature)throw new K.SwapKitError("wallet_ledger_signing_error");let O=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(O.length!==32)throw new K.SwapKitError("wallet_ledger_signing_error",{error:"Invalid public key length"});let B=new Uint8Array(97);B[0]=0,B.set(G.signature,1),B.set(O,65);let w=Buffer.from(B).toString("base64");return{bytes:Buffer.from(L).toString("base64"),signature:w}}catch(R){throw new K.SwapKitError("wallet_ledger_signing_error",{error:R})}}}var M0=(_,L)=>new D0(_,L);var D_=require("@scure/base"),__=require("@swapkit/helpers");var X0=require("@scure/base"),g=require("@swapkit/helpers"),f_=(_)=>{if(_.length<64)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"Too short"});if(_[0]!==48)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected first byte 0x30"});if(_[1]+2!==_.length)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"signature length does not match TLV"});if(_[2]!==2)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02"});let L=_[3],R=_.slice(4,L+4);if(R.length===33&&R[0]===0)R=R.slice(1,33);else if(R.length===33)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"r too long"});while(R.length<32)R.unshift(0);if(_[L+4]!==2)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV encoding: expected length type 0x02 for s"});let N=_[L+5];if(4+L+2+N!==_.length)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"TLV byte lengths do not match message length"});let G=_.slice(L+6,_.length);if(G.length===33&&G[0]===0)G=G.slice(1,33);else if(G.length===33)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"s too long"});while(G.length<32)G.unshift(0);if(R.length!==32||G.length!==32)throw new g.SwapKitError("wallet_ledger_invalid_signature",{reason:"must be 32 bytes each"});return X0.base64.encode(Buffer.concat([R,G]))};function fL(_){if(typeof _==="string")return _;let L=_.chain?.toUpperCase(),R=(_.symbol||_.ticker||"").toUpperCase();if(!(L&&R))return R||L||"";if(_.synth)return`${L}/${R}`;return`${L}.${R}`}function DL(_){return{..._,msgs:_.msgs.map((L)=>{if(!L.type.includes("MsgDeposit"))return L;let R=L.value.coins;if(!Array.isArray(R))return L;return{...L,value:{...L.value,coins:R.map((N)=>({...N,asset:fL(N.asset)}))}}})}}class K_ extends y_{pubKey=null;derivationPath;constructor(_=__.NetworkDerivationPath.THOR,L){super(L);this.chain="thor",this.derivationPath=_}get pubkey(){return this.pubKey}connect=async()=>{await this.checkOrCreateTransportAndLedger();let{compressed_pk:_,bech32_address:L}=await this.getAddressAndPubKey();return this.pubKey=D_.base64.encode(_),L};getAddressAndPubKey=async()=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.ledgerApp.getAddressAndPubKey(this.derivationPath,this.chain);return this.validateResponse(_.return_code,_.error_message),_};showAddressAndPubKey=async()=>{await this.checkOrCreateTransportAndLedger(!0);let _=await this.ledgerApp.showAddressAndPubKey(this.derivationPath,this.chain);return this.validateResponse(_.return_code,_.error_message),_};signTransaction=async(_,L="0")=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:R,error_message:N,signature:G}=await this.ledgerApp.sign(this.derivationPath,_);if(!this.pubKey)throw new __.SwapKitError("wallet_ledger_pubkey_not_found");return this.validateResponse(R,N),[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:L,signature:f_(G)}]};signAmino=async(_,L)=>{await this.checkOrCreateTransportAndLedger(!0);let R=(await this.getAccounts()).find(($)=>$.address===_);if(!R)throw new __.SwapKitError("wallet_ledger_address_not_found",{address:_});let N=await import("@cosmjs/amino"),G=N.encodeSecp256k1Signature??N.default?.encodeSecp256k1Signature,O=N.serializeSignDoc??N.default?.serializeSignDoc,B=DL(L),{return_code:w,error_message:T,signature:U}=await this.ledgerApp.sign(this.derivationPath,O(B));return this.validateResponse(w,T),{signature:G(R.pubkey,D_.base64.decode(f_(U))),signed:L}};getAccounts=async()=>{await this.checkOrCreateTransportAndLedger(!0);let{bech32_address:_,compressed_pk:L}=await this.getAddressAndPubKey();return this.pubKey=D_.base64.encode(L),[{address:_,algo:"secp256k1",pubkey:L}]};sign=async(_)=>{await this.checkOrCreateTransportAndLedger(!0);let{return_code:L,error_message:R,signature:N}=await this.ledgerApp.sign(this.derivationPath,_);if(!this.pubKey)throw new __.SwapKitError("wallet_ledger_pubkey_not_found");return this.validateResponse(L,R),f_(N)}}c();var x=require("@swapkit/helpers");class Z0{derivationPath;ledgerApp=null;ledgerTimeout=50000;injectedTransport;constructor(_,L){this.derivationPath=typeof _==="string"?_:x.derivationPathToString(_||x.NetworkDerivationPath.TRON),this.injectedTransport=L}checkOrCreateTransportAndLedger=async()=>{if(this.ledgerApp)return;await this.createTransportAndLedger()};createTransportAndLedger=async()=>{let _=this.injectedTransport??await H(),L=(await import("@ledgerhq/hw-app-trx")).default;this.ledgerApp=new L(_)};getAddress=async()=>{let _=await this.getAddressAndPubKey();if(!_)throw new x.SwapKitError("wallet_ledger_failed_to_get_address");return _.address};getAddressAndPubKey=async()=>{await this.createTransportAndLedger();let _=await this.ledgerApp?.getAddress(this.derivationPath);if(!_)throw new x.SwapKitError("wallet_ledger_failed_to_get_address");return{address:_.address,publicKey:_.publicKey}};showAddressAndPubKey=async()=>{return await this.createTransportAndLedger(),this.ledgerApp?.getAddress(this.derivationPath,!0)};signTransaction=async(_)=>{if(await this.createTransportAndLedger(),!this.ledgerApp)throw new x.SwapKitError("wallet_ledger_transport_error");try{let L=await this.ledgerApp.signTransaction(this.derivationPath,_.raw_data_hex,[]);if(!L)throw new x.SwapKitError("wallet_ledger_signing_error");return{..._,signature:[L]}}catch(L){throw new x.SwapKitError("wallet_ledger_signing_error",{error:L})}}}var W0=(_,L)=>new Z0(_,L);c();var B_=require("@scure/base"),h=require("@swapkit/helpers"),Y0=["bitcoin-cash","dash","dogecoin","zcash"],J0=({tx:_,inputUtxos:L,btcApp:R,derivationPath:N,chain:G},O)=>{let B=L.map((W)=>{return[R.splitTransaction(W.txHex||"",!Y0.includes(G),G==="zcash"),W.index,void 0,void 0]}),w=B_.hex.encode(_.unsignedTx),T=R.splitTransaction(w,!0),U=R.serializeTransactionOutputs(T).toString("hex"),$=h.getWalletFormatFor(N),f=$!=="legacy",M={additionals:$==="bech32"?["bech32"]:[],associatedKeysets:B.map(()=>N),inputs:B,outputScriptHex:U,segwit:f,useTrustedInputForSegwit:f};return R.createPaymentTransaction({...M,...O})},ML=({tx:_,inputUtxos:L,btcApp:R,derivationPaths:N,chain:G},O)=>{if(N.length!==L.length)throw new h.SwapKitError("wallet_ledger_invalid_params",{message:`Derivation paths count (${N.length}) must match inputs count (${L.length})`});let B=L.map((W)=>{return[R.splitTransaction(W.txHex||"",!Y0.includes(G),G==="zcash"),W.index,void 0,void 0]}),w=B_.hex.encode(_.unsignedTx),T=R.splitTransaction(w,!0),U=R.serializeTransactionOutputs(T).toString("hex"),$=h.getWalletFormatFor(N[0]??""),f=$!=="legacy",M={additionals:$==="bech32"?["bech32"]:[],associatedKeysets:N,inputs:B,outputScriptHex:U,segwit:f,useTrustedInputForSegwit:f};return R.createPaymentTransaction({...M,...O})},L_=({chain:_,additionalSignParams:L})=>{return(R,N)=>{let G,O=null;async function B(){O||=N??await H();let f=(await import("@ledgerhq/hw-app-btc")).default;return G||=new f({currency:_,transport:O}),G}async function w(){return G||await B()}async function T(){if(!N)await O?.close?.();G=void 0,O=null}let U=typeof R==="string"?R:h.derivationPathToString(R),$=h.getWalletFormatFor(U);return{connect:async()=>{await w()},disconnect:T,getAddress:async()=>{let{toCashAddress:f}=await import("@swapkit/toolboxes/utxo"),M=await w(),{bitcoinAddress:W}=await M.getWalletPublicKey(U,{format:$});if(!W)throw new h.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${_} address from ledger derivation path: ${U}`});return _==="bitcoin-cash"&&$==="legacy"?f(W).replace(/(bchtest:|bitcoincash:)/,""):W},getExtendedPublicKey:async(f="84'/0'/0'",M=76067358)=>{return(await w()).getWalletXpub({path:f,xpubVersion:M})},signPCZT:async(f)=>{if(_!=="zcash")throw new h.SwapKitError("wallet_ledger_chain_not_supported",{message:"PCZT signing is only supported for Zcash"});let M=await w(),{ZcashTransaction:W,Script:q}=await import("@swapkit/utxo-signer"),j=f.getGlobal(),k=new W({consensusBranchId:j.consensusBranchId,expiryHeight:j.expiryHeight,lockTime:j.lockTime,version:j.txVersion,versionGroupId:j.versionGroupId}),S=[];for(let D=0;D<f.inputsLength;D++){let Z=f.getInput(D);k.addInput({index:Z.index,script:new Uint8Array,sequence:Z.sequence??4294967295,txid:Z.txid,value:Z.value}),S.push({hash:B_.hex.encode(new Uint8Array([...Z.txid].reverse())),index:Z.index,txHex:XL(Z,j),value:Number(Z.value),witnessUtxo:{script:Z.scriptPubkey,value:Number(Z.value)}})}for(let D=0;D<f.outputsLength;D++){let Z=f.getOutput(D);k.addOutput({amount:Z.value,script:Z.scriptPubkey})}let d=await J0({btcApp:M,chain:_,derivationPath:U,inputUtxos:S,tx:k},{...L,expiryHeight:(()=>{let D=Buffer.alloc(4);return D.writeUInt32LE(j.expiryHeight),D})(),lockTime:j.lockTime}),F=W.fromHex(d,{allowUnknownOutputs:!0}),z=f.clone();for(let D=0;D<F.inputsLength;D++){let Z=F.getInput(D);if(Z.script&&Z.script.length>0){let C=q.decode(Z.script);if(C.length>=2)z.addSignature(D,C[1],C[0])}}return z},signTransaction:async(f,M)=>{let W=await w();return J0({btcApp:W,chain:_,derivationPath:U,inputUtxos:M,tx:f},L)},signTransactionWithMultiplePaths:async(f,M,W)=>{let q=await w();return ML({btcApp:q,chain:_,derivationPaths:W,inputUtxos:M,tx:f},L)}}}};function XL(_,L){let R=[],N=(L.txVersion|2147483648)>>>0;R.push(N&255,N>>8&255,N>>16&255,N>>24&255);let G=L.versionGroupId;R.push(G&255,G>>8&255,G>>16&255,G>>24&255),R.push(0);let O=_.index+1;if(O<253)R.push(O);else R.push(253,O&255,O>>8&255);for(let T=0;T<_.index;T++)R.push(0,0,0,0,0,0,0,0),R.push(0);let B=_.value;R.push(Number(B&0xffn),Number(B>>8n&0xffn),Number(B>>16n&0xffn),Number(B>>24n&0xffn),Number(B>>32n&0xffn),Number(B>>40n&0xffn),Number(B>>48n&0xffn),Number(B>>56n&0xffn));let w=_.scriptPubkey;if(w.length<253)R.push(w.length);else R.push(253,w.length&255,w.length>>8&255);for(let T of w)R.push(T);return R.push(L.lockTime&255,L.lockTime>>8&255,L.lockTime>>16&255,L.lockTime>>24&255),R.push(L.expiryHeight&255,L.expiryHeight>>8&255,L.expiryHeight>>16&255,L.expiryHeight>>24&255),R.push(0,0,0,0,0,0,0,0),R.push(0),R.push(0),R.push(0),B_.hex.encode(new Uint8Array(R))}var j0=L_({chain:"bitcoin"}),Q0=L_({chain:"litecoin"}),F0=L_({additionalSignParams:{additionals:["abc"],segwit:!1,sigHashType:65},chain:"bitcoin-cash"}),q0=L_({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),C0=L_({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),H0=L_({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let _=Buffer.alloc(4);return _.writeUInt32LE(0),_})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});c();var A0=e0(require("@ledgerhq/hw-app-xrp")),R_=require("@swapkit/helpers"),k_=require("ripple-binary-codec"),ZL=2147483648;function WL(_){let L={};for(let R in _)if(_[R]!==null&&_[R]!==void 0)L[R]=_[R];return L}function JL(_){return new A0.default(_)}var z0=async(_,L)=>{let R=R_.derivationPathToString(_||R_.NetworkDerivationPath[R_.Chain.Ripple]),N=L??await H(),G=JL(N),{address:O,publicKey:B}=await G.getAddress(R);async function w(T){let{hashes:U}=await import("xrpl"),f={...WL(T),Flags:T.Flags||ZL,SigningPubKey:B.toUpperCase()},M=k_.encode(f),W=await G.signTransaction(R,M),q=k_.encode({...f,TxnSignature:W});return{hash:U.hashSignedTx(q),tx_blob:q}}return{getAddress:()=>O,signTransaction:w}};var P=async({chain:_,derivationPath:L,transport:R})=>{let{match:N}=await import("ts-pattern");return N(_).returnType().with(X.Chain.THORChain,()=>Promise.resolve(new K_(L,R))).with(X.Chain.Cosmos,()=>Promise.resolve(new z_(L,R))).with(X.Chain.Bitcoin,()=>Promise.resolve(j0(L,R))).with(X.Chain.BitcoinCash,()=>Promise.resolve(F0(L,R))).with(X.Chain.Dash,()=>Promise.resolve(C0(L,R))).with(X.Chain.Dogecoin,()=>Promise.resolve(q0(L,R))).with(X.Chain.Litecoin,()=>Promise.resolve(Q0(L,R))).with(X.Chain.Zcash,()=>Promise.resolve(H0(L,R))).with(X.Chain.Ripple,()=>Promise.resolve(z0(L,R))).with(X.Chain.Tron,()=>Promise.resolve(W0(L,R))).with(X.Chain.Sui,()=>Promise.resolve(M0(L,R))).with(X.Chain.Near,()=>{return Promise.resolve(f0(L,R))}).with(X.Chain.Arbitrum,X.Chain.Arc,X.Chain.Aurora,X.Chain.Avalanche,X.Chain.Berachain,X.Chain.BinanceSmartChain,X.Chain.Ethereum,X.Chain.Gnosis,X.Chain.Monad,X.Chain.Optimism,X.Chain.Polygon,X.Chain.Base,X.Chain.XLayer,async()=>{let{getProvider:G}=await import("@swapkit/toolboxes/evm"),O={derivationPath:L,provider:await G(_),transport:R};return N(_).with(X.Chain.BinanceSmartChain,()=>w0(O)).with(X.Chain.Avalanche,()=>R0(O)).with(X.Chain.Arbitrum,()=>e_(O)).with(X.Chain.Arc,()=>_0(O)).with(X.Chain.Berachain,()=>U0(O)).with(X.Chain.Optimism,()=>y0(O)).with(X.Chain.Polygon,()=>B0(O)).with(X.Chain.Base,()=>N0(O)).with(X.Chain.Aurora,()=>L0(O)).with(X.Chain.Gnosis,()=>O0(O)).with(X.Chain.Monad,()=>T0(O)).with(X.Chain.XLayer,()=>$0(O)).otherwise(()=>G0(O))}).otherwise(()=>{throw new X.SwapKitError("wallet_chain_not_supported",{chain:_,wallet:X.WalletOption.LEDGER})})};c();var g0=X_.createWallet({connect:({addChain:_,supportedChains:L,walletType:R})=>async function(G,O,{address:B,transport:w}={}){let[T]=y.filterSupportedChains({chains:G,supportedChains:L,walletType:R});if(!T)return!1;let U=O??y.NetworkDerivationPath[T],$=await SL({address:B,chain:T,derivationPath:U,transport:w});return _({...$,chain:T,walletType:y.WalletOption.LEDGER}),!0},directSigningSupport:{[y.Chain.Arbitrum]:!0,[y.Chain.Arc]:!0,[y.Chain.Aurora]:!0,[y.Chain.Avalanche]:!0,[y.Chain.Base]:!0,[y.Chain.Berachain]:!0,[y.Chain.BinanceSmartChain]:!0,[y.Chain.Ethereum]:!0,[y.Chain.Gnosis]:!0,[y.Chain.Monad]:!0,[y.Chain.Bitcoin]:!0,[y.Chain.BitcoinCash]:!0,[y.Chain.Cosmos]:!0,[y.Chain.Dash]:!0,[y.Chain.Dogecoin]:!0,[y.Chain.Litecoin]:!0,[y.Chain.Near]:!0,[y.Chain.Optimism]:!0,[y.Chain.Polygon]:!0,[y.Chain.Ripple]:!0,[y.Chain.Sui]:!0,[y.Chain.THORChain]:!0,[y.Chain.Tron]:!0,[y.Chain.XLayer]:!0},getExtendedPublicKey:x0,name:"connectLedger",supportedChains:[y.Chain.Arbitrum,y.Chain.Arc,y.Chain.Aurora,y.Chain.Avalanche,y.Chain.Base,y.Chain.Berachain,y.Chain.BinanceSmartChain,y.Chain.Bitcoin,y.Chain.BitcoinCash,y.Chain.Cosmos,y.Chain.Dash,y.Chain.Dogecoin,y.Chain.Ethereum,y.Chain.Gnosis,y.Chain.Litecoin,y.Chain.Monad,y.Chain.Near,y.Chain.Optimism,y.Chain.Polygon,y.Chain.Ripple,y.Chain.Sui,y.Chain.THORChain,y.Chain.XLayer,y.Chain.Tron,y.Chain.Zcash],walletType:y.WalletOption.LEDGER}),KL=X_.getWalletSupportedChains(g0);function kL(_,L="t"){if(!_?.includes("=:"))return _;let R=_.includes(`:${L}:`)?_.split(`:${L}:`)[0]:_;return R?.substring(0,R.lastIndexOf(":"))}async function x0(_,L,{accountIndex:R}={}){if(![y.Chain.BitcoinCash,y.Chain.Bitcoin,y.Chain.Dash,y.Chain.Dogecoin,y.Chain.Litecoin,y.Chain.Zcash].includes(_))throw new y.SwapKitError("wallet_chain_not_supported",{chain:_,wallet:y.WalletOption.LEDGER});let N=_,G=await P({chain:N,derivationPath:L});if(!G.getExtendedPublicKey)return;let O=Q.getUTXOAccountPath({accountIndex:R,chain:N,derivationPath:L}),B=y.derivationPathToString(O),w=_===y.Chain.Bitcoin||_===y.Chain.Litecoin?B:B.replace(/^m\//,""),T=Q.getNetworkForChain(N).bip32.public;try{let U=await G.getExtendedPublicKey(w,T);return{accountIndex:Q.getUTXOAccountIndexFromPath(O),path:B,xpub:U}}finally{await G.disconnect?.()}}async function SL({address:_,chain:L,derivationPath:R,transport:N}){switch(L){case y.Chain.BitcoinCash:case y.Chain.Bitcoin:case y.Chain.Dash:case y.Chain.Dogecoin:case y.Chain.Litecoin:case y.Chain.Zcash:{let k=function(D={}){return j(D)},{getUtxoToolbox:G}=await import("@swapkit/toolboxes/utxo"),O=L,B=await P({chain:L,derivationPath:R,transport:N}),w=_??await o({chain:L,ledgerClient:B}),T=Q.getScriptTypeForAddress(w,O),U,$,f;if(L===y.Chain.Bitcoin){let{BitcoinPsbtLedger:D}=await Promise.resolve().then(() => (P0(),m0)),Z=D(R,N);$=T===y.UTXOScriptType.P2SH_P2WPKH?await Z.getPublicKey():void 0,U={getAddress:Z.getAddress,publicKey:$,signTransaction:Z.signTransaction}}else if(L===y.Chain.BitcoinCash||L===y.Chain.Dogecoin||L===y.Chain.Dash||L===y.Chain.Litecoin){let{createLegacyPsbtSigner:D,signLegacyPsbtTransaction:Z}=await Promise.resolve().then(() => (l0(),c0));U=D({address:w,chain:O,legacyClient:B}),f=async(C)=>{let A=await Z({chain:O,legacyClient:B,tx:C});return M.broadcastTx(A)}}let M=U?await G(O,{scriptType:T,signer:U}):G(O,{scriptType:T}),W=f??M.signAndBroadcastTransaction,q=async(D)=>{let Z=D.feeRate||(await M.getFeeRates())[y.FeeOption.Average],C=[y.Chain.Bitcoin].includes(L)?D.memo:kL(D.memo),{tx:A,inputs:I}=await M.createTransaction({...D,feeRate:Z,fetchTxHex:!0,memo:C,publicKey:D.publicKey??$,sender:w}),V=await B.signTransaction(A,I);return await M.broadcastTx(V)};async function j({accountIndex:D}={}){if(!B.getExtendedPublicKey)return;let Z=Q.getUTXOAccountPath({accountIndex:D,chain:O,derivationPath:R}),C=y.derivationPathToString(Z),A=L===y.Chain.Bitcoin||L===y.Chain.Litecoin?C:C.replace(/^m\//,""),I=Q.getNetworkForChain(O).bip32.public,V=await B.getExtendedPublicKey(A,I);return{accountIndex:Q.getUTXOAccountIndexFromPath(Z),path:C,xpub:V}}async function S({accountIndex:D,index:Z,change:C=!1}){try{let A=Q.getUTXOAddressPath({accountIndex:D,chain:O,change:C,derivationPath:R,index:Z}),I=await P({chain:O,derivationPath:A,transport:N}),V=await o({chain:O,ledgerClient:I});return{accountIndex:Q.getUTXOAccountIndexFromPath(A),address:V,change:C,index:Z,path:y.derivationPathToString(A),pubkey:""}}catch{return}}async function d({accountIndex:D,count:Z,startIndex:C=0,change:A=!1}){return Q.assertDerivationIndex("count",Z),Q.assertDerivationIndex("startIndex",C),(await Promise.all(Array.from({length:Z},(V,r)=>S({accountIndex:D,change:A,index:C+r})))).filter((V)=>!!V)}let F=Q.createHDWalletHelpers({chain:O,deriveAddress:S,getBalance:M.getBalance,getUtxos:(D)=>Q.getUtxoApi(O).getUtxos({address:D,fetchTxHex:!0})});async function z({utxos:D,recipient:Z,assetValue:C,memo:A,feeRate:I,feeOptionKey:V,changeAddress:r}){if(!D.length)throw new y.SwapKitError("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let i=I||(await M.getFeeRates())[V||y.FeeOption.Fast],v=A?Q.compileMemo(A):null,S_=[{address:Z,value:C.getBaseValue("number")}];if(v)S_.push({script:v,value:0});let h0=D.map(({hash:T_,index:$_,value:Z_,txHex:W_,witnessUtxo:J_})=>({hash:T_,index:$_,txHex:W_,value:Z_,witnessUtxo:J_})),{inputs:w_,outputs:V_}=M.accumulative({chain:O,feeRate:i,inputs:h0,outputs:S_});if(!(w_&&V_))throw new y.SwapKitError("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:u0}=await import("@swapkit/utxo-signer"),m_=new u0({allowLegacyWitnessUtxo:!0,version:1}),d0=r||D[0]?.address||Z;Q.addInputsAndOutputs({chain:O,compiledMemo:v,inputs:w_,outputs:V_,sender:d0,tx:m_});let o0=Q.getUTXOAccountPath({chain:O,derivationPath:R}),n0=w_.map((T_)=>{let $_=D.find((P_)=>P_.hash===T_.hash&&P_.index===T_.index),Z_=$_?.derivationIndex??0,W_=$_?.isChange??!1,J_=[...o0,Number(W_),Z_];return y.derivationPathToString(J_)});if(!B.signTransactionWithMultiplePaths)throw new y.SwapKitError("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let i0=await B.signTransactionWithMultiplePaths(m_,w_,n0);return M.broadcastTx(i0)}return{...M,...F,address:w,deriveAddressAtIndex:S,deriveAddresses:d,getExtendedPublicKey:k,getExtendedPublicKeyInfo:j,signAndBroadcastTransaction:W,transfer:q,transferFromMultipleAddresses:z}}case y.Chain.Ethereum:case y.Chain.Avalanche:case y.Chain.Arbitrum:case y.Chain.Arc:case y.Chain.Berachain:case y.Chain.Optimism:case y.Chain.Polygon:case y.Chain.BinanceSmartChain:case y.Chain.Base:case y.Chain.Aurora:case y.Chain.Gnosis:case y.Chain.Monad:case y.Chain.XLayer:{let{getEvmToolboxAsync:G}=await import("@swapkit/toolboxes/evm"),O=await P({chain:L,derivationPath:R,transport:N}),B=await o({chain:L,ledgerClient:O});return{...await G(L,{signer:O}),address:B}}case y.Chain.Cosmos:{let{createSigningStargateClient:G,getDefaultChainFee:O,getMsgSendDenom:B,getCosmosToolbox:w}=await import("@swapkit/toolboxes/cosmos"),T=await P({chain:L,derivationPath:R,transport:N}),U=await o({chain:L,ledgerClient:T});return{...await w(y.Chain.Cosmos,{signer:T}),address:U,transfer:async({assetValue:M,recipient:W,memo:q})=>{if(!M)throw new y.SwapKitError("wallet_ledger_invalid_asset");let j={amount:[{amount:M.getBaseValue("string"),denom:B(`u${M.symbol}`).toLowerCase()}],fromAddress:U,toAddress:W},k=await y.getRPCUrl(L),S=await G(k,T,"0.007uatom"),{transactionHash:d}=await S.signAndBroadcast(U,[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:j}],O(y.Chain.Cosmos),q);return d}}}case y.Chain.THORChain:{let G=await P({chain:L,derivationPath:R,transport:N}),{getCosmosToolbox:O}=await import("@swapkit/toolboxes/cosmos"),B=O(L,{signer:G}),w=await o({chain:L,ledgerClient:G}),{sign:T}=G;return{...B,address:w,signMessage:T}}case y.Chain.Near:{let{getNearToolbox:G}=await import("@swapkit/toolboxes/near"),O=await P({chain:L,derivationPath:R,transport:N}),B=await O.getAddress();return{...G({signer:O}),address:B}}case y.Chain.Ripple:{let{getRippleToolbox:G}=await import("@swapkit/toolboxes/ripple"),O=await P({chain:L,derivationPath:R,transport:N}),B=O.getAddress();return{...G({signer:O}),address:B}}case y.Chain.Tron:{let{getTronToolbox:G}=await import("@swapkit/toolboxes/tron"),O=await P({chain:L,derivationPath:R,transport:N}),B=await o({chain:L,ledgerClient:O});return{...G({signer:O}),address:B}}case y.Chain.Sui:{let{getSuiToolbox:G}=await import("@swapkit/toolboxes/sui"),O=await P({chain:L,derivationPath:R,transport:N}),B=await o({chain:L,ledgerClient:O});return{...G({signer:O}),address:B}}default:throw new y.SwapKitError("wallet_ledger_chain_not_supported",{chain:L})}}
|
|
1
|
+
var su=Object.create;var{getPrototypeOf:iu,defineProperty:Kq,getOwnPropertyNames:MP,getOwnPropertyDescriptor:au}=Object,TP=Object.prototype.hasOwnProperty;function NP(Q){return this[Q]}var ru,tu,JZ=(Q,Z,Y)=>{var $=Q!=null&&typeof Q==="object";if($){var J=Z?ru??=new WeakMap:tu??=new WeakMap,X=J.get(Q);if(X)return X}Y=Q!=null?su(iu(Q)):{};let G=Z||!Q||!Q.__esModule?Kq(Y,"default",{value:Q,enumerable:!0}):Y;for(let W of MP(Q))if(!TP.call(G,W))Kq(G,W,{get:NP.bind(Q,W),enumerable:!0});if($)J.set(Q,G);return G},oQ=(Q)=>{var Z=(AP??=new WeakMap).get(Q),Y;if(Z)return Z;if(Z=Kq({},"__esModule",{value:!0}),Q&&typeof Q==="object"||typeof Q==="function"){for(var $ of MP(Q))if(!TP.call(Z,$))Kq(Z,$,{get:NP.bind(Q,$),enumerable:!(Y=au(Q,$))||Y.enumerable})}return AP.set(Q,Z),Z},AP,XQ=(Q,Z)=>()=>(Z||Q((Z={exports:{}}).exports,Z),Z.exports);var eu=(Q)=>Q;function Qp(Q,Z){this[Q]=eu.bind(null,Z)}var j$=(Q,Z)=>{for(var Y in Z)Kq(Q,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:Qp.bind(Z,Y)})};var w=(Q,Z)=>()=>(Q&&(Z=Q(Q=0)),Z);var mJ=XQ(()=>{/*! *****************************************************************************
|
|
2
|
+
Copyright (C) Microsoft. All rights reserved.
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
4
|
+
this file except in compliance with the License. You may obtain a copy of the
|
|
5
|
+
License at http://www.apache.org/licenses/LICENSE-2.0
|
|
2
6
|
|
|
3
|
-
|
|
7
|
+
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
8
|
+
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
|
|
9
|
+
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
|
|
10
|
+
MERCHANTABLITY OR NON-INFRINGEMENT.
|
|
11
|
+
|
|
12
|
+
See the Apache Version 2.0 License for specific language governing permissions
|
|
13
|
+
and limitations under the License.
|
|
14
|
+
***************************************************************************** */var BP;(function(Q){(function(Z){var Y=typeof globalThis==="object"?globalThis:typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:W(),$=J(Q);if(typeof Y.Reflect<"u")$=J(Y.Reflect,$);if(Z($,Y),typeof Y.Reflect>"u")Y.Reflect=Q;function J(U,K){return function(O,I){if(Object.defineProperty(U,O,{configurable:!0,writable:!0,value:I}),K)K(O,I)}}function X(){try{return Function("return this;")()}catch(U){}}function G(){try{return(0,eval)("(function() { return this; })()")}catch(U){}}function W(){return X()||G()}})(function(Z,Y){var $=Object.prototype.hasOwnProperty,J=typeof Symbol==="function",X=J&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",G=J&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",W=typeof Object.create==="function",U={__proto__:[]}instanceof Array,K=!W&&!U,O={create:W?function(){return y0(Object.create(null))}:U?function(){return y0({__proto__:null})}:function(){return y0({})},has:K?function(s,M0){return $.call(s,M0)}:function(s,M0){return M0 in s},get:K?function(s,M0){return $.call(s,M0)?s[M0]:void 0}:function(s,M0){return s[M0]}},I=Object.getPrototypeOf(Function),L=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:c0(),A=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:u0(),M=typeof WeakMap==="function"?WeakMap:$Z(),k=J?Symbol.for("@reflect-metadata:registry"):void 0,B=QQ(),C=V0(B);function S(s,M0,G0,H0){if(!N(G0)){if(!j0(s))throw TypeError();if(!y(M0))throw TypeError();if(!y(H0)&&!N(H0)&&!T(H0))throw TypeError();if(T(H0))H0=void 0;return G0=Y0(G0),z(s,M0,G0,H0)}else{if(!j0(s))throw TypeError();if(!D0(M0))throw TypeError();return V(s,M0)}}Z("decorate",S);function _(s,M0){function G0(H0,KQ){if(!y(H0))throw TypeError();if(!N(KQ)&&!$Q(KQ))throw TypeError();j(s,M0,H0,KQ)}return G0}Z("metadata",_);function x(s,M0,G0,H0){if(!y(G0))throw TypeError();if(!N(H0))H0=Y0(H0);return j(s,M0,G0,H0)}Z("defineMetadata",x);function f(s,M0,G0){if(!y(M0))throw TypeError();if(!N(G0))G0=Y0(G0);return H(s,M0,G0)}Z("hasMetadata",f);function h(s,M0,G0){if(!y(M0))throw TypeError();if(!N(G0))G0=Y0(G0);return F(s,M0,G0)}Z("hasOwnMetadata",h);function i(s,M0,G0){if(!y(M0))throw TypeError();if(!N(G0))G0=Y0(G0);return D(s,M0,G0)}Z("getMetadata",i);function Z0(s,M0,G0){if(!y(M0))throw TypeError();if(!N(G0))G0=Y0(G0);return P(s,M0,G0)}Z("getOwnMetadata",Z0);function t(s,M0){if(!y(s))throw TypeError();if(!N(M0))M0=Y0(M0);return R(s,M0)}Z("getMetadataKeys",t);function c(s,M0){if(!y(s))throw TypeError();if(!N(M0))M0=Y0(M0);return q(s,M0)}Z("getOwnMetadataKeys",c);function l(s,M0,G0){if(!y(M0))throw TypeError();if(!N(G0))G0=Y0(G0);if(!y(M0))throw TypeError();if(!N(G0))G0=Y0(G0);var H0=jQ(M0,G0,!1);if(N(H0))return!1;return H0.OrdinaryDeleteMetadata(s,M0,G0)}Z("deleteMetadata",l);function V(s,M0){for(var G0=s.length-1;G0>=0;--G0){var H0=s[G0],KQ=H0(M0);if(!N(KQ)&&!T(KQ)){if(!D0(KQ))throw TypeError();M0=KQ}}return M0}function z(s,M0,G0,H0){for(var KQ=s.length-1;KQ>=0;--KQ){var f0=s[KQ],h0=f0(M0,G0,H0);if(!N(h0)&&!T(h0)){if(!y(h0))throw TypeError();H0=h0}}return H0}function H(s,M0,G0){var H0=F(s,M0,G0);if(H0)return!0;var KQ=d(M0);if(!T(KQ))return H(s,KQ,G0);return!1}function F(s,M0,G0){var H0=jQ(M0,G0,!1);if(N(H0))return!1;return x0(H0.OrdinaryHasOwnMetadata(s,M0,G0))}function D(s,M0,G0){var H0=F(s,M0,G0);if(H0)return P(s,M0,G0);var KQ=d(M0);if(!T(KQ))return D(s,KQ,G0);return}function P(s,M0,G0){var H0=jQ(M0,G0,!1);if(N(H0))return;return H0.OrdinaryGetOwnMetadata(s,M0,G0)}function j(s,M0,G0,H0){var KQ=jQ(G0,H0,!0);KQ.OrdinaryDefineOwnMetadata(s,M0,G0,H0)}function R(s,M0){var G0=q(s,M0),H0=d(s);if(H0===null)return G0;var KQ=R(H0,M0);if(KQ.length<=0)return G0;if(G0.length<=0)return KQ;var f0=new A,h0=[];for(var LQ=0,E0=G0;LQ<E0.length;LQ++){var A0=E0[LQ],GQ=f0.has(A0);if(!GQ)f0.add(A0),h0.push(A0)}for(var T0=0,S0=KQ;T0<S0.length;T0++){var A0=S0[T0],GQ=f0.has(A0);if(!GQ)f0.add(A0),h0.push(A0)}return h0}function q(s,M0){var G0=jQ(s,M0,!1);if(!G0)return[];return G0.OrdinaryOwnMetadataKeys(s,M0)}function E(s){if(s===null)return 1;switch(typeof s){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return s===null?1:6;default:return 6}}function N(s){return s===void 0}function T(s){return s===null}function v(s){return typeof s==="symbol"}function y(s){return typeof s==="object"?s!==null:typeof s==="function"}function p(s,M0){switch(E(s)){case 0:return s;case 1:return s;case 2:return s;case 3:return s;case 4:return s;case 5:return s}var G0=M0===3?"string":M0===5?"number":"default",H0=n(s,X);if(H0!==void 0){var KQ=H0.call(s,G0);if(y(KQ))throw TypeError();return KQ}return J0(s,G0==="default"?"number":G0)}function J0(s,M0){if(M0==="string"){var G0=s.toString;if($0(G0)){var H0=G0.call(s);if(!y(H0))return H0}var KQ=s.valueOf;if($0(KQ)){var H0=KQ.call(s);if(!y(H0))return H0}}else{var KQ=s.valueOf;if($0(KQ)){var H0=KQ.call(s);if(!y(H0))return H0}var f0=s.toString;if($0(f0)){var H0=f0.call(s);if(!y(H0))return H0}}throw TypeError()}function x0(s){return!!s}function K0(s){return""+s}function Y0(s){var M0=p(s,3);if(v(M0))return M0;return K0(M0)}function j0(s){return Array.isArray?Array.isArray(s):s instanceof Object?s instanceof Array:Object.prototype.toString.call(s)==="[object Array]"}function $0(s){return typeof s==="function"}function D0(s){return typeof s==="function"}function $Q(s){switch(E(s)){case 3:return!0;case 4:return!0;default:return!1}}function m(s,M0){return s===M0||s!==s&&M0!==M0}function n(s,M0){var G0=s[M0];if(G0===void 0||G0===null)return;if(!$0(G0))throw TypeError();return G0}function B0(s){var M0=n(s,G);if(!$0(M0))throw TypeError();var G0=M0.call(s);if(!y(G0))throw TypeError();return G0}function F0(s){return s.value}function z0(s){var M0=s.next();return M0.done?!1:M0}function l0(s){var M0=s.return;if(M0)M0.call(s)}function d(s){var M0=Object.getPrototypeOf(s);if(typeof s!=="function"||s===I)return M0;if(M0!==I)return M0;var G0=s.prototype,H0=G0&&Object.getPrototypeOf(G0);if(H0==null||H0===Object.prototype)return M0;var KQ=H0.constructor;if(typeof KQ!=="function")return M0;if(KQ===s)return M0;return KQ}function X0(){var s;if(!N(k)&&typeof Y.Reflect<"u"&&!(k in Y.Reflect)&&typeof Y.Reflect.defineMetadata==="function")s=P0(Y.Reflect);var M0,G0,H0,KQ=new M,f0={registerProvider:h0,getProvider:E0,setProvider:GQ};return f0;function h0(T0){if(!Object.isExtensible(f0))throw Error("Cannot add provider to a frozen registry.");switch(!0){case s===T0:break;case N(M0):M0=T0;break;case M0===T0:break;case N(G0):G0=T0;break;case G0===T0:break;default:if(H0===void 0)H0=new A;H0.add(T0);break}}function LQ(T0,S0){if(!N(M0)){if(M0.isProviderFor(T0,S0))return M0;if(!N(G0)){if(G0.isProviderFor(T0,S0))return M0;if(!N(H0)){var gQ=B0(H0);while(!0){var g0=z0(gQ);if(!g0)return;var d0=F0(g0);if(d0.isProviderFor(T0,S0))return l0(gQ),d0}}}}if(!N(s)&&s.isProviderFor(T0,S0))return s;return}function E0(T0,S0){var gQ=KQ.get(T0),g0;if(!N(gQ))g0=gQ.get(S0);if(!N(g0))return g0;if(g0=LQ(T0,S0),!N(g0)){if(N(gQ))gQ=new L,KQ.set(T0,gQ);gQ.set(S0,g0)}return g0}function A0(T0){if(N(T0))throw TypeError();return M0===T0||G0===T0||!N(H0)&&H0.has(T0)}function GQ(T0,S0,gQ){if(!A0(gQ))throw Error("Metadata provider not registered.");var g0=E0(T0,S0);if(g0!==gQ){if(!N(g0))return!1;var d0=KQ.get(T0);if(N(d0))d0=new L,KQ.set(T0,d0);d0.set(S0,gQ)}return!0}}function QQ(){var s;if(!N(k)&&y(Y.Reflect)&&Object.isExtensible(Y.Reflect))s=Y.Reflect[k];if(N(s))s=X0();if(!N(k)&&y(Y.Reflect)&&Object.isExtensible(Y.Reflect))Object.defineProperty(Y.Reflect,k,{enumerable:!1,configurable:!1,writable:!1,value:s});return s}function V0(s){var M0=new M,G0={isProviderFor:function(A0,GQ){var T0=M0.get(A0);if(N(T0))return!1;return T0.has(GQ)},OrdinaryDefineOwnMetadata:h0,OrdinaryHasOwnMetadata:KQ,OrdinaryGetOwnMetadata:f0,OrdinaryOwnMetadataKeys:LQ,OrdinaryDeleteMetadata:E0};return B.registerProvider(G0),G0;function H0(A0,GQ,T0){var S0=M0.get(A0),gQ=!1;if(N(S0)){if(!T0)return;S0=new L,M0.set(A0,S0),gQ=!0}var g0=S0.get(GQ);if(N(g0)){if(!T0)return;if(g0=new L,S0.set(GQ,g0),!s.setProvider(A0,GQ,G0)){if(S0.delete(GQ),gQ)M0.delete(A0);throw Error("Wrong provider for target.")}}return g0}function KQ(A0,GQ,T0){var S0=H0(GQ,T0,!1);if(N(S0))return!1;return x0(S0.has(A0))}function f0(A0,GQ,T0){var S0=H0(GQ,T0,!1);if(N(S0))return;return S0.get(A0)}function h0(A0,GQ,T0,S0){var gQ=H0(T0,S0,!0);gQ.set(A0,GQ)}function LQ(A0,GQ){var T0=[],S0=H0(A0,GQ,!1);if(N(S0))return T0;var gQ=S0.keys(),g0=B0(gQ),d0=0;while(!0){var _Z=z0(g0);if(!_Z)return T0.length=d0,T0;var o0=F0(_Z);try{T0[d0]=o0}catch(b){try{l0(g0)}finally{throw b}}d0++}}function E0(A0,GQ,T0){var S0=H0(GQ,T0,!1);if(N(S0))return!1;if(!S0.delete(A0))return!1;if(S0.size===0){var gQ=M0.get(GQ);if(!N(gQ)){if(gQ.delete(T0),gQ.size===0)M0.delete(gQ)}}return!0}}function P0(s){var{defineMetadata:M0,hasOwnMetadata:G0,getOwnMetadata:H0,getOwnMetadataKeys:KQ,deleteMetadata:f0}=s,h0=new M,LQ={isProviderFor:function(E0,A0){var GQ=h0.get(E0);if(!N(GQ)&&GQ.has(A0))return!0;if(KQ(E0,A0).length){if(N(GQ))GQ=new A,h0.set(E0,GQ);return GQ.add(A0),!0}return!1},OrdinaryDefineOwnMetadata:M0,OrdinaryHasOwnMetadata:G0,OrdinaryGetOwnMetadata:H0,OrdinaryOwnMetadataKeys:KQ,OrdinaryDeleteMetadata:f0};return LQ}function jQ(s,M0,G0){var H0=B.getProvider(s,M0);if(!N(H0))return H0;if(G0){if(B.setProvider(s,M0,C))return C;throw Error("Illegal state.")}return}function c0(){var s={},M0=[],G0=function(){function LQ(E0,A0,GQ){this._index=0,this._keys=E0,this._values=A0,this._selector=GQ}return LQ.prototype["@@iterator"]=function(){return this},LQ.prototype[G]=function(){return this},LQ.prototype.next=function(){var E0=this._index;if(E0>=0&&E0<this._keys.length){var A0=this._selector(this._keys[E0],this._values[E0]);if(E0+1>=this._keys.length)this._index=-1,this._keys=M0,this._values=M0;else this._index++;return{value:A0,done:!1}}return{value:void 0,done:!0}},LQ.prototype.throw=function(E0){if(this._index>=0)this._index=-1,this._keys=M0,this._values=M0;throw E0},LQ.prototype.return=function(E0){if(this._index>=0)this._index=-1,this._keys=M0,this._values=M0;return{value:E0,done:!0}},LQ}(),H0=function(){function LQ(){this._keys=[],this._values=[],this._cacheKey=s,this._cacheIndex=-2}return Object.defineProperty(LQ.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),LQ.prototype.has=function(E0){return this._find(E0,!1)>=0},LQ.prototype.get=function(E0){var A0=this._find(E0,!1);return A0>=0?this._values[A0]:void 0},LQ.prototype.set=function(E0,A0){var GQ=this._find(E0,!0);return this._values[GQ]=A0,this},LQ.prototype.delete=function(E0){var A0=this._find(E0,!1);if(A0>=0){var GQ=this._keys.length;for(var T0=A0+1;T0<GQ;T0++)this._keys[T0-1]=this._keys[T0],this._values[T0-1]=this._values[T0];if(this._keys.length--,this._values.length--,m(E0,this._cacheKey))this._cacheKey=s,this._cacheIndex=-2;return!0}return!1},LQ.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=s,this._cacheIndex=-2},LQ.prototype.keys=function(){return new G0(this._keys,this._values,KQ)},LQ.prototype.values=function(){return new G0(this._keys,this._values,f0)},LQ.prototype.entries=function(){return new G0(this._keys,this._values,h0)},LQ.prototype["@@iterator"]=function(){return this.entries()},LQ.prototype[G]=function(){return this.entries()},LQ.prototype._find=function(E0,A0){if(!m(this._cacheKey,E0)){this._cacheIndex=-1;for(var GQ=0;GQ<this._keys.length;GQ++)if(m(this._keys[GQ],E0)){this._cacheIndex=GQ;break}}if(this._cacheIndex<0&&A0)this._cacheIndex=this._keys.length,this._keys.push(E0),this._values.push(void 0);return this._cacheIndex},LQ}();return H0;function KQ(LQ,E0){return LQ}function f0(LQ,E0){return E0}function h0(LQ,E0){return[LQ,E0]}}function u0(){var s=function(){function M0(){this._map=new L}return Object.defineProperty(M0.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),M0.prototype.has=function(G0){return this._map.has(G0)},M0.prototype.add=function(G0){return this._map.set(G0,G0),this},M0.prototype.delete=function(G0){return this._map.delete(G0)},M0.prototype.clear=function(){this._map.clear()},M0.prototype.keys=function(){return this._map.keys()},M0.prototype.values=function(){return this._map.keys()},M0.prototype.entries=function(){return this._map.entries()},M0.prototype["@@iterator"]=function(){return this.keys()},M0.prototype[G]=function(){return this.keys()},M0}();return s}function $Z(){var s=16,M0=O.create(),G0=H0();return function(){function E0(){this._key=H0()}return E0.prototype.has=function(A0){var GQ=KQ(A0,!1);return GQ!==void 0?O.has(GQ,this._key):!1},E0.prototype.get=function(A0){var GQ=KQ(A0,!1);return GQ!==void 0?O.get(GQ,this._key):void 0},E0.prototype.set=function(A0,GQ){var T0=KQ(A0,!0);return T0[this._key]=GQ,this},E0.prototype.delete=function(A0){var GQ=KQ(A0,!1);return GQ!==void 0?delete GQ[this._key]:!1},E0.prototype.clear=function(){this._key=H0()},E0}();function H0(){var E0;do E0="@@WeakMap@@"+LQ();while(O.has(M0,E0));return M0[E0]=!0,E0}function KQ(E0,A0){if(!$.call(E0,G0)){if(!A0)return;Object.defineProperty(E0,G0,{value:O.create()})}return E0[G0]}function f0(E0,A0){for(var GQ=0;GQ<A0;++GQ)E0[GQ]=Math.random()*255|0;return E0}function h0(E0){if(typeof Uint8Array==="function"){var A0=new Uint8Array(E0);if(typeof crypto<"u")crypto.getRandomValues(A0);else if(typeof msCrypto<"u")msCrypto.getRandomValues(A0);else f0(A0,E0);return A0}return f0(Array(E0),E0)}function LQ(){var E0=h0(s);E0[6]=E0[6]&79|64,E0[8]=E0[8]&191|128;var A0="";for(var GQ=0;GQ<s;++GQ){var T0=E0[GQ];if(GQ===4||GQ===6||GQ===8)A0+="-";if(T0<16)A0+="0";A0+=T0.toString(16).toLowerCase()}return A0}}function y0(s){return s.__=void 0,delete s.__,s}})})(BP||(BP={}))});class PG{cla;ins;p1;p2;data;constructor(Q,Z,Y,$,J){this.cla=Q,this.ins=Z,this.p1=Y,this.p2=$,this.data=J??new Uint8Array}getRawApdu(){let Q=Uint8Array.from([this.cla,this.ins,this.p1,this.p2,this.data.length]),Z=new Uint8Array(Q.length+this.data.length);return Z.set(Q,0),this.data.length>0&&Z.set(this.data,Q.length),Z}}var LO=()=>{};function dQ(Q){return typeof Q=="string"&&/^0x[0-9a-fA-F]*$/.test(Q)}function mQ(Q){if(Q.startsWith("0x")&&(Q=Q.slice(2)),Q.length===0)return new Uint8Array;if(Q.length%2!==0&&(Q="0"+Q),/^[0-9a-fA-F]*$/.test(Q)===!1)return null;let Z=Q.match(/.{1,2}/g)?.map((Y)=>parseInt(Y,16));return!Z||Z.some(isNaN)?null:new Uint8Array(Z)}function DQ(Q,Z=!0){return`${Z?"0x":""}${Array.from(Q,(Y)=>Y.toString(16).padStart(2,"0")).join("")}`}var O8=()=>{};class bX{_tag="ValueOverflow";originalError;message;constructor(Q,Z=YZ){this.message=`Value overflow for ${Q}, max is ${Z}`}}class jG{_tag="DataOverflow";message;originalError;constructor(Q,Z=0){this.message=Z===0?`this.data is already full (value: ${Q})`:`this.data will overflow with "${Q}", remaining bytes: ${Z}`}}class Oq{_tag="HexaString";message;originalError;constructor(Q){this.message=`Invalid encoded hexa string or length is null: ${Q}`}}var EO=w(()=>{a$()});class WQ{constructor(Q=Wp){this.maxPayloadSize=Q}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=(Q)=>this.addNumberToData(Q,8n,!1,!1);add16BitUIntToData=(Q,Z=!0)=>this.addNumberToData(Q,16n,!1,Z);add32BitUIntToData=(Q,Z=!0)=>this.addNumberToData(Q,32n,!1,Z);add64BitUIntToData=(Q,Z=!0)=>this.addNumberToData(Q,64n,!1,Z);add128BitUIntToData=(Q,Z=!0)=>this.addNumberToData(Q,128n,!1,Z);add256BitUIntToData=(Q,Z=!0)=>this.addNumberToData(Q,256n,!1,Z);add16BitIntToData=(Q,Z=!0)=>this.addNumberToData(Q,16n,!0,Z);add32BitIntToData=(Q,Z=!0)=>this.addNumberToData(Q,32n,!0,Z);add64BitIntToData=(Q,Z=!0)=>this.addNumberToData(Q,64n,!0,Z);add128BitIntToData=(Q,Z=!0)=>this.addNumberToData(Q,128n,!0,Z);add256BitIntToData=(Q,Z=!0)=>this.addNumberToData(Q,256n,!0,Z);addBufferToData=(Q)=>this.hasEnoughLengthRemaining(Q)?(this.data=Uint8Array.from([...this.data,...Q]),this):(this.errors.push(new jG(Q.toString())),this);addHexaStringToData=(Q)=>{let Z=mQ(Q);return Z===null||Z.length===0?(this.errors.push(new Oq(Q)),this):(this.addBufferToData(Z),this)};addAsciiStringToData=(Q)=>{let Z=new TextEncoder().encode(Q);return this.addBufferToData(Z),this};encodeInLVFromHexa=(Q)=>{let Z=mQ(Q);return Z===null||Z.length===0?(this.errors.push(new Oq(Q)),this):this.hasEnoughLengthRemaining(Z,!0)?(this.add8BitUIntToData(Z.length),this.addBufferToData(Z),this):(this.errors.push(new jG(Q)),this)};encodeInLVFromBuffer=(Q)=>this.hasEnoughLengthRemaining(Q,!0)?(this.add8BitUIntToData(Q.length),this.addBufferToData(Q),this):(this.errors.push(new jG(Q.toString())),this);encodeInLVFromAscii=(Q)=>this.hasEnoughLengthRemaining(Q,!0)?(this.add8BitUIntToData(Q.length),this.addAsciiStringToData(Q),this):(this.errors.push(new jG(Q)),this);encodeInTLVFromAscii=(Q,Z)=>(this.add8BitUIntToData(Q),this.encodeInLVFromAscii(Z));encodeInTLVFromHexa=(Q,Z)=>(this.add8BitUIntToData(Q),this.encodeInLVFromHexa(Z));encodeInTLVFromBuffer=(Q,Z)=>(this.add8BitUIntToData(Q),this.encodeInLVFromBuffer(Z));encodeInTLVFromUInt8=(Q,Z)=>(this.add8BitUIntToData(Q),this.add8BitUIntToData(1),this.add8BitUIntToData(Z));encodeInTLVFromUInt16=(Q,Z,Y=!0)=>(this.add8BitUIntToData(Q),this.add8BitUIntToData(2),this.add16BitUIntToData(Z,Y));encodeInTLVFromUInt32=(Q,Z,Y=!0)=>(this.add8BitUIntToData(Q),this.add8BitUIntToData(4),this.add32BitUIntToData(Z,Y));encodeInTLVFromUInt64=(Q,Z,Y=!0)=>(this.add8BitUIntToData(Q),this.add8BitUIntToData(8),this.add64BitUIntToData(Z,Y));getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(Q,Z=!1)=>this.data.length+Q.length+(Z?1:0)<=this.maxPayloadSize;addNumberToData(Q,Z,Y,$){let J=this.checkBoundsAndConvert(Q,Z,Y);if(J===void 0)return this;let X=Number(Z)/8,G=new Uint8Array(X);if($)for(let W=X-1;W>=0;W--)G[W]=Number(J&0xffn),J>>=8n;else for(let W=0;W<X;W++)G[W]=Number(J&0xffn),J>>=8n;return this.addBufferToData(G)}checkBoundsAndConvert(Q,Z,Y){if(typeof Q=="number"){if(!Number.isInteger(Q)||Q>Number.MAX_SAFE_INTEGER){this.errors.push(new bX(Q.toString()));return}Q=BigInt(Q)}if(Y){let $=1n<<Z-1n;if(Q>=$||Q<-$){this.errors.push(new bX(Q.toString(),$-1n));return}if(Q<0n){let J=(1n<<Z)-1n;Q=-Q,Q=(~Q&J)+1n}}else{let $=1n<<Z;if(Q<0||Q>=$){this.errors.push(new bX(Q.toString(),$-1n));return}}return Q}}var Wp=4294967295;var PO=w(()=>{O8();EO()});class w0{_ins;_cla;_p1;p2;data=new WQ(YZ);constructor({ins:Q,cla:Z,p1:Y,p2:$}){this._cla=Z&255,this._ins=Q&255,this._p1=Y&255,this.p2=$&255}build=()=>new PG(this._cla,this._ins,this._p1,this.p2,this.data.build());add8BitUIntToData=(Q)=>(this.data.add8BitUIntToData(Q),this);add16BitUIntToData=(Q)=>(this.data.add16BitUIntToData(Q),this);add32BitUIntToData=(Q)=>(this.data.add32BitUIntToData(Q),this);add64BitUIntToData=(Q,Z=!0)=>(this.data.add64BitUIntToData(Q,Z),this);addBufferToData=(Q)=>(this.data.addBufferToData(Q),this);addHexaStringToData=(Q)=>(this.data.addHexaStringToData(Q),this);addAsciiStringToData=(Q)=>(this.data.addAsciiStringToData(Q),this);encodeInLVFromHexa=(Q)=>(this.data.encodeInLVFromHexa(Q),this);encodeInLVFromBuffer=(Q)=>(this.data.encodeInLVFromBuffer(Q),this);encodeInLVFromAscii=(Q)=>(this.data.encodeInLVFromAscii(Q),this);getAvailablePayloadLength=()=>this.data.getAvailablePayloadLength();getErrors=()=>this.data.getErrors()}var YZ=255,D60;var a$=w(()=>{LO();PO();D60=YZ+5});class BY{constructor(Q){this.buffer=Q}index=0;testMinimalLength(Q){return Q<=this.buffer.length-this.index}extract8BitUInt(){if(!this.outOfRange(1))return this.buffer[this.index++]}extract16BitUInt(Q=!0){let Z=this.extractNumber(16n,!1,Q);return Z===void 0?void 0:Number(Z)}extract16BitInt(Q=!0){let Z=this.extractNumber(16n,!0,Q);return Z===void 0?void 0:Number(Z)}extract32BitUInt(Q=!0){let Z=this.extractNumber(32n,!1,Q);return Z===void 0?void 0:Number(Z)}extract32BitInt(Q=!0){let Z=this.extractNumber(32n,!0,Q);return Z===void 0?void 0:Number(Z)}extract64BitUInt(Q=!0){return this.extractNumber(64n,!1,Q)}extract64BitInt(Q=!0){return this.extractNumber(64n,!0,Q)}extract128BitUInt(Q=!0){return this.extractNumber(128n,!1,Q)}extract128BitInt(Q=!0){return this.extractNumber(128n,!0,Q)}extract256BitUInt(Q=!0){return this.extractNumber(256n,!1,Q)}extract256BitInt(Q=!0){return this.extractNumber(256n,!0,Q)}extractFieldByLength(Q){if(this.outOfRange(Q))return;if(Q===0)return new Uint8Array;let Z=this.buffer.slice(this.index,this.index+Q);return this.index+=Q,Z}extractFieldLVEncoded(){let Q=this.extract8BitUInt();if(Q===void 0)return;if(Q===0)return new Uint8Array;let Z=this.extractFieldByLength(Q);return Z===void 0&&this.index--,Z}extractFieldTLVEncoded(){if(this.outOfRange(2))return;let Q=this.index,Z=this.extract8BitUInt(),Y=this.extractFieldLVEncoded();if(Z===void 0||Y===void 0){this.index--;return}let $=this.index;return{tag:Z,value:Y,tlv:this.buffer.slice(Q,$)}}encodeToHexaString(Q,Z=!1){if(Q===void 0||Q.length===0)return"";let Y=DQ(Q);return Z?Y:Y.slice(2)}encodeToString(Q){let Z="",Y=0;if(!Q)return Z;for(;Y<=Q.length;){let $=Q[Y];$&&(Z+=String.fromCharCode($)),Y++}return Z}getCurrentIndex(){return this.index}resetIndex(){this.index=0}getUnparsedRemainingLength(){return this.buffer.length-this.index}outOfRange(Q){return this.index+Q>this.buffer.length}extractNumber(Q,Z,Y){let $=Number(Q)/8;if(this.outOfRange($))return;let J=0n;if(Y)for(let X=0;X<$;X++)J=J<<8n|BigInt(this.buffer[X+this.index]);else for(let X=$-1;X>=0;X--)J=J<<8n|BigInt(this.buffer[X+this.index]);if(Z){let X=1n<<Q-1n;J&X&&(J-=X<<1n)}return this.index+=$,J}}var jO=w(()=>{O8()});class FQ{parser;constructor(Q){this.parser=new BY(Q.data)}testMinimalLength=(Q)=>this.parser.testMinimalLength(Q);extract8BitUInt=()=>this.parser.extract8BitUInt();extract16BitUInt=()=>this.parser.extract16BitUInt();extract32BitUInt=()=>this.parser.extract32BitUInt();extractFieldByLength=(Q)=>this.parser.extractFieldByLength(Q);extractFieldLVEncoded=()=>this.parser.extractFieldLVEncoded();extractFieldTLVEncoded=()=>this.parser.extractFieldTLVEncoded();encodeToHexaString(Q,Z=!1){return Z?this.parser.encodeToHexaString(Q,!0):this.parser.encodeToHexaString(Q,!1)}encodeToString=(Q)=>this.parser.encodeToString(Q);getUnparsedRemainingLength=()=>this.parser.getUnparsedRemainingLength()}var r$=w(()=>{jO()});class C0{_tag="InvalidStatusWordError";originalError;constructor(Q){this.originalError=Error(Q??"Invalid status word.")}}class AG{_tag="InvalidResponseFormatError";originalError;constructor(Q){this.originalError=Error(Q??"Invalid response format.")}}var MG=()=>{};function Kp(Q){return"error"in Q&&Q.error!==void 0}function zQ(Q){return Kp(Q)?{status:"ERROR",error:Q.error}:{status:"SUCCESS",data:Q.data}}function t$(Q){return Q.status==="SUCCESS"}var Hq;var TG=w(()=>{Hq=((Q)=>(Q.Error="ERROR",Q.Success="SUCCESS",Q))(Hq||{})});function o({data:Q,error:Z}){return Z!==void 0?zQ({error:Z}):zQ({data:Q})}function N0(Q){return t$(Q)}var TZ=w(()=>{TG()});class hQ{static isValidStatusCode(Q){return Q.length===2}static isSuccessResponse({statusCode:Q}){return hQ.isValidStatusCode(Q)?Q[0]===144&&Q[1]===0:!1}static isLockedDeviceResponse({statusCode:Q}){return hQ.isValidStatusCode(Q)?Q[0]===85&&Q[1]===21||Q[0]===105&&Q[1]===130||Q[0]===83&&Q[1]===3:!1}static isRefusedByUser({statusCode:Q}){return hQ.isValidStatusCode(Q)?Q[0]===85&&Q[1]===1||Q[0]===105&&Q[1]===133:!1}static isAppAlreadyInstalled({statusCode:Q}){return hQ.isValidStatusCode(Q)?Q[0]===106&&Q[1]===128||Q[0]===106&&Q[1]===129||Q[0]===106&&Q[1]===142||Q[0]===106&&Q[1]===143:!1}static isOutOfMemory({statusCode:Q}){return hQ.isValidStatusCode(Q)?Q[0]===106&&Q[1]===132||Q[0]===106&&Q[1]===133||Q[0]===81&&Q[1]===2||Q[0]===81&&Q[1]===3:!1}static isApduThatTriggersDisconnection(Q){let Z=new Map;return Z.set("openApp",new Uint8Array([224,216,0,0])),Z.set("closeApp",new Uint8Array([176,167,0,0])),Array.from(Z.values()).some((Y)=>{for(let $=0;$<4;$++)if(Y[$]!==Q[$])return!1;return!0})}}var oY=()=>{};class DZ{_tag;originalError;errorCode;message;constructor({tag:Q,errorCode:Z,originalError:Y,message:$}){this._tag=Q,this.originalError=Y,this.errorCode=Z,this.message=$??"An error occured during device exchange."}}class sY{_tag="UnknownDeviceExchangeError";originalError;message;constructor(Q){this.originalError=Q,this.message="Unexpected device exchange error happened."}}class kP{_tag="DeviceBusyError";originalError;constructor(Q){this.originalError=Q??Error("Device is busy, please try again later")}}class Dq{_tag="InvalidArgumentError";originalError;constructor(Q){this.originalError=Error(Q??"Invalid argument.")}}var dJ=()=>{};var kY=(Q,Z)=>Object.keys(Z).includes(Q);var I1=()=>{};class NZ{static handle(Q){let Z=new FQ(Q).encodeToHexaString(Q.statusCode);return kY(Z,s4)?new i4({...s4[Z],errorCode:Z}):new sY({message:"UnknownError",errorCode:Z})}}var i4,s4;var VJ=w(()=>{r$();dJ();I1();i4=class i4 extends DZ{constructor(Q){super({tag:"GlobalCommandError",...Q})}};s4={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"}}});class NG{name="closeApp";args=void 0;triggersDisconnection=!0;getApdu(){return new w0({cla:176,ins:167,p1:0,p2:0}).build()}parseResponse(Q){return hQ.isSuccessResponse(Q)?o({data:void 0}):o({error:NZ.handle(Q)})}}var a4=w(()=>{a$();TZ();oY();VJ()});class Iq{constructor(Q){this.args=Q}name="deleteLanguagePack";getApdu(){let Q={cla:224,ins:51,p1:this.args.languagePackageId,p2:0};return new w0(Q).build()}parseResponse(Q){let Z=new FQ(Q);if(!hQ.isSuccessResponse(Q)){let Y=Z.encodeToHexaString(Q.statusCode);return kY(Y,CP)?o({error:new r4({...CP[Y],errorCode:Y})}):o({error:NZ.handle(Q)})}return o({data:void 0})}}var CP,r4;var AO=w(()=>{a$();r$();TZ();I1();oY();VJ();dJ();CP={"681a":{message:"Invalid LANG_ID value."}};r4=class r4 extends DZ{constructor({message:Q,errorCode:Z}){super({message:Q,errorCode:Z,tag:"DeleteLanguagePackCommandError"})}}});class e${name="getAppAndVersion";args=void 0;getApdu(){return new w0({cla:176,ins:1,p1:0,p2:0}).build()}parseResponse(Q){if(!hQ.isSuccessResponse(Q))return o({error:NZ.handle(Q)});let Z=new FQ(Q);if(Z.extract8BitUInt()!==1)return o({error:new AG("getAppAndVersion: format not supported")});let Y=Z.encodeToString(Z.extractFieldLVEncoded()),$=Z.encodeToString(Z.extractFieldLVEncoded());if(Z.getUnparsedRemainingLength()===0)return o({data:{name:Y,version:$}});let J=Z.extractFieldLVEncoded();return o({data:{name:Y,version:$,flags:J}})}}var Rq=w(()=>{a$();r$();MG();TZ();oY();VJ()});class Lq{name="getBackgroundImageSize";getApdu(){return new w0({cla:224,ins:100,p1:0,p2:0}).build()}parseResponse(Q){let Z=new FQ(Q);if(!hQ.isSuccessResponse(Q)){let $=Z.encodeToHexaString(Q.statusCode);return kY($,SP)?o({error:new t4({...SP[$],errorCode:$})}):o({error:NZ.handle(Q)})}let Y=Z.extract32BitUInt();return Y===void 0?o({error:new C0("Didn't receive any size")}):o({data:Y})}}var SP,t4;var MO=w(()=>{a$();r$();MG();TZ();I1();oY();VJ();dJ();SP={"662e":{message:"Invalid state, no background image loaded."},"662f":{message:"Invalid state, device is in recovery mode."}};t4=class t4 extends DZ{constructor({message:Q,errorCode:Z}){super({message:Q,errorCode:Z,tag:"GetBackgroundImageSizeCommandError"})}}});class NO{name="getBatteryStatus";args;constructor(Q){this.args=Q}getApdu(){let Q={cla:224,ins:16,p1:0,p2:this.args.statusType};return new w0(Q).build()}parseResponse(Q){if(!hQ.isSuccessResponse(Q))return o({error:NZ.handle(Q)});let Z=new FQ(Q),Y=($)=>o({error:new AG($)});switch(this.args.statusType){case 0:{let $=Z.extract8BitUInt();return $===void 0?Y("getBatteryStatus: missing battery percentage in response"):o({data:$>100?-1:$})}case 1:{let $=Z.extract16BitUInt();return $===void 0?Y("getBatteryStatus: missing battery voltage in response"):o({data:$})}case 2:case 3:{let $=Z.extract8BitUInt();return $===void 0?Y(this.args.statusType===2?"getBatteryStatus: missing battery temperature in response":"getBatteryStatus: missing battery current in response"):o({data:$<<24>>24})}case 4:{let $=Z.extract32BitUInt();if($===void 0)return Y("getBatteryStatus: missing battery flags in response");let J=!!($&8),X=!J&&!!($&1);return o({data:{charging:X?2:J?1:0,issueCharging:!!($&16),issueTemperature:!!($&32),issueBattery:!!($&128)}})}default:return Y("getBatteryStatus: unsupported battery status type")}}}var TO,Up;var wP=w(()=>{a$();r$();MG();TZ();oY();VJ();TO=((Q)=>(Q[Q.BATTERY_PERCENTAGE=0]="BATTERY_PERCENTAGE",Q[Q.BATTERY_VOLTAGE=1]="BATTERY_VOLTAGE",Q[Q.BATTERY_TEMPERATURE=2]="BATTERY_TEMPERATURE",Q[Q.BATTERY_CURRENT=3]="BATTERY_CURRENT",Q[Q.BATTERY_FLAGS=4]="BATTERY_FLAGS",Q))(TO||{}),Up=((Q)=>(Q[Q.NONE=0]="NONE",Q[Q.USB=1]="USB",Q[Q.QI=2]="QI",Q))(Up||{})});var Eq=XQ((HF0,_P)=>{var Op=Number.MAX_SAFE_INTEGER||9007199254740991,Hp=["major","premajor","minor","preminor","patch","prepatch","prerelease"];_P.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:Op,RELEASE_TYPES:Hp,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Pq=XQ((DF0,vP)=>{var Dp=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...Q)=>console.error("SEMVER",...Q):()=>{};vP.exports=Dp});var cX=XQ((nJ,xP)=>{var{MAX_SAFE_COMPONENT_LENGTH:BO,MAX_SAFE_BUILD_LENGTH:Ip,MAX_LENGTH:Rp}=Eq(),Lp=Pq();nJ=xP.exports={};var Ep=nJ.re=[],Pp=nJ.safeRe=[],UQ=nJ.src=[],jp=nJ.safeSrc=[],OQ=nJ.t={},Ap=0,kO="[a-zA-Z0-9-]",Mp=[["\\s",1],["\\d",Rp],[kO,Ip]],Tp=(Q)=>{for(let[Z,Y]of Mp)Q=Q.split(`${Z}*`).join(`${Z}{0,${Y}}`).split(`${Z}+`).join(`${Z}{1,${Y}}`);return Q},uQ=(Q,Z,Y)=>{let $=Tp(Z),J=Ap++;Lp(Q,J,Z),OQ[Q]=J,UQ[J]=Z,jp[J]=$,Ep[J]=new RegExp(Z,Y?"g":void 0),Pp[J]=new RegExp($,Y?"g":void 0)};uQ("NUMERICIDENTIFIER","0|[1-9]\\d*");uQ("NUMERICIDENTIFIERLOOSE","\\d+");uQ("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${kO}*`);uQ("MAINVERSION",`(${UQ[OQ.NUMERICIDENTIFIER]})\\.(${UQ[OQ.NUMERICIDENTIFIER]})\\.(${UQ[OQ.NUMERICIDENTIFIER]})`);uQ("MAINVERSIONLOOSE",`(${UQ[OQ.NUMERICIDENTIFIERLOOSE]})\\.(${UQ[OQ.NUMERICIDENTIFIERLOOSE]})\\.(${UQ[OQ.NUMERICIDENTIFIERLOOSE]})`);uQ("PRERELEASEIDENTIFIER",`(?:${UQ[OQ.NONNUMERICIDENTIFIER]}|${UQ[OQ.NUMERICIDENTIFIER]})`);uQ("PRERELEASEIDENTIFIERLOOSE",`(?:${UQ[OQ.NONNUMERICIDENTIFIER]}|${UQ[OQ.NUMERICIDENTIFIERLOOSE]})`);uQ("PRERELEASE",`(?:-(${UQ[OQ.PRERELEASEIDENTIFIER]}(?:\\.${UQ[OQ.PRERELEASEIDENTIFIER]})*))`);uQ("PRERELEASELOOSE",`(?:-?(${UQ[OQ.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${UQ[OQ.PRERELEASEIDENTIFIERLOOSE]})*))`);uQ("BUILDIDENTIFIER",`${kO}+`);uQ("BUILD",`(?:\\+(${UQ[OQ.BUILDIDENTIFIER]}(?:\\.${UQ[OQ.BUILDIDENTIFIER]})*))`);uQ("FULLPLAIN",`v?${UQ[OQ.MAINVERSION]}${UQ[OQ.PRERELEASE]}?${UQ[OQ.BUILD]}?`);uQ("FULL",`^${UQ[OQ.FULLPLAIN]}$`);uQ("LOOSEPLAIN",`[v=\\s]*${UQ[OQ.MAINVERSIONLOOSE]}${UQ[OQ.PRERELEASELOOSE]}?${UQ[OQ.BUILD]}?`);uQ("LOOSE",`^${UQ[OQ.LOOSEPLAIN]}$`);uQ("GTLT","((?:<|>)?=?)");uQ("XRANGEIDENTIFIERLOOSE",`${UQ[OQ.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);uQ("XRANGEIDENTIFIER",`${UQ[OQ.NUMERICIDENTIFIER]}|x|X|\\*`);uQ("XRANGEPLAIN",`[v=\\s]*(${UQ[OQ.XRANGEIDENTIFIER]})(?:\\.(${UQ[OQ.XRANGEIDENTIFIER]})(?:\\.(${UQ[OQ.XRANGEIDENTIFIER]})(?:${UQ[OQ.PRERELEASE]})?${UQ[OQ.BUILD]}?)?)?`);uQ("XRANGEPLAINLOOSE",`[v=\\s]*(${UQ[OQ.XRANGEIDENTIFIERLOOSE]})(?:\\.(${UQ[OQ.XRANGEIDENTIFIERLOOSE]})(?:\\.(${UQ[OQ.XRANGEIDENTIFIERLOOSE]})(?:${UQ[OQ.PRERELEASELOOSE]})?${UQ[OQ.BUILD]}?)?)?`);uQ("XRANGE",`^${UQ[OQ.GTLT]}\\s*${UQ[OQ.XRANGEPLAIN]}$`);uQ("XRANGELOOSE",`^${UQ[OQ.GTLT]}\\s*${UQ[OQ.XRANGEPLAINLOOSE]}$`);uQ("COERCEPLAIN",`(^|[^\\d])(\\d{1,${BO}})(?:\\.(\\d{1,${BO}}))?(?:\\.(\\d{1,${BO}}))?`);uQ("COERCE",`${UQ[OQ.COERCEPLAIN]}(?:$|[^\\d])`);uQ("COERCEFULL",UQ[OQ.COERCEPLAIN]+`(?:${UQ[OQ.PRERELEASE]})?(?:${UQ[OQ.BUILD]})?(?:$|[^\\d])`);uQ("COERCERTL",UQ[OQ.COERCE],!0);uQ("COERCERTLFULL",UQ[OQ.COERCEFULL],!0);uQ("LONETILDE","(?:~>?)");uQ("TILDETRIM",`(\\s*)${UQ[OQ.LONETILDE]}\\s+`,!0);nJ.tildeTrimReplace="$1~";uQ("TILDE",`^${UQ[OQ.LONETILDE]}${UQ[OQ.XRANGEPLAIN]}$`);uQ("TILDELOOSE",`^${UQ[OQ.LONETILDE]}${UQ[OQ.XRANGEPLAINLOOSE]}$`);uQ("LONECARET","(?:\\^)");uQ("CARETTRIM",`(\\s*)${UQ[OQ.LONECARET]}\\s+`,!0);nJ.caretTrimReplace="$1^";uQ("CARET",`^${UQ[OQ.LONECARET]}${UQ[OQ.XRANGEPLAIN]}$`);uQ("CARETLOOSE",`^${UQ[OQ.LONECARET]}${UQ[OQ.XRANGEPLAINLOOSE]}$`);uQ("COMPARATORLOOSE",`^${UQ[OQ.GTLT]}\\s*(${UQ[OQ.LOOSEPLAIN]})$|^$`);uQ("COMPARATOR",`^${UQ[OQ.GTLT]}\\s*(${UQ[OQ.FULLPLAIN]})$|^$`);uQ("COMPARATORTRIM",`(\\s*)${UQ[OQ.GTLT]}\\s*(${UQ[OQ.LOOSEPLAIN]}|${UQ[OQ.XRANGEPLAIN]})`,!0);nJ.comparatorTrimReplace="$1$2$3";uQ("HYPHENRANGE",`^\\s*(${UQ[OQ.XRANGEPLAIN]})\\s+-\\s+(${UQ[OQ.XRANGEPLAIN]})\\s*$`);uQ("HYPHENRANGELOOSE",`^\\s*(${UQ[OQ.XRANGEPLAINLOOSE]})\\s+-\\s+(${UQ[OQ.XRANGEPLAINLOOSE]})\\s*$`);uQ("STAR","(<|>)?=?\\s*\\*");uQ("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");uQ("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var e4=XQ((IF0,fP)=>{var Np=Object.freeze({loose:!0}),Bp=Object.freeze({}),kp=(Q)=>{if(!Q)return Bp;if(typeof Q!=="object")return Np;return Q};fP.exports=kp});var CO=XQ((RF0,hP)=>{var yP=/^[0-9]+$/,gP=(Q,Z)=>{let Y=yP.test(Q),$=yP.test(Z);if(Y&&$)Q=+Q,Z=+Z;return Q===Z?0:Y&&!$?-1:$&&!Y?1:Q<Z?-1:1},Cp=(Q,Z)=>gP(Z,Q);hP.exports={compareIdentifiers:gP,rcompareIdentifiers:Cp}});var iY=XQ((LF0,cP)=>{var Q9=Pq(),{MAX_LENGTH:bP,MAX_SAFE_INTEGER:Z9}=Eq(),{safeRe:Y9,t:$9}=cX(),Sp=e4(),{compareIdentifiers:uX}=CO();class BJ{constructor(Q,Z){if(Z=Sp(Z),Q instanceof BJ)if(Q.loose===!!Z.loose&&Q.includePrerelease===!!Z.includePrerelease)return Q;else Q=Q.version;else if(typeof Q!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof Q}".`);if(Q.length>bP)throw TypeError(`version is longer than ${bP} characters`);Q9("SemVer",Q,Z),this.options=Z,this.loose=!!Z.loose,this.includePrerelease=!!Z.includePrerelease;let Y=Q.trim().match(Z.loose?Y9[$9.LOOSE]:Y9[$9.FULL]);if(!Y)throw TypeError(`Invalid Version: ${Q}`);if(this.raw=Q,this.major=+Y[1],this.minor=+Y[2],this.patch=+Y[3],this.major>Z9||this.major<0)throw TypeError("Invalid major version");if(this.minor>Z9||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>Z9||this.patch<0)throw TypeError("Invalid patch version");if(!Y[4])this.prerelease=[];else this.prerelease=Y[4].split(".").map(($)=>{if(/^[0-9]+$/.test($)){let J=+$;if(J>=0&&J<Z9)return J}return $});this.build=Y[5]?Y[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(Q){if(Q9("SemVer.compare",this.version,this.options,Q),!(Q instanceof BJ)){if(typeof Q==="string"&&Q===this.version)return 0;Q=new BJ(Q,this.options)}if(Q.version===this.version)return 0;return this.compareMain(Q)||this.comparePre(Q)}compareMain(Q){if(!(Q instanceof BJ))Q=new BJ(Q,this.options);return uX(this.major,Q.major)||uX(this.minor,Q.minor)||uX(this.patch,Q.patch)}comparePre(Q){if(!(Q instanceof BJ))Q=new BJ(Q,this.options);if(this.prerelease.length&&!Q.prerelease.length)return-1;else if(!this.prerelease.length&&Q.prerelease.length)return 1;else if(!this.prerelease.length&&!Q.prerelease.length)return 0;let Z=0;do{let Y=this.prerelease[Z],$=Q.prerelease[Z];if(Q9("prerelease compare",Z,Y,$),Y===void 0&&$===void 0)return 0;else if($===void 0)return 1;else if(Y===void 0)return-1;else if(Y===$)continue;else return uX(Y,$)}while(++Z)}compareBuild(Q){if(!(Q instanceof BJ))Q=new BJ(Q,this.options);let Z=0;do{let Y=this.build[Z],$=Q.build[Z];if(Q9("build compare",Z,Y,$),Y===void 0&&$===void 0)return 0;else if($===void 0)return 1;else if(Y===void 0)return-1;else if(Y===$)continue;else return uX(Y,$)}while(++Z)}inc(Q,Z,Y){if(Q.startsWith("pre")){if(!Z&&Y===!1)throw Error("invalid increment argument: identifier is empty");if(Z){let $=`-${Z}`.match(this.options.loose?Y9[$9.PRERELEASELOOSE]:Y9[$9.PRERELEASE]);if(!$||$[1]!==Z)throw Error(`invalid identifier: ${Z}`)}}switch(Q){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",Z,Y);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",Z,Y);break;case"prepatch":this.prerelease.length=0,this.inc("patch",Z,Y),this.inc("pre",Z,Y);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",Z,Y);this.inc("pre",Z,Y);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let $=Number(Y)?1:0;if(this.prerelease.length===0)this.prerelease=[$];else{let J=this.prerelease.length;while(--J>=0)if(typeof this.prerelease[J]==="number")this.prerelease[J]++,J=-2;if(J===-1){if(Z===this.prerelease.join(".")&&Y===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push($)}}if(Z){let J=[Z,$];if(Y===!1)J=[Z];if(uX(this.prerelease[0],Z)===0){if(isNaN(this.prerelease[1]))this.prerelease=J}else this.prerelease=J}break}default:throw Error(`invalid increment argument: ${Q}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}cP.exports=BJ});var BG=XQ((EF0,pP)=>{var uP=iY(),wp=(Q,Z,Y=!1)=>{if(Q instanceof uP)return Q;try{return new uP(Q,Z)}catch($){if(!Y)return null;throw $}};pP.exports=wp});var mP=XQ((PF0,lP)=>{var _p=BG(),vp=(Q,Z)=>{let Y=_p(Q,Z);return Y?Y.version:null};lP.exports=vp});var nP=XQ((jF0,dP)=>{var xp=BG(),fp=(Q,Z)=>{let Y=xp(Q.trim().replace(/^[=v]+/,""),Z);return Y?Y.version:null};dP.exports=fp});var iP=XQ((AF0,sP)=>{var oP=iY(),yp=(Q,Z,Y,$,J)=>{if(typeof Y==="string")J=$,$=Y,Y=void 0;try{return new oP(Q instanceof oP?Q.version:Q,Y).inc(Z,$,J).version}catch(X){return null}};sP.exports=yp});var tP=XQ((MF0,rP)=>{var aP=BG(),gp=(Q,Z)=>{let Y=aP(Q,null,!0),$=aP(Z,null,!0),J=Y.compare($);if(J===0)return null;let X=J>0,G=X?Y:$,W=X?$:Y,U=!!G.prerelease.length;if(!!W.prerelease.length&&!U){if(!W.patch&&!W.minor)return"major";if(W.compareMain(G)===0){if(W.minor&&!W.patch)return"minor";return"patch"}}let O=U?"pre":"";if(Y.major!==$.major)return O+"major";if(Y.minor!==$.minor)return O+"minor";if(Y.patch!==$.patch)return O+"patch";return"prerelease"};rP.exports=gp});var Qj=XQ((TF0,eP)=>{var hp=iY(),bp=(Q,Z)=>new hp(Q,Z).major;eP.exports=bp});var Yj=XQ((NF0,Zj)=>{var cp=iY(),up=(Q,Z)=>new cp(Q,Z).minor;Zj.exports=up});var Jj=XQ((BF0,$j)=>{var pp=iY(),lp=(Q,Z)=>new pp(Q,Z).patch;$j.exports=lp});var Xj=XQ((kF0,Gj)=>{var mp=BG(),dp=(Q,Z)=>{let Y=mp(Q,Z);return Y&&Y.prerelease.length?Y.prerelease:null};Gj.exports=dp});var qJ=XQ((CF0,qj)=>{var Vj=iY(),np=(Q,Z,Y)=>new Vj(Q,Y).compare(new Vj(Z,Y));qj.exports=np});var zj=XQ((SF0,Fj)=>{var op=qJ(),sp=(Q,Z,Y)=>op(Z,Q,Y);Fj.exports=sp});var Kj=XQ((wF0,Wj)=>{var ip=qJ(),ap=(Q,Z)=>ip(Q,Z,!0);Wj.exports=ap});var J9=XQ((_F0,Oj)=>{var Uj=iY(),rp=(Q,Z,Y)=>{let $=new Uj(Q,Y),J=new Uj(Z,Y);return $.compare(J)||$.compareBuild(J)};Oj.exports=rp});var Dj=XQ((vF0,Hj)=>{var tp=J9(),ep=(Q,Z)=>Q.sort((Y,$)=>tp(Y,$,Z));Hj.exports=ep});var Rj=XQ((xF0,Ij)=>{var Ql=J9(),Zl=(Q,Z)=>Q.sort((Y,$)=>Ql($,Y,Z));Ij.exports=Zl});var jq=XQ((fF0,Lj)=>{var Yl=qJ(),$l=(Q,Z,Y)=>Yl(Q,Z,Y)>0;Lj.exports=$l});var G9=XQ((yF0,Ej)=>{var Jl=qJ(),Gl=(Q,Z,Y)=>Jl(Q,Z,Y)<0;Ej.exports=Gl});var SO=XQ((gF0,Pj)=>{var Xl=qJ(),Vl=(Q,Z,Y)=>Xl(Q,Z,Y)===0;Pj.exports=Vl});var wO=XQ((hF0,jj)=>{var ql=qJ(),Fl=(Q,Z,Y)=>ql(Q,Z,Y)!==0;jj.exports=Fl});var X9=XQ((bF0,Aj)=>{var zl=qJ(),Wl=(Q,Z,Y)=>zl(Q,Z,Y)>=0;Aj.exports=Wl});var V9=XQ((cF0,Mj)=>{var Kl=qJ(),Ul=(Q,Z,Y)=>Kl(Q,Z,Y)<=0;Mj.exports=Ul});var _O=XQ((uF0,Tj)=>{var Ol=SO(),Hl=wO(),Dl=jq(),Il=X9(),Rl=G9(),Ll=V9(),El=(Q,Z,Y,$)=>{switch(Z){case"===":if(typeof Q==="object")Q=Q.version;if(typeof Y==="object")Y=Y.version;return Q===Y;case"!==":if(typeof Q==="object")Q=Q.version;if(typeof Y==="object")Y=Y.version;return Q!==Y;case"":case"=":case"==":return Ol(Q,Y,$);case"!=":return Hl(Q,Y,$);case">":return Dl(Q,Y,$);case">=":return Il(Q,Y,$);case"<":return Rl(Q,Y,$);case"<=":return Ll(Q,Y,$);default:throw TypeError(`Invalid operator: ${Z}`)}};Tj.exports=El});var Bj=XQ((pF0,Nj)=>{var Pl=iY(),jl=BG(),{safeRe:q9,t:F9}=cX(),Al=(Q,Z)=>{if(Q instanceof Pl)return Q;if(typeof Q==="number")Q=String(Q);if(typeof Q!=="string")return null;Z=Z||{};let Y=null;if(!Z.rtl)Y=Q.match(Z.includePrerelease?q9[F9.COERCEFULL]:q9[F9.COERCE]);else{let U=Z.includePrerelease?q9[F9.COERCERTLFULL]:q9[F9.COERCERTL],K;while((K=U.exec(Q))&&(!Y||Y.index+Y[0].length!==Q.length)){if(!Y||K.index+K[0].length!==Y.index+Y[0].length)Y=K;U.lastIndex=K.index+K[1].length+K[2].length}U.lastIndex=-1}if(Y===null)return null;let $=Y[2],J=Y[3]||"0",X=Y[4]||"0",G=Z.includePrerelease&&Y[5]?`-${Y[5]}`:"",W=Z.includePrerelease&&Y[6]?`+${Y[6]}`:"";return jl(`${$}.${J}.${X}${G}${W}`,Z)};Nj.exports=Al});var Sj=XQ((lF0,Cj)=>{class kj{constructor(){this.max=1000,this.map=new Map}get(Q){let Z=this.map.get(Q);if(Z===void 0)return;else return this.map.delete(Q),this.map.set(Q,Z),Z}delete(Q){return this.map.delete(Q)}set(Q,Z){if(!this.delete(Q)&&Z!==void 0){if(this.map.size>=this.max){let $=this.map.keys().next().value;this.delete($)}this.map.set(Q,Z)}return this}}Cj.exports=kj});var FJ=XQ((mF0,xj)=>{var Ml=/\s+/g;class Aq{constructor(Q,Z){if(Z=Nl(Z),Q instanceof Aq)if(Q.loose===!!Z.loose&&Q.includePrerelease===!!Z.includePrerelease)return Q;else return new Aq(Q.raw,Z);if(Q instanceof vO)return this.raw=Q.value,this.set=[[Q]],this.formatted=void 0,this;if(this.options=Z,this.loose=!!Z.loose,this.includePrerelease=!!Z.includePrerelease,this.raw=Q.trim().replace(Ml," "),this.set=this.raw.split("||").map((Y)=>this.parseRange(Y.trim())).filter((Y)=>Y.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let Y=this.set[0];if(this.set=this.set.filter(($)=>!_j($[0])),this.set.length===0)this.set=[Y];else if(this.set.length>1){for(let $ of this.set)if($.length===1&&vl($[0])){this.set=[$];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let Q=0;Q<this.set.length;Q++){if(Q>0)this.formatted+="||";let Z=this.set[Q];for(let Y=0;Y<Z.length;Y++){if(Y>0)this.formatted+=" ";this.formatted+=Z[Y].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(Q){let Y=((this.options.includePrerelease&&wl)|(this.options.loose&&_l))+":"+Q,$=wj.get(Y);if($)return $;let J=this.options.loose,X=J?A$[F$.HYPHENRANGELOOSE]:A$[F$.HYPHENRANGE];Q=Q.replace(X,ll(this.options.includePrerelease)),BZ("hyphen replace",Q),Q=Q.replace(A$[F$.COMPARATORTRIM],kl),BZ("comparator trim",Q),Q=Q.replace(A$[F$.TILDETRIM],Cl),BZ("tilde trim",Q),Q=Q.replace(A$[F$.CARETTRIM],Sl),BZ("caret trim",Q);let G=Q.split(" ").map((O)=>xl(O,this.options)).join(" ").split(/\s+/).map((O)=>pl(O,this.options));if(J)G=G.filter((O)=>{return BZ("loose invalid filter",O,this.options),!!O.match(A$[F$.COMPARATORLOOSE])});BZ("range list",G);let W=new Map,U=G.map((O)=>new vO(O,this.options));for(let O of U){if(_j(O))return[O];W.set(O.value,O)}if(W.size>1&&W.has(""))W.delete("");let K=[...W.values()];return wj.set(Y,K),K}intersects(Q,Z){if(!(Q instanceof Aq))throw TypeError("a Range is required");return this.set.some((Y)=>{return vj(Y,Z)&&Q.set.some(($)=>{return vj($,Z)&&Y.every((J)=>{return $.every((X)=>{return J.intersects(X,Z)})})})})}test(Q){if(!Q)return!1;if(typeof Q==="string")try{Q=new Bl(Q,this.options)}catch(Z){return!1}for(let Z=0;Z<this.set.length;Z++)if(ml(this.set[Z],Q,this.options))return!0;return!1}}xj.exports=Aq;var Tl=Sj(),wj=new Tl,Nl=e4(),vO=Mq(),BZ=Pq(),Bl=iY(),{safeRe:A$,t:F$,comparatorTrimReplace:kl,tildeTrimReplace:Cl,caretTrimReplace:Sl}=cX(),{FLAG_INCLUDE_PRERELEASE:wl,FLAG_LOOSE:_l}=Eq(),_j=(Q)=>Q.value==="<0.0.0-0",vl=(Q)=>Q.value==="",vj=(Q,Z)=>{let Y=!0,$=Q.slice(),J=$.pop();while(Y&&$.length)Y=$.every((X)=>{return J.intersects(X,Z)}),J=$.pop();return Y},xl=(Q,Z)=>{return BZ("comp",Q,Z),Q=gl(Q,Z),BZ("caret",Q),Q=fl(Q,Z),BZ("tildes",Q),Q=bl(Q,Z),BZ("xrange",Q),Q=ul(Q,Z),BZ("stars",Q),Q},z$=(Q)=>!Q||Q.toLowerCase()==="x"||Q==="*",fl=(Q,Z)=>{return Q.trim().split(/\s+/).map((Y)=>yl(Y,Z)).join(" ")},yl=(Q,Z)=>{let Y=Z.loose?A$[F$.TILDELOOSE]:A$[F$.TILDE];return Q.replace(Y,($,J,X,G,W)=>{BZ("tilde",Q,$,J,X,G,W);let U;if(z$(J))U="";else if(z$(X))U=`>=${J}.0.0 <${+J+1}.0.0-0`;else if(z$(G))U=`>=${J}.${X}.0 <${J}.${+X+1}.0-0`;else if(W)BZ("replaceTilde pr",W),U=`>=${J}.${X}.${G}-${W} <${J}.${+X+1}.0-0`;else U=`>=${J}.${X}.${G} <${J}.${+X+1}.0-0`;return BZ("tilde return",U),U})},gl=(Q,Z)=>{return Q.trim().split(/\s+/).map((Y)=>hl(Y,Z)).join(" ")},hl=(Q,Z)=>{BZ("caret",Q,Z);let Y=Z.loose?A$[F$.CARETLOOSE]:A$[F$.CARET],$=Z.includePrerelease?"-0":"";return Q.replace(Y,(J,X,G,W,U)=>{BZ("caret",Q,J,X,G,W,U);let K;if(z$(X))K="";else if(z$(G))K=`>=${X}.0.0${$} <${+X+1}.0.0-0`;else if(z$(W))if(X==="0")K=`>=${X}.${G}.0${$} <${X}.${+G+1}.0-0`;else K=`>=${X}.${G}.0${$} <${+X+1}.0.0-0`;else if(U)if(BZ("replaceCaret pr",U),X==="0")if(G==="0")K=`>=${X}.${G}.${W}-${U} <${X}.${G}.${+W+1}-0`;else K=`>=${X}.${G}.${W}-${U} <${X}.${+G+1}.0-0`;else K=`>=${X}.${G}.${W}-${U} <${+X+1}.0.0-0`;else if(BZ("no pr"),X==="0")if(G==="0")K=`>=${X}.${G}.${W}${$} <${X}.${G}.${+W+1}-0`;else K=`>=${X}.${G}.${W}${$} <${X}.${+G+1}.0-0`;else K=`>=${X}.${G}.${W} <${+X+1}.0.0-0`;return BZ("caret return",K),K})},bl=(Q,Z)=>{return BZ("replaceXRanges",Q,Z),Q.split(/\s+/).map((Y)=>cl(Y,Z)).join(" ")},cl=(Q,Z)=>{Q=Q.trim();let Y=Z.loose?A$[F$.XRANGELOOSE]:A$[F$.XRANGE];return Q.replace(Y,($,J,X,G,W,U)=>{BZ("xRange",Q,$,J,X,G,W,U);let K=z$(X),O=K||z$(G),I=O||z$(W),L=I;if(J==="="&&L)J="";if(U=Z.includePrerelease?"-0":"",K)if(J===">"||J==="<")$="<0.0.0-0";else $="*";else if(J&&L){if(O)G=0;if(W=0,J===">")if(J=">=",O)X=+X+1,G=0,W=0;else G=+G+1,W=0;else if(J==="<=")if(J="<",O)X=+X+1;else G=+G+1;if(J==="<")U="-0";$=`${J+X}.${G}.${W}${U}`}else if(O)$=`>=${X}.0.0${U} <${+X+1}.0.0-0`;else if(I)$=`>=${X}.${G}.0${U} <${X}.${+G+1}.0-0`;return BZ("xRange return",$),$})},ul=(Q,Z)=>{return BZ("replaceStars",Q,Z),Q.trim().replace(A$[F$.STAR],"")},pl=(Q,Z)=>{return BZ("replaceGTE0",Q,Z),Q.trim().replace(A$[Z.includePrerelease?F$.GTE0PRE:F$.GTE0],"")},ll=(Q)=>(Z,Y,$,J,X,G,W,U,K,O,I,L)=>{if(z$($))Y="";else if(z$(J))Y=`>=${$}.0.0${Q?"-0":""}`;else if(z$(X))Y=`>=${$}.${J}.0${Q?"-0":""}`;else if(G)Y=`>=${Y}`;else Y=`>=${Y}${Q?"-0":""}`;if(z$(K))U="";else if(z$(O))U=`<${+K+1}.0.0-0`;else if(z$(I))U=`<${K}.${+O+1}.0-0`;else if(L)U=`<=${K}.${O}.${I}-${L}`;else if(Q)U=`<${K}.${O}.${+I+1}-0`;else U=`<=${U}`;return`${Y} ${U}`.trim()},ml=(Q,Z,Y)=>{for(let $=0;$<Q.length;$++)if(!Q[$].test(Z))return!1;if(Z.prerelease.length&&!Y.includePrerelease){for(let $=0;$<Q.length;$++){if(BZ(Q[$].semver),Q[$].semver===vO.ANY)continue;if(Q[$].semver.prerelease.length>0){let J=Q[$].semver;if(J.major===Z.major&&J.minor===Z.minor&&J.patch===Z.patch)return!0}}return!1}return!0}});var Mq=XQ((dF0,cj)=>{var Tq=Symbol("SemVer ANY");class z9{static get ANY(){return Tq}constructor(Q,Z){if(Z=fj(Z),Q instanceof z9)if(Q.loose===!!Z.loose)return Q;else Q=Q.value;if(Q=Q.trim().split(/\s+/).join(" "),fO("comparator",Q,Z),this.options=Z,this.loose=!!Z.loose,this.parse(Q),this.semver===Tq)this.value="";else this.value=this.operator+this.semver.version;fO("comp",this)}parse(Q){let Z=this.options.loose?yj[gj.COMPARATORLOOSE]:yj[gj.COMPARATOR],Y=Q.match(Z);if(!Y)throw TypeError(`Invalid comparator: ${Q}`);if(this.operator=Y[1]!==void 0?Y[1]:"",this.operator==="=")this.operator="";if(!Y[2])this.semver=Tq;else this.semver=new hj(Y[2],this.options.loose)}toString(){return this.value}test(Q){if(fO("Comparator.test",Q,this.options.loose),this.semver===Tq||Q===Tq)return!0;if(typeof Q==="string")try{Q=new hj(Q,this.options)}catch(Z){return!1}return xO(Q,this.operator,this.semver,this.options)}intersects(Q,Z){if(!(Q instanceof z9))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new bj(Q.value,Z).test(this.value)}else if(Q.operator===""){if(Q.value==="")return!0;return new bj(this.value,Z).test(Q.semver)}if(Z=fj(Z),Z.includePrerelease&&(this.value==="<0.0.0-0"||Q.value==="<0.0.0-0"))return!1;if(!Z.includePrerelease&&(this.value.startsWith("<0.0.0")||Q.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&Q.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&Q.operator.startsWith("<"))return!0;if(this.semver.version===Q.semver.version&&this.operator.includes("=")&&Q.operator.includes("="))return!0;if(xO(this.semver,"<",Q.semver,Z)&&this.operator.startsWith(">")&&Q.operator.startsWith("<"))return!0;if(xO(this.semver,">",Q.semver,Z)&&this.operator.startsWith("<")&&Q.operator.startsWith(">"))return!0;return!1}}cj.exports=z9;var fj=e4(),{safeRe:yj,t:gj}=cX(),xO=_O(),fO=Pq(),hj=iY(),bj=FJ()});var Nq=XQ((nF0,uj)=>{var dl=FJ(),nl=(Q,Z,Y)=>{try{Z=new dl(Z,Y)}catch($){return!1}return Z.test(Q)};uj.exports=nl});var lj=XQ((oF0,pj)=>{var ol=FJ(),sl=(Q,Z)=>new ol(Q,Z).set.map((Y)=>Y.map(($)=>$.value).join(" ").trim().split(" "));pj.exports=sl});var dj=XQ((sF0,mj)=>{var il=iY(),al=FJ(),rl=(Q,Z,Y)=>{let $=null,J=null,X=null;try{X=new al(Z,Y)}catch(G){return null}return Q.forEach((G)=>{if(X.test(G)){if(!$||J.compare(G)===-1)$=G,J=new il($,Y)}}),$};mj.exports=rl});var oj=XQ((iF0,nj)=>{var tl=iY(),el=FJ(),Qm=(Q,Z,Y)=>{let $=null,J=null,X=null;try{X=new el(Z,Y)}catch(G){return null}return Q.forEach((G)=>{if(X.test(G)){if(!$||J.compare(G)===1)$=G,J=new tl($,Y)}}),$};nj.exports=Qm});var aj=XQ((aF0,ij)=>{var yO=iY(),Zm=FJ(),sj=jq(),Ym=(Q,Z)=>{Q=new Zm(Q,Z);let Y=new yO("0.0.0");if(Q.test(Y))return Y;if(Y=new yO("0.0.0-0"),Q.test(Y))return Y;Y=null;for(let $=0;$<Q.set.length;++$){let J=Q.set[$],X=null;if(J.forEach((G)=>{let W=new yO(G.semver.version);switch(G.operator){case">":if(W.prerelease.length===0)W.patch++;else W.prerelease.push(0);W.raw=W.format();case"":case">=":if(!X||sj(W,X))X=W;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${G.operator}`)}}),X&&(!Y||sj(Y,X)))Y=X}if(Y&&Q.test(Y))return Y;return null};ij.exports=Ym});var tj=XQ((rF0,rj)=>{var $m=FJ(),Jm=(Q,Z)=>{try{return new $m(Q,Z).range||"*"}catch(Y){return null}};rj.exports=Jm});var W9=XQ((tF0,YA)=>{var Gm=iY(),ZA=Mq(),{ANY:Xm}=ZA,Vm=FJ(),qm=Nq(),ej=jq(),QA=G9(),Fm=V9(),zm=X9(),Wm=(Q,Z,Y,$)=>{Q=new Gm(Q,$),Z=new Vm(Z,$);let J,X,G,W,U;switch(Y){case">":J=ej,X=Fm,G=QA,W=">",U=">=";break;case"<":J=QA,X=zm,G=ej,W="<",U="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(qm(Q,Z,$))return!1;for(let K=0;K<Z.set.length;++K){let O=Z.set[K],I=null,L=null;if(O.forEach((A)=>{if(A.semver===Xm)A=new ZA(">=0.0.0");if(I=I||A,L=L||A,J(A.semver,I.semver,$))I=A;else if(G(A.semver,L.semver,$))L=A}),I.operator===W||I.operator===U)return!1;if((!L.operator||L.operator===W)&&X(Q,L.semver))return!1;else if(L.operator===U&&G(Q,L.semver))return!1}return!0};YA.exports=Wm});var JA=XQ((eF0,$A)=>{var Km=W9(),Um=(Q,Z,Y)=>Km(Q,Z,">",Y);$A.exports=Um});var XA=XQ((Q40,GA)=>{var Om=W9(),Hm=(Q,Z,Y)=>Om(Q,Z,"<",Y);GA.exports=Hm});var FA=XQ((Z40,qA)=>{var VA=FJ(),Dm=(Q,Z,Y)=>{return Q=new VA(Q,Y),Z=new VA(Z,Y),Q.intersects(Z,Y)};qA.exports=Dm});var WA=XQ((Y40,zA)=>{var Im=Nq(),Rm=qJ();zA.exports=(Q,Z,Y)=>{let $=[],J=null,X=null,G=Q.sort((O,I)=>Rm(O,I,Y));for(let O of G)if(Im(O,Z,Y)){if(X=O,!J)J=O}else{if(X)$.push([J,X]);X=null,J=null}if(J)$.push([J,null]);let W=[];for(let[O,I]of $)if(O===I)W.push(O);else if(!I&&O===G[0])W.push("*");else if(!I)W.push(`>=${O}`);else if(O===G[0])W.push(`<=${I}`);else W.push(`${O} - ${I}`);let U=W.join(" || "),K=typeof Z.raw==="string"?Z.raw:String(Z);return U.length<K.length?U:Z}});var IA=XQ(($40,DA)=>{var KA=FJ(),hO=Mq(),{ANY:gO}=hO,Bq=Nq(),bO=qJ(),Lm=(Q,Z,Y={})=>{if(Q===Z)return!0;Q=new KA(Q,Y),Z=new KA(Z,Y);let $=!1;Q:for(let J of Q.set){for(let X of Z.set){let G=Pm(J,X,Y);if($=$||G!==null,G)continue Q}if($)return!1}return!0},Em=[new hO(">=0.0.0-0")],UA=[new hO(">=0.0.0")],Pm=(Q,Z,Y)=>{if(Q===Z)return!0;if(Q.length===1&&Q[0].semver===gO)if(Z.length===1&&Z[0].semver===gO)return!0;else if(Y.includePrerelease)Q=Em;else Q=UA;if(Z.length===1&&Z[0].semver===gO)if(Y.includePrerelease)return!0;else Z=UA;let $=new Set,J,X;for(let A of Q)if(A.operator===">"||A.operator===">=")J=OA(J,A,Y);else if(A.operator==="<"||A.operator==="<=")X=HA(X,A,Y);else $.add(A.semver);if($.size>1)return null;let G;if(J&&X){if(G=bO(J.semver,X.semver,Y),G>0)return null;else if(G===0&&(J.operator!==">="||X.operator!=="<="))return null}for(let A of $){if(J&&!Bq(A,String(J),Y))return null;if(X&&!Bq(A,String(X),Y))return null;for(let M of Z)if(!Bq(A,String(M),Y))return!1;return!0}let W,U,K,O,I=X&&!Y.includePrerelease&&X.semver.prerelease.length?X.semver:!1,L=J&&!Y.includePrerelease&&J.semver.prerelease.length?J.semver:!1;if(I&&I.prerelease.length===1&&X.operator==="<"&&I.prerelease[0]===0)I=!1;for(let A of Z){if(O=O||A.operator===">"||A.operator===">=",K=K||A.operator==="<"||A.operator==="<=",J){if(L){if(A.semver.prerelease&&A.semver.prerelease.length&&A.semver.major===L.major&&A.semver.minor===L.minor&&A.semver.patch===L.patch)L=!1}if(A.operator===">"||A.operator===">="){if(W=OA(J,A,Y),W===A&&W!==J)return!1}else if(J.operator===">="&&!Bq(J.semver,String(A),Y))return!1}if(X){if(I){if(A.semver.prerelease&&A.semver.prerelease.length&&A.semver.major===I.major&&A.semver.minor===I.minor&&A.semver.patch===I.patch)I=!1}if(A.operator==="<"||A.operator==="<="){if(U=HA(X,A,Y),U===A&&U!==X)return!1}else if(X.operator==="<="&&!Bq(X.semver,String(A),Y))return!1}if(!A.operator&&(X||J)&&G!==0)return!1}if(J&&K&&!X&&G!==0)return!1;if(X&&O&&!J&&G!==0)return!1;if(L||I)return!1;return!0},OA=(Q,Z,Y)=>{if(!Q)return Z;let $=bO(Q.semver,Z.semver,Y);return $>0?Q:$<0?Z:Z.operator===">"&&Q.operator===">="?Z:Q},HA=(Q,Z,Y)=>{if(!Q)return Z;let $=bO(Q.semver,Z.semver,Y);return $<0?Q:$>0?Z:Z.operator==="<"&&Q.operator==="<="?Z:Q};DA.exports=Lm});var kG=XQ((J40,EA)=>{var cO=cX(),RA=Eq(),jm=iY(),LA=CO(),Am=BG(),Mm=mP(),Tm=nP(),Nm=iP(),Bm=tP(),km=Qj(),Cm=Yj(),Sm=Jj(),wm=Xj(),_m=qJ(),vm=zj(),xm=Kj(),fm=J9(),ym=Dj(),gm=Rj(),hm=jq(),bm=G9(),cm=SO(),um=wO(),pm=X9(),lm=V9(),mm=_O(),dm=Bj(),nm=Mq(),om=FJ(),sm=Nq(),im=lj(),am=dj(),rm=oj(),tm=aj(),em=tj(),Qd=W9(),Zd=JA(),Yd=XA(),$d=FA(),Jd=WA(),Gd=IA();EA.exports={parse:Am,valid:Mm,clean:Tm,inc:Nm,diff:Bm,major:km,minor:Cm,patch:Sm,prerelease:wm,compare:_m,rcompare:vm,compareLoose:xm,compareBuild:fm,sort:ym,rsort:gm,gt:hm,lt:bm,eq:cm,neq:um,gte:pm,lte:lm,cmp:mm,coerce:dm,Comparator:nm,Range:om,satisfies:sm,toComparators:im,maxSatisfying:am,minSatisfying:rm,minVersion:tm,validRange:em,outside:Qd,gtr:Zd,ltr:Yd,intersects:$d,simplifyRange:Jd,subset:Gd,SemVer:jm,re:cO.re,src:cO.src,tokens:cO.t,SEMVER_SPEC_VERSION:RA.SEMVER_SPEC_VERSION,RELEASE_TYPES:RA.RELEASE_TYPES,compareIdentifiers:LA.compareIdentifiers,rcompareIdentifiers:LA.rcompareIdentifiers}});class CG{id;model;name;constructor({id:Q,model:Z,name:Y}){this.id=Q,this.model=Z,this.name=Y}}var JQ,kq=11415;var R1=w(()=>{JQ=((Q)=>(Q.NANO_S="nanoS",Q.NANO_SP="nanoSP",Q.NANO_X="nanoX",Q.STAX="stax",Q.FLEX="flex",Q.APEX="apexp",Q))(JQ||{})});var pX,dZ;var uO=w(()=>{pX={Twelve:12,Eighteen:18,TwentyFour:24},dZ=((Q)=>(Q.Unknown="unknown",Q.WelcomeScreen1="welcome-screen-1",Q.WelcomeScreen2="welcome-screen-2",Q.WelcomeScreen3="welcome-screen-3",Q.WelcomeScreen4="welcome-screen-4",Q.WelcomeScreenReminder="welcome-screen-reminder",Q.SetupChoice="setup-choice",Q.Pin="pin",Q.NewDevice="new-device",Q.ConfirmNewDevice="confirm-new-device",Q.RestoreRecoveryPhrase="restore-recovery-phrase",Q.SafetyWarning="safety-warning",Q.DeviceIsReady="device-is-ready",Q.ChooseName="choose-name",Q.RestoreRecoverBackup="restore-recover-backup",Q.SetupRestoreChoice="setup-restore-choice",Q.OnboardingStatusCheck="onboarding-status-check",Q.RestoreWithRk="restore-with-rk",Q))(dZ||{})});class pO{seFlags;constructor(Q){this.seFlags=new Uint8Array(4),this.seFlags.set(Q.subarray(0,this.seFlags.length))}generalDeviceState(){let Q=this.seFlags[0]??0;return{isPinValidated:this._checkNthBitInByte(Q,1),hasMcuSerialNumber:this._checkNthBitInByte(Q,2),hasValidCertificate:this._checkNthBitInByte(Q,3),isCustomAuthorityConnectionAllowed:this._checkNthBitInByte(Q,4),isSecureConnectionAllowed:this._checkNthBitInByte(Q,5),isOnboarded:this._checkNthBitInByte(Q,6),isMcuCodeSigned:this._checkNthBitInByte(Q,7),isInRecoveryMode:this._checkNthBitInByte(Q,8)}}endorsementInformation(){let Q=this.seFlags[1]??0;return{hasEndorsementCertificateInSlot1:(Q&1)!==0,hasEndorsementCertificateInSlot2:(Q&2)!==0}}wordsInformation(){let Q=this.seFlags[2]??0,Z=Q>>5&3;return{numberOfWords:[pX.TwentyFour,pX.Eighteen,pX.Twelve,void 0][Z],currentWordIndex:Q&31}}onboardingStatus(){let Q=this.seFlags[3]??0;return{onboardingState:Xd[Q]??dZ.Unknown}}_checkNthBitInByte(Q,Z){return(Q>>8-Z&1)===1}}var Xd;var PA=w(()=>{uO();Xd={0:dZ.WelcomeScreen1,1:dZ.WelcomeScreen2,2:dZ.WelcomeScreen3,3:dZ.WelcomeScreen4,4:dZ.WelcomeScreenReminder,5:dZ.SetupChoice,6:dZ.Pin,7:dZ.NewDevice,8:dZ.ConfirmNewDevice,9:dZ.RestoreRecoveryPhrase,10:dZ.SafetyWarning,11:dZ.DeviceIsReady,12:dZ.ChooseName,13:dZ.RestoreRecoverBackup,14:dZ.SetupRestoreChoice,15:dZ.OnboardingStatusCheck,16:dZ.RestoreWithRk}});class IY{name="getOsVersion";args=void 0;getApdu(){return new w0({cla:224,ins:1,p1:0,p2:0}).build()}parseResponse(Q,Z){if(!hQ.isSuccessResponse(Q))return o({error:NZ.handle(Q)});let Y=new FQ(Q),$=Y.extract32BitUInt();if($===void 0)return o({error:new C0("Missing target ID in OS version")});let J=Y.encodeToString(Y.extractFieldLVEncoded()),X=Y.extractFieldLVEncoded()??new Uint8Array(0),G=new pO(X),W={...G.generalDeviceState(),...G.endorsementInformation(),...G.wordsInformation(),...G.onboardingStatus()};J||(J="0.0.0",X=new Uint8Array);let U=($&4026531840)!==805306368,K=J.includes("-osu"),O="",I="",L="",A="",M,k,B,C;if(U){L=J,M=$;let S=Y.extractFieldLVEncoded();S&&(S.length>=5?(O=Y.encodeToString(S),k=parseInt(Y.encodeToHexaString(Y.extractFieldLVEncoded()),16)):k=parseInt(Y.encodeToHexaString(S),16))}else{if(O=J,k=$,I=Y.encodeToString(Y.extractFieldLVEncoded()),this.isBootloaderVersionSupported(O,Z)&&(L=Y.encodeToString(Y.extractFieldLVEncoded())),this.isHardwareVersionSupported(O,Z)?A=Y.encodeToHexaString(Y.extractFieldLVEncoded()):A="00",this.isLocalizationSupported(O,Z)){let S=Y.extractFieldLVEncoded();S!==void 0&&(B=parseInt(Y.encodeToHexaString(S),16))}if(this.isRecoverSupported(O,Z)){let S=Y.extractFieldLVEncoded();S!==void 0&&(C=parseInt(Y.encodeToHexaString(S),16))}}return o({data:{isBootloader:U,isOsu:K,targetId:$,seTargetId:k,mcuTargetId:M,seVersion:O,seFlags:X,mcuSephVersion:I,mcuBootloaderVersion:L,hwVersion:A,langId:B,recoverState:C,secureElementFlags:W}})}isBootloaderVersionSupported(Q,Z){let Y=M$.coerce(Q)??"";switch(Z){case JQ.NANO_S:case JQ.NANO_X:return M$.gte(Y,"2.0.0");default:return!0}}isHardwareVersionSupported(Q,Z){let Y=M$.coerce(Q)??"";switch(Z){case JQ.NANO_X:return M$.gte(Y,"2.0.0");default:return!1}}isLocalizationSupported(Q,Z){let Y=M$.coerce(Q)??"";switch(Z){case JQ.NANO_S:return!1;case JQ.NANO_SP:return M$.gte(Y,"1.1.0");case JQ.NANO_X:return M$.gte(Y,"2.1.0");default:return!0}}isRecoverSupported(Q,Z){let Y=M$.coerce(Q)??"";switch(Z){case JQ.NANO_S:return!1;case JQ.NANO_SP:return M$.gte(Y,"1.1.2");case JQ.NANO_X:return M$.gte(Y,"2.2.3");case JQ.STAX:return M$.gte(Y,"1.4.0");case JQ.FLEX:return M$.gte(Y,"1.0.1");default:return!0}}}var M$;var H8=w(()=>{a$();r$();MG();TZ();oY();VJ();R1();PA();M$=JZ(kG(),1)});class Cq{name="listApps";args;constructor(Q={isContinue:!1}){this.args=Q}getApdu(){let Q={cla:224,ins:this.args.isContinue?223:222,p1:0,p2:0};return new w0(Q).build()}parseResponse(Q){let Z=[],Y=new FQ(Q);if(!hQ.isSuccessResponse(Q)){let $=Y.encodeToHexaString(Q.statusCode);return kY($,jA)?o({error:new AA({...jA[$],errorCode:$})}):o({error:NZ.handle(Q)})}if(Q.data.length<=0)return o({data:[]});for(Y.extract8BitUInt();Y.getUnparsedRemainingLength()>0;){let $=Y.extract8BitUInt(),J=Y.extract16BitUInt();Y.extract16BitUInt();let X=Y.encodeToHexaString(Y.extractFieldByLength(32)),G=Y.encodeToHexaString(Y.extractFieldByLength(32)),W=Y.encodeToString(Y.extractFieldLVEncoded());Z.push({appEntryLength:$,appSizeInBlocks:J,appCodeHash:X,appFullHash:G,appName:W})}return o({data:Z})}}var jA,AA;var lO=w(()=>{a$();r$();TZ();I1();oY();VJ();dJ();jA={6624:{message:"Invalid state (List applications command must be sent)"}};AA=class AA extends DZ{constructor({message:Q,errorCode:Z}){super({message:Q,errorCode:Z,tag:"ListAppsCommandError"})}}});class Sq{constructor(Q){this.args=Q}name="listLanguagePack";getApdu(){let Q={cla:224,ins:52,p1:this.args.firstChunk?0:1,p2:0};return new w0(Q).build()}parseResponse(Q){let Z=new FQ(Q);if(!hQ.isSuccessResponse(Q)){let G=Z.encodeToHexaString(Q.statusCode);return kY(G,MA)?o({error:new K9({...MA[G],errorCode:G})}):o({error:NZ.handle(Q)})}if(Z.extract8BitUInt()===void 0)return o({data:void 0});Z.extract8BitUInt();let Y=Z.extractFieldLVEncoded();if(Y===void 0)return o({error:new C0("Failed to get language pack id")});let $=Z.extractFieldLVEncoded();if($===void 0)return o({error:new C0("Failed to get language pack size")});let J=parseInt(DQ(Y),16),X=parseInt(DQ($),16);return o({data:{id:J,size:X}})}}var MA,K9;var mO=w(()=>{a$();r$();MG();TZ();I1();oY();VJ();dJ();O8();MA={"662d":{message:"Invalid LIST_ARG, first command must be sent with P1_LIST_LANGUAGE_PACKS_FIRST."}};K9=class K9 extends DZ{constructor({message:Q,errorCode:Z}){super({message:Q,errorCode:Z,tag:"ListLanguagePackCommandError"})}}});class L1{name="loadCertificate";args;triggersDisconnection=!1;constructor(Q){this.args=Q}getApdu(){let Q={cla:176,ins:6,p1:this.args.keyUsage,p2:0};return new w0(Q).addBufferToData(this.args.certificate).build()}parseResponse(Q){if(hQ.isSuccessResponse(Q))return o({data:void 0});let Z=new FQ(Q).encodeToHexaString(Q.statusCode);return kY(Z,TA)?o({error:new NA({...TA[Z],errorCode:Z})}):o({error:NZ.handle(Q)})}}var TA,NA;var BA=w(()=>{a$();r$();TZ();I1();oY();VJ();dJ();TA={"422f":{message:"Incorrect structure type"},4230:{message:"Incorrect certificate version"},4231:{message:"Incorrect certificate validity"},4232:{message:"Incorrect certificate validity index"},4233:{message:"Unknown signer key ID"},4234:{message:"Unknown signature algorithm"},4235:{message:"Unknown public key ID"},4236:{message:"Unknown public key usage"},4237:{message:"Incorrect elliptic curve ID"},4238:{message:"Incorrect signature algorithm associated to the public key"},4239:{message:"Unknown target device"},"422d":{message:"Unknown certificate tag"},3301:{message:"Failed to hash data"},"422e":{message:"expected_key_usage doesn't match certificate key usage"},5720:{message:"Failed to verify signature"},4118:{message:"trusted_name buffer is too small to contain the trusted name"},ffff:{message:"Cryptography-related error"}};NA=class NA extends DZ{constructor({message:Q,errorCode:Z}){super({tag:"ProvidePkiCertificateCommandError",message:Q,errorCode:Z})}}});class wq{name="openApp";args;triggersDisconnection=!0;constructor(Q){this.args=Q}getApdu(){return new w0({cla:224,ins:216,p1:0,p2:0}).addAsciiStringToData(this.args.appName).build()}parseResponse(Q){if(hQ.isSuccessResponse(Q))return o({data:void 0});let Z=new FQ(Q).encodeToHexaString(Q.statusCode);return kY(Z,kA)?o({error:new CA({...kA[Z],errorCode:Z})}):o({error:NZ.handle(Q)})}}var kA,CA;var dO=w(()=>{a$();r$();TZ();I1();oY();VJ();dJ();kA={"670a":{message:"No app name provided"},6807:{message:"Unknown application name"}};CA=class CA extends DZ{constructor({message:Q,errorCode:Z}){super({tag:"OpenAppCommandError",message:Q,errorCode:Z})}}});var aY;var U9=w(()=>{aY=((Q)=>(Q.LOCKED="LOCKED",Q.BUSY="BUSY",Q.CONNECTED="CONNECTED",Q.NOT_CONNECTED="NOT CONNECTED",Q))(aY||{})});var D8;var nO=w(()=>{D8=((Q)=>(Q.NotStarted="not-started",Q.Pending="pending",Q.Stopped="stopped",Q.Completed="completed",Q.Error="error",Q))(D8||{})});var k0;var CY=w(()=>{k0=((Q)=>(Q.None="none",Q.UnlockDevice="unlock-device",Q.AllowSecureConnection="allow-secure-connection",Q.ConfirmOpenApp="confirm-open-app",Q.SignTransaction="sign-transaction",Q.SignTypedData="sign-typed-data",Q.AllowListApps="allow-list-apps",Q.VerifyAddress="verify-address",Q.SignPersonalMessage="sign-personal-message",Q.SignDelegationAuthorization="sign-delegation-authorization",Q.Web3ChecksOptIn="web3-checks-opt-in",Q.VerifySafeAddress="verify-safe-address",Q.RegisterWallet="register-wallet",Q.ConfirmLoadImage="confirm-load-image",Q.ConfirmCommitImage="confirm-commit-image",Q.ConfirmRemoveImage="confirm-remove-image",Q.GrantConsent="grant-consent",Q.AllowInstallFirmware="allow-install-firmware",Q))(k0||{})});class O9{constructor(Q){this.__value=Q,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(){let Q=this.__value;return Q instanceof Date?Q.toJSON():Q}equals(Q){return this.extract()===Q.extract()}map(Q){return HQ(Q(this.__value))}ap(Q){return Q.isJust()?this.map(Q.extract()):YQ}alt(Q){return this}altLazy(Q){return this}chain(Q){return Q(this.__value)}chainNullable(Q){return q0.fromNullable(Q(this.__value))}join(){return this.__value}reduce(Q,Z){return Q(Z,this.__value)}extend(Q){return HQ(Q(this))}unsafeCoerce(){return this.__value}caseOf(Q){return"_"in Q?Q._():Q.Just(this.__value)}orDefault(Q){return this.__value}orDefaultLazy(Q){return this.__value}toList(){return[this.__value]}mapOrDefault(Q,Z){return Q(this.__value)}extract(){return this.__value}extractNullable(){return this.__value}toEither(Q){return U0(this.__value)}ifJust(Q){return Q(this.__value),this}ifNothing(Q){return this}filter(Q){return Q(this.__value)?HQ(this.__value):YQ}}class H9{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(Q){return this.extract()===Q.extract()}map(Q){return YQ}ap(Q){return YQ}alt(Q){return Q}altLazy(Q){return Q()}chain(Q){return YQ}chainNullable(Q){return YQ}join(){return YQ}reduce(Q,Z){return Z}extend(Q){return YQ}unsafeCoerce(){throw Error("Maybe#unsafeCoerce was ran on a Nothing")}caseOf(Q){return"_"in Q?Q._():Q.Nothing()}orDefault(Q){return Q}orDefaultLazy(Q){return Q()}toList(){return[]}mapOrDefault(Q,Z){return Z}extract(){return}extractNullable(){return null}toEither(Q){return a(Q)}ifJust(Q){return this}ifNothing(Q){return Q(),this}filter(Q){return YQ}}var q0,HQ=(Q)=>new O9(Q),YQ;var _q=w(()=>{vq();q0={of(Q){return HQ(Q)},empty(){return YQ},zero(){return YQ},fromNullable(Q){return Q==null?YQ:HQ(Q)},fromFalsy(Q){return Q?HQ(Q):YQ},fromPredicate(Q,Z){switch(arguments.length){case 1:return(Y)=>q0.fromPredicate(Q,Y);default:return Q(Z)?HQ(Z):YQ}},mapMaybe(Q,Z){switch(arguments.length){case 1:return(Y)=>q0.mapMaybe(Q,Y);default:return q0.catMaybes(Z.map(Q))}},catMaybes(Q){let Z=[];for(let Y of Q)if(Y.isJust())Z.push(Y.extract());return Z},encase(Q){try{return HQ(Q())}catch{return YQ}},isMaybe(Q){return Q instanceof O9||Q instanceof H9},sequence(Q){let Z=[];for(let Y of Q)if(Y.isJust())Z.push(Y.extract());else return YQ;return HQ(Z)},"fantasy-land/of"(Q){return this.of(Q)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};O9.prototype.constructor=q0;H9.prototype.constructor=q0;YQ=new H9});class D9{constructor(Q){this.__value=Q,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(Q,Z){return U0(Z(this.__value))}map(Q){return U0(Q(this.__value))}mapLeft(Q){return this}ap(Q){return Q.isRight()?this.map(Q.extract()):Q}equals(Q){return Q.isRight()?this.__value===Q.extract():!1}chain(Q){return Q(this.__value)}chainLeft(Q){return this}join(){return this.__value}alt(Q){return this}altLazy(Q){return this}reduce(Q,Z){return Q(Z,this.__value)}extend(Q){return U0(Q(this))}unsafeCoerce(){return this.__value}caseOf(Q){return"_"in Q?Q._():Q.Right(this.__value)}leftOrDefault(Q){return Q}orDefault(Q){return this.__value}orDefaultLazy(Q){return this.__value}leftOrDefaultLazy(Q){return Q()}ifLeft(Q){return this}ifRight(Q){return Q(this.__value),this}toMaybe(){return HQ(this.__value)}leftToMaybe(){return YQ}extract(){return this.__value}swap(){return a(this.__value)}}class I9{constructor(Q){this.__value=Q,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(Q,Z){return a(Q(this.__value))}map(Q){return this}mapLeft(Q){return a(Q(this.__value))}ap(Q){return Q.isLeft()?Q:this}equals(Q){return Q.isLeft()?Q.extract()===this.__value:!1}chain(Q){return this}chainLeft(Q){return Q(this.__value)}join(){return this}alt(Q){return Q}altLazy(Q){return Q()}reduce(Q,Z){return Z}extend(Q){return this}unsafeCoerce(){if(this.__value instanceof Error)throw this.__value;throw Error("Either#unsafeCoerce was ran on a Left")}caseOf(Q){return"_"in Q?Q._():Q.Left(this.__value)}leftOrDefault(Q){return this.__value}orDefault(Q){return Q}orDefaultLazy(Q){return Q()}leftOrDefaultLazy(Q){return this.__value}ifLeft(Q){return Q(this.__value),this}ifRight(Q){return this}toMaybe(){return YQ}leftToMaybe(){return HQ(this.__value)}extract(){return this.__value}swap(){return U0(this.__value)}}var GZ,a=(Q)=>new I9(Q),U0=(Q)=>new D9(Q);var vq=w(()=>{_q();GZ={of(Q){return U0(Q)},lefts(Q){let Z=[];for(let Y of Q)if(Y.isLeft())Z.push(Y.extract());return Z},rights(Q){let Z=[];for(let Y of Q)if(Y.isRight())Z.push(Y.extract());return Z},encase(Q){try{return U0(Q())}catch(Z){return a(Z)}},sequence(Q){let Z=[];for(let Y of Q){if(Y.isLeft())return Y;Z.push(Y.extract())}return U0(Z)},isEither(Q){return Q instanceof I9||Q instanceof D9},"fantasy-land/of"(Q){return GZ.of(Q)}};D9.prototype.constructor=GZ;I9.prototype.constructor=GZ});var E1=(Q)=>Q;var oO=()=>{};var Vd=(Q)=>Q,sO;var SA=w(()=>{_q();sO=Object.assign(Vd,{fromArray:(Q)=>sO.isNonEmpty(Q)?HQ(Q):YQ,unsafeCoerce:(Q)=>{if(sO.isNonEmpty(Q))return Q;throw Error("NonEmptyList#unsafeCoerce was ran on an empty array")},fromTuple:(Q)=>sO(Q.toArray()),head:(Q)=>Q[0],last:(Q)=>Q[Q.length-1],isNonEmpty:(Q)=>Q.length>0,tail:(Q)=>Q.slice(1)})});var R9=(Q,Z)=>{return typeof Z==="bigint"?Z.toString():Z},wA=(Q)=>typeof Q==="object"&&Q!==null&&!Array.isArray(Q),oJ=(Q,Z)=>{let Y="";switch(typeof Z){case"undefined":Y="undefined";break;case"object":Y=Z===null?"null":Array.isArray(Z)?"an array with value "+JSON.stringify(Z,R9):"an object with value "+JSON.stringify(Z,R9);break;case"boolean":Y="a boolean";break;case"symbol":Y="a symbol";break;case"function":Y="a function";break;case"bigint":Y=`a bigint with value ${Z.toString()}`}return Y=Y||`a ${typeof Z} with value ${JSON.stringify(Z,R9)}`,`Expected ${Q}, but received ${Y}`},qd=(Q)=>{if(Object.keys(Q).length===1&&Q.oneOf?.length===1&&typeof Q.oneOf[0]==="object")Object.assign(Q,Q.oneOf[0]),delete Q.oneOf;return Q},Fd=(Q)=>{if(Array.isArray(Q.oneOf))for(let Z=0;Z<Q.oneOf.length;Z++){let Y=Q.oneOf[Z];if(typeof Y==="object"&&Y.oneOf)return Q.oneOf.splice(Z,1),Q.oneOf.push(...Y.oneOf),_A(Q)}return Q},_A=(Q)=>{return Fd(Q),qd(Q),Q},RQ,TQ,I8,z90,zd,WZ=(Q)=>({...iO([Q,zd]),schema:Q.schema,_isOptional:!0}),W90,K90,iO=(Q)=>RQ.custom({decode:(Z)=>{let Y=[];for(let $ of Q){let J=$.decode(Z);if(J.isRight())return J;else Y.push(J.extract())}return a(`One of the following problems occured: ${Y.map(($,J)=>`(${J}) ${$}`).join(", ")}`)},encode:(Z)=>{for(let Y of Q)if(GZ.encase(()=>Y.encode(Z)).mapLeft((J)=>"").chain(Y.decode).isRight())return Y.encode(Z);return Z},schema:()=>({oneOf:Q.map((Z)=>Z.schema())})}),bZ=(Q)=>RQ.custom({decode:(Z)=>{if(!Array.isArray(Z))return a(oJ("an array",Z));else{let Y=[];for(let $=0;$<Z.length;$++){let J=Q.decode(Z[$]);if(J.isRight())Y.push(J.extract());else return a(`Problem with the value at index ${$}: ${J.extract()}`)}return U0(Y)}},encode:(Z)=>Z.map(Q.encode),schema:()=>({type:"array",items:Q.schema()})}),Wd,aO=(Q,Z)=>RQ.custom({decode:(Y)=>{let $={},J=Q===I8?Wd:Q;if(!wA(Y))return a(oJ("an object",Y));for(let X of Object.keys(Y))if(Y.hasOwnProperty(X)){let G=J.decode(X),W=Z.decode(Y[X]);if(G.isRight()&&W.isRight())$[G.extract()]=W.extract();else if(G.isLeft())return a(`Problem with key type of property "${X}": ${G.extract()}`);else if(W.isLeft())return a(`Problem with the value of property "${X}": ${W.extract()}`)}return U0($)},encode:(Y)=>{let $={};for(let J in Y)if(Y.hasOwnProperty(J))$[Q.encode(J)]=Z.encode(Y[J]);return $},schema:()=>({type:"object",additionalProperties:Z.schema()})}),lX=(...Q)=>RQ.custom({decode:(Z)=>Q.includes(Z)?U0(Z):a(oJ(Q.map((Y)=>JSON.stringify(Y)).join(", "),Z)),encode:E1,schema:()=>({oneOf:Q.map((Z)=>({type:typeof Z,enum:[Z]}))})}),U90;var vA=w(()=>{vq();oO();RQ={interface(Q){let Z=Object.keys(Q),Y=(J)=>{if(!wA(J))return a(oJ("an object",J));let X={};for(let G of Z){if(!J.hasOwnProperty(G)&&!Q[G]._isOptional)return a(`Problem with property "${G}": it does not exist in received object ${JSON.stringify(J,R9)}`);let W=Q[G].decode(J[G]);if(W.isLeft())return a(`Problem with the value of property "${G}": ${W.extract()}`);let U=W.extract();if(U!==void 0)X[G]=U}return U0(X)};return{decode:Y,encode:(J)=>{let X={};for(let G of Z)X[G]=Q[G].encode(J[G]);return X},unsafeDecode:(J)=>Y(J).mapLeft(Error).unsafeCoerce(),schema:()=>Z.reduce((J,X)=>{if(!Q[X]._isOptional)J.required.push(X);return J.properties[X]=_A(Q[X].schema()),J},{type:"object",properties:{},required:[]})}},custom({decode:Q,encode:Z,schema:Y}){return{decode:Q,encode:Z,unsafeDecode:($)=>Q($).mapLeft(Error).unsafeCoerce(),schema:Y??(()=>({}))}}},TQ=RQ.custom({decode:(Q)=>typeof Q==="string"?U0(Q):a(oJ("a string",Q)),encode:E1,schema:()=>({type:"string"})}),I8=RQ.custom({decode:(Q)=>typeof Q==="number"?U0(Q):a(oJ("a number",Q)),encode:E1,schema:()=>({type:"number"})}),z90=RQ.custom({decode:(Q)=>Q===null?U0(Q):a(oJ("a null",Q)),encode:E1,schema:()=>({type:"null"})}),zd=RQ.custom({decode:(Q)=>Q===void 0?U0(Q):a(oJ("an undefined",Q)),encode:E1}),W90=RQ.custom({decode:(Q)=>typeof Q==="boolean"?U0(Q):a(oJ("a boolean",Q)),encode:E1,schema:()=>({type:"boolean"})}),K90=RQ.custom({decode:U0,encode:E1,schema:()=>({})}),Wd=RQ.custom({decode:(Q)=>TQ.decode(Q).chain((Z)=>isFinite(+Z)?U0(Z):a(oJ("a number",Q))),encode:E1,schema:I8.schema}),U90=RQ.custom({decode:(Q)=>TQ.decode(Q).mapLeft((Z)=>`Problem with date string: ${Z}`).chain((Z)=>Number.isNaN(Date.parse(Z))?a("Expected a valid date string, but received a string that cannot be parsed"):U0(new Date(Z))),encode:(Q)=>Q.toISOString(),schema:()=>({type:"string",format:"date-time"})})});var rO,sJ;var xA=w(()=>{rO=class rO{constructor(Q,Z){this.first=Q,this.second=Z,this.length=2,this["fantasy-land/equals"]=this.equals,this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/ap"]=this.ap,this[0]=Q,this[1]=Z}*[Symbol.iterator](){yield this.first,yield this.second}toJSON(){return this.toArray()}inspect(){return`Tuple(${JSON.stringify(this.first)}, ${JSON.stringify(this.second)})`}toString(){return this.inspect()}fst(){return this.first}snd(){return this.second}equals(Q){return this.first===Q.fst()&&this.second===Q.snd()}bimap(Q,Z){return sJ(Q(this.first),Z(this.second))}mapFirst(Q){return sJ(Q(this.first),this.second)}map(Q){return sJ(this.first,Q(this.second))}reduce(Q,Z){return Q(Z,this.second)}toArray(){return[this.first,this.second]}swap(){return sJ(this.second,this.first)}ap(Q){return sJ(this.first,Q.snd()(this.second))}every(Q){return Q(this.first)&&Q(this.second)}some(Q){return Q(this.first)||Q(this.second)}};sJ=Object.assign((Q,Z)=>new rO(Q,Z),{fromArray:([Q,Z])=>{return sJ(Q,Z)},fanout:(...Q)=>{let[Z,Y,$]=Q;switch(Q.length){case 3:return sJ(Z($),Y($));case 2:return(J)=>sJ.fanout(Z,Y,J);default:return(J)=>(X)=>sJ.fanout(Z,J,X)}}});rO.prototype.constructor=sJ});var fA=()=>{};class tO{constructor(Q){this.runPromise=Q,this[yA]="EitherAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this.then=(Z,Y)=>{return this.run().then(Z,Y)}}leftOrDefault(Q){return this.run().then((Z)=>Z.leftOrDefault(Q))}orDefault(Q){return this.run().then((Z)=>Z.orDefault(Q))}join(){return EQ(async(Q)=>{let Z=await this;if(Z.isRight()){let Y=await Z.extract();return Q.liftEither(Y)}return Q.liftEither(Z)})}ap(Q){return EQ(async(Z)=>{let Y=await Q;if(Y.isRight()){let $=await this.run();if($.isRight())return Y.extract()($.extract());else return Z.liftEither($)}return Z.liftEither(Y)})}alt(Q){return EQ(async(Z)=>{let Y=await this.run();if(Y.isRight())return Y.extract();else{let $=await Q;return Z.liftEither($)}})}extend(Q){return EQ(async(Z)=>{let Y=await this.run();if(Y.isRight()){let $=EQ.liftEither(Y);return Z.liftEither(U0(Q($)))}return Z.liftEither(Y)})}async run(){try{return U0(await this.runPromise(gA))}catch(Q){return a(Q)}}bimap(Q,Z){return EQ(async(Y)=>{let $=await this.run();try{return await Y.liftEither($.bimap(Q,Z))}catch(J){throw await J}})}map(Q){return EQ((Z)=>this.runPromise(Z).then(Q))}mapLeft(Q){return EQ(async(Z)=>{try{return await this.runPromise(Z)}catch(Y){throw await Q(Y)}})}chain(Q){return EQ(async(Z)=>{let Y=await this.runPromise(Z);return Z.fromPromise(Q(Y))})}chainLeft(Q){return EQ(async(Z)=>{try{return await this.runPromise(Z)}catch(Y){return Z.fromPromise(Q(Y))}})}toMaybeAsync(){return QY(async({liftMaybe:Q})=>{let Z=await this.run();return Q(Z.toMaybe())})}swap(){return EQ(async(Q)=>{let Z=await this.run();if(Z.isRight())Q.throwE(Z.extract());return Q.liftEither(U0(Z.extract()))})}ifLeft(Q){return EQ(async(Z)=>{let Y=await this.run();return Y.ifLeft(Q),Z.liftEither(Y)})}ifRight(Q){return EQ(async(Z)=>{let Y=await this.run();return Y.ifRight(Q),Z.liftEither(Y)})}void(){return this.map((Q)=>{})}caseOf(Q){return this.run().then((Z)=>Z.caseOf(Q))}finally(Q){return EQ(({fromPromise:Z})=>Z(this.run().finally(Q)))}}var yA,gA,EQ;var eO=w(()=>{vq();Q2();gA={liftEither(Q){if(Q.isRight())return Promise.resolve(Q.extract());throw Q.extract()},fromPromise(Q){return Q.then(gA.liftEither)},throwE(Q){throw Q}};yA=Symbol.toStringTag;EQ=Object.assign((Q)=>new tO(Q),{fromPromise:(Q)=>EQ(({fromPromise:Z})=>Z(Q())),liftEither:(Q)=>EQ(({liftEither:Z})=>Z(Q)),lefts:(Q)=>Promise.all(Q.map((Z)=>Z.run())).then(GZ.lefts),rights:(Q)=>Promise.all(Q.map((Z)=>Z.run())).then(GZ.rights),sequence:(Q)=>EQ(async(Z)=>{let Y=[];for await(let $ of Q){if($.isLeft())return Z.liftEither($);Y.push($.extract())}return Z.liftEither(U0(Y))}),all:(Q)=>EQ.fromPromise(async()=>Promise.all(Q).then(GZ.sequence))});tO.prototype.constructor=EQ});class Z2{constructor(Q){this.runPromise=Q,this[hA]="MaybeAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/filter"]=this.filter,this["fantasy-land/alt"]=this.alt}orDefault(Q){return this.run().then((Z)=>Z.orDefault(Q))}join(){return QY(async(Q)=>{let Z=await this.run();if(Z.isJust()){let Y=await Z.extract();return Q.liftMaybe(Y)}return Q.liftMaybe(YQ)})}ap(Q){return QY(async(Z)=>{let Y=await Q;if(Y.isJust()){let $=await this.run();if($.isJust())return Y.extract()($.extract());else return Z.liftMaybe(YQ)}return Z.liftMaybe(YQ)})}alt(Q){return QY(async(Z)=>{let Y=await this.run();if(Y.isJust())return Y.extract();else{let $=await Q;return Z.liftMaybe($)}})}extend(Q){return QY(async(Z)=>{let Y=await this.run();if(Y.isJust()){let $=QY.liftMaybe(Y);return Z.liftMaybe(HQ(Q($)))}return Z.liftMaybe(YQ)})}filter(Q){return QY(async(Z)=>{let Y=await this.run();return Z.liftMaybe(Y.filter(Q))})}async run(){try{return HQ(await this.runPromise(bA))}catch{return YQ}}map(Q){return QY((Z)=>this.runPromise(Z).then(Q))}chain(Q){return QY(async(Z)=>{let Y=await this.runPromise(Z);return Z.fromPromise(Q(Y))})}toEitherAsync(Q){return EQ(async({liftEither:Z})=>{let Y=await this.run();return Z(Y.toEither(Q))})}ifJust(Q){return QY(async(Z)=>{let Y=await this.run();return Y.ifJust(Q),Z.liftMaybe(Y)})}ifNothing(Q){return QY(async(Z)=>{let Y=await this.run();return Y.ifNothing(Q),Z.liftMaybe(Y)})}void(){return this.map((Q)=>{})}caseOf(Q){return this.run().then((Z)=>Z.caseOf(Q))}finally(Q){return QY(({fromPromise:Z})=>Z(this.run().finally(Q)))}then(Q,Z){return this.run().then(Q,Z)}}var hA,bA,QY;var Q2=w(()=>{_q();eO();bA={liftMaybe(Q){if(Q.isJust())return Promise.resolve(Q.extract());throw YQ},fromPromise(Q){return Q.then(bA.liftMaybe)}};hA=Symbol.toStringTag;QY=Object.assign((Q)=>new Z2(Q),{catMaybes:(Q)=>Promise.all(Q).then(q0.catMaybes),fromPromise:(Q)=>QY(({fromPromise:Z})=>Z(Q())),liftMaybe:(Q)=>QY(({liftMaybe:Z})=>Z(Q))});Z2.prototype.constructor=QY});var R0=w(()=>{Q2();eO();vA();vq();oO();fA();_q();SA();xA()});function Kd(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function Ud(){let Q=Kd();if(Q.__xstate__)return Q.__xstate__;return}var cA=(Q)=>{if(typeof window>"u")return;let Z=Ud();if(Z)Z.register(Q)};var uA=()=>{};class J2{constructor(Q){this._process=Q,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){if(this._current)this._current.next=null,this._last=this._current}enqueue(Q){let Z={value:Q,next:null};if(this._current){this._last.next=Z,this._last=Z;return}if(this._current=Z,this._last=Z,this._active)this.flush()}flush(){while(this._current){let Q=this._current;this._process(Q.value),this._current=Q.next}this._last=null}}function Id(Q,Z){return{type:`xstate.after.${Q}.${Z}`}}function G2(Q,Z){return{type:`xstate.done.state.${Q}`,output:Z}}function Rd(Q,Z){return{type:`xstate.done.actor.${Q}`,output:Z,actorId:Q}}function sA(Q,Z){return{type:`xstate.error.actor.${Q}`,error:Z,actorId:Q}}function z2(Q){return{type:oA,input:Q}}function P1(Q){setTimeout(()=>{throw Q})}function W2(Q,Z){let Y=pA(Q),$=pA(Z);if(typeof $==="string"){if(typeof Y==="string")return $===Y;return!1}if(typeof Y==="string")return Y in $;return Object.keys(Y).every((J)=>{if(!(J in $))return!1;return W2(Y[J],$[J])})}function P9(Q){if(rA(Q))return Q;let Z=[],Y="";for(let $=0;$<Q.length;$++){switch(Q.charCodeAt($)){case 92:Y+=Q[$+1],$++;continue;case 46:Z.push(Y),Y="";continue}Y+=Q[$]}return Z.push(Y),Z}function pA(Q){if(KM(Q))return Q.value;if(typeof Q!=="string")return Q;let Z=P9(Q);return iA(Z)}function iA(Q){if(Q.length===1)return Q[0];let Z={},Y=Z;for(let $=0;$<Q.length-1;$++)if($===Q.length-2)Y[Q[$]]=Q[$+1];else{let J=Y;Y={},J[Q[$]]=Y}return Z}function K2(Q,Z){let Y={},$=Object.keys(Q);for(let J=0;J<$.length;J++){let X=$[J];Y[X]=Z(Q[X],X,Q,J)}return Y}function aA(Q){if(rA(Q))return Q;return[Q]}function j1(Q){if(Q===void 0)return[];return aA(Q)}function X2(Q,Z,Y,$){if(typeof Q==="function")return Q({context:Z,event:Y,self:$});return Q}function rA(Q){return Array.isArray(Q)}function Ed(Q){return Q.type.startsWith("xstate.error.actor")}function SG(Q){return aA(Q).map((Z)=>{if(typeof Z>"u"||typeof Z==="string")return{target:Z};return Z})}function tA(Q){if(Q===void 0||Q===Od)return;return j1(Q)}function L9(Q,Z,Y){let $=typeof Q==="object",J=$?Q:void 0;return{next:($?Q.next:Q)?.bind(J),error:($?Q.error:Z)?.bind(J),complete:($?Q.complete:Y)?.bind(J)}}function U2(Q,Z){return`${Z}.${Q}`}function fq(Q,Z){let Y=Z.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!Y)return Q.implementations.actors[Z];let[,$,J]=Y,G=Q.getStateNodeById(J).config.invoke;return(Array.isArray(G)?G[$]:G).src}function lA(Q,Z){return`${Q.sessionId}.${Z}`}function jd(Q,Z){let Y=new Map,$=new Map,J=new WeakMap,X=new Set,G={},{clock:W,logger:U}=Z,K={schedule:(L,A,M,k,B=Math.random().toString(36).slice(2))=>{let C={source:L,target:A,event:M,delay:k,id:B,startedAt:Date.now()},S=lA(L,B);I._snapshot._scheduledEvents[S]=C;let _=W.setTimeout(()=>{delete G[S],delete I._snapshot._scheduledEvents[S],I._relay(L,A,M)},k);G[S]=_},cancel:(L,A)=>{let M=lA(L,A),k=G[M];if(delete G[M],delete I._snapshot._scheduledEvents[M],k!==void 0)W.clearTimeout(k)},cancelAll:(L)=>{for(let A in I._snapshot._scheduledEvents){let M=I._snapshot._scheduledEvents[A];if(M.source===L)K.cancel(L,M.id)}}},O=(L)=>{if(!X.size)return;let A={...L,rootId:Q.sessionId};X.forEach((M)=>M.next?.(A))},I={_snapshot:{_scheduledEvents:(Z?.snapshot&&Z.snapshot.scheduler)??{}},_bookId:()=>`x:${Pd++}`,_register:(L,A)=>{return Y.set(L,A),L},_unregister:(L)=>{Y.delete(L.sessionId);let A=J.get(L);if(A!==void 0)$.delete(A),J.delete(L)},get:(L)=>{return $.get(L)},_set:(L,A)=>{let M=$.get(L);if(M&&M!==A)throw Error(`Actor with system ID '${L}' already exists.`);$.set(L,A),J.set(A,L)},inspect:(L)=>{let A=L9(L);return X.add(A),{unsubscribe(){X.delete(A)}}},_sendInspectionEvent:O,_relay:(L,A,M)=>{I._sendInspectionEvent({type:"@xstate.event",sourceRef:L,actorRef:A,event:M}),A._send(M)},scheduler:K,getSnapshot:()=>{return{_scheduledEvents:{...I._snapshot._scheduledEvents}}},start:()=>{let L=I._snapshot._scheduledEvents;I._snapshot._scheduledEvents={};for(let A in L){let{source:M,target:k,event:B,delay:C,id:S}=L[A];K.schedule(M,k,B,C,S)}},_clock:W,_logger:U};return I}function zJ(Q,...[Z]){return new O2(Q,Z)}function Md(Q,Z,Y,$,{sendId:J}){let X=typeof J==="function"?J(Y,$):J;return[Z,{sendId:X},void 0]}function Td(Q,Z){Q.defer(()=>{Q.system.scheduler.cancel(Q.self,Z.sendId)})}function H2(Q){function Z(Y,$){}return Z.type="xstate.cancel",Z.sendId=Q,Z.resolve=Md,Z.execute=Td,Z}function Nd(Q,Z,Y,$,{id:J,systemId:X,src:G,input:W,syncSnapshot:U}){let K=typeof G==="string"?fq(Z.machine,G):G,O=typeof J==="function"?J(Y):J,I,L=void 0;if(K)L=typeof W==="function"?W({context:Z.context,event:Y.event,self:Q.self}):W,I=zJ(K,{id:O,src:G,parent:Q.self,syncSnapshot:U,systemId:X,input:L});return[E8(Z,{children:{...Z.children,[O]:I}}),{id:J,systemId:X,actorRef:I,src:G,input:L},void 0]}function Bd(Q,{actorRef:Z}){if(!Z)return;Q.defer(()=>{if(Z._processingStatus===W$.Stopped)return;Z.start()})}function D2(...[Q,{id:Z,systemId:Y,input:$,syncSnapshot:J=!1}={}]){function X(G,W){}return X.type="xstate.spawnChild",X.id=Z,X.systemId=Y,X.src=Q,X.input=$,X.syncSnapshot=J,X.resolve=Nd,X.execute=Bd,X}function kd(Q,Z,Y,$,{actorRef:J}){let X=typeof J==="function"?J(Y,$):J,G=typeof X==="string"?Z.children[X]:X,W=Z.children;if(G)W={...W},delete W[G.id];return[E8(Z,{children:W}),G,void 0]}function Cd(Q,Z){if(!Z)return;if(Q.system._unregister(Z),Z._processingStatus!==W$.Running){Q.stopChild(Z);return}Q.defer(()=>{Q.stopChild(Z)})}function A9(Q){function Z(Y,$){}return Z.type="xstate.stopChild",Z.actorRef=Q,Z.resolve=kd,Z.execute=Cd,Z}function Sd(Q,{context:Z,event:Y},{guards:$}){return $.every((J)=>oX(J,Z,Y,Q))}function yq(Q){function Z(Y,$){return!1}return Z.check=Sd,Z.guards=Q,Z}function oX(Q,Z,Y,$){let{machine:J}=$,X=typeof Q==="function",G=X?Q:J.implementations.guards[typeof Q==="string"?Q:Q.type];if(!X&&!G)throw Error(`Guard '${typeof Q==="string"?Q:Q.type}' is not implemented.'.`);if(typeof G!=="function")return oX(G,Z,Y,$);let W={context:Z,event:Y},U=X||typeof Q==="string"?void 0:("params"in Q)?typeof Q.params==="function"?Q.params({context:Z,event:Y}):Q.params:void 0;if(!("check"in G))return G(W,U);return G.check($,W,G)}function dX(Q){return Object.values(Q.states).filter((Z)=>Z.type!=="history")}function gq(Q,Z){let Y=[];if(Z===Q)return Y;let $=Q.parent;while($&&$!==Z)Y.push($),$=$.parent;return Y}function hq(Q){let Z=new Set(Q),Y=QM(Z);for(let $ of Z)if($.type==="compound"&&(!Y.get($)||!Y.get($).length))mA($).forEach((J)=>Z.add(J));else if($.type==="parallel")for(let J of dX($)){if(J.type==="history")continue;if(!Z.has(J)){let X=mA(J);for(let G of X)Z.add(G)}}for(let $ of Z){let J=$.parent;while(J)Z.add(J),J=J.parent}return Z}function eA(Q,Z){let Y=Z.get(Q);if(!Y)return{};if(Q.type==="compound"){let J=Y[0];if(J){if(I2(J))return J.key}else return{}}let $={};for(let J of Y)$[J.key]=eA(J,Z);return $}function QM(Q){let Z=new Map;for(let Y of Q){if(!Z.has(Y))Z.set(Y,[]);if(Y.parent){if(!Z.has(Y.parent))Z.set(Y.parent,[]);Z.get(Y.parent).push(Y)}}return Z}function ZM(Q,Z){let Y=hq(Z);return eA(Q,QM(Y))}function M9(Q,Z){if(Z.type==="compound")return dX(Z).some((Y)=>Y.type==="final"&&Q.has(Y));if(Z.type==="parallel")return dX(Z).every((Y)=>M9(Q,Y));return Z.type==="final"}function YM(Q,Z){return Q.transitions.get(Z)||[...Q.transitions.keys()].filter(($)=>{if($===Dd)return!0;if(!$.endsWith(".*"))return!1;let J=$.split("."),X=Z.split(".");for(let G=0;G<J.length;G++){let W=J[G],U=X[G];if(W==="*")return G===J.length-1;if(W!==U)return!1}return!0}).sort(($,J)=>J.length-$.length).flatMap(($)=>Q.transitions.get($))}function $M(Q){let Z=Q.config.after;if(!Z)return[];let Y=(J)=>{let X=Id(J,Q.id),G=X.type;return Q.entry.push(E2(X,{id:G,delay:J})),Q.exit.push(H2(G)),G};return Object.keys(Z).flatMap((J)=>{let X=Z[J],G=typeof X==="string"?{target:X}:X,W=Number.isNaN(+J)?J:+J,U=Y(W);return j1(G).map((K)=>({...K,event:U,delay:W}))}).map((J)=>{let{delay:X}=J;return{...R8(Q,J.event,J),delay:X}})}function R8(Q,Z,Y){let $=tA(Y.target),J=Y.reenter??!1,X=wd(Q,$),G={...Y,actions:j1(Y.actions),guard:Y.guard,target:X,source:Q,reenter:J,eventType:Z,toJSON:()=>({...G,source:`#${Q.id}`,target:X?X.map((W)=>`#${W.id}`):void 0})};return G}function JM(Q){let Z=new Map;if(Q.config.on)for(let Y of Object.keys(Q.config.on)){if(Y===F2)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let $=Q.config.on[Y];Z.set(Y,SG($).map((J)=>R8(Q,Y,J)))}if(Q.config.onDone){let Y=`xstate.done.state.${Q.id}`;Z.set(Y,SG(Q.config.onDone).map(($)=>R8(Q,Y,$)))}for(let Y of Q.invoke){if(Y.onDone){let $=`xstate.done.actor.${Y.id}`;Z.set($,SG(Y.onDone).map((J)=>R8(Q,$,J)))}if(Y.onError){let $=`xstate.error.actor.${Y.id}`;Z.set($,SG(Y.onError).map((J)=>R8(Q,$,J)))}if(Y.onSnapshot){let $=`xstate.snapshot.${Y.id}`;Z.set($,SG(Y.onSnapshot).map((J)=>R8(Q,$,J)))}}for(let Y of Q.after){let $=Z.get(Y.eventType);if(!$)$=[],Z.set(Y.eventType,$);$.push(Y)}return Z}function GM(Q,Z){let Y=typeof Z==="string"?Q.states[Z]:Z?Q.states[Z.target]:void 0;if(!Y&&Z)throw Error(`Initial state node "${Z}" not found on parent state node #${Q.id}`);let $={source:Q,actions:!Z||typeof Z==="string"?[]:j1(Z.actions),eventType:null,reenter:!1,target:Y?[Y]:[],toJSON:()=>({...$,source:`#${Q.id}`,target:Y?[`#${Y.id}`]:[]})};return $}function wd(Q,Z){if(Z===void 0)return;return Z.map((Y)=>{if(typeof Y!=="string")return Y;if(bq(Y))return Q.machine.getStateNodeById(Y);let $=Y[0]===q2;if($&&!Q.parent)return xq(Q,Y.slice(1));let J=$?Q.key+Y:Y;if(Q.parent)try{return xq(Q.parent,J)}catch(X){throw Error(`Invalid transition definition for state node '${Q.id}':
|
|
15
|
+
${X.message}`)}else throw Error(`Invalid target: "${Y}" is not a valid target from the root node. Did you mean ".${Y}"?`)})}function XM(Q){let Z=tA(Q.config.target);if(!Z)return Q.parent.initial;return{target:Z.map((Y)=>typeof Y==="string"?xq(Q.parent,Y):Y)}}function wG(Q){return Q.type==="history"}function mA(Q){let Z=R2(Q);for(let Y of Z)for(let $ of gq(Y,Q))Z.add($);return Z}function R2(Q){let Z=new Set;function Y($){if(Z.has($))return;if(Z.add($),$.type==="compound")Y($.initial.target[0]);else if($.type==="parallel")for(let J of dX($))Y(J)}return Y(Q),Z}function nX(Q,Z){if(bq(Z))return Q.machine.getStateNodeById(Z);if(!Q.states)throw Error(`Unable to retrieve child state '${Z}' from '${Q.id}'; no child states exist.`);let Y=Q.states[Z];if(!Y)throw Error(`Child state '${Z}' does not exist on '${Q.id}'`);return Y}function xq(Q,Z){if(typeof Z==="string"&&bq(Z))try{return Q.machine.getStateNodeById(Z)}catch{}let Y=P9(Z).slice(),$=Q;while(Y.length){let J=Y.shift();if(!J.length)break;$=nX($,J)}return $}function sX(Q,Z){if(typeof Z==="string"){let J=Q.states[Z];if(!J)throw Error(`State '${Z}' does not exist on '${Q.id}'`);return[Q,J]}let Y=Object.keys(Z),$=Y.map((J)=>nX(Q,J)).filter(Boolean);return[Q.machine.root,Q].concat($,Y.reduce((J,X)=>{let G=nX(Q,X);if(!G)return J;let W=sX(G,Z[X]);return J.concat(W)},[]))}function _d(Q,Z,Y,$){let X=nX(Q,Z).next(Y,$);if(!X||!X.length)return Q.next(Y,$);return X}function vd(Q,Z,Y,$){let J=Object.keys(Z),X=nX(Q,J[0]),G=T9(X,Z[J[0]],Y,$);if(!G||!G.length)return Q.next(Y,$);return G}function xd(Q,Z,Y,$){let J=[];for(let X of Object.keys(Z)){let G=Z[X];if(!G)continue;let W=nX(Q,X),U=T9(W,G,Y,$);if(U)J.push(...U)}if(!J.length)return Q.next(Y,$);return J}function T9(Q,Z,Y,$){if(typeof Z==="string")return _d(Q,Z,Y,$);if(Object.keys(Z).length===1)return vd(Q,Z,Y,$);return xd(Q,Z,Y,$)}function fd(Q){return Object.keys(Q.states).map((Z)=>Q.states[Z]).filter((Z)=>Z.type==="history")}function L8(Q,Z){let Y=Q;while(Y.parent&&Y.parent!==Z)Y=Y.parent;return Y.parent===Z}function yd(Q,Z){let Y=new Set(Q),$=new Set(Z);for(let J of Y)if($.has(J))return!0;for(let J of $)if(Y.has(J))return!0;return!1}function VM(Q,Z,Y){let $=new Set;for(let J of Q){let X=!1,G=new Set;for(let W of $)if(yd(V2([J],Z,Y),V2([W],Z,Y)))if(L8(J.source,W.source))G.add(W);else{X=!0;break}if(!X){for(let W of G)$.delete(W);$.add(J)}}return Array.from($)}function gd(Q){let[Z,...Y]=Q;for(let $ of gq(Z,void 0))if(Y.every((J)=>L8(J,$)))return $}function L2(Q,Z){if(!Q.target)return[];let Y=new Set;for(let $ of Q.target)if(wG($))if(Z[$.id])for(let J of Z[$.id])Y.add(J);else for(let J of L2(XM($),Z))Y.add(J);else Y.add($);return[...Y]}function qM(Q,Z){let Y=L2(Q,Z);if(!Y)return;if(!Q.reenter&&Y.every((J)=>J===Q.source||L8(J,Q.source)))return Q.source;let $=gd(Y.concat(Q.source));if($)return $;if(Q.reenter)return;return Q.source.machine.root}function V2(Q,Z,Y){let $=new Set;for(let J of Q)if(J.target?.length){let X=qM(J,Y);if(J.reenter&&J.source===X)$.add(X);for(let G of Z)if(L8(G,X))$.add(G)}return[...$]}function hd(Q,Z){if(Q.length!==Z.size)return!1;for(let Y of Q)if(!Z.has(Y))return!1;return!0}function E9(Q,Z,Y,$,J,X){if(!Q.length)return Z;let G=new Set(Z._nodes),W=Z.historyValue,U=VM(Q,G,W),K=Z;if(!J)[K,W]=pd(K,$,Y,U,G,W,X,Y.actionExecutor);K=vG(K,$,Y,U.flatMap((I)=>I.actions),X,void 0),K=cd(K,$,Y,U,G,X,W,J);let O=[...G];if(K.status==="done")K=vG(K,$,Y,O.sort((I,L)=>L.order-I.order).flatMap((I)=>I.exit),X,void 0);try{if(W===Z.historyValue&&hd(Z._nodes,G))return K;return E8(K,{_nodes:O,historyValue:W})}catch(I){throw I}}function bd(Q,Z,Y,$,J){if($.output===void 0)return;let X=G2(J.id,J.output!==void 0&&J.parent?X2(J.output,Q.context,Z,Y.self):void 0);return X2($.output,Q.context,X,Y.self)}function cd(Q,Z,Y,$,J,X,G,W){let U=Q,K=new Set,O=new Set;if(ud($,G,O,K),W)O.add(Q.machine.root);let I=new Set;for(let L of[...K].sort((A,M)=>A.order-M.order)){J.add(L);let A=[];A.push(...L.entry);for(let M of L.invoke)A.push(D2(M.src,{...M,syncSnapshot:!!M.onSnapshot}));if(O.has(L)){let M=L.initial.actions;A.push(...M)}if(U=vG(U,Z,Y,A,X,L.invoke.map((M)=>M.id)),L.type==="final"){let M=L.parent,k=M?.type==="parallel"?M:M?.parent,B=k||L;if(M?.type==="compound")X.push(G2(M.id,L.output!==void 0?X2(L.output,U.context,Z,Y.self):void 0));while(k?.type==="parallel"&&!I.has(k)&&M9(J,k))I.add(k),X.push(G2(k.id)),B=k,k=k.parent;if(k)continue;U=E8(U,{status:"done",output:bd(U,Z,Y,U.machine.root,B)})}}return U}function ud(Q,Z,Y,$){for(let J of Q){let X=qM(J,Z);for(let W of J.target||[]){if(!wG(W)&&(J.source!==W||J.source!==X||J.reenter))$.add(W),Y.add(W);mX(W,Z,Y,$)}let G=L2(J,Z);for(let W of G){let U=gq(W,X);if(X?.type==="parallel")U.push(X);FM($,Z,Y,U,!J.source.parent&&J.reenter?void 0:X)}}}function mX(Q,Z,Y,$){if(wG(Q))if(Z[Q.id]){let J=Z[Q.id];for(let X of J)$.add(X),mX(X,Z,Y,$);for(let X of J)$2(X,Q.parent,$,Z,Y)}else{let J=XM(Q);for(let X of J.target){if($.add(X),J===Q.parent?.initial)Y.add(Q.parent);mX(X,Z,Y,$)}for(let X of J.target)$2(X,Q.parent,$,Z,Y)}else if(Q.type==="compound"){let[J]=Q.initial.target;if(!wG(J))$.add(J),Y.add(J);mX(J,Z,Y,$),$2(J,Q,$,Z,Y)}else if(Q.type==="parallel"){for(let J of dX(Q).filter((X)=>!wG(X)))if(![...$].some((X)=>L8(X,J))){if(!wG(J))$.add(J),Y.add(J);mX(J,Z,Y,$)}}}function FM(Q,Z,Y,$,J){for(let X of $){if(!J||L8(X,J))Q.add(X);if(X.type==="parallel"){for(let G of dX(X).filter((W)=>!wG(W)))if(![...Q].some((W)=>L8(W,G)))Q.add(G),mX(G,Z,Y,Q)}}}function $2(Q,Z,Y,$,J){FM(Y,$,J,gq(Q,Z))}function pd(Q,Z,Y,$,J,X,G,W){let U=Q,K=V2($,J,X);K.sort((I,L)=>L.order-I.order);let O;for(let I of K)for(let L of fd(I)){let A;if(L.history==="deep")A=(M)=>I2(M)&&L8(M,I);else A=(M)=>{return M.parent===I};O??={...X},O[L.id]=Array.from(J).filter(A)}for(let I of K)U=vG(U,Z,Y,[...I.exit,...I.invoke.map((L)=>A9(L.id))],G,void 0),J.delete(I);return[U,O||X]}function ld(Q,Z){return Q.implementations.actions[Z]}function zM(Q,Z,Y,$,J,X){let{machine:G}=Q,W=Q;for(let U of $){let K=typeof U==="function",O=K?U:ld(G,typeof U==="string"?U:U.type),I={context:W.context,event:Z,self:Y.self,system:Y.system},L=K||typeof U==="string"?void 0:("params"in U)?typeof U.params==="function"?U.params({context:W.context,event:Z}):U.params:void 0;if(!O||!("resolve"in O)){Y.actionExecutor({type:typeof U==="string"?U:typeof U==="object"?U.type:U.name||"(anonymous)",info:I,params:L,exec:O});continue}let A=O,[M,k,B]=A.resolve(Y,W,I,L,O,J);if(W=M,"retryResolve"in A)X?.push([A,k]);if("execute"in A)Y.actionExecutor({type:A.type,info:I,params:k,exec:A.execute.bind(null,Y,k)});if(B)W=zM(W,Z,Y,B,J,X)}return W}function vG(Q,Z,Y,$,J,X){let G=X?[]:void 0,W=zM(Q,Z,Y,$,{internalQueue:J,deferredActorIds:X},G);return G?.forEach(([U,K])=>{U.retryResolve(Y,W,K)}),W}function N9(Q,Z,Y,$){let J=Q,X=[];function G(K,O,I){Y.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:Y.self,event:O,snapshot:K,_transitions:I}),X.push(K)}if(Z.type===_G)return J=E8(dA(J,Z,Y),{status:"stopped"}),G(J,Z,[]),{snapshot:J,microstates:X};let W=Z;if(W.type!==oA){let K=W,O=Ed(K),I=nA(K,J);if(O&&!I.length)return J=E8(Q,{status:"error",error:K.error}),G(J,K,[]),{snapshot:J,microstates:X};J=E9(I,Q,Y,W,!1,$),G(J,K,I)}let U=!0;while(J.status==="active"){let K=U?md(J,W):[],O=K.length?J:void 0;if(!K.length){if(!$.length)break;W=$.shift(),K=nA(W,J)}J=E9(K,J,Y,W,!1,$),U=J!==O,G(J,W,K)}if(J.status!=="active")dA(J,W,Y);return{snapshot:J,microstates:X}}function dA(Q,Z,Y){return vG(Q,Z,Y,Object.values(Q.children).map(($)=>A9($)),[],void 0)}function nA(Q,Z){return Z.machine.getTransitionData(Z,Q)}function md(Q,Z){let Y=new Set,$=Q._nodes.filter(I2);for(let J of $)Q:for(let X of[J].concat(gq(J,void 0))){if(!X.always)continue;for(let G of X.always)if(G.guard===void 0||oX(G.guard,Q.context,Z,Q)){Y.add(G);break Q}}return VM(Array.from(Y),new Set(Q._nodes),Q.historyValue)}function WM(Q,Z){let Y=hq(sX(Q,Z));return ZM(Q,[...Y])}function KM(Q){return!!Q&&typeof Q==="object"&&"machine"in Q&&"value"in Q}function cq(Q,Z){return{status:Q.status,output:Q.output,error:Q.error,machine:Z,context:Q.context,_nodes:Q._nodes,value:ZM(Z.root,Q._nodes),tags:new Set(Q._nodes.flatMap((Y)=>Y.tags)),children:Q.children,historyValue:Q.historyValue||{},matches:dd,hasTag:nd,can:od,getMeta:id,toJSON:sd}}function E8(Q,Z={}){return cq({...Q,...Z},Q.machine)}function UM(Q,Z){let{_nodes:Y,tags:$,machine:J,children:X,context:G,can:W,hasTag:U,matches:K,getMeta:O,toJSON:I,...L}=Q,A={};for(let k in X){let B=X[k];A[k]={snapshot:B.getPersistedSnapshot(Z),src:B.src,systemId:B._systemId,syncSnapshot:B._syncSnapshot}}return{...L,context:OM(G),children:A}}function OM(Q){let Z;for(let Y in Q){let $=Q[Y];if($&&typeof $==="object")if("sessionId"in $&&"send"in $&&"ref"in $)Z??=Array.isArray(Q)?Q.slice():{...Q},Z[Y]={xstate$$type:j9,id:$.id};else{let J=OM($);if(J!==$)Z??=Array.isArray(Q)?Q.slice():{...Q},Z[Y]=J}}return Z??Q}function ad(Q,Z,Y,$,{event:J,id:X,delay:G},{internalQueue:W}){let U=Z.machine.implementations.delays;if(typeof J==="string")throw Error(`Only event objects may be used with raise; use raise({ type: "${J}" }) instead`);let K=typeof J==="function"?J(Y,$):J,O;if(typeof G==="string"){let I=U&&U[G];O=typeof I==="function"?I(Y,$):I}else O=typeof G==="function"?G(Y,$):G;if(typeof O!=="number")W.push(K);return[Z,{event:K,id:X,delay:O},void 0]}function rd(Q,Z){let{event:Y,delay:$,id:J}=Z;if(typeof $==="number"){Q.defer(()=>{let X=Q.self;Q.system.scheduler.schedule(X,X,Y,$,J)});return}}function E2(Q,Z){function Y($,J){}return Y.type="xstate.raise",Y.event=Q,Y.id=Z?.id,Y.delay=Z?.delay,Y.resolve=ad,Y.execute=rd,Y}var q2=".",Od="",F2="",Hd="#",Dd="*",oA="xstate.init",_G="xstate.stop",Ld,Pd=0,Y2=!1,j9=1,W$,Ad,O2,I2=(Q)=>Q.type==="atomic"||Q.type==="final",bq=(Q)=>Q[0]===Hd,dd=function(Z){return W2(Z,this.value)},nd=function(Z){return this.tags.has(Z)},od=function(Z){let Y=this.machine.getTransitionData(this,Z);return!!Y?.length&&Y.some(($)=>$.target!==void 0||$.actions.length)},sd=function(){let{_nodes:Z,tags:Y,machine:$,getMeta:J,toJSON:X,can:G,hasTag:W,matches:U,...K}=this;return{...K,tags:Array.from(Y)}},id=function(){return this._nodes.reduce((Z,Y)=>{if(Y.meta!==void 0)Z[Y.id]=Y.meta;return Z},{})};var uq=w(()=>{uA();Ld=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();W$=function(Q){return Q[Q.NotStarted=0]="NotStarted",Q[Q.Running=1]="Running",Q[Q.Stopped=2]="Stopped",Q}({}),Ad={clock:{setTimeout:(Q,Z)=>{return setTimeout(Q,Z)},clearTimeout:(Q)=>{return clearTimeout(Q)}},logger:console.log.bind(console),devTools:!1};O2=class O2{constructor(Q,Z){this.logic=Q,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new J2(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=W$.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let Y={...Ad,...Z},{clock:$,logger:J,parent:X,syncSnapshot:G,id:W,systemId:U,inspect:K}=Y;if(this.system=X?X.system:jd(this,{clock:$,logger:J}),K&&!X)this.system.inspect(L9(K));if(this.sessionId=this.system._bookId(),this.id=W??this.sessionId,this.logger=Z?.logger??this.system._logger,this.clock=Z?.clock??this.system._clock,this._parent=X,this._syncSnapshot=G,this.options=Y,this.src=Y.src??Q,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:(O)=>{this._deferred.push(O)},system:this.system,stopChild:(O)=>{if(O._parent!==this)throw Error(`Cannot stop child actor ${O.id} of ${this.id} because it is not a child`);O._stop()},emit:(O)=>{let I=this.eventListeners.get(O.type),L=this.eventListeners.get("*");if(!I&&!L)return;let A=[...I?I.values():[],...L?L.values():[]];for(let M of A)M(O)},actionExecutor:(O)=>{let I=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:O.type,params:O.params}}),!O.exec)return;let L=Y2;try{Y2=!0,O.exec(O.info,O.params)}finally{Y2=L}};if(this._processingStatus===W$.Running)I();else this._deferred.push(I)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),U)this._systemId=U,this.system._set(U,this);if(this._initState(Z?.snapshot??Z?.state),U&&this._snapshot.status!=="active")this.system._unregister(this)}_initState(Q){try{this._snapshot=Q?this.logic.restoreSnapshot?this.logic.restoreSnapshot(Q,this._actorScope):Q:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(Z){this._snapshot={status:"error",output:void 0,error:Z}}}update(Q,Z){this._snapshot=Q;let Y;while(Y=this._deferred.shift())try{Y()}catch($){this._deferred.length=0,this._snapshot={...Q,status:"error",error:$}}switch(this._snapshot.status){case"active":for(let $ of this.observers)try{$.next?.(Q)}catch(J){P1(J)}break;case"done":for(let $ of this.observers)try{$.next?.(Q)}catch(J){P1(J)}if(this._stopProcedure(),this._complete(),this._doneEvent=Rd(this.id,this._snapshot.output),this._parent)this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:Z,snapshot:Q})}subscribe(Q,Z,Y){let $=L9(Q,Z,Y);if(this._processingStatus!==W$.Stopped)this.observers.add($);else switch(this._snapshot.status){case"done":try{$.complete?.()}catch(J){P1(J)}break;case"error":{let J=this._snapshot.error;if(!$.error)P1(J);else try{$.error(J)}catch(X){P1(X)}break}}return{unsubscribe:()=>{this.observers.delete($)}}}on(Q,Z){let Y=this.eventListeners.get(Q);if(!Y)Y=new Set,this.eventListeners.set(Q,Y);let $=Z.bind(void 0);return Y.add($),{unsubscribe:()=>{Y.delete($)}}}start(){if(this._processingStatus===W$.Running)return this;if(this._syncSnapshot)this.subscribe({next:(Y)=>{if(Y.status==="active")this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:Y})},error:()=>{}});if(this.system._register(this.sessionId,this),this._systemId)this.system._set(this._systemId,this);this._processingStatus=W$.Running;let Q=z2(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:Q}),this._snapshot.status){case"done":return this.update(this._snapshot,Q),this;case"error":return this._error(this._snapshot.error),this}if(!this._parent)this.system.start();if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(Y){return this._snapshot={...this._snapshot,status:"error",error:Y},this._error(Y),this}if(this.update(this._snapshot,Q),this.options.devTools)this.attachDevTools();return this.mailbox.start(),this}_process(Q){let Z,Y;try{Z=this.logic.transition(this._snapshot,Q,this._actorScope)}catch($){Y={err:$}}if(Y){let{err:$}=Y;this._snapshot={...this._snapshot,status:"error",error:$},this._error($);return}if(this.update(Z,Q),Q.type===_G)this._stopProcedure(),this._complete()}_stop(){if(this._processingStatus===W$.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===W$.NotStarted)return this._processingStatus=W$.Stopped,this;return this.mailbox.enqueue({type:_G}),this}stop(){if(this._parent)throw Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(let Q of this.observers)try{Q.complete?.()}catch(Z){P1(Z)}this.observers.clear()}_reportError(Q){if(!this.observers.size){if(!this._parent)P1(Q);return}let Z=!1;for(let Y of this.observers){let $=Y.error;Z||=!$;try{$?.(Q)}catch(J){P1(J)}}if(this.observers.clear(),Z)P1(Q)}_error(Q){if(this._stopProcedure(),this._reportError(Q),this._parent)this.system._relay(this,this._parent,sA(this.id,Q))}_stopProcedure(){if(this._processingStatus!==W$.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new J2(this._process.bind(this)),this._processingStatus=W$.Stopped,this.system._unregister(this),this}_send(Q){if(this._processingStatus===W$.Stopped)return;this.mailbox.enqueue(Q)}send(Q){this.system._relay(void 0,this,Q)}attachDevTools(){let{devTools:Q}=this.options;if(Q)(typeof Q==="function"?Q:cA)(this)}toJSON(){return{xstate$$type:j9,id:this.id}}getPersistedSnapshot(Q){return this.logic.getPersistedSnapshot(this._snapshot,Q)}[Ld](){return this}getSnapshot(){return this._snapshot}}});function PM(Q,Z){return{config:Q,transition:(Y,$,J)=>{return{...Y,context:Q(Y.context,$,J)}},getInitialSnapshot:(Y,$)=>{return{status:"active",output:void 0,error:void 0,context:typeof Z==="function"?Z({input:$}):Z}},getPersistedSnapshot:(Y)=>Y,restoreSnapshot:(Y)=>Y}}function P2(Q){return{config:Q,start:(Y,$)=>{let{self:J,system:X,emit:G}=$,W={receivers:void 0,dispose:void 0};HM.set(J,W),W.dispose=Q({input:Y.input,system:X,self:J,sendBack:(U)=>{if(J.getSnapshot().status==="stopped")return;if(J._parent)X._relay(J,J._parent,U)},receive:(U)=>{W.receivers??=new Set,W.receivers.add(U)},emit:G})},transition:(Y,$,J)=>{let X=HM.get(J.self);if($.type===_G)return Y={...Y,status:"stopped",error:void 0},X.dispose?.(),Y;return X.receivers?.forEach((G)=>G($)),Y},getInitialSnapshot:(Y,$)=>{return{status:"active",output:void 0,error:void 0,input:$}},getPersistedSnapshot:(Y)=>Y,restoreSnapshot:(Y)=>Y}}function cY(Q){return{config:Q,transition:(Y,$)=>{if(Y.status!=="active")return Y;switch($.type){case DM:return{...Y,context:$.data};case IM:return{...Y,status:"error",error:$.data,input:void 0,_subscription:void 0};case RM:return{...Y,status:"done",input:void 0,_subscription:void 0};case _G:return Y._subscription.unsubscribe(),{...Y,status:"stopped",input:void 0,_subscription:void 0};default:return Y}},getInitialSnapshot:(Y,$)=>{return{status:"active",output:void 0,error:void 0,context:void 0,input:$,_subscription:void 0}},start:(Y,{self:$,system:J,emit:X})=>{if(Y.status==="done")return;Y._subscription=Q({input:Y.input,system:J,self:$,emit:X}).subscribe({next:(G)=>{J._relay($,$,{type:DM,data:G})},error:(G)=>{J._relay($,$,{type:IM,data:G})},complete:()=>{J._relay($,$,{type:RM})}})},getPersistedSnapshot:({_subscription:Y,...$})=>$,restoreSnapshot:(Y)=>({...Y,_subscription:void 0})}}function VQ(Q){return{config:Q,transition:(Y,$,J)=>{if(Y.status!=="active")return Y;switch($.type){case LM:{let X=$.data;return{...Y,status:"done",output:X,input:void 0}}case EM:return{...Y,status:"error",error:$.data,input:void 0};case _G:return B9.get(J.self)?.abort(),{...Y,status:"stopped",input:void 0};default:return Y}},start:(Y,{self:$,system:J,emit:X})=>{if(Y.status!=="active")return;let G=new AbortController;B9.set($,G),Promise.resolve(Q({input:Y.input,system:J,self:$,signal:G.signal,emit:X})).then((U)=>{if($.getSnapshot().status!=="active")return;B9.delete($),J._relay($,$,{type:LM,data:U})},(U)=>{if($.getSnapshot().status!=="active")return;B9.delete($),J._relay($,$,{type:EM,data:U})})},getInitialSnapshot:(Y,$)=>{return{status:"active",output:void 0,error:void 0,input:$}},getPersistedSnapshot:(Y)=>Y,restoreSnapshot:(Y)=>Y}}var HM,DM="xstate.observable.next",IM="xstate.observable.error",RM="xstate.observable.complete",LM="xstate.promise.resolve",EM="xstate.promise.reject",B9,g90;var jM=w(()=>{uq();HM=new WeakMap;B9=new WeakMap;g90=PM((Q)=>{return},void 0)});function td(Q,{machine:Z,context:Y},$,J){let X=(G,W)=>{if(typeof G==="string"){let U=fq(Z,G);if(!U)throw Error(`Actor logic '${G}' not implemented in machine '${Z.id}'`);let K=zJ(U,{id:W?.id,parent:Q.self,syncSnapshot:W?.syncSnapshot,input:typeof W?.input==="function"?W.input({context:Y,event:$,self:Q.self}):W?.input,src:G,systemId:W?.systemId});return J[K.id]=K,K}else return zJ(G,{id:W?.id,parent:Q.self,syncSnapshot:W?.syncSnapshot,input:W?.input,src:G,systemId:W?.systemId})};return(G,W)=>{let U=X(G,W);return J[U.id]=U,Q.defer(()=>{if(U._processingStatus===W$.Stopped)return;U.start()}),U}}function ed(Q,Z,Y,$,{assignment:J}){if(!Z.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let X={},G={context:Z.context,event:Y.event,spawn:td(Q,Z,Y.event,X),self:Q.self,system:Q.system},W={};if(typeof J==="function")W=J(G,$);else for(let K of Object.keys(J)){let O=J[K];W[K]=typeof O==="function"?O(G,$):O}let U=Object.assign({},Z.context,W);return[E8(Z,{context:U,children:Object.keys(X).length?{...Z.children,...X}:Z.children}),void 0,void 0]}function r(Q){function Z(Y,$){}return Z.type="xstate.assign",Z.assignment=Q,Z.resolve=ed,Z}function Qn(Q,Z,Y,$,{event:J}){let X=typeof J==="function"?J(Y,$):J;return[Z,{event:X},void 0]}function Zn(Q,{event:Z}){Q.defer(()=>Q.emit(Z))}function j2(Q){function Z(Y,$){}return Z.type="xstate.emit",Z.event=Q,Z.resolve=Qn,Z.execute=Zn,Z}var A2=w(()=>{uq()});function iX(Q,Z,Y){let $=AM.get(Q);if(!$)$={[Z]:Y()},AM.set(Q,$);else if(!(Z in $))$[Z]=Y();return $[Z]}class M2{constructor(Q,Z){if(this.config=Q,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=Z._parent,this.key=Z._key,this.machine=Z._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(q2),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?K2(this.config.states,(Y,$)=>{return new M2(Y,{_parent:this,_key:$,_machine:this.machine})}):Yn,this.type==="compound"&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=j1(this.config.entry).slice(),this.exit=j1(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=j1(Q.tags).slice()}_initialize(){if(this.transitions=JM(this),this.config.always)this.always=SG(this.config.always).map((Q)=>R8(this,F2,Q));Object.keys(this.states).forEach((Q)=>{this.states[Q]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(pq),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((Q)=>`#${Q.id}`),source:`#${this.id}`,actions:this.initial.actions.map(pq),eventType:null})}:void 0,history:this.history,states:K2(this.states,(Q)=>{return Q.definition}),on:this.on,transitions:[...this.transitions.values()].flat().map((Q)=>({...Q,actions:Q.actions.map(pq)})),entry:this.entry.map(pq),exit:this.exit.map(pq),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return iX(this,"invoke",()=>j1(this.config.invoke).map((Q,Z)=>{let{src:Y,systemId:$}=Q,J=Q.id??U2(this.id,Z),X=typeof Y==="string"?Y:`xstate.invoke.${U2(this.id,Z)}`;return{...Q,src:X,id:J,systemId:$,toJSON(){let{onDone:G,onError:W,...U}=Q;return{...U,type:"xstate.invoke",src:X,id:J}}}}))}get on(){return iX(this,"on",()=>{return[...this.transitions].flatMap(([Z,Y])=>Y.map(($)=>[Z,$])).reduce((Z,[Y,$])=>{return Z[Y]=Z[Y]||[],Z[Y].push($),Z},{})})}get after(){return iX(this,"delayedTransitions",()=>$M(this))}get initial(){return iX(this,"initial",()=>GM(this,this.config.initial))}next(Q,Z){let Y=Z.type,$=[],J,X=iX(this,`candidates-${Y}`,()=>YM(this,Y));for(let G of X){let{guard:W}=G,U=Q.context,K=!1;try{K=!W||oX(W,U,Z,Q)}catch(O){let I=typeof W==="string"?W:typeof W==="object"?W.type:void 0;throw Error(`Unable to evaluate guard ${I?`'${I}' `:""}in transition for event '${Y}' in state node '${this.id}':
|
|
16
|
+
${O.message}`)}if(K){$.push(...G.actions),J=G;break}}return J?[J]:void 0}get events(){return iX(this,"events",()=>{let{states:Q}=this,Z=new Set(this.ownEvents);if(Q)for(let Y of Object.keys(Q)){let $=Q[Y];if($.states)for(let J of $.events)Z.add(`${J}`)}return Array.from(Z)})}get ownEvents(){let Q=new Set([...this.transitions.keys()].filter((Z)=>{return this.transitions.get(Z).some((Y)=>!(!Y.target&&!Y.actions.length&&!Y.reenter))}));return Array.from(Q)}}class T2{constructor(Q,Z){this.config=Q,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=Q.id||"(machine)",this.implementations={actors:Z?.actors??{},actions:Z?.actions??{},delays:Z?.delays??{},guards:Z?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new M2(Q,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(Q){let{actions:Z,guards:Y,actors:$,delays:J}=this.implementations;return new T2(this.config,{actions:{...Z,...Q.actions},guards:{...Y,...Q.guards},actors:{...$,...Q.actors},delays:{...J,...Q.delays}})}resolveState(Q){let Z=WM(this.root,Q.value),Y=hq(sX(this.root,Z));return cq({_nodes:[...Y],context:Q.context||{},children:{},status:M9(Y,this.root)?"done":Q.status||"active",output:Q.output,error:Q.error,historyValue:Q.historyValue},this)}transition(Q,Z,Y){return N9(Q,Z,Y,[]).snapshot}microstep(Q,Z,Y){return N9(Q,Z,Y,[]).microstates}getTransitionData(Q,Z){return T9(this.root,Q.value,Q,Z)||[]}getPreInitialState(Q,Z,Y){let{context:$}=this.config,J=cq({context:typeof $!=="function"&&$?$:{},_nodes:[this.root],children:{},status:"active"},this);if(typeof $==="function")return vG(J,Z,Q,[r(({spawn:G,event:W,self:U})=>$({spawn:G,input:W.input,self:U}))],Y,void 0);return J}getInitialSnapshot(Q,Z){let Y=z2(Z),$=[],J=this.getPreInitialState(Q,Y,$),X=E9([{target:[...R2(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],J,Q,Y,!0,$),{snapshot:G}=N9(X,Y,Q,$);return G}start(Q){Object.values(Q.children).forEach((Z)=>{if(Z.getSnapshot().status==="active")Z.start()})}getStateNodeById(Q){let Z=P9(Q),Y=Z.slice(1),$=bq(Z[0])?Z[0].slice($n.length):Z[0],J=this.idMap.get($);if(!J)throw Error(`Child state node '#${$}' does not exist on machine '${this.id}'`);return xq(J,Y)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(Q,Z){return UM(Q,Z)}restoreSnapshot(Q,Z){let Y={},$=Q.children;Object.keys($).forEach((W)=>{let U=$[W],K=U.snapshot,O=U.src,I=typeof O==="string"?fq(this,O):O;if(!I)return;let L=zJ(I,{id:W,parent:Z.self,syncSnapshot:U.syncSnapshot,snapshot:K,src:O,systemId:U.systemId});Y[W]=L});let J=cq({...Q,children:Y,_nodes:Array.from(hq(sX(this.root,Q.value)))},this),X=new Set;function G(W,U){if(X.has(W))return;X.add(W);for(let K in W){let O=W[K];if(O&&typeof O==="object"){if("xstate$$type"in O&&O.xstate$$type===j9){W[K]=U[O.id];continue}G(O,U)}}}return G(J.context,Y),J}}function Jn(Q,Z){return new T2(Q,Z)}function NQ({schemas:Q,actors:Z,actions:Y,guards:$,delays:J}){return{createMachine:(X)=>Jn({...X,schemas:Q},{actors:Z,actions:Y,guards:$,delays:J})}}var AM,Yn,pq=(Q)=>{if(typeof Q==="string")return{type:Q};if(typeof Q==="function"){if("resolve"in Q)return{type:Q.type};return{type:Q.name}}return Q},$n="#";var KZ=w(()=>{jM();uq();uq();A2();A2();AM=new WeakMap;Yn={}});class lq{_tag="DeviceNotOnboardedError";originalError;constructor(Q){this.originalError=Error(Q??"Device not onboarded.")}}class iJ{_tag="DeviceLockedError";originalError;constructor(Q){this.originalError=Error(Q??"Device locked.")}}class P8{_tag="UnsupportedFirmwareDAError";originalError;constructor(Q){this.originalError=Error(Q??"Unknown error.")}}class A1{_tag="RefusedByUserDAError";originalError;constructor(Q){this.originalError=Error(Q??"Unknown error.")}}class mq{_tag="AppAlreadyInstalledDAError";originalError;constructor(Q){this.originalError=Error(Q??"Unknown error.")}}class aJ{_tag="OutOfMemoryDAError";originalError;constructor(Q){this.originalError=Error(Q??"Unknown error.")}}class xQ{_tag="UnknownDAError";originalError;constructor(Q){this.originalError=Error(Q??"Unknown error.")}}class N2{_tag="UnsupportedApplicationDAError";originalError;constructor(Q){this.originalError=Error(Q??"Application currently not supported.")}}class B2{_tag="MissingLanguagePackagesForOSDAError";originalError;constructor(Q){this.originalError=Error(Q??"Missing Language Packages for OS DAError.")}}class k2{_tag="MissingLanguagePackageDAError";originalError;constructor(Q){this.originalError=Error(Q??"Missing Language Package DAError.")}}class dq{_tag="DeleteLanguagePackDAError";originalError;constructor(Q){this.originalError=Error(Q??"Delete language pack failed.")}}class C2{_tag="NetworkDAError";originalError;constructor(Q){this.originalError=Error(Q??"Network error.")}}var rY=()=>{};var qZ=60000;var tY=()=>{};var S2,aX=(Q)=>S2;var w2=w(()=>{S2={subscribers:[],error:()=>{},warn:()=>{},info:()=>{},debug:()=>{}}});class AQ{input;inspect=!1;logger;loggerFactory;constructor(Q){this.input=Q.input,this.inspect=!!Q.inspect,this.logger=Q.logger,this.loggerFactory=Q.loggerFactory}getLoggerFactory(Q){return this.loggerFactory??Q.loggerFactory??aX}_execute(Q){let Z=this.makeStateMachine(Q);return!this.logger&&Z.id&&(this.logger=this.getLoggerFactory(Q)(Z.id)),this._subscribeToStateMachine(Z)}_subscribeToStateMachine(Q){let Z=zJ(Q,{input:this.input}),Y=new rX.ReplaySubject,$=!1,J=(W)=>{let{context:U,status:K,output:O,error:I}=W;if(this.logger&&!$&&($=!0,this.logger.debug("[XStateDeviceAction] Input",{data:{input:U.input}})),this.logger&&(K==="active"||K==="done")){let L=typeof W.value=="string"?W.value:JSON.stringify(W.value);this.logger.debug(`[XStateDeviceAction] State: ${L}`,{data:{internalState:U._internalState,intermediateValue:U.intermediateValue}})}switch(K){case"active":Y.next({status:D8.Pending,intermediateValue:U.intermediateValue});break;case"done":O.caseOf({Left:(L)=>{Y.next({status:D8.Error,error:L})},Right:(L)=>{Y.next({status:D8.Completed,output:L})}}),Y.complete();break;case"error":Y.error(I),Y.complete();break;case"stopped":Y.next({status:D8.Stopped}),Y.complete();break;default:this._exhaustiveMatchingGuard(K)}},X=new rX.Observable((W)=>{let U=Y.subscribe(W);return()=>{G.unsubscribe(),U.unsubscribe(),Z.stop()}}),G=Z.subscribe(J);return Z.start(),{observable:X.pipe(rX.share()),cancel:()=>{Z.stop(),G.unsubscribe(),J(Z.getSnapshot())}}}_exhaustiveMatchingGuard(Q){throw console.log("_exhaustiveMatchingGuard status",Q),Error(`Unhandled status: ${Q}`)}}var rX;var SY=w(()=>{KZ();nO();w2();rX=require("rxjs")});var k9="BOLOS",Gn,j8=(Q)=>Q!=null&&Gn.includes(Q);var tX=w(()=>{Gn=["BOLOS","OLOS","OLOS\x00"]});var C9;var MM=w(()=>{C9=Object.freeze({GET_APP_AND_VERSION:"os.waitForAppAndVersion.steps.getAppAndVersion",UNLOCK_DEVICE:"os.waitForAppAndVersion.steps.unlockDevice"})});var rJ,NM,TM=(Q)=>!N0(Q)&&("errorCode"in Q.error)&&Q.error.errorCode==="5515",Xn=(Q)=>!N0(Q)&&("errorCode"in Q.error)&&Q.error.errorCode==="6e00",kJ;var _2=w(()=>{R0();KZ();TZ();Rq();CY();tY();rY();SY();tX();MM();rJ=require("rxjs"),NM=require("rxjs/operators");kJ=class kJ extends AQ{makeStateMachine(Q){let{getAppAndVersion:Z,waitForDeviceUnlock:Y}=this.extractDependencies(Q),$=this.input.unlockTimeout??qZ;return NQ({types:{input:{unlockTimeout:$},context:{},output:{}},actors:{getAppAndVersion:VQ(Z),waitForDeviceUnlock:cY(Y)},guards:{isDeviceLocked:({context:J})=>J._internalState.locked,hasError:({context:J})=>J._internalState.error!==null},actions:{assignErrorDeviceLocked:r({_internalState:(J)=>({...J.context._internalState,error:new iJ})}),assignErrorFromEvent:r({_internalState:(J)=>({...J.context._internalState,error:J.event.error})})}}).createMachine({id:"WaitForAppAndVersionDeviceAction",initial:"GetAppAndVersion",context:(J)=>({input:{unlockTimeout:J.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None,step:C9.GET_APP_AND_VERSION},_internalState:{appAndVersion:null,locked:!1,error:null}}),states:{GetAppAndVersion:{entry:r({intermediateValue:(J)=>({...J.context.intermediateValue,step:C9.GET_APP_AND_VERSION,requiredUserInteraction:k0.None})}),invoke:{src:"getAppAndVersion",onDone:{target:"CheckGetAppAndVersionResult",actions:r({_internalState:(J)=>N0(J.event.output)?{...J.context._internalState,locked:!1,appAndVersion:J.event.output.data}:TM(J.event.output)?{...J.context._internalState,locked:!0}:Xn(J.event.output)?{...J.context._internalState,locked:!1,appAndVersion:{name:k9,version:"0.0.0"}}:{...J.context._internalState,error:J.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CheckGetAppAndVersionResult:{always:[{guard:"hasError",target:"Error"},{guard:"isDeviceLocked",target:"AwaitingForDeviceUnlocked"},{target:"Success"}]},AwaitingForDeviceUnlocked:{entry:r({intermediateValue:(J)=>({...J.context.intermediateValue,requiredUserInteraction:k0.UnlockDevice,step:C9.UNLOCK_DEVICE})}),invoke:{id:"AwaitingForDeviceUnlocked",src:"waitForDeviceUnlock",input:(J)=>({unlockTimeout:$}),onDone:{target:"GetAppAndVersion",actions:r({_internalState:(J)=>({...J.context._internalState,locked:!1})})},onError:{target:"Error",actions:"assignErrorDeviceLocked"}}},Success:{type:"final"},Error:{type:"final"}},output:(J)=>{let{context:X}=J,{error:G,appAndVersion:W}=X._internalState;return G?a(G):U0(W)}})}extractDependencies(Q){return{getAppAndVersion:()=>Q.sendCommand(new e$),waitForDeviceUnlock:({input:Z})=>rJ.interval(1000).pipe(rJ.switchMap(()=>rJ.from(Q.sendCommand(new e$))),rJ.first((Y)=>!TM(Y)),rJ.map(()=>{}),NM.timeout(Z.unlockTimeout))}}}});var CQ;var K$=w(()=>{CQ=((Q)=>(Q[Q.Connected=0]="Connected",Q[Q.ReadyWithoutSecureChannel=1]="ReadyWithoutSecureChannel",Q[Q.ReadyWithSecureChannel=2]="ReadyWithSecureChannel",Q))(CQ||{})});var v2;var BM=w(()=>{v2=Object.freeze({WAIT_FOR_APP_AND_VERSION:"os.getDeviceStatus.steps.waitForAppAndVersion",ONBOARD_CHECK:"os.getDeviceStatus.steps.onboardCheck"})});var Vn=(Q)=>({mcu:Q.mcuSephVersion,bootloader:Q.mcuBootloaderVersion,os:Q.seVersion,metadata:Q}),xG;var S9=w(()=>{R0();KZ();TZ();H8();U9();CY();tY();rY();_2();SY();K$();tX();BM();xG=class xG extends AQ{makeStateMachine(Q){let{getOsVersion:Z,getDeviceSessionState:Y,setDeviceSessionState:$}=this.extractDependencies(Q),J=this.input.unlockTimeout??qZ,X=this.input.allowNonOnboardedDevice??!0,G=(U)=>{let K=Y();K.sessionStateType!==CQ.Connected&&$({...K,firmwareVersion:Vn(U),isSecureConnectionAllowed:U.secureElementFlags.isSecureConnectionAllowed})},W=new kJ({input:{unlockTimeout:J}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:J,allowNonOnboardedDevice:X},context:{},output:{}},actors:{waitForAppAndVersion:W,getOsVersion:VQ(Z)},guards:{isCurrentAppBolos:({context:U})=>j8(U._internalState.currentApp),isOnboardedFromOsVersion:({context:U})=>U._internalState.osVersionMetadata?.secureElementFlags.isOnboarded===!0,isAllowedNonOnboardedDevice:({context:U})=>{let K=U._internalState.osVersionMetadata?.secureElementFlags;return U.input.allowNonOnboardedDevice===!0&&K?.isOnboarded===!1},hasError:({context:U})=>U._internalState.error!==null},actions:{assignErrorDeviceNotOnboarded:r({_internalState:(U)=>({...U.context._internalState,error:new lq})}),assignErrorFromEvent:r({_internalState:(U)=>({...U.context._internalState,error:U.event.error})})}}).createMachine({id:"GetDeviceStatusDeviceAction",initial:"DeviceReady",context:(U)=>{let K=Y(),{sessionStateType:O}=K;return{input:{unlockTimeout:U.input.unlockTimeout,allowNonOnboardedDevice:U.input.allowNonOnboardedDevice??!0},intermediateValue:{requiredUserInteraction:k0.None,step:v2.WAIT_FOR_APP_AND_VERSION},_internalState:{onboarded:!1,currentApp:O===CQ.ReadyWithoutSecureChannel?K.currentApp.name:null,currentAppVersion:null,osVersionMetadata:null,error:null}}},states:{DeviceReady:{always:{target:"WaitForAppAndVersion"}},WaitForAppAndVersion:{invoke:{src:"waitForAppAndVersion",input:(U)=>({unlockTimeout:U.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(U)=>({...U.context.intermediateValue,requiredUserInteraction:U.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"WaitForAppAndVersionResultCheck",actions:r({_internalState:(U)=>U.event.output.caseOf({Left:(K)=>({...U.context._internalState,error:K}),Right:(K)=>{let O=Y();return O.sessionStateType!==CQ.Connected?$({...O,currentApp:K}):$({deviceModelId:O.deviceModelId,sessionStateType:CQ.ReadyWithoutSecureChannel,deviceStatus:aY.CONNECTED,currentApp:K,installedApps:[],isSecureConnectionAllowed:!1}),{...U.context._internalState,currentApp:K.name,currentAppVersion:K.version}}})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},WaitForAppAndVersionResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"OnboardingCheck"}]},OnboardingCheck:{entry:r({intermediateValue:(U)=>({...U.context.intermediateValue,requiredUserInteraction:k0.None,step:v2.ONBOARD_CHECK})}),always:[{guard:"isCurrentAppBolos",target:"GetOsVersion"},{target:"Success",actions:r({_internalState:(U)=>({...U.context._internalState,onboarded:!0})})}]},GetOsVersion:{invoke:{src:"getOsVersion",onDone:{target:"OnboardingResultCheck",actions:r({_internalState:(U)=>N0(U.event.output)?(G(U.event.output.data),{...U.context._internalState,osVersionMetadata:U.event.output.data}):{...U.context._internalState,error:U.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},OnboardingResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"isOnboardedFromOsVersion",target:"Success",actions:r({_internalState:(U)=>({...U.context._internalState,onboarded:!0})})},{guard:"isAllowedNonOnboardedDevice",target:"Success"},{target:"Error",actions:"assignErrorDeviceNotOnboarded"}]},Success:{type:"final"},Error:{type:"final"}},output:(U)=>{let{context:K}=U,{error:O,currentApp:I,currentAppVersion:L}=K._internalState;return O?a(O):U0({currentApp:I,currentAppVersion:L})}})}extractDependencies(Q){return{getOsVersion:()=>Q.sendCommand(new IY),getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});class vZ{_tag="GeneralDmkError";originalError;constructor(Q){Q instanceof Error?this.originalError=Q:Q!==void 0&&(this.originalError=Error(String(Q)))}}var kM,w9,eX,fG,nq,A8,CM,QV,_9,SM,wM,_M,vM,xM,v9,M8,ZV,x9,f9;var M1=w(()=>{kM=class kM extends vZ{constructor(Q){super(Q);this.err=Q}_tag="DeviceAlreadyDiscoveredError"};w9=class w9 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="DeviceNotRecognizedError"};eX=class eX extends vZ{constructor(Q){super(Q);this.err=Q}_tag="NoAccessibleDeviceError"};fG=class fG extends vZ{_tag="ConnectionOpeningError";constructor(Q){super(Q)}};nq=class nq extends vZ{constructor(Q){super(Q);this.err=Q}_tag="UnknownDeviceError"};A8=class A8 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="TransportNotSupportedError"};CM=class CM extends vZ{constructor(Q){super(Q);this.err=Q}_tag="SendApduConcurrencyError"};QV=class QV extends vZ{constructor(Q){super(Q);this.err=Q}_tag="SendApduTimeoutError"};_9=class _9 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="SendCommandTimeoutError"};SM=class SM extends vZ{constructor(Q){super(Q);this.err=Q}_tag="SendApduEmptyResponseError"};wM=class wM extends vZ{constructor(Q){super(Q);this.err=Q}_tag="DisconnectError"};_M=class _M extends vZ{constructor(Q){super(Q);this.err=Q}_tag="ReconnectionFailedError"};vM=class vM extends vZ{constructor(Q){super(Q);this.err=Q}_tag="DeviceNotInitializedError"};xM=class xM extends vZ{constructor(Q){super(Q);this.err=Q}_tag="NoTransportsProvidedError"};v9=class v9 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="TransportAlreadyExistsError"};M8=class M8 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="DeviceDisconnectedWhileSendingError"};ZV=class ZV extends vZ{constructor(Q){super(Q);this.err=Q}_tag="AlreadySendingApduError"};x9=class x9 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="DeviceDisconnectedBeforeSendingApdu"};f9=class f9 extends vZ{constructor(Q){super(Q);this.err=Q}_tag="NoTransportProvidedError"}});var fM;var yM=w(()=>{fM=Object.freeze({LIST_APPS:"os.openApp.steps.listApps",ONBOARD_CHECK:"os.openApp.steps.onboardCheck",GET_DEVICE_STATUS:"os.openApp.steps.getDeviceStatus",DASHBOARD_CHECK:"os.openApp.steps.dashboardCheck",CONFIRM_OPEN_APP:"os.openApp.steps.confirmOpenApp",CLOSE_APP:"os.openApp.steps.closeApp"})});var kZ;var oq=w(()=>{R0();KZ();TZ();a4();dO();CY();tY();S9();SY();K$();M1();tX();yM();kZ=class kZ extends AQ{makeStateMachine(Q){let{closeApp:Z,openApp:Y,getDeviceSessionState:$,setDeviceSessionState:J}=this.extractDependencies(Q),X=this.input.unlockTimeout??qZ,G=new xG({input:{unlockTimeout:X,allowNonOnboardedDevice:!1}}).makeStateMachine(Q);return NQ({types:{input:{},context:{},output:{}},actors:{closeApp:VQ(Z),openApp:VQ(Y),getDeviceStatus:G},guards:{isRequestedAppOpen:({context:W})=>W._internalState.currentlyRunningApp===null?!1:W._internalState.currentlyRunningApp===W.input.appName,isDashboardOpen:({context:W})=>{if(W._internalState.currentlyRunningApp===null)throw Error("context.currentlyRunningApp === null");return j8(W._internalState.currentlyRunningApp)},hasDisconnectedWhileSending:({context:W})=>W._internalState.error!==null&&W._internalState.error instanceof M8,hasError:({context:W})=>W._internalState.error!==null},actions:{assignUserActionNeededOpenApp:r({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k0.ConfirmOpenApp})}),assignNoUserActionNeeded:r({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k0.None})}),assignErrorFromEvent:r({_internalState:(W)=>({...W.context._internalState,error:W.event.error})}),assignNoError:r({_internalState:(W)=>({...W.context._internalState,error:null})})}}).createMachine({id:"OpenAppDeviceAction",initial:"DeviceReady",context:({input:W})=>{let U=$(),{sessionStateType:K}=U;return{input:W,intermediateValue:{requiredUserInteraction:k0.None,step:fM.GET_DEVICE_STATUS},_internalState:{error:null,currentlyRunningApp:K===CQ.ReadyWithoutSecureChannel?U.currentApp.name:null}}},states:{DeviceReady:{always:{target:"GetDeviceStatus"}},GetDeviceStatus:{invoke:{id:"deviceStatus",src:"getDeviceStatus",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,allowNonOnboardedDevice:!1}),onSnapshot:{actions:r({intermediateValue:(W)=>W.event.snapshot.context.intermediateValue})},onDone:{target:"CheckDeviceStatus",actions:r({_internalState:(W)=>W.event.output.caseOf({Right:(U)=>{let K=$();return K.sessionStateType!==CQ.Connected&&J({...K,currentApp:{name:U.currentApp,version:U.currentAppVersion}}),{...W.context._internalState,currentlyRunningApp:U.currentApp}},Left:(U)=>({...W.context._internalState,currentlyRunningApp:null,error:U})})})},onError:{target:"Error",actions:[r({_internalState:(W)=>({...W.context._internalState,currentlyRunningApp:null})}),"assignErrorFromEvent"]}}},CheckDeviceStatus:{always:[{target:"ApplicationReady",guard:"isRequestedAppOpen",actions:"assignNoError"},{target:"Error",guard:"hasError"},{target:"DashboardCheck"}]},DashboardCheck:{always:[{target:"OpenApplication",guard:"isDashboardOpen"},"CloseApplication"]},OpenApplication:{entry:"assignUserActionNeededOpenApp",exit:"assignNoUserActionNeeded",invoke:{src:"openApp",input:({context:W})=>({appName:W.input.appName}),onDone:{target:"OpenApplicationResultCheck",actions:r({_internalState:(W)=>N0(W.event.output)?{...W.context._internalState,currentlyRunningApp:W.context.input.appName}:{...W.context._internalState,error:W.event.output.error}})},onError:{target:"OpenApplicationResultCheck",actions:"assignErrorFromEvent"}}},OpenApplicationResultCheck:{always:[{target:"GetDeviceStatus",guard:"hasDisconnectedWhileSending"},{target:"Error",guard:"hasError"},{target:"GetDeviceStatus"}]},CloseApplication:{invoke:{src:"closeApp",onDone:{target:"CloseApplicationResultCheck",actions:r({_internalState:(W)=>N0(W.event.output)?{...W.context._internalState,currentlyRunningApp:k9}:{...W.context._internalState,error:W.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CloseApplicationResultCheck:{always:[{target:"Error",guard:"hasError"},{target:"OpenApplication"}]},ApplicationReady:{always:"Success"},Success:{type:"final",actions:"assignNoError"},Error:{type:"final"}},output:({context:W})=>W._internalState.error?a(W._internalState.error):U0(void 0)})}extractDependencies(Q){return{closeApp:async()=>Q.sendCommand(new NG),openApp:async(Z)=>Q.sendCommand(new wq({appName:Z.input.appName})),getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var y9;var gM=w(()=>{y9=Object.freeze({OPEN_APP:"os.callTaskInApp.steps.openApp",CALL_TASK:"os.callTaskInApp.steps.callTask"})});var nZ;var hM=w(()=>{R0();KZ();CY();rY();oq();SY();TG();gM();nZ=class nZ extends AQ{makeStateMachine(Q){let{callTask:Z}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{callTask:VQ(Z),openAppStateMachine:new kZ({input:{appName:this.input.appName}}).makeStateMachine(Q)},guards:{skipOpenApp:()=>this.input.skipOpenApp,noInternalError:({context:Y})=>Y._internalState.error===null},actions:{assignErrorFromEvent:r({_internalState:(Y)=>({...Y.context._internalState,error:Y.event.error})})}}).createMachine({id:"CallTaskInAppDeviceAction",initial:"InitialState",context:({input:Y})=>({input:Y,intermediateValue:{requiredUserInteraction:k0.None,step:y9.OPEN_APP},_internalState:{taskResponse:null,error:null}}),states:{InitialState:{always:[{target:"CallTask",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:this.input.appName},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:(Y)=>Y.event.snapshot.context.intermediateValue})},onDone:{actions:r({_internalState:(Y)=>Y.event.output.caseOf({Right:()=>Y.context._internalState,Left:($)=>({...Y.context._internalState,error:$})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"CallTask",guard:"noInternalError"},"Error"]},CallTask:{entry:r({intermediateValue:{requiredUserInteraction:this.input.requiredUserInteraction,step:y9.CALL_TASK}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:y9.CALL_TASK}}),invoke:{id:"callTask",src:"callTask",input:(Y)=>Y.context.input.task,onDone:{target:"CallTaskResultCheck",actions:[r({_internalState:({event:Y,context:$})=>t$(Y.output)?{...$._internalState,taskResponse:Y.output.data}:{...$._internalState,error:Y.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CallTaskResultCheck:{always:[{target:"Success",guard:"noInternalError"},"Error"]},Success:{type:"final"},Error:{type:"final"}},output:({context:Y})=>Y._internalState.taskResponse?U0(Y._internalState.taskResponse):a(Y._internalState.error||new xQ("No error in final state"))})}extractDependencies(Q){return{callTask:(Z)=>Z.input(Q)}}}});var sq;var bM=w(()=>{sq=Object.freeze({GET_DEVICE_STATUS:"os.goToDashboard.steps.getDeviceStatus",DASHBOARD_CHECK:"os.goToDashboard.steps.dashboardCheck",CLOSE_APP:"os.goToDashboard.steps.closeApp",CONFIRM_DASHBOARD_OPEN:"os.goToDashboard.steps.confirmDashboardOpen"})});var RY;var T1=w(()=>{R0();KZ();TZ();a4();Rq();CY();tY();rY();S9();SY();K$();tX();bM();RY=class RY extends AQ{makeStateMachine(Q){let{getDeviceSessionState:Z,setDeviceSessionState:Y,closeApp:$,getAppAndVersion:J}=this.extractDependencies(Q),X=this.input.unlockTimeout??qZ,G=new xG({input:{unlockTimeout:X}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:X},context:{},output:{}},actors:{getAppAndVersion:VQ(J),closeApp:VQ($),getDeviceStatus:G},guards:{hasError:({context:W})=>W._internalState.error!==null,isDashboardOpen:({context:W})=>W._internalState.currentApp!==null&&j8(W._internalState.currentApp)},actions:{assignErrorFromEvent:r({_internalState:(W)=>({...W.context._internalState,error:W.event.error})})}}).createMachine({id:"GoToDashboardDeviceAction",initial:"DeviceReady",context:(W)=>{let U=Z();return{input:{unlockTimeout:W.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None,step:sq.GET_DEVICE_STATUS},_internalState:{currentApp:"currentApp"in U?U.currentApp.name:null,error:null}}},states:{DeviceReady:{always:{target:"GetDeviceStatus"}},GetDeviceStatus:{invoke:{id:"deviceStatus",src:"getDeviceStatus",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(W)=>W.event.snapshot.context.intermediateValue})},onDone:{target:"CheckDeviceStatus",actions:r({_internalState:(W)=>W.event.output.caseOf({Right:(U)=>({...W.context._internalState,currentApp:U.currentApp}),Left:(U)=>({...W.context._internalState,error:U})})})}}},CheckDeviceStatus:{always:[{target:"Error",guard:"hasError"},{target:"DashboardCheck"}]},DashboardCheck:{always:[{target:"Success",guard:"isDashboardOpen"},{target:"Error",guard:"hasError"},{target:"Error",guard:(W)=>W.context._internalState.currentApp===null,actions:r({_internalState:(W)=>({...W.context._internalState,error:new xQ("currentApp === null")}),intermediateValue:(W)=>({requiredUserInteraction:k0.None,step:sq.DASHBOARD_CHECK})})},{target:"CloseApp"}]},CloseApp:{invoke:{src:"closeApp",onDone:{target:"CloseAppCheck",actions:r({_internalState:(W)=>N0(W.event.output)?W.context._internalState:{...W.context._internalState,error:W.event.output.error},intermediateValue:(W)=>({requiredUserInteraction:k0.None,step:sq.CLOSE_APP})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CloseAppCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetAppAndVersion",reenter:!0}]},GetAppAndVersion:{invoke:{src:"getAppAndVersion",onDone:{target:"DashboardCheck",actions:r({_internalState:(W)=>{if(N0(W.event.output)){let U=Z();return U.sessionStateType!==CQ.Connected&&Y({...U,currentApp:W.event.output.data}),{...W.context._internalState,currentApp:W.event.output.data.name}}return{...W.context._internalState,error:W.event.output.error}},intermediateValue:(W)=>({requiredUserInteraction:k0.None,step:sq.CONFIRM_DASHBOARD_OPEN})})}}},Success:{type:"final"},Error:{type:"final"}},output:(W)=>W.context._internalState.error?a(W.context._internalState.error):U0(void 0)})}extractDependencies(Q){return{closeApp:async()=>Q.sendCommand(new NG),getAppAndVersion:async()=>Q.sendCommand(new e$),getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var x2;var cM=w(()=>{x2=Object.freeze({GO_TO_DASHBOARD:"os.listApps.steps.goToDashboard",LIST_APPS:"os.listApps.steps.listApps"})});var yG;var g9=w(()=>{R0();KZ();TZ();lO();CY();tY();T1();SY();cM();yG=class yG extends AQ{makeStateMachine(Q){let{listApps:Z}=this.extractDependencies(Q),Y=this.input.unlockTimeout??qZ,$=new RY({input:{unlockTimeout:Y}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:Y},context:{},output:{}},actors:{listApps:VQ(Z),goToDashboard:$},guards:{hasError:({context:J})=>J._internalState.error!==null,hasMoreApps:(J)=>J.context._internalState.shouldContinue},actions:{assignAllowListApps:r({intermediateValue:(J)=>({requiredUserInteraction:k0.AllowListApps,step:x2.LIST_APPS})}),assignErrorFromEvent:r({_internalState:(J)=>({...J.context._internalState,error:J.event.error})})}}).createMachine({id:"ListAppsDeviceAction",initial:"DeviceReady",context:(J)=>({input:{unlockTimeout:J.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None,step:x2.GO_TO_DASHBOARD},_internalState:{error:null,apps:[],shouldContinue:!1}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"dashboard",src:"goToDashboard",input:(J)=>({unlockTimeout:J.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(J)=>J.event.snapshot.context.intermediateValue})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(J)=>J.event.output.caseOf({Right:()=>J.context._internalState,Left:(X)=>({...J.context._internalState,error:X})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"ListApps"}]},ListApps:{entry:"assignAllowListApps",invoke:{src:"listApps",input:(J)=>!1,onDone:{target:"Continue",actions:r({_internalState:(J)=>N0(J.event.output)?{...J.context._internalState,apps:J.context._internalState.apps.concat(J.event.output.data),shouldContinue:J.event.output.data.length>=2}:{...J.context._internalState,error:J.event.output.error},intermediateValue:(J)=>({...J.context.intermediateValue,requiredUserInteraction:k0.None})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},"ListAppsContinue"]},ListAppsContinue:{invoke:{src:"listApps",input:(J)=>!0,onDone:{target:"Continue",actions:r({_internalState:(J)=>N0(J.event.output)?{...J.context._internalState,apps:J.context._internalState.apps.concat(J.event.output.data),shouldContinue:J.event.output.data.length>=2}:{...J.context._internalState,error:J.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Continue:{always:[{target:"ListAppsContinue",guard:"hasMoreApps"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(J)=>J.context._internalState.error?a(J.context._internalState.error):U0(J.context._internalState.apps)})}extractDependencies(Q){return{listApps:async({input:Z})=>{let Y=new Cq({isContinue:Z});return Q.sendCommand(Y)}}}}});class iq{_tag="InvalidGetFirmwareMetadataResponseError";originalError;constructor(Q){this.originalError=Error(Q??"Invalid Firmware Metadata response error.")}}class YV{_tag="GetApplicationsMetadataTaskError";originalError;constructor(Q){this.originalError=Error(Q??"Failed to get applications metadata.")}}var h9=()=>{};class f2{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=this.args.installedApps.filter((O)=>this.isApplication(O)),Z=this.api.getManagerApiService(),Y=Q.map((O)=>O.hash),$=await Z.getAppsByHash(Y).chain((O)=>Z.getAppList(this.args.firmwareVersion.metadata).map((I)=>({applications:O,catalog:I})));if($.isLeft())return zQ({error:new YV("Cannot get the application catalog")});let{applications:J,catalog:X}=$.unsafeCoerce(),G=J.reduce((O,I,L)=>{if(I!==null)return[...O,I];let A=Q[L],M=X.find((k)=>k.versionName===A.name);return M?[...O,M]:O},[]),W=J.filter((O)=>O!==null).reduce((O,I)=>{let L=X.find((A)=>A.versionName===I.versionName);return L&&uM.gt(L.version,I.version)?[...O,L]:O},[]),U=[];for(let O=0;;O++){let I=await this.api.sendCommand(new Sq({firstChunk:O===0}));if(!N0(I)||I.data===void 0)break;U=[...U,I.data]}let K=await Z.getLanguagePackages(this.args.deviceVersion,this.args.firmware);return K.isRight()?zQ({data:{applications:G,applicationsUpdates:W,installedLanguages:U,catalog:{applications:X,languagePackages:K.extract()}}}):zQ({error:new YV("Cannot get the languages catalog")})}isApplication(Q){return Q.hashCode!==qn}}var uM,qn="0000000000000000000000000000000000000000000000000000000000000000";var pM=w(()=>{TZ();mO();h9();TG();uM=JZ(kG(),1)});class y2{constructor(Q){this.api=Q}async run(){let Q=await this.api.sendCommand(new IY);if(!N0(Q))return zQ({error:Q.error});let Z={mcu:Q.data.mcuSephVersion,bootloader:Q.data.mcuBootloaderVersion,os:Q.data.seVersion,metadata:Q.data},Y=this.api.getManagerApiService(),$=await Y.getDeviceVersion(Q.data).chain((O)=>Y.getFirmwareVersion(Q.data,O).map((I)=>({deviceVersion:O,currentFirmware:I})));if($.isLeft())return zQ({error:new iq});let{deviceVersion:J,currentFirmware:X}=$.unsafeCoerce(),G=await this.getAvailableUpdate(Y,X,J,Z),W={currentFirmware:X,availableUpdate:G},U={},K=await this.api.sendCommand(new Lq);return N0(K)&&(U={size:K.data}),zQ({data:{deviceVersion:J,firmware:X,firmwareVersion:Z,firmwareUpdateContext:W,customImage:U}})}async getAvailableUpdate(Q,Z,Y,$){let J=await Q.getLatestFirmwareVersion(Z,Y);if(J.isLeft())return;let X=J.unsafeCoerce();if(!X.isNothing())return this.getFirmwareUpdate(Q,X.unsafeCoerce(),$)}async getFirmwareUpdate(Q,Z,Y){let $=await Q.getNextFirmwareVersion(Z);if($.isLeft())return;let J=await Q.getMcuList();if(J.isLeft())return;let X=$.unsafeCoerce(),G=J.unsafeCoerce().find((W)=>W.name===Y.mcu);return{osuFirmware:Z,finalFirmware:X,mcuUpdateRequired:G===void 0||!X.mcuVersions.includes(G.id)}}}var lM=w(()=>{TZ();MO();H8();h9();TG()});function b9(Q){return Array.isArray(Q)&&Q.every((Z)=>typeof Z=="object"&&Z!==null&&("flags"in Z)&&("hash"in Z)&&("hash_code_data"in Z)&&("name"in Z)&&typeof Z.flags=="number"&&typeof Z.hash=="string"&&typeof Z.hash_code_data=="string"&&typeof Z.name=="string")}var g2=()=>{};var $V=null,c9;var h2=w(()=>{if(typeof WebSocket<"u")$V=WebSocket;else if(typeof MozWebSocket<"u")$V=MozWebSocket;else if(typeof global<"u")$V=global.WebSocket||global.MozWebSocket;else if(typeof window<"u")$V=window.WebSocket||window.MozWebSocket;else if(typeof self<"u")$V=self.WebSocket||self.MozWebSocket;c9=$V});var Fn,N1,u9,fQ;var B1=w(()=>{Fn=((Q)=>(Q.GenuineCheck="GenuineCheck",Q.ListInstalledApps="ListInstalledApps",Q.UpdateMcu="UpdateMcu",Q.UpdateFirmware="UpdateFirmware",Q.InstallApp="InstallApp",Q.UninstallApp="UninstallApp",Q))(Fn||{}),N1=((Q)=>(Q.EXCHANGE="exchange",Q.BULK="bulk",Q.ERROR="error",Q.WARNING="warning",Q.SUCCESS="success",Q))(N1||{}),u9=((Q)=>(Q.SUCCESS="success",Q.ERROR="error",Q))(u9||{}),fQ=((Q)=>(Q.Opened="opened",Q.Closed="closed",Q.PermissionRequested="permission-requested",Q.PermissionGranted="permission-granted",Q.PreExchange="pre-exchange",Q.Exchange="exchange",Q.DeviceId="device-id",Q.Progress="progress",Q.Warning="warning",Q.Error="error",Q.Result="result",Q))(fQ||{})});var mM="0000";var dM=()=>{};function nM(Q){return Q[0]===224&&Q[1]===81}function oM(Q){return Q[0]===224&&Q[1]===82}function sM(Q){try{let Z=new FQ(Q);return Z.extractFieldLVEncoded()?Z.extractFieldLVEncoded()??null:null}catch{return null}}function iM(Q){return Q===mM}var b2=w(()=>{r$();dM()});function zn(Q,Z=!1){if(Z)return{h:Number(Q&p9),l:Number(Q>>aM&p9)};return{h:Number(Q>>aM&p9)|0,l:Number(Q&p9)|0}}function rM(Q,Z=!1){let Y=Q.length,$=new Uint32Array(Y),J=new Uint32Array(Y);for(let X=0;X<Y;X++){let{h:G,l:W}=zn(Q[X],Z);[$[X],J[X]]=[G,W]}return[$,J]}var p9,aM,tM=(Q,Z,Y)=>Q<<Y|Z>>>32-Y,eM=(Q,Z,Y)=>Z<<Y|Q>>>32-Y,QT=(Q,Z,Y)=>Z<<Y-32|Q>>>64-Y,ZT=(Q,Z,Y)=>Q<<Y-32|Z>>>64-Y;var YT=w(()=>{p9=BigInt(4294967295),aM=BigInt(32)});function Wn(Q){return Q instanceof Uint8Array||ArrayBuffer.isView(Q)&&Q.constructor.name==="Uint8Array"}function c2(Q){if(!Number.isSafeInteger(Q)||Q<0)throw Error("positive integer expected, got "+Q)}function gG(Q,...Z){if(!Wn(Q))throw Error("Uint8Array expected");if(Z.length>0&&!Z.includes(Q.length))throw Error("Uint8Array expected of length "+Z+", got length="+Q.length)}function JV(Q,Z=!0){if(Q.destroyed)throw Error("Hash instance has been destroyed");if(Z&&Q.finished)throw Error("Hash#digest() has already been called")}function l9(Q,Z){gG(Q);let Y=Z.outputLen;if(Q.length<Y)throw Error("digestInto() expects output buffer of length at least "+Y)}function $T(Q){return new Uint32Array(Q.buffer,Q.byteOffset,Math.floor(Q.byteLength/4))}function CJ(...Q){for(let Z=0;Z<Q.length;Z++)Q[Z].fill(0)}function m9(Q){return new DataView(Q.buffer,Q.byteOffset,Q.byteLength)}function SJ(Q,Z){return Q<<32-Z|Q>>>Z}function aq(Q,Z){return Q<<Z|Q>>>32-Z>>>0}function Un(Q){return Q<<24&4278190080|Q<<8&16711680|Q>>>8&65280|Q>>>24&255}function On(Q){for(let Z=0;Z<Q.length;Z++)Q[Z]=Un(Q[Z]);return Q}function Hn(Q){if(typeof Q!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(Q))}function rq(Q){if(typeof Q==="string")Q=Hn(Q);return gG(Q),Q}class tq{}function GV(Q){let Z=($)=>Q().update(rq($)).digest(),Y=Q();return Z.outputLen=Y.outputLen,Z.blockLen=Y.blockLen,Z.create=()=>Q(),Z}var Kn,u2;var eq=w(()=>{/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Kn=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();u2=Kn?(Q)=>Q:On});function An(Q,Z=24){let Y=new Uint32Array(10);for(let $=24-Z;$<24;$++){for(let G=0;G<10;G++)Y[G]=Q[G]^Q[G+10]^Q[G+20]^Q[G+30]^Q[G+40];for(let G=0;G<10;G+=2){let W=(G+8)%10,U=(G+2)%10,K=Y[U],O=Y[U+1],I=JT(K,O,1)^Y[W],L=GT(K,O,1)^Y[W+1];for(let A=0;A<50;A+=10)Q[G+A]^=I,Q[G+A+1]^=L}let J=Q[2],X=Q[3];for(let G=0;G<24;G++){let W=VT[G],U=JT(J,X,W),K=GT(J,X,W),O=XT[G];J=Q[O],X=Q[O+1],Q[O]=U,Q[O+1]=K}for(let G=0;G<50;G+=10){for(let W=0;W<10;W++)Y[W]=Q[G+W];for(let W=0;W<10;W++)Q[G+W]^=~Y[(W+2)%10]&Y[(W+4)%10]}Q[0]^=Pn[$],Q[1]^=jn[$]}CJ(Y)}var Dn,Q6,In,Rn,Ln,En,XT,VT,qT,FT,Pn,jn,JT=(Q,Z,Y)=>Y>32?QT(Q,Z,Y):tM(Q,Z,Y),GT=(Q,Z,Y)=>Y>32?ZT(Q,Z,Y):eM(Q,Z,Y),p2,Mn=(Q,Z,Y)=>GV(()=>new p2(Z,Q,Y)),zT;var WT=w(()=>{YT();eq();Dn=BigInt(0),Q6=BigInt(1),In=BigInt(2),Rn=BigInt(7),Ln=BigInt(256),En=BigInt(113),XT=[],VT=[],qT=[];for(let Q=0,Z=Q6,Y=1,$=0;Q<24;Q++){[Y,$]=[$,(2*Y+3*$)%5],XT.push(2*(5*$+Y)),VT.push((Q+1)*(Q+2)/2%64);let J=Dn;for(let X=0;X<7;X++)if(Z=(Z<<Q6^(Z>>Rn)*En)%Ln,Z&In)J^=Q6<<(Q6<<BigInt(X))-Q6;qT.push(J)}FT=rM(qT,!0),Pn=FT[0],jn=FT[1];p2=class p2 extends tq{constructor(Q,Z,Y,$=!1,J=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=Q,this.suffix=Z,this.outputLen=Y,this.enableXOF=$,this.rounds=J,c2(Y),!(0<Q&&Q<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=$T(this.state)}clone(){return this._cloneInto()}keccak(){u2(this.state32),An(this.state32,this.rounds),u2(this.state32),this.posOut=0,this.pos=0}update(Q){JV(this),Q=rq(Q),gG(Q);let{blockLen:Z,state:Y}=this,$=Q.length;for(let J=0;J<$;){let X=Math.min(Z-this.pos,$-J);for(let G=0;G<X;G++)Y[this.pos++]^=Q[J++];if(this.pos===Z)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:Q,suffix:Z,pos:Y,blockLen:$}=this;if(Q[Y]^=Z,(Z&128)!==0&&Y===$-1)this.keccak();Q[$-1]^=128,this.keccak()}writeInto(Q){JV(this,!1),gG(Q),this.finish();let Z=this.state,{blockLen:Y}=this;for(let $=0,J=Q.length;$<J;){if(this.posOut>=Y)this.keccak();let X=Math.min(Y-this.posOut,J-$);Q.set(Z.subarray(this.posOut,this.posOut+X),$),this.posOut+=X,$+=X}return Q}xofInto(Q){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(Q)}xof(Q){return c2(Q),this.xofInto(new Uint8Array(Q))}digestInto(Q){if(l9(Q,this),this.finished)throw Error("digest() was already called");return this.writeInto(Q),this.destroy(),Q}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,CJ(this.state)}_cloneInto(Q){let{blockLen:Z,suffix:Y,outputLen:$,rounds:J,enableXOF:X}=this;return Q||(Q=new p2(Z,Y,$,X,J)),Q.state32.set(this.state32),Q.pos=this.pos,Q.posOut=this.posOut,Q.finished=this.finished,Q.rounds=J,Q.suffix=Y,Q.outputLen=$,Q.enableXOF=X,Q.destroyed=this.destroyed,Q}};zT=(()=>Mn(6,136,32))()});class l2{sha3_256(Q){return zT(Q)}}var KT=w(()=>{WT()});class m2{constructor(Q){this.error=Q,this.originalError=Q}_tag="WebSocketConnectionError";originalError}class ZY{constructor(Q,Z=4){this.error=Q,this.errorType=Z,this.originalError=Q}_tag="SecureChannelError";originalError;mapDAErrors(){switch(this.errorType){case 1:return new iJ;case 3:return new A1;default:return this}}mapInstallDAErrors(){switch(this.errorType){case 1:return new iJ;case 3:return new A1;case 0:return new mq;case 2:return new aJ;default:return this}}mapUpdateFirmwareDAErrors(){switch(this.errorType){case 2:return new aJ;case 1:return new iJ;case 3:return new A1;case 4:return new xQ;default:return this}}mapFlashMcuDAErrors(){switch(this.errorType){case 1:return new iJ;case 4:return new xQ;default:return this}}}var XV;var d9=w(()=>{rY();XV=((Q)=>(Q[Q.AppAlreadyInstalled=0]="AppAlreadyInstalled",Q[Q.DeviceLocked=1]="DeviceLocked",Q[Q.OutOfMemory=2]="OutOfMemory",Q[Q.RefusedByUser=3]="RefusedByUser",Q[Q.Unknown=4]="Unknown",Q))(XV||{})});class U${constructor(Q,Z){if(this._api=Q,this._args=Z,this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new ZY(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`);this._cryptoService=this._args.cryptoService??new l2}_connection;_cryptoService;_deviceIdCaptured=!1;run(){return new UT.Observable((Q)=>{let Z=!1,Y=!1,$=!1,J=(X)=>{Q.next({type:fQ.Error,error:X}),Q.complete(),Y=!0};return this._connection.onopen=()=>{Q.next({type:fQ.Opened})},this._connection.onerror=(X)=>{Y||(Q.next({type:fQ.Error,error:new ZY({url:this._connection.url,errorMessage:X.message})}),Q.complete())},this._connection.onclose=()=>{Y||($?Q.next({type:fQ.Closed}):Q.next({type:fQ.Error,error:new ZY({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),Q.complete())},this._connection.onmessage=async(X)=>{if(Z)return;let G;try{let W=JSON.parse(String(X.data));if(this.isInMessageType(W))G=W;else throw Error("Data does not match InMessageType")}catch{J(new ZY({url:this._connection.url,errorMessage:`Invalid message received: ${String(X.data)}`}));return}switch(G.query){case N1.EXCHANGE:{let{nonce:W,data:U}=G;if(typeof U!="string"){J(new ZY(`${N1.EXCHANGE} data type should be an APDU`));return}let K=mQ(U);if(K===null||K.length<5){J(new ZY(`Received invalid APDU data: ${U}`));return}Q.next({type:fQ.PreExchange,payload:{nonce:W,apdu:K}});let O=!1;nM(K)&&!this.isSecureConnectionAllowed()&&(O=!0,Q.next({type:fQ.PermissionRequested}));let I=await this._api.sendApdu(K);if(Z)return;I.caseOf({Left:(L)=>{J(new ZY(L))},Right:(L)=>{let A,M=this.mapDeviceError(L);if(M===null){if(A=u9.SUCCESS,!this._deviceIdCaptured&&oM(K)){this._deviceIdCaptured=!0;let B=sM(L);if(B){let C=this._cryptoService.sha3_256(B);Q.next({type:fQ.DeviceId,payload:{deviceId:C}})}}Q.next({type:fQ.Exchange,payload:{nonce:W,apdu:K,data:L.data,status:L.statusCode}}),O&&Q.next({type:fQ.PermissionGranted})}else A=u9.ERROR,J(M);let k={nonce:W,response:A,data:DQ(L.data,!1)};this._connection.send(JSON.stringify(k))}});break}case N1.BULK:{if(Y=!0,this._connection.close(),!Array.isArray(G.data)||G.data.length===0||!G.data.every((W)=>typeof W=="string")){J(new ZY("Invalid bulk data received"));return}for(let W=0,U=G.data.length;W<U;W++){let K=mQ(G.data[W]);if(K===null||K.length<5){J(new ZY(`Received invalid APDU bulk data: ${G.data[W]}`));return}let O=await this._api.sendApdu(K);if(Z)return;if(O.isLeft()){J(new ZY(O.extract()));return}else if(O.isRight()){let I=this.mapDeviceError(O.extract());if(I===null)Q.next({type:fQ.Progress,payload:{progress:+Number((W+1)/U).toFixed(2),index:W,total:U}});else{J(I);return}}}$=!0,Q.complete();break}case N1.SUCCESS:{if(Y)break;let W=G.result??G.data;W&&Q.next({type:fQ.Result,payload:W??""}),$=!0,Q.complete();break}case N1.WARNING:{if(Y)break;Q.next({type:fQ.Warning,payload:{message:String(G.data)}});break}case N1.ERROR:{if(Y)break;J(new ZY({url:this._connection.url,errorMessage:String(G.data)}))}}},()=>{Z=!0,this._connection.readyState===c9.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){let Q=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in Q&&Q.isSecureConnectionAllowed}isInMessageType(Q){if(typeof Q!="object"||!Q)return!1;let Z=Q;return typeof Z.uuid=="string"&&typeof Z.session=="string"&&typeof Z.query=="string"&&Object.values(N1).includes(Z.query)&&typeof Z.nonce=="number"}mapDeviceError(Q){return hQ.isSuccessResponse(Q)?null:hQ.isLockedDeviceResponse(Q)?new ZY({url:this._connection.url,errorMessage:"Device is locked"},XV.DeviceLocked):hQ.isRefusedByUser(Q)?new ZY({url:this._connection.url,errorMessage:"User refused on the device"},XV.RefusedByUser):hQ.isAppAlreadyInstalled(Q)?new ZY({url:this._connection.url,errorMessage:"App already installed"},XV.AppAlreadyInstalled):hQ.isOutOfMemory(Q)?new ZY({url:this._connection.url,errorMessage:"Out of memory"},XV.OutOfMemory):new ZY({url:this._connection.url,errorMessage:`Invalid status code: ${DQ(Q.statusCode)}`})}}var UT;var T8=w(()=>{h2();oY();B1();b2();O8();KT();d9();UT=require("rxjs")});var hG;var d2=w(()=>{hG=Object.freeze({GET_DEVICE_METADATA:"os.getDeviceMetadata.steps.getDeviceMetadata",GO_TO_DASHBOARD:"os.getDeviceMetadata.steps.goToDashboard",GET_FIRMWARE_METADATA:"os.getDeviceMetadata.steps.getFirmwareMetadata",LIST_APPS_SECURE_CHANNEL:"os.getDeviceMetadata.steps.listAppsSecureChannel",LIST_APPS:"os.getDeviceMetadata.steps.listApps",GET_APPLICATIONS_METADATA:"os.getDeviceMetadata.steps.getApplicationsMetadata"})});var k1;var Z6=w(()=>{R0();KZ();CY();tY();T1();g9();pM();lM();SY();K$();TG();g2();T8();B1();d2();k1=class k1 extends AQ{makeStateMachine(Q){let{getDeviceMetadata:Z,getFirmwareMetadata:Y,getApplicationsMetadata:$,listAppsSecureChannel:J}=this.extractDependencies(Q),X=this.input.unlockTimeout??qZ,G=new RY({input:{unlockTimeout:X}}).makeStateMachine(Q),W=new yG({input:{unlockTimeout:X}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:X},context:{},output:{}},actors:{goToDashboard:G,getDeviceMetadata:VQ(Z),getFirmwareMetadata:VQ(Y),getApplicationsMetadata:VQ($),listApps:W,listAppsSecureChannel:cY(J)},guards:{hasError:({context:U})=>U._internalState.error!==null,hasMetadata:({context:U})=>U._internalState.firmwareVersion!==null&&U._internalState.firmwareUpdateContext!==null&&U._internalState.customImage!==null&&U._internalState.applications!==null&&U._internalState.applicationsUpdates!==null&&U._internalState.installedLanguages!==null&&U._internalState.catalog!==null,forceUpdate:({context:U})=>!!U.input.forceUpdate,useSecureChannel:({context:U})=>!!U.input.useSecureChannel},actions:{assignErrorFromEvent:r({_internalState:(U)=>({...U.context._internalState,error:U.event.error})})}}).createMachine({id:"GetDeviceMetadataDeviceAction",initial:"DeviceReady",context:(U)=>({input:{useSecureChannel:U.input.useSecureChannel,forceUpdate:U.input.forceUpdate,unlockTimeout:U.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None,step:hG.GET_DEVICE_METADATA},_internalState:{error:null,deviceVersion:null,firmware:null,firmwareVersion:null,firmwareUpdateContext:null,customImage:null,installedApps:null,applications:null,applicationsUpdates:null,installedLanguages:null,catalog:null}}),states:{DeviceReady:{always:[{target:"GoToDashboard",guard:"forceUpdate"},{target:"GetDeviceMetadataFromContext"}]},GetDeviceMetadataFromContext:{invoke:{src:"getDeviceMetadata",onDone:{target:"GetDeviceMetadataFromContextResultCheck",actions:r({_internalState:(U)=>U.event.output===null?U.context._internalState:{...U.context._internalState,firmwareVersion:U.event.output.firmwareVersion,firmwareUpdateContext:U.event.output.firmwareUpdateContext,customImage:U.event.output.customImage,applications:U.event.output.applications,applicationsUpdates:U.event.output.applicationsUpdates,installedLanguages:U.event.output.installedLanguages,catalog:U.event.output.catalog}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceMetadataFromContextResultCheck:{always:[{target:"Success",guard:"hasMetadata"},{target:"GoToDashboard"}]},GoToDashboard:{exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:hG.GO_TO_DASHBOARD}}),invoke:{id:"dashboard",src:"goToDashboard",input:(U)=>({unlockTimeout:U.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(U)=>U.event.snapshot.context.intermediateValue})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(U)=>U.event.output.caseOf({Right:()=>U.context._internalState,Left:(K)=>({...U.context._internalState,error:K})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareMetadata"}]},GetFirmwareMetadata:{invoke:{src:"getFirmwareMetadata",onDone:{target:"GetFirmwareMetadataResultCheck",actions:r({_internalState:(U)=>{if(t$(U.event.output)){let K=Q.getDeviceSessionState();return K.sessionStateType!==CQ.Connected&&Q.setDeviceSessionState({...K,firmwareVersion:U.event.output.data.firmwareVersion,firmwareUpdateContext:U.event.output.data.firmwareUpdateContext,customImage:U.event.output.data.customImage}),{...U.context._internalState,deviceVersion:U.event.output.data.deviceVersion,firmware:U.event.output.data.firmware,firmwareVersion:U.event.output.data.firmwareVersion,firmwareUpdateContext:U.event.output.data.firmwareUpdateContext,customImage:U.event.output.data.customImage}}return{...U.context._internalState,error:U.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareMetadataResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"useSecureChannel",target:"ListAppsSecureChannel"},{target:"ListApps"}]},ListAppsSecureChannel:{exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:hG.LIST_APPS_SECURE_CHANNEL}}),invoke:{id:"listAppsSecureChannel",src:"listAppsSecureChannel",input:(U)=>({firmware:U.context._internalState.firmware,firmwareVersion:U.context._internalState.firmwareVersion}),onSnapshot:{actions:r({intermediateValue:(U)=>{switch(U.event.snapshot.context?.type){case fQ.DeviceId:return{...U.context.intermediateValue,deviceId:U.event.snapshot.context.payload.deviceId};case fQ.PermissionRequested:return{...U.context.intermediateValue,requiredUserInteraction:k0.AllowSecureConnection};case fQ.PermissionGranted:{let K=Q.getDeviceSessionState();return K.sessionStateType!==CQ.Connected&&Q.setDeviceSessionState({...K,isSecureConnectionAllowed:!0}),{...U.context.intermediateValue,requiredUserInteraction:k0.None}}default:return{...U.context.intermediateValue}}},_internalState:(U)=>{if(U.event.snapshot.context?.type===fQ.Error)return{...U.context._internalState,error:U.event.snapshot.context.error.mapDAErrors()};if(U.event.snapshot.context?.type===fQ.Result){if(b9(U.event.snapshot.context.payload))return{...U.context._internalState,installedApps:U.event.snapshot.context.payload.map((K)=>({name:K.name,hash:K.hash,hashCode:K.hash_code_data}))};throw Error(`Invalid result ${JSON.stringify(U.event.snapshot.context.payload)}`)}return{...U.context._internalState}}})},onDone:{target:"ListAppsCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListApps:{exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:hG.LIST_APPS}}),invoke:{id:"listApps",src:"listApps",input:(U)=>({unlockTimeout:U.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(U)=>U.event.snapshot.context.intermediateValue})},onDone:{target:"ListAppsCheck",actions:r({_internalState:(U)=>U.event.output.isLeft()?{...U.context._internalState,error:U.event.output.extract()}:{...U.context._internalState,installedApps:U.event.output.unsafeCoerce().map((K)=>({name:K.appName,hash:K.appFullHash,hashCode:K.appCodeHash}))}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetApplicationsMetadata"}]},GetApplicationsMetadata:{invoke:{src:"getApplicationsMetadata",input:(U)=>({deviceVersion:U.context._internalState.deviceVersion,firmware:U.context._internalState.firmware,firmwareVersion:U.context._internalState.firmwareVersion,installedApps:U.context._internalState.installedApps}),onDone:{target:"GetApplicationsMetadataResultCheck",actions:r({_internalState:(U)=>{if(t$(U.event.output)){let K=Q.getDeviceSessionState();return K.sessionStateType!==CQ.Connected&&Q.setDeviceSessionState({...K,installedApps:U.event.output.data.applications,appsUpdates:U.event.output.data.applicationsUpdates,installedLanguages:U.event.output.data.installedLanguages,catalog:U.event.output.data.catalog}),{...U.context._internalState,applications:U.event.output.data.applications,applicationsUpdates:U.event.output.data.applicationsUpdates,installedLanguages:U.event.output.data.installedLanguages,catalog:U.event.output.data.catalog}}return{...U.context._internalState,error:U.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetApplicationsMetadataResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(U)=>{let{context:K}=U,{error:O,firmwareVersion:I,firmwareUpdateContext:L,customImage:A,applications:M,applicationsUpdates:k,installedLanguages:B,catalog:C}=K._internalState;return O?a(O):U0({firmwareVersion:I,firmwareUpdateContext:L,customImage:A,applications:M,applicationsUpdates:k,installedLanguages:B,catalog:C})}})}extractDependencies(Q){return{getDeviceMetadata:()=>{let Z=Q.getDeviceSessionState();return Z.sessionStateType===CQ.Connected||Z.firmwareVersion?.metadata===void 0||Z.firmwareUpdateContext===void 0||Z.customImage===void 0||Z.installedApps.length===0||Z.appsUpdates===void 0||Z.installedLanguages===void 0||Z.catalog===void 0?Promise.resolve(null):Promise.resolve({firmwareVersion:Z.firmwareVersion,firmwareUpdateContext:Z.firmwareUpdateContext,customImage:Z.customImage,applications:Z.installedApps,applicationsUpdates:Z.appsUpdates,installedLanguages:Z.installedLanguages,catalog:Z.catalog})},getFirmwareMetadata:async()=>new y2(Q).run(),getApplicationsMetadata:async(Z)=>new f2(Q,{deviceVersion:Z.input.deviceVersion,firmware:Z.input.firmware,firmwareVersion:Z.input.firmwareVersion,installedApps:Z.input.installedApps}).run(),listAppsSecureChannel:(Z)=>{let{firmware:Y,firmwareVersion:$}=Z.input,J=Q.getSecureChannelService().listInstalledApps($.metadata,Y);return new U$(Q,{connection:J}).run()}}}}});class n2{constructor(Q,Z){this.api=Q,this.args=Z}run(){return new OT.Observable((Q)=>{(async()=>{let Z;try{let $=await fetch(this.args.apduInstallUrl);if(!$.ok)throw Error(`HTTP ${$.status} ${$.statusText}`);Z=await $.text()}catch($){throw new C2(`Failed to fetch APDUs: ${$ instanceof Error?$.message:String($)}`)}let Y=Z.split(/\r?\n/).filter(Boolean);if(typeof Z!="string"||Y.length===0)throw new xQ(`Language pack install script contains no APDUs: ${this.args.apduInstallUrl}`);for(let $=0;$<Y.length;$++){let J=Y[$],X=mQ(J);if(X===null||X.length<5)throw new xQ(`Invalid APDU data: ${J}`);let G=(await this.api.sendApdu(X)).caseOf({Left:(W)=>new xQ(`Device communication error: ${String(W)}`),Right:(W)=>hQ.isRefusedByUser(W)?new A1("Language install refused on device."):hQ.isOutOfMemory(W)?new aJ("Not enough space for language pack."):hQ.isSuccessResponse(W)?null:new xQ(`Unexpected device response: ${DQ(W.statusCode)}`)});if(G)throw G;Q.next({type:"progress",progress:($+1)/Y.length})}})().then(()=>Q.complete(),(Z)=>Q.error(Z))})}}var OT;var HT=w(()=>{oY();rY();O8();OT=require("rxjs")});var DT,IT;var o2=w(()=>{DT={0:"english",1:"french",2:"spanish",3:"brazilian",4:"german",5:"russian",6:"turkish",7:"thai"},IT=Object.freeze({DEVICE_READY:"os.installLanguagePackage.steps.deviceReady",GET_DEVICE_METADATA:"os.installLanguagePackage.steps.getDeviceMetadata",DELETE_CURRENT_LANGUAGE_PACK:"os.installLanguagePackage.steps.deleteCurrentLanguagePack",INSTALL_LANGUAGE_PACK:"os.installLanguagePackage.steps.installLanguagePack"})});var s2;var RT=w(()=>{R0();KZ();TZ();AO();CY();tY();rY();Z6();d2();HT();SY();o2();s2=class s2 extends AQ{makeStateMachine(Q){let{deleteCurrentLanguagePack:Z,installLanguagePack:Y}=this.extractDependencies(Q),$=this.input.unlockTimeout??qZ,J=this.input.language,{None:X}=k0,{DEVICE_READY:G,GET_DEVICE_METADATA:W,DELETE_CURRENT_LANGUAGE_PACK:U,INSTALL_LANGUAGE_PACK:K}=IT,O=new k1({input:{unlockTimeout:$}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:$,language:J},context:{},output:{}},actors:{getDeviceMetadata:O,deleteCurrentLanguagePack:VQ(Z),installLanguagePack:cY(({input:I})=>Y(I.apduInstallUrl))},guards:{isDefaultLanguage:({context:I})=>I.input.language==="english",hasError:({context:I})=>I._internalState.error!==null,shouldSkipInstall:({context:I})=>I._internalState.shouldSkipInstall},actions:{assignErrorFromEvent:r({_internalState:(I)=>({...I.context._internalState,error:I.event.error,shouldSkipInstall:!1})}),assignGetDeviceMetadataSnapshot:r({intermediateValue:(I)=>{let L=I.event.snapshot.context.intermediateValue;return L.step===hG.GET_DEVICE_METADATA?{...L,step:W}:L}}),assignGetDeviceMetadataDone:r({_internalState:(I)=>I.event.output.caseOf({Right:(L)=>{let A=L.catalog.languagePackages;if(!A)return{...I.context._internalState,error:new B2(`Language packages not found for OS ${L?.firmwareVersion?.os}.`)};let M=A.find((k)=>k.language===J);return M?(L.installedLanguages??[]).map(({id:k})=>k).includes(M.languagePackageId)?{...I.context._internalState,shouldSkipInstall:!0}:{...I.context._internalState,languagePackage:M}:{...I.context._internalState,error:new k2(`Language package not found for ${J}.`)}},Left:(L)=>({...I.context._internalState,error:L})})}),assignDeleteCurrentLanguagePackSnapshot:r({intermediateValue:(I)=>({requiredUserInteraction:X,step:U})}),assignDeleteCurrentLanguagePackDone:r({_internalState:(I)=>{let L=I.event.output;return N0(L)?I.context._internalState:{...I.context._internalState,error:new dq("message"in L.error?L.error.message:"Delete language pack failed.")}}}),assignInstallLanguagePackSnapshot:r({intermediateValue:(I)=>{let L=I.event.snapshot.context,A=I.context,M="progress"in A.intermediateValue?A.intermediateValue.progress??0:0;return{requiredUserInteraction:X,step:K,progress:L?.type==="progress"?L.progress:M}}})}}).createMachine({id:"InstallLanguagePackageDeviceAction",initial:"CheckRequestedLanguage",context:(I)=>({input:{unlockTimeout:I.input.unlockTimeout,language:I.input.language},intermediateValue:{requiredUserInteraction:X,step:G,progress:0},_internalState:{error:null,languagePackage:null,shouldSkipInstall:!1}}),states:{CheckRequestedLanguage:{always:[{guard:"isDefaultLanguage",target:"DeleteCurrentLanguagePack"},{target:"GetDeviceMetadata"}]},GetDeviceMetadata:{invoke:{id:"GetDeviceMetadata",src:"getDeviceMetadata",input:({context:I})=>({unlockTimeout:I.input.unlockTimeout,forceUpdate:!0,useSecureChannel:!0}),onSnapshot:{actions:"assignGetDeviceMetadataSnapshot"},onDone:{target:"LanguagePackCheck",actions:"assignGetDeviceMetadataDone"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},LanguagePackCheck:{always:[{guard:"hasError",target:"Error"},{guard:"shouldSkipInstall",target:"Success"},{target:"DeleteCurrentLanguagePack"}]},DeleteCurrentLanguagePack:{invoke:{id:"DeleteCurrentLanguagePack",src:"deleteCurrentLanguagePack",onSnapshot:{actions:"assignDeleteCurrentLanguagePackSnapshot"},onDone:{target:"DeleteCurrentLanguagePackResultCheck",actions:"assignDeleteCurrentLanguagePackDone"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},DeleteCurrentLanguagePackResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"isDefaultLanguage",target:"Success"},{target:"InstallLanguagePack"}]},InstallLanguagePack:{invoke:{id:"InstallLanguagePack",src:"installLanguagePack",input:({context:I})=>({apduInstallUrl:I._internalState.languagePackage.apduInstallUrl}),onSnapshot:{actions:"assignInstallLanguagePackSnapshot"},onDone:{target:"Success"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final"},Error:{type:"final"}},output:(I)=>I.context._internalState.error!==null?a(I.context._internalState.error):U0(void 0)})}extractDependencies(Q){return{deleteCurrentLanguagePack:()=>Q.sendCommand(new Iq({languagePackageId:255})),installLanguagePack:(Z)=>new n2(Q,{apduInstallUrl:Z}).run()}}}});class a2{constructor(Q,Z){this.api=Q,this.args=Z;let Y=Q.getDeviceModel();this.deviceModelId=Y.id}deviceModelId;run(){let Q=this.api.getDeviceSessionState();if(Q.sessionStateType===CQ.Connected)return{error:new xQ("Invalid device state")};if(Q.catalog===void 0)return{error:new xQ("Device apps metadata not fetched")};let Z=[],Y=[],$=[];for(let J of this.args.applications){let X=Q.catalog.applications.find((W)=>W.versionName===J.name),G=Q.installedApps.find((W)=>W.versionName===J.name);if(G!==void 0&&this.validateConstraint(G,X,J.constraints)){Y=[...Y,J.name];continue}if(X!==void 0&&this.validateConstraint(X,void 0,J.constraints))Z=[...Z,X];else if(this.args.allowMissingApplication)$=[...$,J.name];else return Q.firmwareUpdateContext?.availableUpdate!==void 0&&X!==void 0?{error:new P8(`Application ${J.name} needs latest firmware`)}:Q.firmwareUpdateContext?.availableUpdate!==void 0?{error:new P8(`Application ${J.name} needs latest firmware`)}:{error:new N2(`Application ${J.name} not supported for this device`)}}return Z=[...Z.reduce((J,X)=>{let G=X.parentName;if(G){let W=Q.catalog.applications.find((K)=>K.versionName===G),U=Q.installedApps.find((K)=>K.versionName===G);if(W&&!U)return[...J,W]}return J},[]),...Z],{installPlan:Z.filter((J,X)=>Z.findIndex((G)=>G.versionName===J.versionName)===X),missingApplications:$,alreadyInstalled:Y}}validateConstraint(Q,Z,Y){if(Y===void 0)return!0;for(let $ of Y)if(!($.exemptModels!==void 0&&$.exemptModels.includes(this.deviceModelId))&&!($.applicableModels!==void 0&&!$.applicableModels.includes(this.deviceModelId)))return $.minVersion==="latest"?!Z||i2.gte(Q.version,Z.version):i2.gte(Q.version,$.minVersion);return!0}}var i2;var LT=w(()=>{rY();K$();i2=JZ(kG(),1)});class r2{constructor(Q,Z){this.api=Q,this.args=Z,this.deviceModel=Q.getDeviceModel()}deviceModel;run(){let Q=this.api.getDeviceSessionState();if(Q.sessionStateType===CQ.Connected)return{error:new xQ("Invalid device state")};let{firmwareUpdateContext:Z,customImage:Y,firmwareVersion:$,installedLanguages:J,installedApps:X}=Q;if(Z===void 0||Y===void 0||$===void 0||J===void 0)return{error:new xQ("Device metadata not fetched")};let{blockSize:G,totalMemoryBlocks:W}=this.getMemoryConstants($),U=this.getCurrentMemoryBlocksUsage({firmwareUpdateContext:Z,customImage:Y,installedApps:X,installedLanguages:J,blockSize:G}),K=this.getInstallPlanMemoryBlocksUsage(this.args.installPlan,G);return{outOfMemory:U+K>=W-Tn}}getMemoryConstants(Q){let Z=this.deviceModel.getBlockSize({firmwareVersion:Q.os}),Y=Math.floor(this.deviceModel.memorySize/Z);return{blockSize:Z,totalMemoryBlocks:Y}}getCurrentMemoryBlocksUsage({firmwareUpdateContext:Q,customImage:Z,installedApps:Y,installedLanguages:$,blockSize:J}){let X=(O)=>Math.ceil(O/J),G=X(Q.currentFirmware.bytes||0),W=X(Z.size||0),U=Y.reduce((O,I)=>O+X(I.bytes||0),0),K=$.reduce((O,I)=>O+X(I.size),0);return G+W+U+K}getInstallPlanMemoryBlocksUsage(Q,Z){let Y=($)=>Math.ceil($/Z);return Q.reduce(($,J)=>$+Y(J.bytes||0),0)}}var Tn=1;var ET=w(()=>{rY();K$()});var PT;var jT=w(()=>{PT=Object.freeze({UPDATE_DEVICE_METADATA:"os.installOrUpdateApps.steps.updateDeviceMetadata",BUILD_INSTALL_PLAN:"os.installOrUpdateApps.steps.buildInstallPlan",CHECK_IF_ENOUGH_MEMORY:"os.installOrUpdateApps.steps.checkIfEnoughMemory",INSTALL_APPLICATION:"os.installOrUpdateApps.steps.installApplication"})});var Y6;var t2=w(()=>{R0();KZ();CY();tY();rY();Z6();T1();LT();ET();SY();K$();T8();B1();jT();Y6=class Y6 extends AQ{makeStateMachine(Q){let{buildInstallPlan:Z,predictOutOfMemory:Y,installApp:$}=this.extractDependencies(Q),J=this.input.unlockTimeout??qZ,X=new k1({input:{unlockTimeout:J,useSecureChannel:!0,forceUpdate:!1}}).makeStateMachine(Q),G=new RY({input:{unlockTimeout:J}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:J},context:{},output:{}},actors:{updateMetadata:X,buildInstallPlan:VQ(Z),predictOutOfMemory:VQ(Y),goToDashboard:G,installApp:cY($)},guards:{hasError:({context:W})=>W._internalState.error!==null,hasInstallPlan:(W)=>W.context.intermediateValue.installPlan!==null,hasMoreApps:(W)=>W.context._internalState.currentIndex<W.context.intermediateValue.installPlan.installPlan.length},actions:{assignErrorFromEvent:r({_internalState:(W)=>({...W.context._internalState,error:W.event.error})}),nextAppIndex:r({_internalState:(W)=>({...W.context._internalState,currentIndex:W.context._internalState.currentIndex+1})}),cleanupDeviceState:()=>{let W=Q.getDeviceSessionState();W.sessionStateType!==CQ.Connected&&Q.setDeviceSessionState({...W,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"InstallOrUpdateAppsDeviceAction",initial:"DeviceReady",context:(W)=>({input:{applications:W.input.applications,allowMissingApplication:W.input.allowMissingApplication,unlockTimeout:W.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None,step:PT.UPDATE_DEVICE_METADATA,installPlan:null},_internalState:{error:null,osVersion:null,currentIndex:0}}),states:{DeviceReady:{always:[{target:"UpdateDeviceMetadata"}]},UpdateDeviceMetadata:{exit:r({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k0.None})}),invoke:{id:"updateMetadata",src:"updateMetadata",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,useSecureChannel:!0,forceUpdate:!1}),onSnapshot:{actions:r({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,deviceId:W.event.snapshot.context.intermediateValue.deviceId??W.context.intermediateValue.deviceId})})},onDone:{target:"UpdateDeviceMetadataCheck",actions:r({_internalState:(W)=>W.event.output.caseOf({Right:(U)=>({...W.context._internalState,osVersion:U.firmwareVersion.metadata}),Left:(U)=>({...W.context._internalState,error:U})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},UpdateDeviceMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"hasInstallPlan"},{target:"BuildInstallPlan"}]},BuildInstallPlan:{invoke:{src:"buildInstallPlan",input:(W)=>({applications:W.context.input.applications,allowMissingApplication:W.context.input.allowMissingApplication}),onDone:{target:"BuildInstallPlanCheck",actions:r({_internalState:(W)=>("error"in W.event.output)?{...W.context._internalState,error:W.event.output.error}:W.context._internalState,intermediateValue:(W)=>("error"in W.event.output)?W.context.intermediateValue:{...W.context.intermediateValue,installPlan:{installPlan:W.event.output.installPlan,alreadyInstalled:W.event.output.alreadyInstalled,missingApplications:W.event.output.missingApplications,currentIndex:0,currentProgress:0}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},BuildInstallPlanCheck:{always:[{guard:"hasError",target:"Error"},{target:"PredictOutOfMemory",guard:"hasMoreApps"},{target:"Success"}]},PredictOutOfMemory:{invoke:{src:"predictOutOfMemory",input:(W)=>({installPlan:W.context.intermediateValue.installPlan.installPlan}),onDone:{target:"PredictOutOfMemoryCheck",actions:r({_internalState:(W)=>("error"in W.event.output)?{...W.context._internalState,error:W.event.output.error}:W.event.output.outOfMemory?{...W.context._internalState,error:new aJ("Not enough memory for those applications")}:W.context._internalState})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},PredictOutOfMemoryCheck:{always:[{guard:"hasError",target:"Error"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(W)=>W.event.output.caseOf({Right:()=>W.context._internalState,Left:(U)=>({...W.context._internalState,error:U})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallApp",actions:"cleanupDeviceState"}]},InstallApp:{exit:r({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k0.None})}),invoke:{id:"installApp",src:"installApp",input:(W)=>({osVersion:W.context._internalState.osVersion,application:W.context.intermediateValue.installPlan.installPlan[W.context._internalState.currentIndex]}),onSnapshot:{actions:r({intermediateValue:(W)=>{switch(W.event.snapshot.context?.type){case fQ.DeviceId:return{...W.context.intermediateValue,deviceId:W.event.snapshot.context.payload.deviceId};case fQ.PermissionRequested:return{...W.context.intermediateValue,requiredUserInteraction:k0.AllowSecureConnection};case fQ.PermissionGranted:{let U=Q.getDeviceSessionState();return U.sessionStateType!==CQ.Connected&&Q.setDeviceSessionState({...U,isSecureConnectionAllowed:!0}),{...W.context.intermediateValue,requiredUserInteraction:k0.None}}case fQ.Progress:return{...W.context.intermediateValue,installPlan:{...W.context.intermediateValue.installPlan,currentIndex:W.context._internalState.currentIndex,currentProgress:W.event.snapshot.context.payload.progress}};default:return W.context.intermediateValue}},_internalState:(W)=>W.event.snapshot.context?.type===fQ.Error?{...W.context._internalState,error:W.event.snapshot.context.error.mapInstallDAErrors()}:W.context._internalState})},onDone:{target:"InstallAppCheck",actions:"nextAppIndex"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},InstallAppCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallApp",guard:"hasMoreApps"},{target:"UpdateDeviceMetadata"}]},Success:{type:"final"},Error:{type:"final"}},output:(W)=>{let{context:U}=W,{error:K}=U._internalState,{installPlan:O}=U.intermediateValue;return K?a(K):U0({successfullyInstalled:O.installPlan,alreadyInstalled:O.alreadyInstalled,missingApplications:O.missingApplications})}})}extractDependencies(Q){return{buildInstallPlan:(Z)=>Promise.resolve(new a2(Q,{applications:Z.input.applications,allowMissingApplication:Z.input.allowMissingApplication}).run()),predictOutOfMemory:(Z)=>Promise.resolve(new r2(Q,{installPlan:Z.input.installPlan}).run()),installApp:(Z)=>{let{osVersion:Y,application:$}=Z.input,J=Q.getSecureChannelService().installApp(Y,$);return new U$(Q,{connection:J}).run()}}}}});var e2;var AT=w(()=>{e2=Object.freeze({LIST_APPS:"os.listAppsWithMetadata.steps.listApps",FETCH_METADATA:"os.listAppsWithMetadata.steps.fetchMetadata",SAVE_SESSION:"os.listAppsWithMetadata.steps.saveSession"})});var Q7;var MT=w(()=>{R0();KZ();CY();tY();g9();SY();AT();Q7=class Q7 extends AQ{makeStateMachine(Q){let{getAppsByHash:Z,setDeviceSessionState:Y,getDeviceSessionState:$}=this.extractDependencies(Q),J=this.input.unlockTimeout??qZ,X=new yG({input:{unlockTimeout:J}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:J},context:{},output:{}},actors:{listApps:X,getAppsByHash:VQ(Z),updateDeviceSessionState:P2(({input:G,sendBack:W})=>{let{appsWithMetadata:U}=G,K=U.filter((I)=>I!==null),O={...$(),installedApps:K};try{Y(O),W({type:"done"})}catch(I){W({type:"error",error:I})}})},guards:{hasError:({context:G})=>G._internalState.error!==null,hasNoAppsInstalled:({context:G})=>G._internalState.apps.length===0},actions:{assignErrorFromEvent:r({_internalState:(G)=>({...G.context._internalState,error:G.event.error})})}}).createMachine({id:"ListAppsWithMetadataDeviceAction",initial:"DeviceReady",context:(G)=>({input:G.input,_internalState:{error:null,apps:[],appsWithMetadata:[]},intermediateValue:{requiredUserInteraction:k0.None,step:e2.LIST_APPS}}),states:{DeviceReady:{always:{target:"ListApps"}},ListApps:{invoke:{id:"listApps",src:"listApps",input:(G)=>({unlockTimeout:G.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(G)=>G.event.snapshot.context.intermediateValue})},onDone:{target:"ListAppsCheck",actions:r({intermediateValue:(G)=>({requiredUserInteraction:k0.None,step:e2.LIST_APPS}),_internalState:(G)=>G.event.output.caseOf({Right:(W)=>({...G.context._internalState,apps:W}),Left:(W)=>({...G.context._internalState,error:W})})})}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"hasNoAppsInstalled",actions:r({_internalState:(G)=>({...G.context._internalState,appsWithMetadata:[]})})},{target:"FetchMetadata"}]},FetchMetadata:{invoke:{id:"getAppsByHash",src:"getAppsByHash",input:(G)=>G.context._internalState.apps,onDone:{target:"FetchMetadataCheck",actions:r({_internalState:(G)=>G.event.output.caseOf({Right:(W)=>({...G.context._internalState,appsWithMetadata:W}),Left:(W)=>({...G.context._internalState,error:W})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},FetchMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"SaveSession"}]},SaveSession:{invoke:{src:"updateDeviceSessionState",input:(G)=>({appsWithMetadata:G.context._internalState.appsWithMetadata})},on:{done:{target:"Success"},error:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final"},Error:{type:"final"}},output:(G)=>G.context._internalState.error?a(G.context._internalState.error):U0(G.context._internalState.appsWithMetadata)})}extractDependencies(Q){return{getAppsByHash:({input:Z})=>{let Y=Z.reduce(($,J)=>J.appFullHash?$.concat(J.appFullHash):$,[]);return Q.getManagerApiService().getAppsByHash(Y)},getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var TT;var NT=w(()=>{TT=Object.freeze({GET_DEVICE_METADATA:"os.openAppWithDependencies.steps.getDeviceMetadata",INSTALL_OR_UPDATE_APPS:"os.openAppWithDependencies.steps.installOrUpdateApps",OPEN_APP:"os.openAppWithDependencies.steps.openApp"})});var Z7;var BT=w(()=>{R0();KZ();CY();tY();rY();Z6();t2();oq();SY();NT();Z7=class Z7 extends AQ{makeStateMachine(Q){let Z=this.input.unlockTimeout??qZ,Y=new k1({input:{unlockTimeout:Z,useSecureChannel:!0,forceUpdate:!1}}).makeStateMachine(Q),$=new Y6({input:{unlockTimeout:Z,applications:[...this.input.dependencies,this.input.application],allowMissingApplication:this.input.allowMissingApplication??!1}}).makeStateMachine(Q),J=new kZ({input:{unlockTimeout:Z,appName:this.input.application.name}}).makeStateMachine(Q);return NQ({types:{input:{unlockTimeout:Z},context:{},output:{}},actors:{getMetadata:Y,installApps:$,openApp:J},guards:{hasError:({context:X})=>X._internalState.error!==null},actions:{assignErrorFromEvent:r({_internalState:(X)=>({...X.context._internalState,error:X.event.error})})}}).createMachine({id:"OpenAppWithDependenciesDeviceAction",initial:"DeviceReady",context:(X)=>({input:{application:X.input.application,dependencies:X.input.dependencies,requireLatestFirmware:X.input.requireLatestFirmware,unlockTimeout:X.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None,step:TT.GET_DEVICE_METADATA,installPlan:null},_internalState:{error:null,deviceMetadata:null,installResult:null}}),states:{DeviceReady:{always:[{target:"GetDeviceMetadata"}]},GetDeviceMetadata:{exit:r({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:k0.None})}),invoke:{id:"getMetadata",src:"getMetadata",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout,useSecureChannel:!0,forceUpdate:!1}),onSnapshot:{actions:r({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:X.event.snapshot.context.intermediateValue.requiredUserInteraction,deviceId:X.event.snapshot.context.intermediateValue.deviceId??X.context.intermediateValue.deviceId})})},onDone:{target:"GetDeviceMetadataCheck",actions:r({_internalState:(X)=>X.event.output.caseOf({Right:(G)=>X.context.input.requireLatestFirmware&&G.firmwareUpdateContext.availableUpdate!==void 0?{...X.context._internalState,error:new P8("Firmware is not the latest version")}:{...X.context._internalState,deviceMetadata:G},Left:(G)=>({...X.context._internalState,error:G})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallDependencies"}]},InstallDependencies:{exit:r({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:k0.None})}),invoke:{src:"installApps",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout,applications:[...X.context.input.dependencies,X.context.input.application],allowMissingApplication:this.input.allowMissingApplication??!1}),onSnapshot:{actions:r({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:X.event.snapshot.context.intermediateValue.requiredUserInteraction,installPlan:X.event.snapshot.context.intermediateValue.installPlan,deviceId:X.event.snapshot.context.intermediateValue.deviceId??X.context.intermediateValue.deviceId})})},onDone:{target:"InstallDependenciesCheck",actions:r({_internalState:(X)=>X.event.output.caseOf({Right:(G)=>({...X.context._internalState,installResult:G}),Left:(G)=>({...X.context._internalState,error:G})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},InstallDependenciesCheck:{always:[{guard:"hasError",target:"Error"},{target:"OpenApp"}]},OpenApp:{exit:r({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:k0.None})}),invoke:{src:"openApp",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout,appName:X.context.input.application.name}),onSnapshot:{actions:r({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:X.event.snapshot.context.intermediateValue.requiredUserInteraction,installPlan:null})})},onDone:{target:"OpenAppCheck",actions:r({_internalState:(X)=>X.event.output.caseOf({Right:()=>X.context._internalState,Left:(G)=>({...X.context._internalState,error:G})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},OpenAppCheck:{always:[{guard:"hasError",target:"Error"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(X)=>{let{context:G}=X,{error:W,deviceMetadata:U,installResult:K}=G._internalState;return W?a(W):U0({deviceMetadata:U,installResult:K})}})}}});var n9;var kT=w(()=>{n9=Object.freeze({OPEN_APP:"os.sendCommandInApp.steps.openApp",SEND_COMMAND:"os.sendCommandInApp.steps.sendCommand"})});var QJ;var CT=w(()=>{R0();KZ();TZ();CY();rY();oq();SY();kT();QJ=class QJ extends AQ{makeStateMachine(Q){let{sendCommand:Z}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{sendCommand:VQ(Z),openAppStateMachine:new kZ({input:{appName:this.input.appName}}).makeStateMachine(Q)},guards:{skipOpenApp:()=>this.input.skipOpenApp,noInternalError:({context:Y})=>Y._internalState.error===null},actions:{assignErrorFromEvent:r({_internalState:(Y)=>({...Y.context._internalState,error:Y.event.error})})}}).createMachine({id:"SendCommandInAppDeviceAction",initial:"InitialState",context:({input:Y})=>({input:Y,intermediateValue:{requiredUserInteraction:k0.None,step:n9.OPEN_APP},_internalState:{commandResponse:null,error:null}}),states:{InitialState:{always:[{target:"SendCommand",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:this.input.appName},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:(Y)=>Y.event.snapshot.context.intermediateValue})},onDone:{actions:r({_internalState:(Y)=>Y.event.output.caseOf({Right:()=>Y.context._internalState,Left:($)=>({...Y.context._internalState,error:$})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"SendCommand",guard:"noInternalError"},"Error"]},SendCommand:{entry:r({intermediateValue:{requiredUserInteraction:this.input.requiredUserInteraction,step:n9.SEND_COMMAND}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:n9.SEND_COMMAND}}),invoke:{id:"sendCommand",src:"sendCommand",input:({context:Y})=>Y.input.command,onDone:{target:"SendCommandResultCheck",actions:[r({_internalState:({event:Y,context:$})=>N0(Y.output)?{...$._internalState,commandResponse:Y.output.data}:{...$._internalState,error:Y.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},SendCommandResultCheck:{always:[{target:"Success",guard:"noInternalError"},"Error"]},Success:{type:"final"},Error:{type:"final"}},output:({context:Y})=>Y._internalState.commandResponse?U0(Y._internalState.commandResponse):a(Y._internalState.error||new xQ("No error in final state"))})}extractDependencies(Q){return{sendCommand:(Z)=>Q.sendCommand(Z.input)}}}});function C1(Q,Z){return Reflect.getOwnMetadata(Z,Q)}function $6(Q,Z,Y){Reflect.defineMetadata(Z,Y,Q)}function tJ(Q,Z,Y,$){let J=$(C1(Q,Z)??Y());Reflect.defineMetadata(Z,J,Q)}var Y7=()=>{};function aZ(Q){return(typeof Q=="object"&&Q!==null||typeof Q=="function")&&typeof Q.then=="function"}function eY(Q){switch(typeof Q){case"string":case"symbol":return Q.toString();case"function":return Q.name;default:throw Error(`Unexpected ${typeof Q} service id type`)}}var $7,VV;var J7=w(()=>{$7=Symbol.for("@inversifyjs/common/islazyServiceIdentifier");VV=class VV{[$7];#Q;constructor(Q){this.#Q=Q,this[$7]=!0}static is(Q){return typeof Q=="object"&&Q!==null&&Q[$7]===!0}unwrap(){return this.#Q()}}});var ST=()=>{};function w1(){let Q=C1(Object,G7)??0;return Q===Number.MAX_SAFE_INTEGER?$6(Object,G7,Number.MIN_SAFE_INTEGER):tJ(Object,G7,()=>Q,(Z)=>Z+1),Q}function*oT(...Q){for(let Z of Q)yield*Z}class X6{#Q;#Z;#J;constructor(Q){this.#Q=new Map,this.#Z={};for(let Z of Reflect.ownKeys(Q))this.#Z[Z]=new Map;this.#J=Q}add(Q,Z){this.#Y(Q).push(Z);for(let Y of Reflect.ownKeys(Z))this.#X(Y,Z[Y]).push(Q)}clone(){let Q=Reflect.ownKeys(this.#J),Z=new X6(this.#J);this.#V(this.#Q,Z.#Q);for(let Y of Q)this.#V(this.#Z[Y],Z.#Z[Y]);return Z}get(Q,Z){return this.#Z[Q].get(Z)}getAllKeys(Q){return this.#Z[Q].keys()}removeByRelation(Q,Z){let Y=this.get(Q,Z);if(Y===void 0)return;let $=new Set(Y);for(let J of $){let X=this.#Q.get(J);if(X===void 0)throw Error("Expecting model relation, none found");for(let G of X)G[Q]===Z&&this.#G(J,G);this.#Q.delete(J)}}#Y(Q){let Z=this.#Q.get(Q);return Z===void 0&&(Z=[],this.#Q.set(Q,Z)),Z}#X(Q,Z){let Y=this.#Z[Q].get(Z);return Y===void 0&&(Y=[],this.#Z[Q].set(Z,Y)),Y}#V(Q,Z){for(let[Y,$]of Q)Z.set(Y,[...$])}#G(Q,Z){for(let Y of Reflect.ownKeys(Z))this.#$(Q,Y,Z[Y])}#$(Q,Z,Y){let $=this.#Z[Z].get(Y);if($!==void 0){let J=$.indexOf(Q);J!==-1&&$.splice(J,1),$.length===0&&this.#Z[Z].delete(Y)}}}class zV{#Q;#Z;constructor(Q,Z){this.#Q=Z??new X6({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#Z=Q}static build(Q){return new zV(Q)}add(Q,Z){this.#Q.add(Q,Z)}clone(){return new zV(this.#Z,this.#Q.clone())}get(Q){let Z=[],Y=this.#Q.get(J6.serviceId,Q);Y!==void 0&&Z.push(Y);let $=this.#Z?.get(Q);if($!==void 0&&Z.push($),Z.length!==0)return oT(...Z)}removeAllByModuleId(Q){this.#Q.removeByRelation(J6.moduleId,Q)}removeAllByServiceId(Q){this.#Q.removeByRelation(J6.serviceId,Q)}}class WV{#Q;#Z;constructor(Q,Z){this.#Q=Z??new X6({id:{isOptional:!1},moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#Z=Q}static build(Q){return new WV(Q)}clone(){return new WV(this.#Z,this.#Q.clone())}get(Q){return this.getNonParentBindings(Q)??this.#Z?.get(Q)}getById(Q){return this.#Q.get(WJ.id,Q)??this.#Z?.getById(Q)}getByModuleId(Q){return this.#Q.get(WJ.moduleId,Q)??this.#Z?.getByModuleId(Q)}getNonParentBindings(Q){return this.#Q.get(WJ.serviceId,Q)}getNonParentBoundServices(){return this.#Q.getAllKeys(WJ.serviceId)}removeById(Q){this.#Q.removeByRelation(WJ.id,Q)}removeAllByModuleId(Q){this.#Q.removeByRelation(WJ.moduleId,Q)}removeAllByServiceId(Q){this.#Q.removeByRelation(WJ.serviceId,Q)}set(Q){let Z={[WJ.id]:Q.id,[WJ.serviceId]:Q.serviceIdentifier};Q.moduleId!==void 0&&(Z[WJ.moduleId]=Q.moduleId),this.#Q.add(Q,Z)}}class KV{#Q;#Z;constructor(Q,Z){this.#Q=Z??new X6({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#Z=Q}static build(Q){return new KV(Q)}add(Q,Z){this.#Q.add(Q,Z)}clone(){return new KV(this.#Z,this.#Q.clone())}get(Q){let Z=[],Y=this.#Q.get(G6.serviceId,Q);Y!==void 0&&Z.push(Y);let $=this.#Z?.get(Q);if($!==void 0&&Z.push($),Z.length!==0)return oT(...Z)}removeAllByModuleId(Q){this.#Q.removeByRelation(G6.moduleId,Q)}removeAllByServiceId(Q){this.#Q.removeByRelation(G6.serviceId,Q)}}function FV(){return{constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}function V6(Q){let Z=C1(Q,qV)??FV();if(!function(Y){let $=C1(Y,sT);return $!==void 0&&$!==0}(Q))return function(Y,$){let J=[];if($.length<Y.length)throw new xZ(fZ.missingInjectionDecorator,`Found unexpected missing metadata on type "${Y.name}". "${Y.name}" constructor requires at least ${Y.length.toString()} arguments, found ${$.length.toString()} instead.
|
|
17
|
+
Are you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?
|
|
18
|
+
|
|
19
|
+
If you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let X=0;X<$.length;++X)$[X]===void 0&&J.push(X);if(J.length>0)throw new xZ(fZ.missingInjectionDecorator,`Found unexpected missing metadata on type "${Y.name}" at constructor indexes "${J.join('", "')}".
|
|
20
|
+
|
|
21
|
+
Are you using @inject, @multiInject or @unmanaged decorators at those indexes?
|
|
22
|
+
|
|
23
|
+
If you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(Q,Z.constructorArguments),Z;(function(Y,$){let J=[];for(let X=0;X<$.constructorArguments.length;++X){let G=$.constructorArguments[X];G!==void 0&&G.kind!==UV.unknown||J.push(` - Missing or incomplete metadata for type "${Y.name}" at constructor argument with index ${X.toString()}.
|
|
24
|
+
Every constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`)}for(let[X,G]of $.properties)G.kind===UV.unknown&&J.push(` - Missing or incomplete metadata for type "${Y.name}" at property "${X.toString()}".
|
|
25
|
+
This property must be decorated either with @inject or @multiInject decorator.`);if(J.length===0)throw new xZ(fZ.unknown,`Unexpected class metadata for type "${Y.name}" with uncompletion traces.
|
|
26
|
+
This might be caused by one of the following reasons:
|
|
27
|
+
|
|
28
|
+
1. A third party library is targeting inversify reflection metadata.
|
|
29
|
+
2. A bug is causing the issue. Consider submiting an issue to fix it.`);throw new xZ(fZ.missingInjectionDecorator,`Invalid class metadata at type ${Y.name}:
|
|
30
|
+
|
|
31
|
+
${J.join(`
|
|
32
|
+
|
|
33
|
+
`)}`)})(Q,Z)}function Nn(){return 0}function Bn(Q){return(Z)=>{Z!==void 0&&Z.kind===UV.unknown&&tJ(Q,sT,Nn,(Y)=>Y-1)}}function iT(Q,Z){return(...Y)=>($)=>{if($===void 0)return Q(...Y);if($.kind===S1.unmanaged)throw new xZ(fZ.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return Z($,...Y)}}function aT(Q){if(Q.kind!==UV.unknown&&Q.isFromTypescriptParamType!==!0)throw new xZ(fZ.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found")}function wT(Q,Z){return(Y)=>{let $=Y.properties.get(Z);return Y.properties.set(Z,Q($)),Y}}function Cn(Q,Z,Y,$){if(xZ.isErrorOfKind($,fZ.injectionDecoratorConflict)){let J=function(X,G,W){if(W===void 0){if(G===void 0)throw new xZ(fZ.unknown,"Unexpected undefined property and index values");return{kind:N8.property,property:G,targetClass:X.constructor}}return typeof W=="number"?{index:W,kind:N8.parameter,targetClass:X}:{kind:N8.method,method:G,targetClass:X}}(Q,Z,Y);throw new xZ(fZ.injectionDecoratorConflict,`Unexpected injection error.
|
|
34
|
+
|
|
35
|
+
Cause:
|
|
36
|
+
|
|
37
|
+
${$.message}
|
|
38
|
+
|
|
39
|
+
Details
|
|
40
|
+
|
|
41
|
+
${function(X){switch(X.kind){case N8.method:return`[class: "${X.targetClass.name}", method: "${X.method.toString()}"]`;case N8.parameter:return`[class: "${X.targetClass.name}", index: "${X.index.toString()}"]`;case N8.property:return`[class: "${X.targetClass.name}", property: "${X.property.toString()}"]`}}(J)}`,{cause:$})}throw $}function Sn(Q,Z){return(Y,$,J)=>{try{J===void 0?function(X,G){let W=V7(X,G);return(U,K)=>{tJ(U.constructor,qV,FV,wT(W(U),K))}}(Q,Z)(Y,$):typeof J=="number"?function(X,G){let W=V7(X,G);return(U,K,O)=>{if(!function(I,L){return typeof I=="function"&&L===void 0}(U,K))throw new xZ(fZ.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
|
|
42
|
+
Found @inject decorator at method "${K?.toString()??""}" at class "${U.constructor.name}"`);tJ(U,qV,FV,function(I,L){return(A)=>{let M=A.constructorArguments[L];return A.constructorArguments[L]=I(M),A}}(W(U),O))}}(Q,Z)(Y,$,J):function(X,G){let W=V7(X,G);return(U,K,O)=>{if(!function(I){return I.set!==void 0}(O))throw new xZ(fZ.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
|
|
43
|
+
Found @inject decorator at method "${K.toString()}" at class "${U.constructor.name}"`);tJ(U.constructor,qV,FV,wT(W(U),K))}}(Q,Z)(Y,$,J)}catch(X){Cn(Y,$,J,X)}}}function V7(Q,Z){return(Y)=>{let $=Z(Y);return(J)=>($(J),Q(J))}}function g(Q){return Sn(kn(S1.singleInjection,Q),Bn)}function _n(Q){let Z=C1(Q,"design:paramtypes");Z!==void 0&&tJ(Q,qV,FV,function(Y){return($)=>(Y.forEach((J,X)=>{var G;$.constructorArguments[X]!==void 0||(G=J,wn.includes(G))||($.constructorArguments[X]=function(W){return{isFromTypescriptParamType:!0,kind:S1.singleInjection,name:void 0,optional:!1,tags:new Map,value:W}}(J))}),$)}(Z))}function e(Q){return(Z)=>{(function(Y){if(C1(Y,_T)!==void 0)throw new xZ(fZ.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${Y.name}"`);$6(Y,_T,!0)})(Z),_n(Z),Q!==void 0&&tJ(Z,qV,FV,(Y)=>({...Y,scope:Q}))}}function vT(){return{kind:S1.unmanaged}}class OV{#Q;constructor(Q){this.#Q=Q}get name(){return this.#Q.elem.name}get serviceIdentifier(){return this.#Q.elem.serviceIdentifier}get tags(){return this.#Q.elem.tags}getAncestor(){if(this.#Q.previous!==void 0)return new OV(this.#Q.previous)}}function s9(Q,Z,Y){let $=Y?.customServiceIdentifier??Z.serviceIdentifier,J=[...Q.getBindings($)??[]].filter((X)=>X.isSatisfiedBy(Z));if(J.length===0&&Q.autobindOptions!==void 0&&typeof $=="function"){let X=function(G,W){let U=V6(W),K=U.scope??G.scope;return{cache:{isRight:!1,value:void 0},id:w1(),implementationType:W,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:K,serviceIdentifier:W,type:cZ.Instance}}(Q.autobindOptions,$);Q.setBinding(X),J.push(X)}return J}function uG(Q){return Q.redirections!==void 0}function rT(Q,Z,Y,$){let J,X;uG(Y)?(J=Y.binding.targetServiceIdentifier,X=Y.binding.serviceIdentifier):(J=Y.serviceIdentifier,X=Y.parent?.binding.serviceIdentifier),Array.isArray(Q)?function(G,W,U,K,O){if(G.length!==0){let I=`Ambiguous bindings found for service: "${eY(U)}".
|
|
44
|
+
|
|
45
|
+
Registered bindings:
|
|
46
|
+
|
|
47
|
+
${G.map((L)=>function(A){switch(A.type){case cZ.Instance:return`[ type: "${A.type}", serviceIdentifier: "${eY(A.serviceIdentifier)}", scope: "${A.scope}", implementationType: "${A.implementationType.name}" ]`;case cZ.ServiceRedirection:return`[ type: "${A.type}", serviceIdentifier: "${eY(A.serviceIdentifier)}", redirection: "${eY(A.targetServiceIdentifier)}" ]`;default:return`[ type: "${A.type}", serviceIdentifier: "${eY(A.serviceIdentifier)}", scope: "${A.scope}" ]`}}(L.binding)).join(`
|
|
48
|
+
`)}
|
|
49
|
+
|
|
50
|
+
Trying to resolve bindings for "${tT(U,K)}".
|
|
51
|
+
|
|
52
|
+
${eT(O)}`;throw new xZ(fZ.planning,I)}W||xT(U,K,O)}(Q,Z,J,X,$):function(G,W,U,K,O){if(G!==void 0||W)return;xT(U,K,O)}(Q,Z,J,X,$)}function xT(Q,Z,Y){let $=`No bindings found for service: "${eY(Q)}".
|
|
53
|
+
|
|
54
|
+
Trying to resolve bindings for "${tT(Q,Z)}".
|
|
55
|
+
|
|
56
|
+
${eT(Y)}`;throw new xZ(fZ.planning,$)}function tT(Q,Z){return Z===void 0?`${eY(Q)} (Root service)`:eY(Z)}function eT(Q){let Z=Q.tags.size===0?"":`
|
|
57
|
+
- tags:
|
|
58
|
+
- ${[...Q.tags.keys()].map((Y)=>Y.toString()).join(`
|
|
59
|
+
- `)}`;return`Binding constraints:
|
|
60
|
+
- service identifier: ${eY(Q.serviceIdentifier)}
|
|
61
|
+
- name: ${Q.name?.toString()??"-"}${Z}`}function QN(Q,Z,Y){if(Q.redirections.length!==1)rT(Q.redirections,Z,Q,Y);else{let[$]=Q.redirections;uG($)&&QN($,Z,Y)}}function z7(Q,Z,Y){if(Array.isArray(Q.bindings)&&Q.bindings.length===1){let[$]=Q.bindings;uG($)&&QN($,Z,Y)}else rT(Q.bindings,Z,Q,Y)}function vn(Q,Z){if(function(Y){return Y instanceof Error&&(Y instanceof RangeError&&/stack space|call stack|too much recursion/i.test(Y.message)||Y.name==="InternalError"&&/too much recursion/.test(Y.message))}(Z)){let Y=function($){let J=[...$];if(J.length===0)return"(No dependency trace)";return J.map(eY).join(" -> ")}(function($){let J=new Set;for(let X of $.servicesBranch){if(J.has(X))return[...J,X];J.add(X)}return[...J]}(Q));throw new xZ(fZ.planning,`Circular dependency found: ${Y}`,{cause:Z})}throw Z}function ZN(Q){try{let Z=new Map;Q.rootConstraints.tag!==void 0&&Z.set(Q.rootConstraints.tag.key,Q.rootConstraints.tag.value);let Y=new F7({elem:{name:Q.rootConstraints.name,serviceIdentifier:Q.rootConstraints.serviceIdentifier,tags:Z},previous:void 0}),$=new OV(Y.last),J=s9(Q,$),X=[],G={bindings:X,parent:void 0,serviceIdentifier:Q.rootConstraints.serviceIdentifier};if(X.push(...i9(Q,Y,J,G)),!Q.rootConstraints.isMultiple){z7(G,Q.rootConstraints.isOptional??!1,$);let[W]=X;G.bindings=W}return{tree:{root:G}}}catch(Z){vn(Q,Z)}}function xn(Q,Z,Y,$){let J={binding:Z,classMetadata:Q.getClassMetadata(Z.implementationType),constructorParams:[],parent:$,propertyParams:new Map};return YN({autobindOptions:Q.autobindOptions,getBindings:Q.getBindings,getClassMetadata:Q.getClassMetadata,node:J,servicesBranch:Q.servicesBranch,setBinding:Q.setBinding},Y)}function fT(Q,Z,Y){if(Y.kind===S1.unmanaged)return;let $=VV.is(Y.value)?Y.value.unwrap():Y.value,J=Z.concat({name:Y.name,serviceIdentifier:$,tags:Y.tags}),X=new OV(J.last),G=s9(Q,X),W=[],U={bindings:W,parent:Q.node,serviceIdentifier:$};if(W.push(...i9(Q,J,G,U)),Y.kind===S1.singleInjection){z7(U,Y.optional,X);let[K]=W;U.bindings=K}return U}function fn(Q,Z,Y){let $=VV.is(Y.value)?Y.value.unwrap():Y.value,J=Z.concat({name:Y.name,serviceIdentifier:$,tags:Y.tags}),X=new OV(J.last),G=s9(Q,X),W=[],U={bindings:W,parent:Q.node,serviceIdentifier:$};if(W.push(...i9(Q,J,G,U)),Y.kind===cG.singleInjection){z7(U,Y.optional,X);let[K]=W;U.bindings=K}return U}function yn(Q,Z,Y,$){let J={binding:Z,params:[],parent:$};return YN({autobindOptions:Q.autobindOptions,getBindings:Q.getBindings,getClassMetadata:Q.getClassMetadata,node:J,servicesBranch:Q.servicesBranch,setBinding:Q.setBinding},Y)}function i9(Q,Z,Y,$){let J=uG($)?$.binding.targetServiceIdentifier:$.serviceIdentifier;Q.servicesBranch.push(J);let X=[];for(let G of Y)switch(G.type){case cZ.Instance:X.push(xn(Q,G,Z,$));break;case cZ.ResolvedValue:X.push(yn(Q,G,Z,$));break;case cZ.ServiceRedirection:{let W=gn(Q,Z,G,$);X.push(W);break}default:X.push({binding:G,parent:$})}return Q.servicesBranch.pop(),X}function gn(Q,Z,Y,$){let J={binding:Y,parent:$,redirections:[]},X=s9(Q,new OV(Z.last),{customServiceIdentifier:Y.targetServiceIdentifier});return J.redirections.push(...i9(Q,Z,X,J)),J}function YN(Q,Z){return Q.node.binding.type===cZ.Instance?function(Y,$,J){let X=$.classMetadata;for(let[G,W]of X.constructorArguments.entries())$.constructorParams[G]=fT(Y,J,W);for(let[G,W]of X.properties){let U=fT(Y,J,W);U!==void 0&&$.propertyParams.set(G,U)}return Y.node}(Q,Q.node,Z):function(Y,$,J){let X=$.binding.metadata;for(let[G,W]of X.arguments.entries())$.params[G]=fn(Y,J,W);return Y.node}(Q,Q.node,Z)}class W7{#Q;#Z;#J;#Y;#X;constructor(){this.#Q=this.#V(),this.#Z=this.#V(),this.#Y=this.#V(),this.#J=this.#V(),this.#X=[]}clearCache(){for(let Q of this.#q())Q.clear();for(let Q of this.#X)Q.clearCache()}get(Q){return Q.name===void 0?Q.tag===void 0?this.#$(this.#Q,Q).get(Q.serviceIdentifier):this.#$(this.#J,Q).get(Q.serviceIdentifier)?.get(Q.tag.key)?.get(Q.tag.value):Q.tag===void 0?this.#$(this.#Z,Q).get(Q.serviceIdentifier)?.get(Q.name):this.#$(this.#Y,Q).get(Q.serviceIdentifier)?.get(Q.name)?.get(Q.tag.key)?.get(Q.tag.value)}set(Q,Z){Q.name===void 0?Q.tag===void 0?this.#$(this.#Q,Q).set(Q.serviceIdentifier,Z):this.#G(this.#G(this.#$(this.#J,Q),Q.serviceIdentifier),Q.tag.key).set(Q.tag.value,Z):Q.tag===void 0?this.#G(this.#$(this.#Z,Q),Q.serviceIdentifier).set(Q.name,Z):this.#G(this.#G(this.#G(this.#$(this.#Y,Q),Q.serviceIdentifier),Q.name),Q.tag.key).set(Q.tag.value,Z)}subscribe(Q){this.#X.push(Q)}#V(){let Q=Array(bG.length);for(let Z=0;Z<Q.length;++Z)Q[Z]=new Map;return Q}#G(Q,Z){let Y=Q.get(Z);return Y===void 0&&(Y=new Map,Q.set(Z,Y)),Y}#$(Q,Z){return Q[this.#F(Z)]}#q(){return[...this.#Q,...this.#Z,...this.#Y,...this.#J]}#F(Q){return Q.isMultiple?Q.optional===!0?bG.multipleOptional:bG.multipleMandatory:Q.optional===!0?bG.singleOptional:bG.singleMandatory}}function $N(Q,Z){return aZ(Z)?(Q.cache={isRight:!0,value:Z},Z.then((Y)=>yT(Q,Y))):yT(Q,Z)}function yT(Q,Z){return Q.cache={isRight:!0,value:Z},Z}function hn(Q,Z,Y){let $=Q.getActivations(Z);return $===void 0?Y:aZ(Y)?gT(Q,Y,$[Symbol.iterator]()):function(J,X,G){let W=X,U=G.next();for(;U.done!==!0;){let K=U.value(J.context,W);if(aZ(K))return gT(J,K,G);W=K,U=G.next()}return W}(Q,Y,$[Symbol.iterator]())}async function gT(Q,Z,Y){let $=await Z,J=Y.next();for(;J.done!==!0;)$=await J.value(Q.context,$),J=Y.next();return $}function o9(Q,Z,Y){let $=Y;if(Z.onActivation!==void 0){let J=Z.onActivation;$=aZ($)?$.then((X)=>J(Q.context,X)):J(Q.context,$)}return hn(Q,Z.serviceIdentifier,$)}function K7(Q){return(Z,Y)=>{if(Y.cache.isRight)return Y.cache.value;return $N(Y,o9(Z,Y,Q(Z,Y)))}}function cn(Q){return Q}function U7(Q,Z){return(Y,$)=>{let J=Q($);switch(J.scope){case ZJ.Singleton:if(J.cache.isRight)return J.cache.value;return $N(J,o9(Y,J,Z(Y,$)));case ZJ.Request:{if(Y.requestScopeCache.has(J.id))return Y.requestScopeCache.get(J.id);let X=o9(Y,J,Z(Y,$));return Y.requestScopeCache.set(J.id,X),X}case ZJ.Transient:return o9(Y,J,Z(Y,$))}}}function hT(Q,Z,Y){let $=function(J,X,G){if(G===void 0)return;if(!(G in J))throw new xZ(fZ.resolution,`Expecting a "${G.toString()}" property when resolving "${X.implementationType.name}" class @postConstruct decorated method, none found.`);if(typeof J[G]!="function")throw new xZ(fZ.resolution,`Expecting a "${G.toString()}" method when resolving "${X.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let W;try{W=J[G]()}catch(U){throw new xZ(fZ.resolution,`Unexpected error found when calling "${G.toString()}" @postConstruct decorated method on class "${X.implementationType.name}"`,{cause:U})}if(aZ(W))return async function(U,K,O){try{await O}catch(I){throw new xZ(fZ.resolution,`Unexpected error found when calling "${K.toString()}" @postConstruct decorated method on class "${U.implementationType.name}"`,{cause:I})}}(X,G,W)}}(Q,Z,Y);return aZ($)?$.then(()=>Q):Q}function bT(Q){return(Z,Y,$)=>{let J=new $.binding.implementationType(...Z),X=Q(Y,J,$);return aZ(X)?X.then(()=>hT(J,$.binding,$.classMetadata.lifecycle.postConstructMethodName)):hT(J,$.binding,$.classMetadata.lifecycle.postConstructMethodName)}}function mn(Q){return Q.binding}function dn(Q){return Q.binding}function JN(Q){return a9(Q,Q.planResult.tree.root)}function q7(Q,Z){switch(Z.binding.type){case cZ.ConstantValue:return bn(Q,Z.binding);case cZ.DynamicValue:return un(Q,Z.binding);case cZ.Factory:return pn(Q,Z.binding);case cZ.Instance:return sn(Q,Z);case cZ.Provider:return ln(Q,Z.binding);case cZ.ResolvedValue:return an(Q,Z)}}function a9(Q,Z){if(Z.bindings!==void 0)return Array.isArray(Z.bindings)?function(Y,$){let J=[];for(let X of $)uG(X)?J.push(...uT(Y,X)):J.push(q7(Y,X));if(J.some(aZ))return Promise.all(J);return J}(Q,Z.bindings):function(Y,$){if(uG($)){let J=uT(Y,$);if(J.length===1)return J[0];throw new xZ(fZ.resolution,"Unexpected multiple resolved values on single injection")}return q7(Y,$)}(Q,Z.bindings)}function rn(Q){return Q.scope!==void 0}function pT(Q,Z){if(Q.lifecycle.preDestroyMethodName!==void 0&&typeof Z[Q.lifecycle.preDestroyMethodName]=="function")return Z[Q.lifecycle.preDestroyMethodName]()}function lT(Q,Z,Y){let $=Q.getDeactivations(Z);if($!==void 0)return aZ(Y)?mT(Y,$[Symbol.iterator]()):function(J,X){let G=X.next();for(;G.done!==!0;){let W=G.value(J);if(aZ(W))return mT(J,X);G=X.next()}}(Y,$[Symbol.iterator]())}async function mT(Q,Z){let Y=await Q,$=Z.next();for(;$.done!==!0;)await $.value(Y),$=Z.next()}function tn(Q,Z){let Y=function($,J){if(J.type===cZ.Instance){let X=$.getClassMetadata(J.implementationType),G=J.cache.value;return aZ(G)?G.then((W)=>pT(X,W)):pT(X,G)}}(Q,Z);return Y===void 0?dT(Q,Z):Y.then(()=>dT(Q,Z))}function dT(Q,Z){let Y=Z.cache;return aZ(Y.value)?Y.value.then(($)=>nT(Q,Z,$)):nT(Q,Z,Y.value)}function nT(Q,Z,Y){let $;if(Z.onDeactivation!==void 0)$=(0,Z.onDeactivation)(Y);return $===void 0?lT(Q,Z.serviceIdentifier,Y):$.then(()=>lT(Q,Z.serviceIdentifier,Y))}function r9(Q,Z){if(Z===void 0)return;let Y=function(J){let X=[];for(let G of J)rn(G)&&G.scope===ZJ.Singleton&&G.cache.isRight&&X.push(G);return X}(Z),$=[];for(let J of Y){let X=tn(Q,J);X!==void 0&&$.push(X)}return $.length>0?Promise.all($).then(()=>{}):void 0}function GN(Q,Z){let Y=Q.getBindingsFromModule(Z);return r9(Q,Y)}function O7(Q,Z){let Y=Q.getBindings(Z);return r9(Q,Y)}var G7="@inversifyjs/container/bindingId",ZJ,cZ,J6,WJ,G6,qV="@inversifyjs/core/classMetadataReflectKey",sT="@inversifyjs/core/pendingClassMetadataCountReflectKey",X7,xZ,fZ,UV,S1,kn,N8,_T="@inversifyjs/core/classIsInjectableFlagReflectKey",wn,K50,cG,F7,bG,bn,un,pn,ln,cT,uT,nn,on,sn,an;var H7=w(()=>{Y7();ST();J7();ZJ={Request:"Request",Singleton:"Singleton",Transient:"Transient"},cZ={ConstantValue:"ConstantValue",DynamicValue:"DynamicValue",Factory:"Factory",Instance:"Instance",Provider:"Provider",ResolvedValue:"ResolvedValue",ServiceRedirection:"ServiceRedirection"};(function(Q){Q.moduleId="moduleId",Q.serviceId="serviceId"})(J6||(J6={}));(function(Q){Q.id="id",Q.moduleId="moduleId",Q.serviceId="serviceId"})(WJ||(WJ={}));(function(Q){Q.moduleId="moduleId",Q.serviceId="serviceId"})(G6||(G6={}));X7=Symbol.for("@inversifyjs/core/InversifyCoreError");xZ=class xZ extends Error{[X7];kind;constructor(Q,Z,Y){super(Z,Y),this[X7]=!0,this.kind=Q}static is(Q){return typeof Q=="object"&&Q!==null&&Q[X7]===!0}static isErrorOfKind(Q,Z){return xZ.is(Q)&&Q.kind===Z}};(function(Q){Q[Q.injectionDecoratorConflict=0]="injectionDecoratorConflict",Q[Q.missingInjectionDecorator=1]="missingInjectionDecorator",Q[Q.planning=2]="planning",Q[Q.resolution=3]="resolution",Q[Q.unknown=4]="unknown"})(fZ||(fZ={})),function(Q){Q[Q.unknown=32]="unknown"}(UV||(UV={})),function(Q){Q[Q.multipleInjection=0]="multipleInjection",Q[Q.singleInjection=1]="singleInjection",Q[Q.unmanaged=2]="unmanaged"}(S1||(S1={}));kn=iT(function(Q,Z){return{kind:Q,name:void 0,optional:!1,tags:new Map,value:Z}},function(Q,Z,Y){return aT(Q),{...Q,kind:Z,value:Y}});(function(Q){Q[Q.method=0]="method",Q[Q.parameter=1]="parameter",Q[Q.property=2]="property"})(N8||(N8={}));wn=[Array,BigInt,Boolean,Function,Number,Object,String];K50=iT(vT,function(Q){if(aT(Q),function(Z){return Z.name!==void 0||Z.optional||Z.tags.size>0}(Q))throw new xZ(fZ.injectionDecoratorConflict,"Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections");return vT()});(function(Q){Q[Q.multipleInjection=0]="multipleInjection",Q[Q.singleInjection=1]="singleInjection"})(cG||(cG={}));F7=class F7{last;constructor(Q){this.last=Q}concat(Q){return new F7({elem:Q,previous:this.last})}[Symbol.iterator](){let Q=this.last;return{next:()=>{if(Q===void 0)return{done:!0,value:void 0};let Z=Q.elem;return Q=Q.previous,{done:!1,value:Z}}}}};(function(Q){Q[Q.singleMandatory=0]="singleMandatory",Q[Q.singleOptional=1]="singleOptional",Q[Q.multipleMandatory=2]="multipleMandatory",Q[Q.multipleOptional=3]="multipleOptional",Q[Q.length=4]="length"})(bG||(bG={}));bn=K7(function(Q,Z){return Z.value});un=((Q)=>U7(cn,Q))(function(Q,Z){return Z.value(Q.context)}),pn=K7(function(Q,Z){return Z.factory(Q.context)});ln=K7(function(Q,Z){return Z.provider(Q.context)});cT=function(Q){return(Z,Y,$)=>{let J=[];for(let[X,G]of $.propertyParams){let W=$.classMetadata.properties.get(X);if(W===void 0)throw new xZ(fZ.resolution,`Expecting metadata at property "${X.toString()}", none found`);W.kind!==S1.unmanaged&&G.bindings!==void 0&&(Y[X]=Q(Z,G),aZ(Y[X])&&J.push((async()=>{Y[X]=await Y[X]})()))}if(J.length>0)return Promise.all(J).then(()=>{})}}(a9),uT=function(Q){return function Z(Y,$){let J=[];for(let X of $.redirections)uG(X)?J.push(...Z(Y,X)):J.push(Q(Y,X));return J}}(q7),nn=function(Q,Z,Y){return($,J)=>{let X=Q($,J);return aZ(X)?Z(X,$,J):Y(X,$,J)}}(function(Q){return(Z,Y)=>{let $=[];for(let J of Y.constructorParams)J===void 0?$.push(void 0):$.push(Q(Z,J));return $.some(aZ)?Promise.all($):$}}(a9),function(Q){return async(Z,Y,$)=>{let J=await Z;return Q(J,Y,$)}}(bT(cT)),bT(cT)),on=function(Q){return(Z,Y)=>{let $=Q(Z,Y);return aZ($)?$.then((J)=>Y.binding.factory(...J)):Y.binding.factory(...$)}}(function(Q){return(Z,Y)=>{let $=[];for(let J of Y.params)$.push(Q(Z,J));return $.some(aZ)?Promise.all($):$}}(a9)),sn=((Q)=>U7(mn,Q))(nn),an=((Q)=>U7(dn,Q))(on)});class b0{#Q;#Z;constructor(Q){this.#Q=function(){let Z=C1(Object,D7)??0;return Z===Number.MAX_SAFE_INTEGER?$6(Object,D7,Number.MIN_SAFE_INTEGER):tJ(Object,D7,()=>Z,(Y)=>Y+1),Z}(),this.#Z=Q}get id(){return this.#Q}load(Q){return this.#Z(Q)}}function XN(Q){return typeof Q=="object"&&Q!==null&&Q[VN]===!0}class B8{static always=(Q)=>!0}function L7(Q){return{[VN]:!0,id:Q.id}}function z6(Q){return(Z)=>{for(let Y=Z.getAncestor();Y!==void 0;Y=Y.getAncestor())if(Q(Y))return!0;return!1}}function q6(Q){return(Z)=>Z.name===Q}function t9(Q){return(Z)=>Z.serviceIdentifier===Q}function F6(Q,Z){return(Y)=>Y.tags.has(Q)&&Y.tags.get(Q)===Z}function en(Q){return Q.name===void 0&&Q.tags.size===0}function e9(Q){let Z=z6(Q);return(Y)=>!Z(Y)}function Qz(Q){return(Z)=>{let Y=Z.getAncestor();return Y===void 0||!Q(Y)}}function Zz(Q){return(Z)=>{let Y=Z.getAncestor();return Y!==void 0&&Q(Y)}}class qN{#Q;constructor(Q){this.#Q=Q}getIdentifier(){return L7(this.#Q)}inRequestScope(){return this.#Q.scope=ZJ.Request,new S8(this.#Q)}inSingletonScope(){return this.#Q.scope=ZJ.Singleton,new S8(this.#Q)}inTransientScope(){return this.#Q.scope=ZJ.Transient,new S8(this.#Q)}}class R7{#Q;#Z;#J;#Y;constructor(Q,Z,Y,$){this.#Q=Q,this.#Z=Z,this.#J=Y,this.#Y=$}to(Q){let Z=V6(Q),Y={cache:{isRight:!1,value:void 0},id:w1(),implementationType:Q,isSatisfiedBy:B8.always,moduleId:this.#Z,onActivation:void 0,onDeactivation:void 0,scope:Z.scope??this.#J,serviceIdentifier:this.#Y,type:cZ.Instance};return this.#Q(Y),new Yz(Y)}toSelf(){if(typeof this.#Y!="function")throw Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#Y)}toConstantValue(Q){let Z={cache:{isRight:!1,value:void 0},id:w1(),isSatisfiedBy:B8.always,moduleId:this.#Z,onActivation:void 0,onDeactivation:void 0,scope:ZJ.Singleton,serviceIdentifier:this.#Y,type:cZ.ConstantValue,value:Q};return this.#Q(Z),new S8(Z)}toDynamicValue(Q){let Z={cache:{isRight:!1,value:void 0},id:w1(),isSatisfiedBy:B8.always,moduleId:this.#Z,onActivation:void 0,onDeactivation:void 0,scope:this.#J,serviceIdentifier:this.#Y,type:cZ.DynamicValue,value:Q};return this.#Q(Z),new Yz(Z)}toResolvedValue(Q,Z){let Y={cache:{isRight:!1,value:void 0},factory:Q,id:w1(),isSatisfiedBy:B8.always,metadata:this.#X(Z),moduleId:this.#Z,onActivation:void 0,onDeactivation:void 0,scope:this.#J,serviceIdentifier:this.#Y,type:cZ.ResolvedValue};return this.#Q(Y),new Yz(Y)}toFactory(Q){let Z={cache:{isRight:!1,value:void 0},factory:Q,id:w1(),isSatisfiedBy:B8.always,moduleId:this.#Z,onActivation:void 0,onDeactivation:void 0,scope:ZJ.Singleton,serviceIdentifier:this.#Y,type:cZ.Factory};return this.#Q(Z),new S8(Z)}toProvider(Q){let Z={cache:{isRight:!1,value:void 0},id:w1(),isSatisfiedBy:B8.always,moduleId:this.#Z,onActivation:void 0,onDeactivation:void 0,provider:Q,scope:ZJ.Singleton,serviceIdentifier:this.#Y,type:cZ.Provider};return this.#Q(Z),new S8(Z)}toService(Q){let Z={id:w1(),isSatisfiedBy:B8.always,moduleId:this.#Z,serviceIdentifier:this.#Y,targetServiceIdentifier:Q,type:cZ.ServiceRedirection};this.#Q(Z)}#X(Q){return{arguments:(Q??[]).map((Z)=>function(Y){return typeof Y=="object"&&!VV.is(Y)}(Z)?{kind:Z.isMultiple===!0?cG.multipleInjection:cG.singleInjection,name:Z.name,optional:Z.optional??!1,tags:new Map((Z.tags??[]).map((Y)=>[Y.key,Y.value])),value:Z.serviceIdentifier}:{kind:cG.singleInjection,name:void 0,optional:!1,tags:new Map,value:Z})}}}class E7{#Q;constructor(Q){this.#Q=Q}getIdentifier(){return L7(this.#Q)}onActivation(Q){return this.#Q.onActivation=Q,new $z(this.#Q)}onDeactivation(Q){return this.#Q.onDeactivation=Q,new $z(this.#Q)}}class $z{#Q;constructor(Q){this.#Q=Q}getIdentifier(){return L7(this.#Q)}when(Q){return this.#Q.isSatisfiedBy=Q,new E7(this.#Q)}whenAnyAncestor(Q){return this.when(z6(Q))}whenAnyAncestorIs(Q){return this.when(z6(t9(Q)))}whenAnyAncestorNamed(Q){return this.when(function(Z){return z6(q6(Z))}(Q))}whenAnyAncestorTagged(Q,Z){return this.when(function(Y,$){return z6(F6(Y,$))}(Q,Z))}whenDefault(){return this.when(en)}whenNamed(Q){return this.when(q6(Q))}whenNoParent(Q){return this.when(Qz(Q))}whenNoParentIs(Q){return this.when(Qz(t9(Q)))}whenNoParentNamed(Q){return this.when(function(Z){return Qz(q6(Z))}(Q))}whenNoParentTagged(Q,Z){return this.when(function(Y,$){return Qz(F6(Y,$))}(Q,Z))}whenParent(Q){return this.when(Zz(Q))}whenParentIs(Q){return this.when(Zz(t9(Q)))}whenParentNamed(Q){return this.when(function(Z){return Zz(q6(Z))}(Q))}whenParentTagged(Q,Z){return this.when(function(Y,$){return Zz(F6(Y,$))}(Q,Z))}whenTagged(Q,Z){return this.when(F6(Q,Z))}whenNoAncestor(Q){return this.when(e9(Q))}whenNoAncestorIs(Q){return this.when(e9(t9(Q)))}whenNoAncestorNamed(Q){return this.when(function(Z){return e9(q6(Z))}(Q))}whenNoAncestorTagged(Q,Z){return this.when(function(Y,$){return e9(F6(Y,$))}(Q,Z))}}class T${#Q;#Z;#J;#Y;#X;#V;#G;#$;#q;#F;#U;constructor(Q){this.#J=this.#A(),this.#X=(Z)=>this.#Q.get(Z),this.#$=new W7,this.#q=this.#O(),Q?.parent===void 0?(this.#Q=zV.build(void 0),this.#Z=WV.build(void 0),this.#Y=KV.build(void 0)):(this.#Q=zV.build(Q.parent.#Q),this.#Z=WV.build(Q.parent.#Z),this.#Y=KV.build(Q.parent.#Y),Q.parent.#$.subscribe(this.#$)),this.#V=this.#Z.get.bind(this.#Z),this.#F=this.#K.bind(this),this.#G={autobind:Q?.autobind??!1,defaultScope:Q?.defaultScope??Qo},this.#U=[]}bind(Q){return new R7((Z)=>{this.#K(Z)},void 0,this.#G.defaultScope,Q)}get(Q,Z){let Y=this.#z(!1,Q,Z),$=this.#W(Y);if(aZ($))throw new k8(C8.invalidOperation,`Unexpected asyncronous service when resolving service "${eY(Q)}"`);return $}getAll(Q,Z){let Y=this.#z(!0,Q,Z),$=this.#W(Y);if(aZ($))throw new k8(C8.invalidOperation,`Unexpected asyncronous service when resolving service "${eY(Q)}"`);return $}async getAllAsync(Q,Z){let Y=this.#z(!0,Q,Z);return this.#W(Y)}async getAsync(Q,Z){let Y=this.#z(!1,Q,Z);return this.#W(Y)}isBound(Q,Z){let Y=this.#Z.get(Q);return this.#H(Q,Y,Z)}isCurrentBound(Q,Z){let Y=this.#Z.getNonParentBindings(Q);return this.#H(Q,Y,Z)}async load(...Q){await Promise.all(this.#D(...Q))}loadSync(...Q){let Z=this.#D(...Q);for(let Y of Z)if(Y!==void 0)throw new k8(C8.invalidOperation,"Unexpected asyncronous module load. Consider using Container.load() instead.")}onActivation(Q,Z){this.#Q.add(Z,{serviceId:Q})}onDeactivation(Q,Z){this.#Y.add(Z,{serviceId:Q})}restore(){let Q=this.#U.pop();if(Q===void 0)throw new k8(C8.invalidOperation,"No snapshot available to restore");this.#Q=Q.activationService,this.#Z=Q.bindingService,this.#Y=Q.deactivationService,this.#B()}async rebind(Q){return await this.unbind(Q),this.bind(Q)}rebindSync(Q){return this.unbindSync(Q),this.bind(Q)}snapshot(){this.#U.push({activationService:this.#Q.clone(),bindingService:this.#Z.clone(),deactivationService:this.#Y.clone()})}async unbind(Q){await this.#R(Q)}async unbindAll(){let Q=[...this.#Z.getNonParentBoundServices()];await Promise.all(Q.map(async(Z)=>O7(this.#J,Z)));for(let Z of Q)this.#Q.removeAllByServiceId(Z),this.#Z.removeAllByServiceId(Z),this.#Y.removeAllByServiceId(Z);this.#$.clearCache()}unbindSync(Q){this.#R(Q)!==void 0&&this.#k(Q)}async unload(...Q){await Promise.all(this.#I(...Q)),this.#E(Q)}unloadSync(...Q){let Z=this.#I(...Q);for(let Y of Z)if(Y!==void 0)throw new k8(C8.invalidOperation,"Unexpected asyncronous module unload. Consider using Container.unload() instead.");this.#E(Q)}#j(Q){return{bind:(Z)=>new R7((Y)=>{this.#K(Y)},Q,this.#G.defaultScope,Z),isBound:this.isBound.bind(this),onActivation:(Z,Y)=>{this.#Q.add(Y,{moduleId:Q,serviceId:Z})},onDeactivation:(Z,Y)=>{this.#Y.add(Y,{moduleId:Q,serviceId:Z})},rebind:this.rebind.bind(this),rebindSync:this.rebindSync.bind(this),unbind:this.unbind.bind(this),unbindSync:this.unbindSync.bind(this)}}#A(){return{getBindings:(Q)=>this.#Z.get(Q),getBindingsFromModule:(Q)=>this.#Z.getByModuleId(Q),getClassMetadata:V6,getDeactivations:(Q)=>this.#Y.get(Q)}}#M(Q,Z,Y){return{isMultiple:Q,name:Y?.name,optional:Y?.optional,serviceIdentifier:Z,tag:Y?.tag}}#T(Q,Z,Y){let $={autobindOptions:Y?.autobind??this.#G.autobind?{scope:this.#G.defaultScope}:void 0,getBindings:this.#V,getClassMetadata:V6,rootConstraints:{isMultiple:Z,serviceIdentifier:Q},servicesBranch:[],setBinding:this.#F};return this.#N($,Y),$}#z(Q,Z,Y){let $=this.#M(Q,Z,Y),J=this.#$.get($);if(J!==void 0)return J;let X=ZN(this.#T(Z,Q,Y));return this.#$.set($,X),X}#O(){return{get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#W(Q){return JN({context:this.#q,getActivations:this.#X,planResult:Q,requestScopeCache:new Map})}#N(Q,Z){Z!==void 0&&(Z.name!==void 0&&(Q.rootConstraints.name=Z.name),Z.optional===!0&&(Q.rootConstraints.isOptional=!0),Z.tag!==void 0&&(Q.rootConstraints.tag={key:Z.tag.key,value:Z.tag.value}))}#H(Q,Z,Y){if(Z===void 0)return!1;let $={getAncestor:()=>{},name:Y?.name,serviceIdentifier:Q,tags:new Map};Y?.tag!==void 0&&$.tags.set(Y.tag.key,Y.tag.value);for(let J of Z)if(J.isSatisfiedBy($))return!0;return!1}#D(...Q){return Q.map((Z)=>Z.load(this.#j(Z.id)))}#I(...Q){return Q.map((Z)=>GN(this.#J,Z.id))}#B(){this.#$.clearCache(),this.#X=(Q)=>this.#Q.get(Q),this.#V=this.#Z.get.bind(this.#Z),this.#q=this.#O(),this.#F=this.#K.bind(this)}#K(Q){this.#Z.set(Q),this.#$.clearCache()}#k(Q){let Z;if(XN(Q)){let $=this.#Z.getById(Q.id),J=(Y=$,function(X){if(X===void 0)return;let G=X.next();return G.done!==!0?G.value:void 0}(Y?.[Symbol.iterator]()))?.serviceIdentifier;Z=J===void 0?"Unexpected asyncronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asyncronous deactivation when unbinding "${eY(J)}" binding. Consider using Container.unbind() instead.`}else Z=`Unexpected asyncronous deactivation when unbinding "${eY(Q)}" service. Consider using Container.unbind() instead.`;var Y;throw new k8(C8.invalidOperation,Z)}#R(Q){return XN(Q)?this.#C(Q):this.#S(Q)}#C(Q){let Z=this.#Z.getById(Q.id),Y=r9(this.#J,Z);if(Y!==void 0)return Y.then(()=>{this.#L(Q)});this.#L(Q)}#L(Q){this.#Z.removeById(Q.id),this.#$.clearCache()}#E(Q){for(let Z of Q)this.#Q.removeAllByModuleId(Z.id),this.#Z.removeAllByModuleId(Z.id),this.#Y.removeAllByModuleId(Z.id);this.#$.clearCache()}#S(Q){let Z=O7(this.#J,Q);if(Z!==void 0)return Z.then(()=>{this.#P(Q)});this.#P(Q)}#P(Q){this.#Q.removeAllByServiceId(Q),this.#Z.removeAllByServiceId(Q),this.#Y.removeAllByServiceId(Q),this.#$.clearCache()}}var O50,D7="@inversifyjs/container/bindingId",VN,S8,Yz,I7,k8,C8,Qo;var FN=w(()=>{Y7();J7();H7();O50=JZ(mJ(),1);VN=Symbol.for("@inversifyjs/container/bindingIdentifier");S8=class S8 extends $z{#Q;constructor(Q){super(Q),this.#Q=new E7(Q)}onActivation(Q){return this.#Q.onActivation(Q)}onDeactivation(Q){return this.#Q.onDeactivation(Q)}};Yz=class Yz extends S8{#Q;constructor(Q){super(Q),this.#Q=new qN(Q)}inRequestScope(){return this.#Q.inRequestScope()}inSingletonScope(){return this.#Q.inSingletonScope()}inTransientScope(){return this.#Q.inTransientScope()}};I7=Symbol.for("@inversifyjs/container/InversifyContainerError");k8=class k8 extends Error{[I7];kind;constructor(Q,Z,Y){super(Z,Y),this[I7]=!0,this.kind=Q}static is(Q){return typeof Q=="object"&&Q!==null&&Q[I7]===!0}static isErrorOfKind(Q,Z){return k8.is(Q)&&Q.kind===Z}};(function(Q){Q[Q.invalidOperation=0]="invalidOperation"})(C8||(C8={}));Qo=ZJ.Transient});var k50;var W0=w(()=>{FN();H7();k50=JZ(mJ(),1)});class W6{constructor(Q,Z,Y,$,J){this.deviceModel=Q,this.serviceUuid=Z,this.writeUuid=Y,this.writeCmdUuid=$,this.notifyUuid=J}}var P7=()=>{};class eJ{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(Q){this.id=Q.id,this.productName=Q.productName,this.usbProductId=Q.usbProductId,this.bootloaderUsbProductId=Q.bootloaderUsbProductId,this.usbOnly=Q.usbOnly,this.memorySize=Q.memorySize,this.getBlockSize=Q.getBlockSize,this.masks=Q.masks,this.bluetoothSpec=Q.bluetoothSpec}}var j7=()=>{};var A7,zN,Yo,$o=(Q,Z,Y)=>(Z in Q)?zN(Q,Z,{enumerable:!0,configurable:!0,writable:!0,value:Y}):Q[Z]=Y,Jo=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Yo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&zN(Z,Y,J),J},Go=(Q,Z,Y)=>$o(Q,typeof Z!="symbol"?Z+"":Z,Y),wJ=class{getAllDeviceModels(){return Object.values(wJ.deviceModelByIds)}getDeviceModel(Q){return wJ.deviceModelByIds[Q.id]}filterDeviceModels(Q){return this.getAllDeviceModels().filter((Z)=>Object.entries(Q).every(([Y,$])=>Z[Y]===$))}getBluetoothServicesInfos(){return Object.values(wJ.deviceModelByIds).reduce((Q,Z)=>{let{bluetoothSpec:Y}=Z;return Y?{...Q,...Y.reduce(($,J)=>({...$,[J.serviceUuid]:new W6(Z,J.serviceUuid,J.writeUuid,J.writeCmdUuid,J.notifyUuid)}),{})}:Q},{})}getBluetoothServices(){return Object.values(wJ.deviceModelByIds).map((Q)=>(Q.bluetoothSpec||[]).map((Z)=>Z.serviceUuid)).flat().filter((Q)=>!!Q)}};var M7=w(()=>{W0();R1();P7();j7();A7=JZ(kG(),1),zN=Object.defineProperty,Yo=Object.getOwnPropertyDescriptor;Go(wJ,"deviceModelByIds",{[JQ.NANO_S]:new eJ({id:JQ.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:327680,getBlockSize:(Q)=>A7.default.lt(A7.default.coerce(Q.firmwareVersion)??"","2.0.0")?4096:2048,masks:[823132160]}),[JQ.NANO_SP]:new eJ({id:JQ.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1569792,getBlockSize:()=>512,masks:[856686592]}),[JQ.NANO_X]:new eJ({id:JQ.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2097152,getBlockSize:()=>4096,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"}]}),[JQ.STAX]:new eJ({id:JQ.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1569792,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"}]}),[JQ.FLEX]:new eJ({id:JQ.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1569792,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"}]}),[JQ.APEX]:new eJ({id:JQ.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1569792,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"}]})}),wJ=Jo([e()],wJ)});class pG{statusCode;data;constructor({statusCode:Q,data:Z}){this.statusCode=Q,this.data=Z}}var Jz=()=>{};var T7=5,Q1=1,HV=2,_1=2,DV=2;var Gz=()=>{};var N7;var WN=w(()=>{R0();KZ();TZ();H8();CY();tY();T1();SY();K$();T8();B1();b2();N7=class N7 extends AQ{makeStateMachine(Q){let{getOsVersion:Z,getDeviceVersion:Y,getFirmwareVersion:$,genuineCheck:J,getDeviceSessionState:X,setDeviceSessionState:G}=this.extractDependencies(Q),W=this.input.unlockTimeout??qZ,U=new RY({input:{unlockTimeout:W}}).makeStateMachine(Q);return NQ({types:{input:{},context:{},output:{}},actors:{goToDashboard:U,getOsVersion:VQ(Z),getDeviceVersion:VQ(Y),getFirmwareVersion:VQ($),genuineCheck:cY(J)},guards:{hasError:(K)=>K.context._internalState.error!==null},actions:{assignErrorFromEvent:r({_internalState:(K)=>({...K.context._internalState,error:K.event.error})})}}).createMachine({id:"GenuineCheckDeviceAction",initial:"DeviceReady",context:(K)=>({input:{unlockTimeout:K.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,result:{isGenuine:!1},getOsVersionResponse:null,deviceVersion:null,firmwareVersion:null}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(K)=>({unlockTimeout:K.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(K)=>({...K.context.intermediateValue,requiredUserInteraction:K.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:()=>K.context._internalState,Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(K)=>{},onDone:{target:"GetOsVersionCheck",actions:r({_internalState:(K)=>{if(N0(K.event.output)){let O=X(),I=K.event.output.data.secureElementFlags.isSecureConnectionAllowed;return O.sessionStateType!==CQ.Connected&&G({...O,isSecureConnectionAllowed:I}),{...K.context._internalState,getOsVersionResponse:K.event.output.data}}return{...K.context._internalState,error:K.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetDeviceVersion"}]},GetDeviceVersion:{invoke:{id:"getDeviceVersion",src:"getDeviceVersion",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse}),onDone:{target:"GetDeviceVersionCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:(O)=>({...K.context._internalState,deviceVersion:O}),Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareVersion"}]},GetFirmwareVersion:{invoke:{id:"getFirmwareVersion",src:"getFirmwareVersion",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse,deviceVersion:K.context._internalState.deviceVersion}),onDone:{target:"GetFirmwareVersionCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:(O)=>({...K.context._internalState,firmwareVersion:O}),Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GenuineCheck"}]},GenuineCheck:{invoke:{id:"genuineCheck",src:"genuineCheck",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse,finalFirmware:K.context._internalState.firmwareVersion}),onSnapshot:{actions:r({intermediateValue:(K)=>{switch(K.event.snapshot.context?.type){case fQ.DeviceId:return{...K.context.intermediateValue,deviceId:K.event.snapshot.context.payload.deviceId};case fQ.PermissionRequested:return{...K.context.intermediateValue,requiredUserInteraction:k0.AllowSecureConnection};case fQ.PermissionGranted:return{...K.context.intermediateValue,requiredUserInteraction:k0.None};default:return{...K.context.intermediateValue}}},_internalState:(K)=>K.event.snapshot.context?.type===fQ.Error?{...K.context._internalState,error:K.event.snapshot.context.error.mapDAErrors()}:K.event.snapshot.context?.type===fQ.Result?{...K.context._internalState,result:{isGenuine:iM(K.event.snapshot.context.payload)}}:K.context._internalState})},onDone:{target:"GenuineCheckCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GenuineCheckCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(K)=>K.context._internalState.error?a(K.context._internalState.error):U0(K.context._internalState.result)})}extractDependencies(Q){return{getOsVersion:()=>Q.sendCommand(new IY),getDeviceVersion:({input:Z})=>{let{deviceInfo:Y}=Z;return Q.getManagerApiService().getDeviceVersion(Y)},getFirmwareVersion:({input:Z})=>{let{deviceInfo:Y,deviceVersion:$}=Z;return Q.getManagerApiService().getFirmwareVersion(Y,$)},genuineCheck:({input:Z})=>{let{deviceInfo:Y,finalFirmware:$}=Z,J=Q.getSecureChannelService().genuineCheck(Y,$);return new U$(Q,{connection:J}).run()},getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var lG;var Xz=w(()=>{R0();KZ();TZ();H8();CY();tY();T1();SY();K$();T8();B1();g2();lG=class lG extends AQ{makeStateMachine(Q){let{getOsVersion:Z,getDeviceVersion:Y,getFirmwareVersion:$,listInstalledApps:J,getDeviceSessionState:X,setDeviceSessionState:G}=this.extractDependencies(Q),W=this.input.unlockTimeout??qZ,U=new RY({input:{unlockTimeout:W}}).makeStateMachine(Q);return NQ({types:{input:{},context:{},output:{}},actors:{goToDashboard:U,getOsVersion:VQ(Z),getDeviceVersion:VQ(Y),getFirmwareVersion:VQ($),listInstalledApps:cY(J)},guards:{hasError:(K)=>K.context._internalState.error!==null},actions:{assignErrorFromEvent:r({_internalState:(K)=>({...K.context._internalState,error:K.event.error})})}}).createMachine({id:"ListInstalledAppsDeviceAction",initial:"DeviceReady",context:(K)=>({input:{unlockTimeout:K.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,getOsVersionResponse:null,deviceVersion:null,firmwareVersion:null,result:{installedApps:[]}}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(K)=>({unlockTimeout:K.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(K)=>({...K.context.intermediateValue,requiredUserInteraction:K.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:()=>K.context._internalState,Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(K)=>{},onDone:{target:"GetOsVersionCheck",actions:r({_internalState:(K)=>{if(N0(K.event.output)){let O=X(),I=K.event.output.data.secureElementFlags.isSecureConnectionAllowed;return O.sessionStateType!==CQ.Connected&&G({...O,isSecureConnectionAllowed:I}),{...K.context._internalState,getOsVersionResponse:K.event.output.data}}return{...K.context._internalState,error:K.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetDeviceVersion"}]},GetDeviceVersion:{invoke:{id:"getDeviceVersion",src:"getDeviceVersion",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse}),onDone:{target:"GetDeviceVersionCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:(O)=>({...K.context._internalState,deviceVersion:O}),Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareVersion"}]},GetFirmwareVersion:{invoke:{id:"getFirmwareVersion",src:"getFirmwareVersion",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse,deviceVersion:K.context._internalState.deviceVersion}),onDone:{target:"GetFirmwareVersionCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:(O)=>({...K.context._internalState,firmwareVersion:O}),Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"ListInstalledApps"}]},ListInstalledApps:{invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse,finalFirmware:K.context._internalState.firmwareVersion}),onSnapshot:{actions:r({intermediateValue:(K)=>{switch(K.event.snapshot.context?.type){case fQ.DeviceId:return{...K.context.intermediateValue,deviceId:K.event.snapshot.context.payload.deviceId};case fQ.PermissionRequested:return{...K.context.intermediateValue,requiredUserInteraction:k0.AllowSecureConnection};case fQ.PermissionGranted:return{...K.context.intermediateValue,requiredUserInteraction:k0.None};default:return{...K.context.intermediateValue}}},_internalState:(K)=>{if(K.event.snapshot.context?.type===fQ.Error)return{...K.context._internalState,error:K.event.snapshot.context.error.mapDAErrors()};if(K.event.snapshot.context?.type===fQ.Result){if(b9(K.event.snapshot.context.payload))return{...K.context._internalState,result:{installedApps:K.event.snapshot.context.payload}};throw Error(`Invalid result ${JSON.stringify(K.event.snapshot.context.payload)}`)}return{...K.context._internalState}}})},onDone:{target:"Success"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(K)=>K.context._internalState.error?a(K.context._internalState.error):U0(K.context._internalState.result)})}extractDependencies(Q){return{getOsVersion:()=>Q.sendCommand(new IY),getDeviceVersion:({input:Z})=>{let{deviceInfo:Y}=Z;return Q.getManagerApiService().getDeviceVersion(Y)},getFirmwareVersion:({input:Z})=>{let{deviceInfo:Y,deviceVersion:$}=Z;return Q.getManagerApiService().getFirmwareVersion(Y,$)},listInstalledApps:({input:Z})=>{let{deviceInfo:Y,finalFirmware:$}=Z,J=Q.getSecureChannelService().listInstalledApps(Y,$);return new U$(Q,{connection:J}).run()},getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var B7;var KN=w(()=>{R0();KZ();TZ();H8();CY();tY();rY();T1();SY();K$();Xz();T8();B1();B7=class B7 extends AQ{makeStateMachine(Q){let{getOsVersion:Z,getAppList:Y,installApp:$,getDeviceSessionState:J,setDeviceSessionState:X}=this.extractDependencies(Q),G=this.input.unlockTimeout??qZ,W=new lG({input:{unlockTimeout:G}}).makeStateMachine(Q),U=new RY({input:{unlockTimeout:G}}).makeStateMachine(Q);return NQ({types:{input:{},context:{},output:{}},actors:{listInstalledApps:W,goToDashboard:U,getOsVersion:VQ(Z),getAppList:VQ(Y),installApp:cY($)},guards:{hasError:(K)=>K.context._internalState.error!==null,appInstalled:(K)=>K.context._internalState.installedApps.some((O)=>O.name===K.context.input.appName),appNotFound:(K)=>K.context._internalState.appList.findIndex(({versionName:O})=>O===K.context.input.appName)===-1,depAppNotInstalled:(K)=>{let O=K.context._internalState.appList.find(({versionName:I})=>I===K.context.input.appName);return O?.parentName?K.context._internalState.installedApps.findIndex(({name:I})=>I===O.parentName)===-1:!1}},actions:{assignErrorFromEvent:r({_internalState:(K)=>({...K.context._internalState,error:K.event.error})}),assignAppNotFound:r({_internalState:(K)=>({...K.context._internalState,error:new xQ("App to install not found in manager API")})}),assignDepAppNotInstalled:r({_internalState:(K)=>({...K.context._internalState,error:new xQ("Dep app is not installed on the device")})}),cleanupDeviceState:()=>{let K=J();K.sessionStateType!==CQ.Connected&&X({...K,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"InstallAppDeviceAction",initial:"DeviceReady",context:(K)=>({input:{unlockTimeout:K.input.unlockTimeout,appName:K.input.appName},intermediateValue:{requiredUserInteraction:k0.None,progress:0},_internalState:{error:null,installedApps:[],getOsVersionResponse:null,appList:[]}}),states:{DeviceReady:{always:{target:"ListInstalledApps"}},ListInstalledApps:{value:"ListInstalledApps",invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(K)=>({unlockTimeout:K.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(K)=>({...K.context.intermediateValue,requiredUserInteraction:K.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"ListInstalledAppsCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:({installedApps:O})=>({...K.context._internalState,installedApps:O}),Left:(O)=>({...K.context._internalState,error:O})})})}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"appInstalled"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(K)=>({unlockTimeout:K.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(K)=>({...K.context.intermediateValue,requiredUserInteraction:K.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:()=>K.context._internalState,Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(K)=>{},onDone:{target:"GetOsVersionCheck",actions:r({_internalState:(K)=>{if(N0(K.event.output)){let O=J(),I=K.event.output.data.secureElementFlags.isSecureConnectionAllowed;return O.sessionStateType!==CQ.Connected&&X({...O,isSecureConnectionAllowed:I}),{...K.context._internalState,getOsVersionResponse:K.event.output.data}}return{...K.context._internalState,error:K.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetAppList"}]},GetAppList:{invoke:{id:"getAppList",src:"getAppList",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse}),onDone:{target:"GetAppListCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:(O)=>({...K.context._internalState,appList:O}),Left:(O)=>({...K.context._internalState,error:O})})})}}},GetAppListCheck:{always:[{target:"Error",guard:"hasError"},{target:"Error",guard:"appNotFound",actions:"assignAppNotFound"},{target:"Error",guard:"depAppNotInstalled",actions:"assignDepAppNotInstalled"},{target:"InstallApp"}]},InstallApp:{invoke:{id:"installApp",src:"installApp",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse,app:K.context._internalState.appList.find(({versionName:O})=>O===K.context.input.appName)}),onSnapshot:{actions:r({intermediateValue:(K)=>K.event.snapshot.context?.type===fQ.DeviceId?{...K.context.intermediateValue,deviceId:K.event.snapshot.context.payload.deviceId}:K.event.snapshot.context?.type===fQ.Progress?{...K.context.intermediateValue,progress:K.event.snapshot.context.payload.progress}:{...K.context.intermediateValue},_internalState:(K)=>K.event.snapshot.context?.type===fQ.Error?{...K.context._internalState,error:K.event.snapshot.context.error.mapInstallDAErrors()}:K.context._internalState})},onDone:{target:"ListInstalledApps",actions:"cleanupDeviceState"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final",description:"App installed successfully"},Error:{type:"final"}},output:({context:K})=>K._internalState.error?a(K._internalState.error):U0(void 0)})}extractDependencies(Q){return{getOsVersion:()=>Q.sendCommand(new IY),getAppList:({input:Z})=>{let{deviceInfo:Y}=Z;return Q.getManagerApiService().getAppList(Y)},installApp:({input:Z})=>{let{deviceInfo:Y,app:$}=Z,J=Q.getSecureChannelService().installApp(Y,$);return new U$(Q,{connection:J}).run()},getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var k7;var UN=w(()=>{R0();KZ();TZ();H8();CY();tY();rY();T1();SY();K$();Xz();T8();B1();k7=class k7 extends AQ{makeStateMachine(Q){let{getOsVersion:Z,getAppsByHash:Y,uninstallApp:$,getDeviceSessionState:J,setDeviceSessionState:X}=this.extractDependencies(Q),G=this.input.unlockTimeout??qZ,W=new RY({input:{unlockTimeout:G}}).makeStateMachine(Q),U=new lG({input:{unlockTimeout:G}}).makeStateMachine(Q);return NQ({types:{input:{},context:{},output:{}},actors:{listInstalledApps:U,goToDashboard:W,getOsVersion:VQ(Z),getAppsByHash:VQ(Y),uninstallApp:cY($)},guards:{hasError:(K)=>K.context._internalState.error!==null,appNotInstalled:(K)=>!K.context._internalState.installedApps.some((O)=>O.name===K.context.input.appName),appNotFound:(K)=>K.context._internalState.appList.findIndex((O)=>O?.versionName===K.context.input.appName)===-1,isDepAppOfOther:(K)=>K.context._internalState.appList.some((O)=>O?.parentName===K.context.input.appName)},actions:{assignErrorFromEvent:r({_internalState:(K)=>({...K.context._internalState,error:K.event.error})}),assignAppNotFound:r({_internalState:(K)=>({...K.context._internalState,error:new xQ("App to uninstall not found in manager API")})}),assignIsDepAppOfOther:r({_internalState:(K)=>({...K.context._internalState,error:new xQ("App to uninstall is a dependency of another installed app")})}),cleanupDeviceState:()=>{let K=J();K.sessionStateType!==CQ.Connected&&X({...K,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"UninstallAppDeviceAction",initial:"DeviceReady",context:(K)=>({input:{unlockTimeout:K.input.unlockTimeout,appName:K.input.appName},intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,installedApps:[],appList:[],getOsVersionResponse:null}}),states:{DeviceReady:{always:{target:"ListInstalledApps"}},ListInstalledApps:{invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(K)=>({unlockTimeout:K.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(K)=>({...K.context.intermediateValue,requiredUserInteraction:K.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"ListInstalledAppsCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:({installedApps:O})=>({...K.context._internalState,installedApps:O,hasCheckedInstalledApps:!0}),Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"appNotInstalled"},{target:"GetAppsByHash"}]},GetAppsByHash:{invoke:{id:"getAppsByHash",src:"getAppsByHash",input:(K)=>K.context._internalState.installedApps,onDone:{target:"GetAppsByHashCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:(O)=>({...K.context._internalState,appList:O}),Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetAppsByHashCheck:{always:[{target:"Error",guard:"hasError"},{target:"Error",guard:"appNotFound",actions:"assignAppNotFound"},{target:"Error",guard:"isDepAppOfOther",actions:"assignIsDepAppOfOther"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(K)=>({unlockTimeout:K.context.input.unlockTimeout}),onSnapshot:{actions:r({intermediateValue:(K)=>({...K.context.intermediateValue,requiredUserInteraction:K.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:(K)=>K.event.output.caseOf({Right:()=>K.context._internalState,Left:(O)=>({...K.context._internalState,error:O})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(K)=>{},onDone:{target:"GetOsVersionCheck",actions:r({_internalState:(K)=>{if(N0(K.event.output)){let O=J(),I=K.event.output.data.secureElementFlags.isSecureConnectionAllowed;return O.sessionStateType!==CQ.Connected&&X({...O,isSecureConnectionAllowed:I}),{...K.context._internalState,getOsVersionResponse:K.event.output.data}}return{...K.context._internalState,error:K.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"UninstallApp"}]},UninstallApp:{invoke:{id:"uninstallApp",src:"uninstallApp",input:(K)=>({deviceInfo:K.context._internalState.getOsVersionResponse,app:K.context._internalState.appList.find((O)=>O?.versionName===K.context.input.appName)}),onSnapshot:{actions:r({intermediateValue:(K)=>{switch(K.event.snapshot.context?.type){case fQ.DeviceId:return{...K.context.intermediateValue,deviceId:K.event.snapshot.context.payload.deviceId};case fQ.PermissionRequested:return{...K.context.intermediateValue,requiredUserInteraction:k0.AllowSecureConnection};case fQ.PermissionGranted:return{...K.context.intermediateValue,requiredUserInteraction:k0.None};default:return{...K.context.intermediateValue}}},_internalState:(K)=>K.event.snapshot.context?.type===fQ.Error?{...K.context._internalState,error:K.event.snapshot.context.error.mapDAErrors()}:K.context._internalState})},onDone:{target:"ListInstalledApps",actions:"cleanupDeviceState"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final",description:"App uninstalled successfully"},Error:{type:"final"}},output:({context:K})=>K._internalState.error?a(K._internalState.error):U0(void 0)})}extractDependencies(Q){return{getOsVersion:()=>Q.sendCommand(new IY),getAppsByHash:({input:Z})=>{let Y=Z.map(($)=>$.hash);return Q.getManagerApiService().getAppsByHash(Y)},uninstallApp:({input:Z})=>{let{deviceInfo:Y,app:$}=Z,J=Q.getSecureChannelService().uninstallApp(Y,$);return new U$(Q,{connection:J}).run()},getDeviceSessionState:()=>Q.getDeviceSessionState(),setDeviceSessionState:(Z)=>Q.setDeviceSessionState(Z)}}}});var Xo,C7;var ON=w(()=>{Xo=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),C7={randomUUID:Xo}});function w7(){if(!S7){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");S7=crypto.getRandomValues.bind(crypto)}return S7(Vo)}var S7,Vo;var HN=w(()=>{Vo=new Uint8Array(16)});function DN(Q,Z=0){return(uY[Q[Z+0]]+uY[Q[Z+1]]+uY[Q[Z+2]]+uY[Q[Z+3]]+"-"+uY[Q[Z+4]]+uY[Q[Z+5]]+"-"+uY[Q[Z+6]]+uY[Q[Z+7]]+"-"+uY[Q[Z+8]]+uY[Q[Z+9]]+"-"+uY[Q[Z+10]]+uY[Q[Z+11]]+uY[Q[Z+12]]+uY[Q[Z+13]]+uY[Q[Z+14]]+uY[Q[Z+15]]).toLowerCase()}var uY;var IN=w(()=>{uY=[];for(let Q=0;Q<256;++Q)uY.push((Q+256).toString(16).slice(1))});function qo(Q,Z,Y){if(C7.randomUUID&&!Z&&!Q)return C7.randomUUID();Q=Q||{};let $=Q.random||(Q.rng||w7)();if($[6]=$[6]&15|64,$[8]=$[8]&63|128,Z){Y=Y||0;for(let J=0;J<16;++J)Z[Y+J]=$[J];return Z}return DN($)}var _J;var RN=w(()=>{ON();HN();IN();_J=qo});var IV=w(()=>{RN()});var N$;var K6=w(()=>{N$={getLastBytesFrom(Q,Z){return Q.slice(-Z)},getFirstBytesFrom(Q,Z){return Q.slice(0,Z)},bytesToNumber(Q){return Q.reduce((Z,Y,$)=>Z+Y*Math.pow(256,Q.length-1-$),0)},numberToByteArray(Q,Z){return new Uint8Array(Z).map((Y,$)=>Q>>8*(Z-1-$)&255)}}});var _7=2,Vz=800;var v7=()=>{};class qz{_tag="FramerOverflowError";originalError;constructor(){this.originalError=Error("Frame header length is greater than frame size")}}class x7{_tag="FramerApduError";originalError;constructor(){this.originalError=Error("Frame offset is greater than apdu length")}}class Fz{_tag="ReceiverApduError";originalError;constructor(Q){this.originalError=Error(Q??"Unable to parse apdu")}}class zz{_tag="DeviceSessionNotFound";originalError;constructor(Q){this.originalError=Q??Error("Device session not found")}}var Wz=()=>{};class U6{_header;_data;constructor({header:Q,data:Z}){this._header=Q,this._data=Z}toString(){return JSON.stringify({header:this._header.toString(),data:DQ(this._data)},null,2)}getRawData(){let Q=this._header.getRawData(),Z=new Uint8Array(Q.length+this._data.length);return Z.set(Q,0),Z.set(this._data,Q.length),Z}getHeader(){return this._header}getData(){return this._data}}var f7=w(()=>{O6()});class H6{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:Q,dataSize:Z,index:Y,headTag:$,length:J,channel:X}){this._uuid=Q,this._dataLength=Z,this._index=Y,this._headTag=$,this._length=J,this._channel=X}getDataLength(){return this._dataLength.map((Q)=>N$.bytesToNumber(Q))}setDataSize(Q){return this._dataLength=Q,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:(Q)=>[...Q],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:(Q)=>[...Q],Nothing:()=>[]})])}}var y7=w(()=>{K6()});var bQ;var uZ=w(()=>{bQ={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")}});var jo,Ao,Mo=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ao(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&jo(Z,Y,J),J},To=(Q,Z)=>(Y,$)=>Z(Y,$,Q),RV=class{_channel;_logger;_pendingFrames;constructor({channel:Q=q0.zero()},Z){this._channel=Q,this._logger=Z("ApduReceiverService"),this._pendingFrames=[]}handleFrame(Q){return this.getFrameFromBytes(Q).map((Z)=>{if(this._pendingFrames.push(Z),!this._pendingFrames[0])return YQ;let Y=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(Y)})}getCompleteFrame(Q){return Q.chain((Z)=>{if(!this.isComplete(Z))return this._logger.debug("frame is not complete, waiting for more"),YQ;let Y=N$.getFirstBytesFrom(this.concatFrames(this._pendingFrames),Z),$=N$.getFirstBytesFrom(Y,Y.length-_7),J=N$.getLastBytesFrom(Y,_7);return this._pendingFrames=[],HQ(new pG({data:$,statusCode:J}))})}getFrameFromBytes(Q){let Z=this._channel.caseOf({Just:()=>HV,Nothing:()=>0}),Y=Q.slice(Z,Z+Q1),$=Q.slice(Z+Q1,Z+Q1+_1),J=$.reduce((I,L)=>I+L,0)===0;if(!J&&this._pendingFrames.length===0)return a(new Fz);let X=Z+Q1+_1,G=J?DV:0;if(Q.length<Z+Q1+_1+G)return a(new Fz("Unable to parse header from apdu"));let W=J?HQ(Q.slice(X,X+G)):YQ,U=X+G,K=Q.slice(U),O=new U6({header:new H6({uuid:_J(),channel:this._channel,dataSize:W,headTag:Y,index:$,length:Z+Q1+_1+G}),data:K});return U0(O)}isComplete(Q){return this._pendingFrames.reduce((Z,Y)=>Z+Y.getData().length,0)>=Q}concatFrames(Q){return Q.reduce((Z,Y)=>Uint8Array.from([...Z,...Y.getData()]),new Uint8Array(0))}};var g7=w(()=>{W0();R0();IV();Jz();Gz();K6();v7();Wz();f7();y7();uZ();jo=Object.defineProperty,Ao=Object.getOwnPropertyDescriptor;RV=Mo([e(),To(1,g(bQ.LoggerPublisherServiceFactory))],RV)});var LN=(Q={},Z)=>new RV({channel:q0.of(new Uint8Array([18,52])),...Q},Z);var EN=w(()=>{R0();g7()});var No,Bo,ko=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Bo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&No(Z,Y,J),J},Co=(Q,Z)=>(Y,$)=>Z(Y,$,Q),LV=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:Q,channel:Z=q0.zero(),padding:Y=!1},$){this._frameSize=Q,this._channel=Z,this._padding=Y,this._logger=$("DefaultApduSenderService")}getFrames(Q){let Z=[],Y=0,$=this.getFrameAtIndex(Q,Y);for(;$.isRight();)Z.push($.extract()),Y+=1,$=this.getFrameAtIndex(Q,Y).mapLeft((J)=>(J instanceof qz||this._logger.error("Error while parsing frame",{data:{error:J}}),J));return Z}getFrameAtIndex(Q,Z){let Y=this.getFrameHeaderFrom(Z,Q.length),$=Z===0?0:Z*this._frameSize-this.getHeaderSizeSumFrom(Z);if($>=Q.length)return a(new qz);if(Y.getLength()>this._frameSize)return a(new x7);let J=this._frameSize-Y.getLength(),X=Q.slice($,$+this._frameSize-Y.getLength()),G=this._padding?new Uint8Array(J).fill(0):new Uint8Array(X.length<J?X.length:J);G.set(X,0);let W=new U6({header:Y,data:G});return U0(W)}getFrameHeaderFrom(Q,Z){let Y=new H6({uuid:_J(),channel:this._channel.map(($)=>N$.getLastBytesFrom($,HV)),headTag:new Uint8Array([T7]),index:N$.numberToByteArray(Q,_1),length:this.getFrameHeaderSizeFromIndex(Q),dataSize:q0.zero()});return Q===0&&Y.setDataSize(q0.of(N$.numberToByteArray(Z,DV))),Y}getHeaderSizeSumFrom(Q){let Z=this.getFrameHeaderSizeFromIndex(0),Y=1;for(;Y<Q;)Z+=this.getFrameHeaderSizeFromIndex(Y),Y+=1;return Z}getFrameHeaderSizeFromIndex(Q){return this._channel.caseOf({Just:()=>HV,Nothing:()=>0})+_1+Q1+(Q===0?DV:0)}};var h7=w(()=>{W0();R0();IV();Gz();K6();Wz();f7();y7();uZ();No=Object.defineProperty,Bo=Object.getOwnPropertyDescriptor;LV=ko([e(),Co(1,g(bQ.LoggerPublisherServiceFactory))],LV)});var PN=(Q={},Z)=>new LV({frameSize:64,channel:q0.of(new Uint8Array([18,52])),padding:!0,...Q},Z);var jN=w(()=>{R0();h7()});var D6;var b7=w(()=>{D6={SendCommandUseCase:Symbol.for("SendCommandUseCase")}});var B$;var I6=w(()=>{B$={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService"),GetDmkVersionUseCase:Symbol.for("GetDmkVersionUseCase")}});var cQ;var pY=w(()=>{cQ={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService"),GetDeviceSessionStateUseCase:Symbol.for("GetDeviceSessionStateUseCase"),DisableDeviceSessionRefresherUseCase:Symbol.for("DisableDeviceSessionRefresherUseCase"),CloseSessionsUseCase:Symbol.for("CloseSessionsUseCase"),UnsafeBypassIntentQueueUseCase:Symbol.for("UnsafeBypassIntentQueueUseCase")}});var XZ;var Kz=w(()=>{XZ={StartDiscoveringUseCase:Symbol.for("StartDiscoveringUseCase"),StopDiscoveringUseCase:Symbol.for("StopDiscoveringUseCase"),ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase"),GetConnectedDeviceUseCase:Symbol.for("GetConnectedDeviceUseCase"),ListenToAvailableDevicesUseCase:Symbol.for("ListenToAvailableDevicesUseCase"),ListenToConnectedDeviceUseCase:Symbol.for("ListenToConnectedDeviceUseCase"),ListConnectedDevicesUseCase:Symbol.for("ListConnectedDevicesUseCase"),ReconnectUseCase:Symbol.for("ReconnectUseCase")}});var LY;var mG=w(()=>{LY={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig"),SetProviderUseCase:Symbol.for("SetProviderUseCase")}});var R6;var c7=w(()=>{R6={SendApduUseCase:Symbol.for("SendApduUseCase")}});var rZ;var Z1=w(()=>{rZ={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")}});var So,wo,_o=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?wo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&So(Z,Y,J),J},AN=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Uz=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("SendCommandUseCase")}async execute({sessionId:Q,command:Z,abortTimeout:Y}){return this._sessionService.getDeviceSessionById(Q).caseOf({Right:async($)=>await $.sendCommand(Z,Y),Left:($)=>{throw this._logger.error("Error getting session",{data:{error:$}}),$}})}};var MN=w(()=>{W0();pY();uZ();So=Object.defineProperty,wo=Object.getOwnPropertyDescriptor;Uz=_o([e(),AN(0,g(cQ.DeviceSessionService)),AN(1,g(bQ.LoggerPublisherServiceFactory))],Uz)});var vo,xo,fo=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?xo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&vo(Z,Y,J),J},CZ=class{execute=vi.fn(()=>"stub")};var dG=w(()=>{W0();vo=Object.defineProperty,xo=Object.getOwnPropertyDescriptor;CZ=fo([e()],CZ)});var TN=({stub:Q=!1}={})=>new b0(({bind:Z,rebindSync:Y})=>{Z(D6.SendCommandUseCase).to(Uz),Q&&Y(D6.SendCommandUseCase).to(CZ)});var NN=w(()=>{W0();MN();dG();b7()});var yo,go,ho=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?go(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&yo(Z,Y,J),J},BN=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Oz=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("ExecuteDeviceActionUseCase")}execute({sessionId:Q,deviceAction:Z}){return this._sessionService.getDeviceSessionById(Q).caseOf({Right:(Y)=>Y.executeDeviceAction(Z),Left:(Y)=>{throw this._logger.error("Error getting session",{data:{error:Y}}),Y}})}};var kN=w(()=>{W0();pY();uZ();yo=Object.defineProperty,go=Object.getOwnPropertyDescriptor;Oz=ho([e(),BN(0,g(cQ.DeviceSessionService)),BN(1,g(bQ.LoggerPublisherServiceFactory))],Oz)});var L6;var u7=w(()=>{L6={ExecuteDeviceActionUseCase:Symbol.for("ExecuteDeviceActionUseCase")}});var CN=({stub:Q=!1}={})=>new b0(({bind:Z,rebindSync:Y})=>{Z(L6.ExecuteDeviceActionUseCase).to(Oz),Q&&Y(L6.ExecuteDeviceActionUseCase).to(CZ)});var SN=w(()=>{W0();kN();dG();u7()});function wN(Q){return typeof Q=="object"&&Q!==null&&"version"in Q&&"name"in Q&&typeof Q.version=="string"&&typeof Q.name=="string"}var _N=()=>{};class Hz{constructor(Q){this.err=Q,this.originalError=Q}_tag="ApiCallError";originalError}class p7{constructor(Q){this.err=Q,this.originalError=Q}_tag="ParseResponseError";originalError}class E6{constructor(Q){this.err=Q,this.originalError=Q}_tag="JSONParseError";originalError}class l7{constructor(Q){this.err=Q,this.originalError=Q}_tag="ReadFileError";originalError}var m7=()=>{};var d7;var vN=w(()=>{d7={dependencies:{"@noble/hashes":"^1.8.0","@sentry/minimal":"catalog:",inversify:"catalog:","isomorphic-ws":"catalog:","purify-ts":"catalog:","reflect-metadata":"catalog:",semver:"catalog:",uuid:"catalog:",ws:"catalog:",xstate:"catalog:"},devDependencies:{"@ledgerhq/eslint-config-dsdk":"workspace:^","@ledgerhq/ldmk-tool":"workspace:^","@ledgerhq/prettier-config-dsdk":"workspace:^","@ledgerhq/tsconfig-dsdk":"workspace:^","@ledgerhq/vitest-config-dmk":"workspace:^","@statelyai/inspect":"catalog:","@types/semver":"catalog:","@types/uuid":"catalog:","@types/ws":"catalog:",rxjs:"catalog:","ts-node":"catalog:"},exports:{".":{import:"./lib/esm/index.js",require:"./lib/cjs/index.js",types:"./lib/types/index.d.ts"}},files:["./lib","package.json"],license:"Apache-2.0",name:"@ledgerhq/device-management-kit",peerDependencies:{rxjs:"catalog:"},private:!1,repository:{type:"git",url:"https://github.com/LedgerHQ/device-sdk-ts.git"},scripts:{build:"pnpm ldmk-tool build --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",dev:'concurrently "pnpm watch:builds" "pnpm watch:types"',lint:"eslint","lint:fix":"pnpm lint --fix","module:create":"pnpm hygen core-module with-prompt",postpack:"find . -name '*.tgz' -exec cp {} ../../dist/ \\; ",prebuild:"rimraf lib",prettier:"prettier . --check","prettier:fix":"prettier . --write",test:"vitest run","test:coverage":"vitest run --coverage","test:watch":"vitest",typecheck:"tsc --noEmit","watch:builds":"pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json","watch:types":'concurrently "tsc --watch -p tsconfig.prod.json" "tsc-alias --watch -p tsconfig.prod.json"'},version:"1.9.1"}});var co,uo,po=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?uo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&co(Z,Y,J),J},lo,mo=()=>JSON.stringify(lo),Dz=class{getConfig(){return GZ.encase(()=>mo()).mapLeft((Q)=>new l7(Q)).chain((Q)=>GZ.encase(()=>{let Z=JSON.parse(Q);if(wN(Z))return Z;throw Error("Invalid config file")}).mapLeft((Z)=>new E6(Z)))}};var xN=w(()=>{W0();R0();_N();m7();vN();co=Object.defineProperty,uo=Object.getOwnPropertyDescriptor,lo={name:d7.name,version:d7.version};Dz=po([e()],Dz)});var no,oo,so=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?oo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&no(Z,Y,J),J},Iz=class{getConfig(){return GZ.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};var fN=w(()=>{W0();R0();no=Object.defineProperty,oo=Object.getOwnPropertyDescriptor;Iz=so([e()],Iz)});var io,ao,ro=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?ao(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&io(Z,Y,J),J},Rz=class{async getConfig(){let Q=await this._callApi();if(Q.isLeft())return a(new Hz(Q.extract()));if(!Q.extract().ok)return a(new Hz(Error("response not ok")));let Z=await Q.extract().json();return Z.isLeft()?a(new E6):Z.chain((Y)=>this._parseResponse(Y)).map((Y)=>Y)}_parseResponse(Q){let{name:Z,version:Y}=Q;return!Z||!Y?a(new p7):GZ.of({name:Z,version:Y})}_callApi(){return new Promise((Q)=>{Q(GZ.of({ok:!0,json:async()=>new Promise((Z)=>{Z(GZ.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};var yN=w(()=>{W0();R0();m7();io=Object.defineProperty,ao=Object.getOwnPropertyDescriptor;Rz=ro([e()],Rz)});var to,eo,Qs=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?eo(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&to(Z,Y,J),J},Lz=class{async getConfig(){return new Promise((Q)=>Q(GZ.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};var gN=w(()=>{W0();R0();to=Object.defineProperty,eo=Object.getOwnPropertyDescriptor;Lz=Qs([e()],Lz)});var Zs,Ys,$s=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ys(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Zs(Z,Y,J),J},n7=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Ez=class{_local;_remote;_logger;constructor(Q,Z,Y){this._local=Q,this._remote=Z,this._logger=Y("config")}async getDmkConfig(){let Q=this._local.getConfig().ifLeft((Z)=>{this._logger.error("Local config not available",{data:{error:Z}})});if(Q.isRight()){let Z=Q.extract();return this._logger.info("Local config available",{data:{config:Z}}),Z}return this._remote.getConfig().then((Z)=>Z.mapLeft((Y)=>(this._logger.error("Local config available",{data:{error:Y}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};var hN=w(()=>{W0();I6();uZ();Zs=Object.defineProperty,Ys=Object.getOwnPropertyDescriptor;Ez=$s([e(),n7(0,g(B$.LocalConfigDataSource)),n7(1,g(B$.RemoteConfigDataSource)),n7(2,g(bQ.LoggerPublisherServiceFactory))],Ez)});var Js,Gs,Xs=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Gs(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Js(Z,Y,J),J},Vs=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Pz=class{_configService;constructor(Q){this._configService=Q}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};var bN=w(()=>{W0();I6();Js=Object.defineProperty,Gs=Object.getOwnPropertyDescriptor;Pz=Xs([e(),Vs(0,g(B$.ConfigService))],Pz)});var cN=({stub:Q})=>new b0(({bind:Z,rebindSync:Y})=>{Z(B$.LocalConfigDataSource).to(Dz),Z(B$.RemoteConfigDataSource).to(Rz),Z(B$.GetDmkVersionUseCase).to(Pz),Z(B$.ConfigService).to(Ez),Q&&(Y(B$.LocalConfigDataSource).to(Iz),Y(B$.RemoteConfigDataSource).to(Lz))});var uN=w(()=>{W0();xN();fN();yN();gN();hN();bN();I6()});var jz;var o7=w(()=>{jz={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")}});var pN=({stub:Q})=>new b0(({bind:Z})=>{Z(jz.DeviceModelDataSource).to(wJ)});var lN=w(()=>{W0();M7();o7()});var qs,Fs,zs=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Fs(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&qs(Z,Y,J),J},mN=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Az=class{constructor(Q,Z){this._sessionService=Q,this._logger=Z("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:Q,blockerId:Z}){return this._sessionService.getDeviceSessionById(Q).caseOf({Left:(Y)=>{throw this._logger.error("Error getting device session",{data:{error:Y}}),Y},Right:(Y)=>Y.disableRefresher(Z)})}};var dN=w(()=>{W0();pY();uZ();qs=Object.defineProperty,Fs=Object.getOwnPropertyDescriptor;Az=zs([e(),mN(0,g(cQ.DeviceSessionService)),mN(1,g(bQ.LoggerPublisherServiceFactory))],Az)});var nN,Ws,Ks,Us=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ks(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ws(Z,Y,J),J},Os=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Mz=class{_sessions;_sessionsSubject;_logger;constructor(Q){this._sessions=[],this._sessionsSubject=new nN.ReplaySubject,this._logger=Q("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(Q){return this._sessions.find((Z)=>Z.id===Q.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:Q}}),this):(this._sessions.push(Q),this._sessionsSubject.next(Q),this._logger.info("DeviceSession added",{data:{sessionId:Q.id}}),this)}removeDeviceSession(Q){let Z=this._sessions.find((Y)=>Y.id===Q);return Z?(Z.close(),this._sessions=this._sessions.filter((Y)=>Y.id!==Q),this._logger.info("DeviceSession removed",{data:{sessionId:Q}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:Q}}),this)}getDeviceSessionById(Q){return q0.fromNullable(this._sessions.find((Z)=>Z.id===Q)).toEither(new zz)}getDeviceSessionsByDeviceId(Q){return q0.fromPredicate(({length:Z})=>Z>0,this._sessions.filter((Z)=>Z.connectedDevice.id===Q)).toEither(new zz)}getDeviceSessions(){return this._sessions}};var oN=w(()=>{W0();R0();Wz();uZ();nN=require("rxjs"),Ws=Object.defineProperty,Ks=Object.getOwnPropertyDescriptor;Mz=Us([e(),Os(0,g(bQ.LoggerPublisherServiceFactory))],Mz)});var Hs,Ds,Is=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ds(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Hs(Z,Y,J),J},sN=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Tz=class{_sessionService;_transportService;constructor(Q,Z){this._sessionService=Q,this._transportService=Z}execute(){let Q=this._sessionService.getDeviceSessions();for(let Z of Q)this._transportService.closeConnection(Z.connectedDevice),this._sessionService.removeDeviceSession(Z.id)}};var iN=w(()=>{W0();pY();Z1();Hs=Object.defineProperty,Ds=Object.getOwnPropertyDescriptor;Tz=Is([e(),sN(0,g(cQ.DeviceSessionService)),sN(1,g(rZ.TransportService))],Tz)});var Rs,Ls,Es=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ls(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Rs(Z,Y,J),J},aN=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Nz=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("GetDeviceSessionStateUseCase")}execute({sessionId:Q}){return this._sessionService.getDeviceSessionById(Q).caseOf({Left:(Z)=>{throw this._logger.error("Error getting session device",{data:{error:Z}}),Z},Right:(Z)=>Z.state})}};var rN=w(()=>{W0();pY();uZ();Rs=Object.defineProperty,Ls=Object.getOwnPropertyDescriptor;Nz=Es([e(),aN(0,g(cQ.DeviceSessionService)),aN(1,g(bQ.LoggerPublisherServiceFactory))],Nz)});var Ps,js,As=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?js(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ps(Z,Y,J),J},tN=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Bz=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("UnsafeBypassIntentQueueUseCase")}execute({sessionId:Q,bypass:Z}){this._sessionService.getDeviceSessionById(Q).caseOf({Left:(Y)=>{throw this._logger.error("Error getting session",{data:{error:Y}}),Y},Right:(Y)=>{this._logger.warn(`UNSAFE: ${Z?"Enabling":"Disabling"} intent queue bypass for session ${Q}`),Y._unsafeBypassIntentQueue(Z)}})}};var eN=w(()=>{W0();pY();uZ();Ps=Object.defineProperty,js=Object.getOwnPropertyDescriptor;Bz=As([e(),tN(0,g(cQ.DeviceSessionService)),tN(1,g(bQ.LoggerPublisherServiceFactory))],Bz)});var QB=({stub:Q}={stub:!1})=>new b0(({bind:Z,rebindSync:Y})=>{Z(cQ.ApduSenderServiceFactory).toFactory(($)=>{let J=$.get(bQ.LoggerPublisherServiceFactory);return(X)=>new LV(X,J)}),Z(cQ.ApduReceiverServiceFactory).toFactory(($)=>{let J=$.get(bQ.LoggerPublisherServiceFactory);return(X={})=>new RV(X,J)}),Z(cQ.DeviceSessionService).to(Mz).inSingletonScope(),Z(cQ.GetDeviceSessionStateUseCase).to(Nz),Z(cQ.CloseSessionsUseCase).to(Tz),Z(cQ.DisableDeviceSessionRefresherUseCase).to(Az),Z(cQ.UnsafeBypassIntentQueueUseCase).to(Bz),Q&&(Y(cQ.GetDeviceSessionStateUseCase).to(CZ),Y(cQ.DisableDeviceSessionRefresherUseCase).to(CZ),Y(cQ.UnsafeBypassIntentQueueUseCase).to(CZ))});var ZB=w(()=>{W0();dN();g7();h7();oN();iN();rN();eN();uZ();dG();pY()});function YB(Q){return`[will send APDU] ~...> ${DQ(Q,!1)}`}function kz(Q){return`[exchange] => ${DQ(Q,!1)}`}function P6(Q){return`[exchange] <= ${DQ(Q.data,!1)}${DQ(Q.statusCode,!1)}`}function $B(Q,Z,Y){let $=DQ(Z,!1),J=`${DQ(Y.data,!1)}${DQ(Y.statusCode,!1)}`;return{message:P6(Y),data:{type:Ms,sessionId:Q,apdu:$,response:J}}}var Ms="apdu-exchange";var s7=w(()=>{O8()});var j6=1000,Cz=1000,JB;var Sz=w(()=>{JB={isRefresherDisabled:!1,pollingInterval:1000}});class i7{_eventEmitter=new GB.Subject;listen(){return this._eventEmitter.asObservable()}dispatch(Q){this._eventEmitter.next(Q)}}var GB,AZ;var EV=w(()=>{GB=require("rxjs"),AZ=((Q)=>(Q.NEW_STATE="NEW_STATE",Q.REFRESH_NEEDED="REFRESH_NEEDED",Q.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",Q.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",Q.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",Q.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",Q.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",Q))(AZ||{})});class a7{constructor(Q,Z){this.loggerModuleFactory=Q,this.sessionEventDispatcher=Z,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(Q){this._logger.debug("Enqueueing intent",{data:{type:Q.type}});let Z=new wz.Subject,Y={intent:Q,subject:Z,isCancelled:!1};this._queue.push(Y);let $=()=>{this._logger.debug("Cancelling intent",{data:{type:Q.type}}),Y.isCancelled=!0,this._queue[0]===Y&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,Z.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==Y)&&Z.complete()};return this._isProcessing||this._processQueue(),{observable:Z.asObservable().pipe(wz.finalize(()=>{this._logger.debug("Intent observable finalized",{data:{type:Q.type}})})),cancel:$}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:AZ.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:AZ.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;let Q=this._queue[0];if(Q.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:Q.intent.type}}),Q.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:Q.intent.type}}),this._currentSubscription=Q.intent.execute().subscribe({next:(Z)=>{Q.isCancelled||Q.subject.next(Z)},error:(Z)=>{Q.isCancelled||Q.subject.error(Z),this._onIntentComplete()},complete:()=>{Q.isCancelled||Q.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}}var wz;var XB=w(()=>{EV();wz=require("rxjs")});class r7{constructor(Q,Z){this._refresher=Z,this._logger=Q("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(Q){let Z=`${Q}-${_J()}`;this.addRefresherBlocker(Z),this._logger.debug("Refresher disabled",{data:{blockerId:Z,blockers:Array.from(this._refresherBlockers)}});let Y=!1;return()=>{Y||(Y=!0,this.removeRefresherBlocker(Z),this._logger.debug("Refresher re-enabled",{data:{blockerId:Z,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(Q){let Z=this._refresherBlockers.size;this._refresherBlockers.add(Q),Z===0&&this._refresher.stop()}removeRefresherBlocker(Q){let Z=this._refresherBlockers.size;this._refresherBlockers.delete(Q),Z>0&&this._refresherBlockers.size===0&&this._refresher.start()}}var VB=w(()=>{IV()});class t7{constructor(Q,Z,Y,$){this.connectedDevice=Z,this._sessionEventDispatcher=Y,this._sendCommandFunction=$,this._logger=Q("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async(J)=>await this.mapEventAction(J))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(Q){return this._logger.error("Error while pinging device",{data:{error:Q}}),null}}mapEventAction=async(Q)=>{switch(Q.eventName){case AZ.REFRESH_NEEDED:return await this.ping();default:return null}};async mapDevicePingAction(Q){switch(Q){case JQ.NANO_S:{let Z=async()=>{let J=await this._sendCommandFunction(new e$,Vz);return this._sendCommandFunction(new IY,Vz),J},Y=new Promise((J)=>{setTimeout(()=>J(null),j6*2+100)}),$=await Promise.race([Z(),Y]);return $?this._sessionEventDispatcher.dispatch({eventName:AZ.COMMAND_SUCCEEDED,eventData:$}):this._sessionEventDispatcher.dispatch({eventName:AZ.DEVICE_STATE_UPDATE_LOCKED}),$}default:{let Z=await this._sendCommandFunction(new e$,Vz);return this._sessionEventDispatcher.dispatch({eventName:AZ.COMMAND_SUCCEEDED,eventData:Z}),Z}}}unsubscribe(){this._subscription.unsubscribe()}}var qB=w(()=>{R1();O6();v7();Sz();EV()});class e7{constructor(Q,Z,Y,$){this._sessionEventDispatcher=Y,this._refresherOptions=Z,this._logger=Q("device-session-refresher"),this._connectedDeviceID=$.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;let Q=this.getValidPollingInterval(this._refresherOptions,this._logger),Z=this._sessionEventDispatcher.listen().pipe(Q$.filter((Y)=>Y.eventName===AZ.DEVICE_STATE_UPDATE_BUSY||Y.eventName===AZ.NEW_STATE),Q$.map((Y)=>Y.eventName===AZ.DEVICE_STATE_UPDATE_BUSY),Q$.startWith(!1),Q$.distinctUntilChanged());this._refresherSubscription=Q$.timer(0,Q).pipe(Q$.withLatestFrom(Z),Q$.tap(([Y,$])=>{$&&this._logger.debug("Refresh skipped: device is busy")}),Q$.filter(([Y,$])=>!$),Q$.tap(()=>this._sessionEventDispatcher.dispatch({eventName:AZ.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=(Q,Z)=>{let{pollingInterval:Y}=Q;switch(this._connectedDeviceID){case JQ.NANO_S:{let $=j6*2;return Y!==void 0&&Y<$?(Z.warn(`Polling interval of ${Y} is too low, setting to minimum as ${$}`),$):Y??$}default:return Y!==void 0&&Y<Cz?(Z.warn(`Polling interval of ${Y} is too low, setting to minimum as ${Cz}`),Cz):Y??j6}}}var Q$;var FB=w(()=>{R1();Sz();EV();Q$=require("rxjs")});class QH{constructor(Q,Z,Y,$,J){this._sessionEventDispatcher=Z,this._connectedDevice=Y,this._deviceState=$,this.setDeviceSessionState=J,this._subscription=this._sessionEventDispatcher.listen().subscribe((X)=>this.mapEventAction(X)),this._logger=Q("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=aY.BUSY;_updateDeviceState(Q){let Z=this._parseDeviceStatus(Q);if(Z){let{sessionStateType:Y,deviceStatus:$,currentApp:J}=Z,X=this._deviceState.getValue();X.sessionStateType===CQ.Connected?this.setDeviceSessionState({sessionStateType:Y,deviceStatus:$,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:J,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...X,sessionStateType:Y,deviceStatus:$,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:J})}}mapEventAction=(Q)=>{let{eventName:Z}=Q;switch(Z){case AZ.COMMAND_SUCCEEDED:return this._updateDeviceState(Q.eventData);case AZ.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:aY.BUSY});case AZ.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=aY.LOCKED;return;case AZ.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=aY.CONNECTED;return;case AZ.NEW_STATE:{let Y=this._pendingDeviceStatus;return this._pendingDeviceStatus=aY.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Y})}case AZ.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:aY.BUSY});case AZ.REFRESH_NEEDED:return;default:throw Error(`Unhandled context type ${Z}`)}};_parseDeviceStatus(Q){return N0(Q)?{sessionStateType:CQ.ReadyWithoutSecureChannel,deviceStatus:aY.CONNECTED,currentApp:{name:Q.data.name,version:Q.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:Q}}),null)}unsubscribe(){this._subscription.unsubscribe()}}var zB=w(()=>{O6();EV()});class A6{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new i7;_bypassIntentQueue=!1;constructor({connectedDevice:Q,id:Z=_J()},Y,$,J,X,G=(W)=>new a7(Y,W)){this._id=Z,this._connectedDevice=Q,this._loggerModuleFactory=Y,this._logger=Y("device-session"),this._managerApiService=$,this._intentQueueService=G(this._sessionEventDispatcher),this._secureChannelService=J,this._refresherOptions={...JB,...X},this._deviceState=new vJ.BehaviorSubject({sessionStateType:CQ.Connected,deviceStatus:aY.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new t7(Y,Q,this._sessionEventDispatcher,(W,U)=>this.sendCommand(W,U)),this._deviceSessionRefresher=new e7(Y,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new QH(Y,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,(W)=>this.setDeviceSessionState(W)),this._refresherService=new r7(Y,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(Q){throw this._logger.error("Error while initialising session",{data:{error:Q}}),Q}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(Q){this._deviceState.next(Q)}sendApdu(Q,Z={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(Q,Z):this._internalSendApdu(Q,Z)}_internalSendApdu(Q,Z){let Y=Z.abortTimeout,$=Date.now(),{observable:J,cancel:X}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>vJ.from((async()=>{let W=Date.now()-$;return await this._unsafeInternalSendApdu(Q,{isPolling:Z.isPolling,triggersDisconnection:Z.triggersDisconnection,abortTimeout:Y?Y-W:void 0})})())}),G=Y?J.pipe(vJ.timeout({each:Y,with:()=>{throw X(),new QV}})):J;return vJ.lastValueFrom(G)}async _unsafeInternalSendApdu(Q,Z={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(YB(Q)),(await this._connectedDevice.sendApdu(Q,Z.triggersDisconnection,Z.abortTimeout)).ifRight((Y)=>{let{message:$,data:J}=$B(this._id,Q,Y);this._logger.debug($,{data:J}),hQ.isLockedDeviceResponse(Y)?this._sessionEventDispatcher.dispatch({eventName:AZ.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:AZ.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:AZ.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(Q,Z){return this._logger.debug(`[sendCommand] ${Q.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(Q,Z):this._internalSendCommand(Q,Z)}_internalSendCommand(Q,Z){let Y=Date.now(),{observable:$,cancel:J}=this._intentQueueService.enqueue({type:"send-command",execute:()=>vJ.from((async()=>{let G=Date.now()-Y;return await this._unsafeInternalSendCommand(Q,Z?Z-G:void 0)})())}),X=Z?$.pipe(vJ.timeout({each:Z,with:()=>{throw J(),new _9}})):$;return vJ.lastValueFrom(X)}async _unsafeInternalSendCommand(Q,Z){let Y=Q.getApdu();return(await this._unsafeInternalSendApdu(Y.getRawApdu(),{isPolling:!1,triggersDisconnection:Q.triggersDisconnection??!1,abortTimeout:Z})).caseOf({Left:($)=>{throw this._logger.error("[sendCommand] error",{data:{err:$}}),$},Right:($)=>{let J=Q.parseResponse($,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:J}}),J}})}executeDeviceAction(Q){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(Q):this._internalExecuteDeviceAction(Q)}_internalExecuteDeviceAction(Q){let Z,{observable:Y,cancel:$}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{let{observable:J,cancel:X}=this._unsafeInternalExecuteDeviceAction(Q);return Z=X,J}});return{observable:Y,cancel:()=>{Z?.(),$()}}}_unsafeInternalExecuteDeviceAction(Q){let{observable:Z,cancel:Y}=Q._execute({sendApdu:async($)=>this._unsafeInternalSendApdu($),sendCommand:async($)=>this._unsafeInternalSendCommand($),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:($)=>(this.setDeviceSessionState($),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:Z,cancel:Y}}close(){this._updateDeviceStatus(aY.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(Q){return this._refresherService.disableRefresher(Q)}_unsafeBypassIntentQueue(Q){this._bypassIntentQueue=Q}_updateDeviceStatus(Q){let Z=this._deviceState.getValue();this._deviceState.next({...Z,deviceStatus:Q})}}var vJ;var ZH=w(()=>{IV();oY();U9();K$();M1();s7();Sz();XB();VB();qB();EV();FB();zB();vJ=require("rxjs")});var Y1;var M6=w(()=>{Y1={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")}});var Ts,Ns,Bs=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ns(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ts(Z,Y,J),J},T6=(Q,Z)=>(Y,$)=>Z(Y,$,Q),_z=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(Q,Z,Y,$,J){this._sessionService=Z,this._transportService=Q,this._loggerFactory=Y,this._logger=Y("ConnectUseCase"),this._managerApi=$,this._secureChannel=J}handleDeviceDisconnect(Q){this._sessionService.getDeviceSessionsByDeviceId(Q).ifRight((Z)=>{Z.forEach((Y)=>{this._sessionService.removeDeviceSession(Y.id),this._logger.info("Session removed",{data:{deviceId:Q,sessionId:Y.id}})})})}async execute({device:Q,sessionRefresherOptions:Z}){let Y=this._transportService.getTransport(Q.transport),$="sessionId"in Q?Q.sessionId:void 0;return EQ.liftEither(Y.toEither(new A8(Error("Unknown transport")))).chain(async(J)=>J.connect({deviceId:Q.id,onDisconnect:(X)=>this.handleDeviceDisconnect(X)})).ifLeft((J)=>{this._logger.error("Error connecting to device")}).map(async(J)=>{let X=new A6({connectedDevice:J,id:$},this._loggerFactory,this._managerApi,this._secureChannel,Z);return this._sessionService.addDeviceSession(X),await X.initialiseSession(),X.id}).caseOf({Left:(J)=>{throw J},Right:(J)=>J})}};var WB=w(()=>{W0();R0();M1();pY();ZH();uZ();mG();M6();Z1();Ts=Object.defineProperty,Ns=Object.getOwnPropertyDescriptor;_z=Bs([e(),T6(0,g(rZ.TransportService)),T6(1,g(cQ.DeviceSessionService)),T6(2,g(bQ.LoggerPublisherServiceFactory)),T6(3,g(LY.ManagerApiService)),T6(4,g(Y1.SecureChannelService))],_z)});var ks,Cs,Ss=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Cs(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&ks(Z,Y,J),J},YH=(Q,Z)=>(Y,$)=>Z(Y,$,Q),vz=class{_transportService;_sessionService;_logger;constructor(Q,Z,Y){this._sessionService=Z,this._transportService=Q,this._logger=Y("DisconnectUseCase")}async execute({sessionId:Q}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map((Z)=>Z.id)}}),EQ(async({liftEither:Z})=>{let Y=await Z(this._sessionService.getDeviceSessionById(Q).ifLeft((X)=>{this._logger.error("Device session not found",{data:{sessionId:Q,error:X}})})),$=Y.connectedDevice.transport,J=await Z(this._transportService.getTransport($).toEither(new A8(Error("Unknown transport"))));Y.close(),this._sessionService.removeDeviceSession(Q),await J.disconnect({connectedDevice:Y.connectedDevice})}).caseOf({Left:(Z)=>{throw this._logger.error("Error disconnecting from device",{data:{error:Z}}),Z},Right:()=>{}})}};var KB=w(()=>{W0();R0();M1();pY();uZ();Z1();ks=Object.defineProperty,Cs=Object.getOwnPropertyDescriptor;vz=Ss([e(),YH(0,g(rZ.TransportService)),YH(1,g(cQ.DeviceSessionService)),YH(2,g(bQ.LoggerPublisherServiceFactory))],vz)});class v1{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:Q,deviceModel:{id:Z,productName:Y},type:$,transport:J,name:X},sessionId:G}){this.id=Q,this.sessionId=G,this.modelId=Z,this.name=X??Y,this.type=$,this.transport=J}}var N6=()=>{};var ws,_s,vs=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?_s(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&ws(Z,Y,J),J},UB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),xz=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("GetConnectedDeviceUseCase")}execute({sessionId:Q}){return this._sessionService.getDeviceSessionById(Q).caseOf({Right:(Z)=>new v1({sessionId:Z.id,transportConnectedDevice:Z.connectedDevice}),Left:(Z)=>{throw this._logger.error("Error getting session",{data:{error:Z}}),Z}})}};var OB=w(()=>{W0();N6();pY();uZ();ws=Object.defineProperty,_s=Object.getOwnPropertyDescriptor;xz=vs([e(),UB(0,g(cQ.DeviceSessionService)),UB(1,g(bQ.LoggerPublisherServiceFactory))],xz)});var xs,fs,ys=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?fs(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&xs(Z,Y,J),J},HB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),fz=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map((Q)=>new v1({transportConnectedDevice:Q.connectedDevice,sessionId:Q.id}))}};var DB=w(()=>{W0();N6();pY();uZ();xs=Object.defineProperty,fs=Object.getOwnPropertyDescriptor;fz=ys([e(),HB(0,g(cQ.DeviceSessionService)),HB(1,g(bQ.LoggerPublisherServiceFactory))],fz)});var KJ,gs,hs,bs=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?hs(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&gs(Z,Y,J),J},IB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),yz=class{_transports;_transportService;_logger;constructor(Q,Z){this._transports=Q.getAllTransports(),this._transportService=Q,this._logger=Z("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(Q){let Z=new CG({id:Q.id,model:Q.deviceModel.id,name:Q.deviceModel.productName});return{id:Q.id,deviceModel:Z,transport:Q.transport,name:Q.name||Z.name,rssi:Q.rssi}}execute({transport:Q}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),KJ.from([[]]);if(!Q){this._logger.info("Discovering all available transports");let Z=this._transports.map((Y,$)=>Y.listenToAvailableDevices().pipe(KJ.map((J)=>({index:$,arr:J}))));return KJ.merge(...Z).pipe(KJ.scan((Y,{index:$,arr:J})=>(Y[$]=J,Y),{}),KJ.map((Y)=>Object.values(Y).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${Q}`),this._transportService.getTransport(Q).caseOf({Nothing:()=>(this._logger.error(`Transport ${Q} not found`),KJ.of([])),Just:(Z)=>Z.listenToAvailableDevices().pipe(KJ.map((Y)=>Y.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};var RB=w(()=>{W0();R1();uZ();Z1();KJ=require("rxjs"),gs=Object.defineProperty,hs=Object.getOwnPropertyDescriptor;yz=bs([e(),IB(0,g(rZ.TransportService)),IB(1,g(bQ.LoggerPublisherServiceFactory))],yz)});var EB,cs,us,ps=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?us(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&cs(Z,Y,J),J},LB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),gz=class{constructor(Q,Z){this._sessionService=Q,this._logger=Z("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(EB.map((Q)=>new v1({transportConnectedDevice:Q.connectedDevice,sessionId:Q.id})))}};var PB=w(()=>{W0();N6();pY();uZ();EB=require("rxjs"),cs=Object.defineProperty,us=Object.getOwnPropertyDescriptor;gz=ps([e(),LB(0,g(cQ.DeviceSessionService)),LB(1,g(bQ.LoggerPublisherServiceFactory))],gz)});var ls,ms,ds=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?ms(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&ls(Z,Y,J),J},$H=(Q,Z)=>(Y,$)=>Z(Y,$,Q),hz=class{constructor(Q,Z,Y){this.connectUseCase=Q,this.disconnectUseCase=Z,this._logger=Y("ReconnectUseCase")}_logger;async execute({device:Q,sessionRefresherOptions:Z}){return this._logger.debug("Reconnecting device session",{data:{deviceId:Q.id,transport:Q.transport}}),await this.disconnectUseCase.execute({sessionId:Q.sessionId}),this.connectUseCase.execute({device:Q,sessionRefresherOptions:Z})}};var jB=w(()=>{W0();Kz();uZ();ls=Object.defineProperty,ms=Object.getOwnPropertyDescriptor;hz=ds([e(),$H(0,g(XZ.ConnectUseCase)),$H(1,g(XZ.DisconnectUseCase)),$H(2,g(bQ.LoggerPublisherServiceFactory))],hz)});var nG,ns,os,ss=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?os(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&ns(Z,Y,J),J},is=(Q,Z)=>(Y,$)=>Z(Y,$,Q),bz=class{constructor(Q){this._transportService=Q}mapDiscoveredDevice(Q){let Z=new CG({id:Q.id,model:Q.deviceModel.id,name:Q.deviceModel.productName});return{id:Q.id,deviceModel:Z,transport:Q.transport,name:Q.name||Z.name,rssi:Q.rssi}}execute({transport:Q}={}){if(!Q){let Z=this._transportService.getAllTransports();return nG.of(...Z).pipe(nG.mergeMap((Y)=>Y.startDiscovering().pipe(nG.map(($)=>this.mapDiscoveredDevice($)))))}return this._transportService.getTransport(Q).caseOf({Just:(Z)=>Z.startDiscovering().pipe(nG.map((Y)=>this.mapDiscoveredDevice(Y))),Nothing:()=>{throw new A8(Error("Unknown transport"))}})}};var AB=w(()=>{W0();R1();M1();Z1();nG=require("rxjs"),ns=Object.defineProperty,os=Object.getOwnPropertyDescriptor;bz=ss([e(),is(0,g(rZ.TransportService))],bz)});var as,rs,ts=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?rs(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&as(Z,Y,J),J},MB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),cz=class{constructor(Q,Z){this.transportService=Q,this._logger=Z("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(let Q of this.transportService.getAllTransports())await Q.stopDiscovering()}};var TB=w(()=>{W0();uZ();Z1();as=Object.defineProperty,rs=Object.getOwnPropertyDescriptor;cz=ts([e(),MB(0,g(rZ.TransportService)),MB(1,g(bQ.LoggerPublisherServiceFactory))],cz)});var NB=({stub:Q=!1})=>new b0(({bind:Z,rebindSync:Y})=>{Z(XZ.ConnectUseCase).to(_z),Z(XZ.DisconnectUseCase).to(vz),Z(XZ.ReconnectUseCase).to(hz),Z(XZ.StartDiscoveringUseCase).to(bz),Z(XZ.StopDiscoveringUseCase).to(cz),Z(XZ.GetConnectedDeviceUseCase).to(xz),Z(XZ.ListenToAvailableDevicesUseCase).to(yz),Z(XZ.ListenToConnectedDeviceUseCase).to(gz),Z(XZ.ListConnectedDevicesUseCase).to(fz),Q&&(Y(XZ.ConnectUseCase).to(CZ),Y(XZ.DisconnectUseCase).to(CZ),Y(XZ.StartDiscoveringUseCase).to(CZ),Y(XZ.StopDiscoveringUseCase).to(CZ),Y(XZ.GetConnectedDeviceUseCase).to(CZ),Y(XZ.ListenToAvailableDevicesUseCase).to(CZ),Y(XZ.ListenToConnectedDeviceUseCase).to(CZ),Y(XZ.ListConnectedDevicesUseCase).to(CZ))});var BB=w(()=>{W0();WB();KB();OB();DB();RB();PB();jB();AB();TB();dG();Kz()});var oZ;var B6=w(()=>{oZ=((Q)=>(Q[Q.Fatal=0]="Fatal",Q[Q.Error=1]="Error",Q[Q.Warning=2]="Warning",Q[Q.Info=3]="Info",Q[Q.Debug=4]="Debug",Q))(oZ||{})});class k6{format(Q){return Array.isArray(Q)?Q.map((Z)=>`[${Z}]`).join(" "):`[${Q}]`}}var JH=()=>{};function GH(Q,Z){if(typeof Q=="bigint")return Q.toString();if(Array.isArray(Q))return Z.has(Q)?"[Circular]":(Z.add(Q),Q.map((Y)=>GH(Y,Z)));if(Q!==null&&typeof Q=="object"){if(Z.has(Q))return"[Circular]";Z.add(Q);let Y={};for(let[$,J]of Object.entries(Q))Y[$]=GH(J,Z);return Y}return Q}function kB(Q){let Z=new WeakSet;Z.add(Q);let Y={};for(let[$,J]of Object.entries(Q))Y[$]=GH(J,Z);return Y}var CB=()=>{};var es,Qi,Zi=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Qi(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&es(Z,Y,J),J},uz=class{subscribers;tag;tagFormatter;constructor(Q,Z,Y=new k6){this.subscribers=Q,this.tag=Z,this.tagFormatter=Y}_log(Q,Z,Y){let $=Y?.data?kB(Y.data):void 0,J=Y?.tag??this.tag,X=this.tagFormatter.format(J);this.subscribers.forEach((G)=>{let W={timestamp:Y?.timestamp??Date.now(),tag:X,data:$};G.log(Q,Z,W)})}info(Q,Z){this._log(oZ.Info,Q,Z)}warn(Q,Z){this._log(oZ.Warning,Q,Z)}debug(Q,Z){this._log(oZ.Debug,Q,Z)}error(Q,Z){this._log(oZ.Error,Q,Z)}};var SB=w(()=>{W0();B6();JH();CB();es=Object.defineProperty,Qi=Object.getOwnPropertyDescriptor;uz=Zi([e()],uz)});var wB=({subscribers:Q}={subscribers:[]})=>new b0(({bind:Z})=>{Z(bQ.LoggerPublisherServiceFactory).toFactory((Y)=>($)=>new uz(Q,$))});var _B=w(()=>{W0();SB();uZ()});var xJ;var C6=w(()=>{xJ=class xJ extends Error{status;statusText;responseBody;isTimeout;cause;constructor(Q){super(Q.message),this.name="DmkNetworkClientError",this.status=Q.status,this.statusText=Q.statusText,this.responseBody=Q.responseBody,this.isTimeout=Q.isTimeout??!1,this.cause=Q.cause}}});function $i(Q,Z){if(!Z)return Q;let Y=Q.endsWith("/")?Q.slice(0,-1):Q,$=Z.startsWith("/")?Z:`/${Z}`;return`${Y}${$}`}function Ji(Q){let Z=[];for(let[Y,$]of Object.entries(Q))$!=null&&Z.push(`${encodeURIComponent(Y)}=${encodeURIComponent(String($))}`);return Z.join("&")}function x1(Q){let{url:Z,params:Y,baseUrl:$}=Q,J=/^[a-z][a-z0-9+.-]*:\/\//i.test(Z)?Z:$?$i($,Z):Z,X=Y?Ji(Y):"";if(X.length===0)return J;let G=J.includes("?")?"&":"?";return`${J}${G}${X}`}function Gi(Q,Z){let Y=Z.toLowerCase();return Object.keys(Q).some(($)=>$.toLowerCase()===Y)}function Xi(Q){return!!(typeof Q=="string"||Q instanceof ArrayBuffer||ArrayBuffer.isView(Q)||typeof Blob<"u"&&Q instanceof Blob||typeof FormData<"u"&&Q instanceof FormData||typeof URLSearchParams<"u"&&Q instanceof URLSearchParams||typeof ReadableStream<"u"&&Q instanceof ReadableStream)}function vB(Q){let{method:Z,body:Y,defaultHeaders:$,perRequestHeaders:J}=Q,X={...$,...J};return Y===void 0||Z==="GET"||Z==="HEAD"?{body:void 0,headers:X}:Xi(Y)?{body:Y,headers:X}:(Gi(X,"content-type")||(X["Content-Type"]=Yi),{body:JSON.stringify(Y),headers:X})}function xB(Q){let{timeoutMs:Z}=Q;if(!Z||Z<=0)return{signal:void 0,cleanup:()=>{}};let Y=new AbortController,$=setTimeout(()=>{Y.abort()},Z);return{signal:Y.signal,cleanup:()=>clearTimeout($)}}async function fB(Q,Z){switch(Z){case"void":return;case"text":return await Q.text();case"blob":return await Q.blob();case"arrayBuffer":return await Q.arrayBuffer();case"json":default:{let Y=await Q.text();if(Y.length===0)return;try{return JSON.parse(Y)}catch($){throw new xJ({message:"Failed to parse JSON response body",status:Q.status,statusText:Q.statusText,responseBody:Y,cause:$})}}}}async function yB(Q){try{return await Q.text()}catch{return}}function gB(Q){let{cause:Z,timeoutMs:Y}=Q,$=!!(Y&&Y>0);if(Z instanceof Error&&(Z.name==="AbortError"||Z.name==="TimeoutError")){let J=Z.name==="TimeoutError"||$;return new xJ({message:J?"Request timed out":"Request aborted",isTimeout:J,cause:Z})}return new xJ({message:Z instanceof Error?Z.message:"Network request failed",cause:Z})}var Yi="application/json";var XH=w(()=>{C6()});class oG{baseUrl;defaultHeaders;fetchImpl;constructor(Q={}){this.baseUrl=Q.baseUrl,this.defaultHeaders=Q.headers??{},this.fetchImpl=Q.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(Q,Z){return this.request({...Z,method:"GET",url:Q}).then((Y)=>Y.data)}post(Q,Z,Y){return this.request({...Y,method:"POST",url:Q,body:Z}).then(($)=>$.data)}put(Q,Z,Y){return this.request({...Y,method:"PUT",url:Q,body:Z}).then(($)=>$.data)}patch(Q,Z,Y){return this.request({...Y,method:"PATCH",url:Q,body:Z}).then(($)=>$.data)}delete(Q,Z){return this.request({...Z,method:"DELETE",url:Q}).then((Y)=>Y.data)}head(Q,Z){return this.request({...Z,method:"HEAD",url:Q,responseType:"void"}).then(()=>{})}async request(Q){let Z=x1({url:Q.url,params:Q.params,baseUrl:this.baseUrl}),{body:Y,headers:$}=vB({method:Q.method,body:Q.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:Q.headers}),{signal:J,cleanup:X}=xB({timeoutMs:Q.timeoutMs}),G=Q.throwOnHttpError??!0,W=Q.responseType??"json";try{let U;try{U=await this.getFetch()(Z,{method:Q.method,headers:$,body:Y,signal:J})}catch(K){throw gB({cause:K,timeoutMs:Q.timeoutMs})}if(!U.ok&&G){let K=await yB(U);throw new xJ({message:`HTTP error ${U.status} ${U.statusText}`.trim(),status:U.status,statusText:U.statusText,responseBody:K})}return{data:await fB(U,W),status:U.status,statusText:U.statusText,headers:U.headers,ok:U.ok}}finally{X()}}}var VH=w(()=>{C6();XH()});var PV;var hB=w(()=>{PV=((Q)=>(Q.currency="currency",Q.plugin="plugin",Q.tool="tool",Q.swap="swap",Q))(PV||{})});var pz="https://manager.api.live.ledger.com/api",lz="https://device-mock-server.aws.ldg-ps-default.ldg-tech.com",jV=1,AV="0";var S6=()=>{};class sG{constructor(Q){this.error=Q,this.originalError=Q}_tag="FetchError";originalError}var qH=()=>{};var MV;var bB=w(()=>{MV=((Q)=>(Q.currency="currency",Q.plugin="plugin",Q.tool="tool",Q.swap="swap",Q))(MV||{})});var Vi,qi,Fi=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?qi(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Vi(Z,Y,J),J},zi=(Q,Z)=>(Y,$)=>Z(Y,$,Q),f1=(Q)=>Q instanceof xJ&&Q.cause!==void 0?new sG(Q.cause):new sG(Q),mz=class{http;_provider=jV;_firmwareDistributionSalt=AV;constructor({managerApiUrl:Q,provider:Z,firmwareDistributionSalt:Y}){this.http=new oG({baseUrl:Q}),this._provider=Z,this._firmwareDistributionSalt=Y}setProvider(Q){this._provider===Q||Q<1||(this._provider=Q)}getProvider(){return this._provider}getAppList(Q){let{targetId:Z,firmwareVersionName:Y}=Q;return EQ(()=>this.http.get("/v2/apps/by-target",{params:{target_id:Z,provider:this._provider,firmware_version_name:Y}})).chain(($)=>this.mapApplicationDtoToApplication($)).mapLeft(f1)}getMcuList(){return EQ(()=>this.http.get("/mcu_versions")).chain((Q)=>this.mapMcuDtoToMcu(Q)).mapLeft(f1)}getDeviceVersion(Q){let{targetId:Z}=Q;return EQ(()=>this.http.get("/get_device_version",{params:{target_id:Z,provider:this._provider}})).chain((Y)=>this.mapDeviceVersionDto(Y)).mapLeft(f1)}getFirmwareVersion(Q){let{deviceId:Z,version:Y}=Q;return EQ(()=>this.http.get("/get_firmware_version",{params:{device_version:Z,version_name:Y,provider:this._provider}})).chain(($)=>this.mapFinalFirmwareDto($)).mapLeft(f1)}getFirmwareVersionById(Q){return EQ(()=>this.http.get(`/firmware_final_versions/${Q}`)).chain((Z)=>this.mapFinalFirmwareDto(Z)).mapLeft(f1)}getOsuFirmwareVersion(Q){let{deviceId:Z,version:Y}=Q;return EQ(()=>this.http.get("/get_osu_version",{params:{device_version:Z,version_name:Y,provider:this._provider}})).chain(($)=>this.mapOsuFirmwareDto($)).mapLeft(f1)}getLatestFirmwareVersion(Q){let{currentFinalFirmwareId:Z,deviceId:Y}=Q;return EQ(()=>this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:Z,device_version:Y,provider:this._provider,salt:this._firmwareDistributionSalt}})).chain(($)=>this.mapLatestFirmwareDto($)).mapLeft(f1)}getAppsByHash(Q){let{hashes:Z}=Q;return EQ(()=>this.http.post("/v2/apps/hash",Z)).chain((Y)=>this.mapNullableApplicationDtoToApplication(Y)).mapLeft(f1)}getLanguagePackages(Q){let{deviceId:Z,currentFinalFirmwareId:Y}=Q;return EQ(()=>this.http.get("/language-packages",{params:{device_version:Z,current_se_firmware_final_version:Y}})).chain(($)=>this.mapLanguagesDtoToLanguages($)).mapLeft(f1)}mapAppTypeDtoToAppType(Q){if(Q===null)return null;switch(Q){case MV.currency:return PV.currency;case MV.plugin:return PV.plugin;case MV.tool:return PV.tool;case MV.swap:return PV.swap}}mapApplicationDtoToApplication(Q){return EQ(()=>Promise.resolve(Q.map((Z)=>this.mapApplicationDto(Z))))}mapNullableApplicationDtoToApplication(Q){return EQ(()=>Promise.resolve(Q.map((Z)=>Z===null?null:this.mapApplicationDto(Z))))}mapApplicationDto(Q){if(typeof Q!="object"||typeof Q.versionId!="number"||typeof Q.versionName!="string"||Q.versionDisplayName!==null&&typeof Q.versionDisplayName!="string"||typeof Q.version!="string"||Q.currencyId!==null&&typeof Q.currencyId!="string"||Q.description!==null&&typeof Q.description!="string"||Q.applicationType!==null&&typeof Q.applicationType!="string"||typeof Q.dateModified!="string"||Q.icon!==null&&typeof Q.icon!="string"||Q.authorName!==null&&typeof Q.authorName!="string"||Q.supportURL!==null&&typeof Q.supportURL!="string"||Q.contactURL!==null&&typeof Q.contactURL!="string"||Q.sourceURL!==null&&typeof Q.sourceURL!="string"||Q.compatibleWallets!==null&&typeof Q.compatibleWallets!="string"||typeof Q.hash!="string"||typeof Q.perso!="string"||typeof Q.firmware!="string"||typeof Q.firmwareKey!="string"||typeof Q.delete!="string"||typeof Q.deleteKey!="string"||Q.bytes!==null&&typeof Q.bytes!="number"||Q.warning!==null&&typeof Q.warning!="string"||typeof Q.isDevTools!="boolean"||Q.category!==null&&typeof Q.category!="number"||Q.parent!==null&&typeof Q.parent!="number"||Q.parentName!==null&&typeof Q.parentName!="string")throw Error(`Incomplete application: ${JSON.stringify(Q)}`);let{applicationType:Z,hash:Y,perso:$,firmware:J,firmwareKey:X,delete:G,deleteKey:W,...U}=Q;return{...U,hash:Y,perso:$,firmware:J,firmwareKey:X,delete:G,deleteKey:W,applicationType:this.mapAppTypeDtoToAppType(Z)}}mapMcuDtoToMcu(Q){return EQ(()=>Promise.resolve(Q.map((Z)=>{if(typeof Z!="object"||typeof Z.id!="number"||typeof Z.name!="string"||typeof Z.from_bootloader_version!="string")throw Error(`Incomplete MCU version: ${JSON.stringify(Z)}`);return{id:Z.id,name:Z.name,fromBootloaderVersion:Z.from_bootloader_version,providers:Z.providers}})))}mapDeviceVersionDto(Q){return EQ(()=>{if(typeof Q!="object"||typeof Q.id!="number")throw Error(`Incomplete device version: ${JSON.stringify(Q)}`);let Z={id:Q.id};return Promise.resolve(Z)})}mapFinalFirmwareDto(Q){return EQ(()=>{if(typeof Q!="object"||typeof Q.id!="number"||typeof Q.version!="string"||typeof Q.perso!="string"||Q.firmware!==null&&typeof Q.firmware!="string"||Q.firmware_key!==null&&typeof Q.firmware_key!="string"||Q.hash!==null&&typeof Q.hash!="string"||Q.bytes!==null&&typeof Q.bytes!="number"||!Array.isArray(Q.mcu_versions))throw Error(`Incomplete final firmware: ${JSON.stringify(Q)}`);let Z={id:Q.id,version:Q.version,perso:Q.perso,firmware:Q.firmware,firmwareKey:Q.firmware_key,hash:Q.hash,bytes:Q.bytes,mcuVersions:Q.mcu_versions};return Promise.resolve(Z)})}mapLatestFirmwareDto(Q){return EQ(()=>{if(Q.result==="null")return Promise.resolve(null);if(Q.result!=="success"||!Q.se_firmware_osu_version)throw Error(`Latest firmware could not be retrieved: ${Q.result}`);let Z=Q.se_firmware_osu_version;return Promise.resolve(Z)}).chain((Z)=>Z===null?EQ(()=>Promise.resolve(YQ)):this.mapOsuFirmwareDto(Z).map((Y)=>HQ(Y)))}mapOsuFirmwareDto(Q){return EQ(()=>{if(typeof Q!="object"||typeof Q.id!="number"||Q.notes!==null&&typeof Q.notes!="string"||typeof Q.perso!="string"||typeof Q.firmware!="string"||typeof Q.firmware_key!="string"||Q.hash!==null&&typeof Q.hash!="string"||typeof Q.next_se_firmware_final_version!="number")throw Error(`Incomplete latest firmware: ${JSON.stringify(Q)}`);let Z={id:Q.id,notes:Q.notes,perso:Q.perso,firmware:Q.firmware,firmwareKey:Q.firmware_key,hash:Q.hash,nextFinalFirmware:Q.next_se_firmware_final_version};return Promise.resolve(Z)})}mapLanguagesDtoToLanguages(Q){return EQ(()=>Promise.resolve(Q.map((Z)=>this.mapLanguageDto(Z))))}mapLanguageDto(Q){if(typeof Q!="object"||typeof Q.language!="string"||typeof Q.languagePackageVersionId!="number"||typeof Q.version!="string"||typeof Q.language_package_id!="number"||typeof Q.apdu_install_url!="string"||typeof Q.apdu_uninstall_url!="string"||typeof Q.bytes!="number"||typeof Q.date_creation!="string"||typeof Q.date_last_modified!="string")throw Error(`Incomplete language version: ${JSON.stringify(Q)}`);return{language:Q.language,languagePackageVersionId:Q.languagePackageVersionId,version:Q.version,languagePackageId:Q.language_package_id,apduInstallUrl:Q.apdu_install_url,apduUninstallUrl:Q.apdu_uninstall_url,bytes:Q.bytes,dateCreation:Q.date_creation,dateLastModified:Q.date_last_modified}}};var cB=w(()=>{W0();R0();VH();C6();mG();hB();S6();S6();qH();bB();Vi=Object.defineProperty,qi=Object.getOwnPropertyDescriptor;mz=Fi([e(),zi(0,g(LY.DmkConfig))],mz)});var Wi,Ki,Ui=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ki(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Wi(Z,Y,J),J},Oi=(Q,Z)=>(Y,$)=>Z(Y,$,Q),dz=class{constructor(Q){this.dataSource=Q}getAppList(Q){let Z={targetId:Q.targetId.toString(),firmwareVersionName:Q.seVersion};return this.dataSource.getAppList(Z)}getDeviceVersion(Q){let Z={targetId:Q.targetId.toString()};return this.dataSource.getDeviceVersion(Z)}getFirmwareVersion(Q,Z){let Y={version:Q.seVersion,deviceId:Z.id};return this.dataSource.getFirmwareVersion(Y)}getOsuFirmwareVersion(Q,Z){let Y={version:Q.seVersion,deviceId:Z.id};return this.dataSource.getOsuFirmwareVersion(Y)}getLatestFirmwareVersion(Q,Z){let Y={currentFinalFirmwareId:Q.id,deviceId:Z.id};return this.dataSource.getLatestFirmwareVersion(Y)}getNextFirmwareVersion(Q){return this.dataSource.getFirmwareVersionById(Q.nextFinalFirmware)}getLanguagePackages(Q,Z){let Y={deviceId:Q.id,currentFinalFirmwareId:Z.id};return this.dataSource.getLanguagePackages(Y)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(Q){let Z={hashes:Q};return EQ(async({fromPromise:Y,throwE:$})=>{if(Z.hashes.length===0)return[];try{return await Y(this.dataSource.getAppsByHash(Z))}catch(J){return J instanceof sG?$(J):$(new sG(J))}})}getProvider(){return this.dataSource.getProvider()}};var uB=w(()=>{W0();R0();mG();qH();Wi=Object.defineProperty,Ki=Object.getOwnPropertyDescriptor;dz=Ui([e(),Oi(0,g(LY.ManagerApiDataSource))],dz)});var Hi,Di,Ii=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Di(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Hi(Z,Y,J),J},pB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),nz=class{constructor(Q,Z){this.sessionService=Q,this.managerApiDataSource=Z}execute(Q){for(let Z of this.sessionService.getDeviceSessions()){let Y=Z.getDeviceSessionState();Y.sessionStateType!==CQ.Connected&&Z.setDeviceSessionState({...Y,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(Q)}};var lB=w(()=>{W0();K$();pY();mG();Hi=Object.defineProperty,Di=Object.getOwnPropertyDescriptor;nz=Ii([e(),pB(0,g(cQ.DeviceSessionService)),pB(1,g(LY.ManagerApiDataSource))],nz)});var mB=({stub:Q,config:Z})=>new b0(({bind:Y,rebindSync:$})=>{Y(LY.DmkConfig).toConstantValue(Z),Y(LY.ManagerApiDataSource).to(mz).inSingletonScope(),Y(LY.ManagerApiService).to(dz).inSingletonScope(),Y(LY.SetProviderUseCase).to(nz),Q&&($(LY.ManagerApiDataSource).to(CZ),$(LY.ManagerApiService).to(CZ),$(LY.SetProviderUseCase).to(CZ))});var dB=w(()=>{W0();cB();uB();lB();dG();mG()});var Ri,Li,Ei=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Li(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ri(Z,Y,J),J},Pi=(Q,Z)=>(Y,$)=>Z(Y,$,Q),oz=class{webSocketBaseUrl;constructor({webSocketUrl:Q}){this.webSocketBaseUrl=Q}genuineCheck(Q){let Z=x1({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:Q});return this._connectWebSocket(Z)}installApp(Q){let Z=x1({baseUrl:this.webSocketBaseUrl,url:"/install",params:Q});return this._connectWebSocket(Z)}listInstalledApps(Q){let Z=x1({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:Q});return this._connectWebSocket(Z)}uninstallApp(Q){let Z=x1({baseUrl:this.webSocketBaseUrl,url:"/install",params:Q});return this._connectWebSocket(Z)}updateFirmware(Q){let Z=x1({baseUrl:this.webSocketBaseUrl,url:"/install",params:Q});return this._connectWebSocket(Z)}updateMcu(Q){let Z=x1({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:Q});return this._connectWebSocket(Z)}_connectWebSocket(Q){try{return U0(new c9(Q))}catch(Z){return a(new m2(Z))}}};var nB=w(()=>{W0();h2();R0();XH();M6();d9();Ri=Object.defineProperty,Li=Object.getOwnPropertyDescriptor;oz=Ei([e(),Pi(0,g(Y1.DmkConfig))],oz)});var ji,Ai,Mi=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ai(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&ji(Z,Y,J),J},Ti=(Q,Z)=>(Y,$)=>Z(Y,$,Q),sz=class{constructor(Q){this.dataSource=Q}genuineCheck(Q,Z){let Y={targetId:Q.targetId.toString(),perso:Z.perso};return this.dataSource.genuineCheck(Y)}installApp(Q,Z){let{perso:Y,firmware:$,firmwareKey:J,hash:X}=Z,G={targetId:Q.targetId.toString(),perso:Y,firmware:$,firmwareKey:J,hash:X};return this.dataSource.installApp(G)}listInstalledApps(Q,Z){let Y={targetId:Q.targetId.toString(),perso:Z.perso};return this.dataSource.listInstalledApps(Y)}uninstallApp(Q,Z){let{perso:Y,delete:$,deleteKey:J,hash:X}=Z,G={targetId:Q.targetId.toString(),perso:Y,firmware:$,firmwareKey:J,hash:X};return this.dataSource.uninstallApp(G)}updateFirmware(Q,Z){let Y={targetId:Q.targetId.toString(),perso:Z.perso,firmware:Z.firmware,firmwareKey:Z.firmwareKey};return this.dataSource.updateFirmware(Y)}updateMcu(Q,Z){let Y={targetId:Q.targetId.toString(),version:Z.version};return this.dataSource.updateMcu(Y)}};var oB=w(()=>{W0();M6();ji=Object.defineProperty,Ai=Object.getOwnPropertyDescriptor;sz=Mi([e(),Ti(0,g(Y1.SecureChannelDataSource))],sz)});var sB=({stub:Q,config:Z})=>new b0(({bind:Y})=>{Y(Y1.DmkConfig).toConstantValue(Z),Y(Y1.SecureChannelDataSource).to(oz),Y(Y1.SecureChannelService).to(sz)});var iB=w(()=>{W0();nB();oB();M6()});var iz="wss://scriptrunner.api.live.ledger.com/update";var FH=()=>{};var Ni,Bi,ki=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Bi(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ni(Z,Y,J),J},aB=(Q,Z)=>(Y,$)=>Z(Y,$,Q),az=class{_sessionService;_logger;constructor(Q,Z){this._sessionService=Q,this._logger=Z("SendApduUseCase")}async execute({sessionId:Q,apdu:Z,abortTimeout:Y,triggersDisconnection:$}){return this._sessionService.getDeviceSessionById(Q).caseOf({Right:async(J)=>(await J.sendApdu(Z,{abortTimeout:Y,triggersDisconnection:$})).caseOf({Right:(X)=>X,Left:(X)=>{throw this._logger.error("Error sending APDU",{data:{sessionId:Q,apdu:Z,error:X}}),X}}),Left:(J)=>{throw this._logger.error("Error getting deviceSession",{data:{error:J}}),J}})}};var rB=w(()=>{W0();pY();uZ();Ni=Object.defineProperty,Bi=Object.getOwnPropertyDescriptor;az=ki([e(),aB(0,g(cQ.DeviceSessionService)),aB(1,g(bQ.LoggerPublisherServiceFactory))],az)});var tB=({stub:Q=!1})=>new b0(({bind:Z,rebindSync:Y})=>{Z(R6.SendApduUseCase).to(az),Q&&Y(R6.SendApduUseCase).to(CZ)});var eB=w(()=>{W0();rB();dG();c7()});var Ci,Si,wi=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Si(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ci(Z,Y,J),J},TV=(Q,Z)=>(Y,$)=>Z(Y,$,Q),rz=class{constructor(Q,Z,Y,$,J,X){if(this._config=Z,this._loggerModuleFactory=Y,this._deviceModelDataSource=$,this._apduSenderServiceFactory=J,this._apduReceiverServiceFactory=X,this._logger=Y("TransportService"),Q.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new f9("No transports provided, please check your configuration");for(let G of Q){let W=this.addTransport(G);if(W.isLeft())throw W.extract()}}_transports=new Map;_logger;addTransport(Q){let Z=Q({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(Z)}addTransportInternal(Q){return this.getTransport(Q.getIdentifier()).isJust()?(this._logger.warn(`Transport ${Q.getIdentifier()} already exists, please check your configuration`),a(new v9(`Transport ${Q.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(Q.getIdentifier(),Q),U0(void 0))}getTransport(Q){return q0.fromNullable(this._transports.get(Q))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(Q){this.getTransport(Q.transport).map((Z)=>Z.disconnect({connectedDevice:Q}))}};var Q3=w(()=>{W0();R0();M1();o7();pY();uZ();Z1();Ci=Object.defineProperty,Si=Object.getOwnPropertyDescriptor;rz=wi([e(),TV(0,g(rZ.TransportsInput)),TV(1,g(rZ.DmkConfig)),TV(2,g(bQ.LoggerPublisherServiceFactory)),TV(3,g(jz.DeviceModelDataSource)),TV(4,g(cQ.ApduSenderServiceFactory)),TV(5,g(cQ.ApduReceiverServiceFactory))],rz)});var Z3=({stub:Q=!1,transports:Z=[],config:Y}={})=>new b0(({bind:$})=>{$(rZ.TransportsInput).toConstantValue(Z),$(rZ.TransportService).to(rz).inSingletonScope(),$(rZ.DmkConfig).toConstantValue(Y)});var Y3=w(()=>{W0();Q3();Z1()});var $3=({stub:Q=!1,transports:Z=[],loggers:Y=[],config:$={mockUrl:lz,managerApiUrl:pz,webSocketUrl:iz,provider:jV,firmwareDistributionSalt:AV}})=>{let J=new T$;return J.loadSync(cN({stub:Q}),pN({stub:Q}),Z3({stub:Q,transports:Z,config:$}),mB({stub:Q,config:$}),sB({stub:Q,config:$}),NB({stub:Q}),wB({subscribers:Y}),QB({stub:Q}),tB({stub:Q}),TN({stub:Q}),CN({stub:Q})),J};var J3=w(()=>{W0();NN();SN();uN();lN();ZB();BB();_B();dB();S6();iB();FH();eB();Y3()});class w6{container;constructor({stub:Q,transports:Z,loggers:Y,config:$}={}){this.container=$3({stub:Q,transports:Z,loggers:Y,config:$})}getVersion(){return this.container.get(B$.GetDmkVersionUseCase).getDmkVersion()}startDiscovering(Q){return this.container.get(XZ.StartDiscoveringUseCase).execute(Q)}stopDiscovering(){return this.container.get(XZ.StopDiscoveringUseCase).execute()}listenToAvailableDevices(Q){return this.container.get(XZ.ListenToAvailableDevicesUseCase).execute(Q)}async reconnect(Q){return this.container.get(XZ.ReconnectUseCase).execute(Q)}connect(Q){return this.container.get(XZ.ConnectUseCase).execute(Q)}disconnect(Q){return this.container.get(XZ.DisconnectUseCase).execute(Q)}sendApdu(Q){return this.container.get(R6.SendApduUseCase).execute(Q)}sendCommand(Q){return this.container.get(D6.SendCommandUseCase).execute(Q)}executeDeviceAction(Q){return this.container.get(L6.ExecuteDeviceActionUseCase).execute(Q)}getConnectedDevice(Q){return this.container.get(XZ.GetConnectedDeviceUseCase).execute(Q)}getDeviceSessionState(Q){return this.container.get(cQ.GetDeviceSessionStateUseCase).execute(Q)}close(){return this.container.get(cQ.CloseSessionsUseCase).execute()}listConnectedDevices(){return this.container.get(XZ.ListConnectedDevicesUseCase).execute()}listenToConnectedDevice(){return this.container.get(XZ.ListenToConnectedDeviceUseCase).execute()}disableDeviceSessionRefresher(Q){return this.container.get(cQ.DisableDeviceSessionRefresherUseCase).execute(Q)}_unsafeBypassIntentQueue(Q){return this.container.get(cQ.UnsafeBypassIntentQueueUseCase).execute(Q)}setProvider(Q){return this.container.get(LY.SetProviderUseCase).execute(Q)}getProvider(){return this.container.get(LY.ManagerApiDataSource).getProvider()}isEnvironmentSupported(){return this.container.get(rZ.TransportService).getAllTransports().some((Q)=>Q.isSupported())}getLoggerFactory(){return this.container.get(bQ.LoggerPublisherServiceFactory)}}var zH=w(()=>{b7();I6();pY();Kz();uZ();mG();c7();Z1();J3();u7()});class WH{stub=!1;loggers=[];transports=[];config={managerApiUrl:pz,mockUrl:lz,webSocketUrl:iz,provider:jV,firmwareDistributionSalt:AV};build(){return new w6({stub:this.stub,transports:this.transports,loggers:this.loggers,config:this.config})}setStub(Q){return this.stub=Q,this}addTransport(Q){return this.transports.push(Q),this}addLogger(Q){return this.loggers.push(Q),this}addConfig(Q){return this.config={...this.config,...Q},this}}var G3=w(()=>{S6();FH();zH()});class KH{maxLevel;constructor(Q=oZ.Debug){this.maxLevel=Q}log(Q,Z,Y){let $=Y.tag;switch(Q){case oZ.Info:{this.maxLevel>=oZ.Info&&this.logWithData($,console.info,Z,Y);break}case oZ.Warning:{this.maxLevel>=oZ.Warning&&this.logWithData($,console.warn,Z,Y);break}case oZ.Debug:{this.maxLevel>=oZ.Debug&&this.logWithData($,console.debug,Z,Y);break}case oZ.Error:{this.maxLevel>=oZ.Error&&this.logWithData($,console.error,Z,Y);break}case oZ.Fatal:{this.maxLevel>=oZ.Fatal&&this.logWithData($,console.error,Z,Y);break}default:this.logWithData($,console.log,Z,Y)}}logWithData(Q,Z,Y,$){$.data?Z(Q,Y,$.data):Z(Q,Y)}}var X3=w(()=>{B6()});function _i(){let Q=[];return function(Z,Y){if(Y instanceof Uint8Array){let $=Array.from(Y).map((J)=>J.toString(16).padStart(2,"0"));return{hex:"0x"+$.join(""),readableHex:$.join(" "),value:Y.toString()}}if(Y instanceof A6){let{connectedDevice:{deviceModel:$,type:J,id:X}}=Y;return{id:Y.id,connectedDevice:{deviceModel:$,type:J,id:X}}}if(typeof Y!="object"||Y===null)return Y;for(;Q.length>0&&Q.at(-1)!==this;)Q.pop();return Q.includes(Y)?"[Circular]":(Q.push(Y),Y)}}class UH{logs=[];log(Q,Z,Y){this.logs.push([Q,Z,Y])}formatLogsToJSON(){let Q=this.logs.map(([Z,Y,$])=>{let{timestamp:J,...X}=$;return{level:oZ[Z],message:Y,options:{...X,date:new Date($.timestamp)}}});return JSON.stringify(Q,_i(),2)}exportLogsToJSON(){let Q=this.formatLogsToJSON(),Z=new Blob([Q],{type:"application/json"}),Y=URL.createObjectURL(Z),$=document.createElement("a");$.href=Y,$.download=`ledger-device-management-kit-logs-${new Date().toISOString()}.json`,$.click()}}var V3=w(()=>{B6();ZH()});class _6{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;previousSendApduPromise=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(Q){this.deviceId=Q.deviceId,this.deviceAdpuSender=Q.deviceApduSender,this.timeoutDuration=Q.timeoutDuration,this.machineActor=zJ(fi({sendApduFn:(Z,Y,$)=>this.sendApduToDeviceConnection(Z,Y,$),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{Q.tryToReconnect(this.timeoutDuration)},onTerminated:Q.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(Q,Z,Y){this.deviceAdpuSender.sendApdu(Q,Z,Y).then(($)=>{$.caseOf({Left:(J)=>{this.machineActor.send({type:"ApduSendingError",error:J})},Right:(J)=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:J})}})}).catch(($)=>{this.machineActor.send({type:"ApduSendingError",error:new sY($)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(Q){this.deviceAdpuSender.setDependencies(Q)}getDeviceId(){return this.deviceId}async sendApdu(Q,Z,Y){this.machineActor.getSnapshot().context.apduInProgress.isJust()&&await Promise.race([new Promise((J)=>setTimeout(J,xi)),this.previousSendApduPromise]);let $=new Promise((J)=>{this.machineActor.send({type:"SendApduCalled",apdu:Q,triggersDisconnection:!!Z,abortTimeout:Y,responseCallback:J})});return this.previousSendApduPromise=$,$.finally(()=>{this.previousSendApduPromise===$&&(this.previousSendApduPromise=null)}),$}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function fi({sendApduFn:Q,startReconnectionTimeout:Z,cancelReconnectionTimeout:Y,tryToReconnect:$,onTerminated:J,closeConnection:X}){return NQ({types:{},actions:{startTimer:()=>{Z()},cancelTimer:()=>{Y()},reconnectionTimeoutEvent:j2({type:"ReconnectionTimedOut"}),sendApdu:({context:G})=>{G.apduInProgress.map(({apdu:W,abortTimeout:U})=>{Q(W,!1,U)})},sendApduResponse:({context:G},W)=>{G.apduInProgress.map(({responseCallback:U})=>U(W.response))},sendGetAppAndVersion:()=>{Q(new e$().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{$()},clearApduInProgress:r({apduInProgress:YQ}),clearApduResponse:r({apduResponse:YQ}),signalTermination:()=>{J()},closeConnection:()=>{X()}},guards:{isApduThatTriggersDisconnection:({context:G,event:W})=>W.type!=="ApduResponseReceived"?!1:G.apduInProgress.caseOf({Just:({triggersDisconnection:U,apdu:K})=>(U||hQ.isApduThatTriggersDisconnection(K))&&hQ.isSuccessResponse(W.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:G})=>G.type!=="ApduResponseReceived"?!1:G.apduResponse.statusCode[0]===102&&G.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:YQ,apduResponse:YQ},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:r({apduInProgress:({event:G})=>q0.of({apdu:G.apdu,triggersDisconnection:G.triggersDisconnection,abortTimeout:G.abortTimeout,responseCallback:G.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[r({apduResponse:({event:G})=>q0.of(G.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:G})=>({response:U0(G.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:G})=>({response:a(G.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:a(new M8)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:a(new M8)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:G})=>{G.responseCallback(a(new ZV))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:G})=>({response:G.apduResponse.caseOf({Just:(W)=>U0(W),Nothing:()=>a(new sY)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:G})=>{G.responseCallback(a(new ZV))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:r({apduInProgress:({event:G})=>q0.of({apdu:G.apdu,triggersDisconnection:G.triggersDisconnection,abortTimeout:G.abortTimeout,responseCallback:G.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:a(new x9)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:a(new M8)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:G})=>{G.responseCallback(a(new ZV))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}var xi=1e4;var q3=w(()=>{R0();KZ();Rq();oY();dJ();M1()});class w8{id;deviceModel;sendApdu;type;transport;name;constructor({id:Q,deviceModel:Z,type:Y,transport:$,sendApdu:J,name:X}){this.id=Q,this.deviceModel=Z,this.sendApdu=J,this.type=Y,this.transport=$,this.name=X}}var OH=()=>{};function F3(Q={}){return{id:JQ.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2097152,getBlockSize:()=>4096,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"}],...Q}}var z3=w(()=>{R1()});var W3=({statusCode:Q=Uint8Array.from([144,0]),data:Z=Uint8Array.from([])}={})=>new pG({statusCode:Q,data:Z});var K3=w(()=>{Jz()});function U3(Q={}){let Z=F3();return new w8({deviceModel:Z,id:"42",type:"MOCK",transport:"USB",sendApdu:vi.fn(async()=>Promise.resolve(U0(W3()))),...Q})}var O3=w(()=>{R0();z3();K3();OH()});var H3=w(()=>{o2()});class YY{isCompatible;version;modelId;appName;constructor(Q,Z,Y){this.modelId=Q.deviceModelId,this.appName="currentApp"in Q?Q.currentApp.name:void 0;let $=Y.resolve(Q,Z);this.isCompatible=$.isCompatible,this.version=$.version}withMinVersionInclusive(Q){return fJ.gte(this.version,Q)||(this.isCompatible=!1),this}withMinVersionExclusive(Q){return fJ.gt(this.version,Q)||(this.isCompatible=!1),this}withMinVersionInclusiveAcceptingPrerelease(Q){let Z=fJ.valid(fJ.coerce(this.version)),Y=fJ.valid(fJ.coerce(Q));return(Z===null||Y===null||!fJ.gte(Z,Y))&&(this.isCompatible=!1),this}excludeDeviceModel(Q){return this.modelId===Q&&(this.isCompatible=!1),this}excludeDeviceModels(...Q){for(let Z of Q)this.excludeDeviceModel(Z);return this}excludeApp(Q){return this.appName===Q&&(this.isCompatible=!1),this}excludeApps(...Q){for(let Z of Q)this.excludeApp(Z);return this}check(){return this.isCompatible}}var fJ;var D3=w(()=>{fJ=JZ(kG(),1)});function I3(Q){return Q.replace(/\s/g,"")}function HH(Q){let Z=I3(Q);return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(Z)}function yi(){if(typeof window<"u"&&typeof window.atob=="function")return window.atob.bind(window);if(typeof atob=="function")return atob}function gi(){if(typeof window<"u"&&typeof window.btoa=="function")return window.btoa.bind(window);if(typeof btoa=="function")return btoa}function tz(Q){let Z=I3(Q);if(Z.length===0)return new Uint8Array;if(!HH(Z))return null;let Y=yi();if(Y){let $=Y(Z),J=new Uint8Array($.length);for(let X=0;X<$.length;X++)J[X]=$.charCodeAt(X);return J}if(typeof globalThis.Buffer<"u")return Uint8Array.from(globalThis.Buffer.from(Z,"base64"));throw Error("No Base64 decoder available in this environment.")}function R3(Q){let Z=gi();if(Z){let Y="";for(let $=0;$<Q.length;$++){let J=Q[$];if(J===void 0)throw Error("Unexpected undefined byte in array.");Y+=String.fromCharCode(J)}return Z(Y)}if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(Q).toString("base64");throw Error("No Base64 encoder available in this environment.")}var L3=()=>{};var O6=w(()=>{LO();a$();r$();PO();jO();MG();TZ();a4();AO();Rq();MO();wP();H8();lO();mO();BA();dO();I1();oY();VJ();R1();U9();uO();nO();CY();hM();tY();rY();Z6();S9();T1();RT();t2();g9();MT();oq();BT();CT();_2();h9();SY();M7();P7();j7();Jz();K$();TG();WN();KN();Xz();UN();T8();B1();d9();EN();jN();K6();zH();G3();w2();B6();X3();JH();V3();VH();C6();N6();q3();OH();O3();s7();D3();tX();L3();O8();EO();Gz();dJ();M1();H3()});var Gj0;var E3=w(()=>{Gj0=JZ(mJ(),1);O6()});var NV={};j$(NV,{noopLoggerFactory:()=>aX,noopLogger:()=>S2,isSuccessDmkResult:()=>t$,isSuccessCommandResult:()=>N0,isHexaString:()=>dQ,isDashboardName:()=>j8,isCommandErrorCode:()=>kY,isBase64String:()=>HH,hexaStringToBuffer:()=>mQ,formatApduSentLog:()=>kz,formatApduReceivedLog:()=>P6,defaultApduSenderServiceStubBuilder:()=>PN,defaultApduReceiverServiceStubBuilder:()=>LN,connectedDeviceStubBuilder:()=>U3,bufferToHexaString:()=>DQ,bufferToBase64String:()=>R3,base64StringToBuffer:()=>tz,XStateDeviceAction:()=>AQ,WebLogsExporterLogger:()=>UH,WaitForAppAndVersionDeviceAction:()=>kJ,ValueOverflowError:()=>bX,UserInteractionRequired:()=>k0,UnsupportedFirmwareDAError:()=>P8,UnknownDeviceExchangeError:()=>sY,UnknownDeviceError:()=>nq,UnknownDAError:()=>xQ,UninstallAppDeviceAction:()=>k7,TransportNotSupportedError:()=>A8,TransportDeviceModel:()=>eJ,TransportConnectedDevice:()=>w8,TransportAlreadyExistsError:()=>v9,StaticDeviceModelDataSource:()=>wJ,SendCommandTimeoutError:()=>_9,SendCommandInAppDeviceAction:()=>QJ,SendApduTimeoutError:()=>QV,SendApduEmptyResponseError:()=>SM,SendApduConcurrencyError:()=>CM,SeedWordCount:()=>pX,SecureChannelEventType:()=>fQ,SecureChannelError:()=>ZY,RefusedByUserDAError:()=>A1,ReconnectionFailedError:()=>_M,OutOfMemoryDAError:()=>aJ,OpeningConnectionError:()=>fG,OpenAppWithDependenciesDeviceAction:()=>Z7,OpenAppDeviceAction:()=>kZ,OpenAppCommand:()=>wq,OnboardingState:()=>dZ,NoTransportsProvidedError:()=>xM,NoTransportProvidedError:()=>f9,NoAccessibleDeviceError:()=>eX,LogLevel:()=>oZ,LoadCertificateCommand:()=>L1,ListLanguagePackCommandError:()=>K9,ListLanguagePackCommand:()=>Sq,ListInstalledAppsDeviceAction:()=>lG,ListAppsWithMetadataDeviceAction:()=>Q7,ListAppsDeviceAction:()=>yG,ListAppsCommand:()=>Cq,LEDGER_VENDOR_ID:()=>kq,LANGUAGE_ID_TO_LANGUAGE:()=>DT,InvalidStatusWordError:()=>C0,InvalidResponseFormatError:()=>AG,InvalidGetFirmwareMetadataResponseError:()=>iq,InvalidArgumentError:()=>Dq,InstallOrUpdateAppsDeviceAction:()=>Y6,InstallLanguagePackageDeviceAction:()=>s2,InstallAppDeviceAction:()=>B7,INDEX_LENGTH:()=>_1,HexaStringEncodeError:()=>Oq,HEAD_TAG_LENGTH:()=>Q1,HEAD_TAG:()=>T7,GoToDashboardDeviceAction:()=>RY,GlobalCommandErrorHandler:()=>NZ,GlobalCommandError:()=>i4,GetOsVersionCommand:()=>IY,GetDeviceStatusDeviceAction:()=>xG,GetDeviceMetadataDeviceAction:()=>k1,GetBatteryStatusCommand:()=>NO,GetBackgroundImageSizeCommandError:()=>t4,GetBackgroundImageSizeCommand:()=>Lq,GetApplicationsMetadataTaskError:()=>YV,GetAppAndVersionCommand:()=>e$,GenuineCheckDeviceAction:()=>N7,GeneralDmkError:()=>vZ,GLOBAL_ERRORS:()=>s4,FramerUtils:()=>N$,DmkResultStatus:()=>Hq,DmkResultFactory:()=>zQ,DmkNetworkClientError:()=>xJ,DmkNetworkClient:()=>oG,DisconnectError:()=>wM,DeviceStatus:()=>aY,DeviceSessionStateType:()=>CQ,DeviceNotRecognizedError:()=>w9,DeviceNotOnboardedError:()=>lq,DeviceNotInitializedError:()=>vM,DeviceModelId:()=>JQ,DeviceModel:()=>CG,DeviceManagementKitBuilder:()=>WH,DeviceManagementKit:()=>w6,DeviceLockedError:()=>iJ,DeviceExchangeError:()=>DZ,DeviceDisconnectedWhileSendingError:()=>M8,DeviceDisconnectedBeforeSendingApdu:()=>x9,DeviceConnectionStateMachine:()=>_6,DeviceBusyError:()=>kP,DeviceAlreadyConnectedError:()=>kM,DeviceActionStatus:()=>D8,DeleteLanguagePackDAError:()=>dq,DeleteLanguagePackCommandError:()=>r4,DeleteLanguagePackCommand:()=>Iq,DefaultLogTagFormatter:()=>k6,DataOverflowError:()=>jG,DEFAULT_UNLOCK_TIMEOUT_MS:()=>qZ,ConsoleLogger:()=>KH,ConnectedDevice:()=>v1,ConnectToSecureChannelTask:()=>U$,CommandUtils:()=>hQ,CommandResultStatus:()=>Hq,CommandResultFactory:()=>o,CloseAppCommand:()=>NG,CallTaskInAppDeviceAction:()=>nZ,CHANNEL_LENGTH:()=>HV,ByteArrayParser:()=>BY,ByteArrayBuilder:()=>WQ,BleDeviceInfos:()=>W6,BatteryStatusType:()=>TO,ApplicationChecker:()=>YY,AppAlreadyInstalledDAError:()=>mq,ApduResponse:()=>pG,ApduParser:()=>FQ,ApduBuilder:()=>w0,Apdu:()=>PG,AlreadySendingApduError:()=>ZV,APDU_MAX_PAYLOAD:()=>YZ,APDU_DATA_LENGTH_LENGTH:()=>DV});var I0=w(()=>{E3()});var ez,QW;var ZW=w(()=>{I0();ez=class ez extends vZ{constructor(Q){super(Q);this.err=Q}_tag="WebHidTransportNotSupportedError"};QW=class QW extends vZ{constructor(Q){super(Q);this.err=Q}_tag="WebHidSendReportError"}});function P3(Q,Z){DH(Q,Z);function Y(){this.constructor=Q}Q.prototype=Z===null?Object.create(Z):(Y.prototype=Z.prototype,new Y)}function j3(Q){var Z=typeof Symbol==="function"&&Symbol.iterator,Y=Z&&Q[Z],$=0;if(Y)return Y.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&$>=Q.length)Q=void 0;return{value:Q&&Q[$++],done:!Q}}};throw TypeError(Z?"Object is not iterable.":"Symbol.iterator is not defined.")}function v6(Q,Z){var Y=typeof Symbol==="function"&&Q[Symbol.iterator];if(!Y)return Q;var $=Y.call(Q),J,X=[],G;try{while((Z===void 0||Z-- >0)&&!(J=$.next()).done)X.push(J.value)}catch(W){G={error:W}}finally{try{if(J&&!J.done&&(Y=$.return))Y.call($)}finally{if(G)throw G.error}}return X}function UJ(){for(var Q=[],Z=0;Z<arguments.length;Z++)Q=Q.concat(v6(arguments[Z]));return Q}var DH=function(Q,Z){return DH=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Y,$){Y.__proto__=$}||function(Y,$){for(var J in $)if($.hasOwnProperty(J))Y[J]=$[J]},DH(Q,Z)},MQ=function(){return MQ=Object.assign||function(Z){for(var Y,$=1,J=arguments.length;$<J;$++){Y=arguments[$];for(var X in Y)if(Object.prototype.hasOwnProperty.call(Y,X))Z[X]=Y[X]}return Z},MQ.apply(this,arguments)};var iG=w(()=>{/*! *****************************************************************************
|
|
62
|
+
Copyright (c) Microsoft Corporation.
|
|
63
|
+
|
|
64
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
65
|
+
purpose with or without fee is hereby granted.
|
|
66
|
+
|
|
67
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
68
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
69
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
70
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
71
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
72
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
73
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
74
|
+
***************************************************************************** */});function A3(){return typeof __SENTRY_BROWSER_BUNDLE__<"u"&&!!__SENTRY_BROWSER_BUNDLE__}function BV(){return!A3()&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]"}function M3(Q,Z){return Q.require(Z)}var YW=()=>{};function k$(){return BV()?global:typeof window<"u"?window:typeof self<"u"?self:hi}function kV(Q,Z,Y){var $=Y||k$(),J=$.__SENTRY__=$.__SENTRY__||{},X=J[Q]||(J[Q]=Z());return X}var hi;var CV=w(()=>{YW();hi={}});function ci(Q,Z){return bi.call(Q)==="[object "+Z+"]"}function $W(Q){return ci(Q,"Object")}function JW(Q){return Boolean(Q&&Q.then&&typeof Q.then==="function")}var bi;var GW=w(()=>{bi=Object.prototype.toString});var T3=()=>{};function ui(Q,Z){return Q.__proto__=Z,Q}function pi(Q,Z){for(var Y in Z)if(!Object.prototype.hasOwnProperty.call(Q,Y))Q[Y]=Z[Y];return Q}var N3;var B3=w(()=>{N3=Object.setPrototypeOf||({__proto__:[]}instanceof Array?ui:pi)});var Aj0;var k3=w(()=>{iG();B3();Aj0=function(Q){P3(Z,Q);function Z(Y){var $=this.constructor,J=Q.call(this,Y)||this;return J.message=Y,J.name=$.prototype.constructor.name,N3(J,$.prototype),J}return Z}(Error)});var IH;var C3=w(()=>{IH=typeof __SENTRY_DEBUG__>"u"?!0:__SENTRY_DEBUG__});var S3=()=>{};var w3=()=>{};function LH(Q){var Z=k$();if(!("console"in Z))return Q();var Y=Z.console,$={};RH.forEach(function(J){var X=Y[J]&&Y[J].__sentry_original__;if(J in Z.console&&X)$[J]=Y[J],Y[J]=X});try{return Q()}finally{Object.keys($).forEach(function(J){Y[J]=$[J]})}}function _3(){var Q=!1,Z={enable:function(){Q=!0},disable:function(){Q=!1}};if(IH)RH.forEach(function(Y){Z[Y]=function(){var $=[];for(var J=0;J<arguments.length;J++)$[J]=arguments[J];if(Q)LH(function(){var X;(X=li.console)[Y].apply(X,UJ([mi+"["+Y+"]:"],$))})}});else RH.forEach(function(Y){Z[Y]=function(){return}});return Z}var li,mi="Sentry Logger ",RH,x6;var v3=w(()=>{iG();C3();CV();li=k$(),RH=["debug","info","warn","error","log","assert"];if(IH)x6=kV("logger",_3);else x6=_3()});var x3=()=>{};function XW(Q){var Z,Y;if($W(Q)){var $={};try{for(var J=j3(Object.keys(Q)),X=J.next();!X.done;X=J.next()){var G=X.value;if(typeof Q[G]<"u")$[G]=XW(Q[G])}}catch(W){Z={error:W}}finally{try{if(X&&!X.done&&(Y=J.return))Y.call(J)}finally{if(Z)throw Z.error}}return $}if(Array.isArray(Q))return Q.map(XW);return Q}var f3=w(()=>{iG();GW()});var y3=()=>{};var g3=()=>{};var mj0;var h3=w(()=>{CV();mj0=k$()});function aG(){var Q=k$(),Z=Q.crypto||Q.msCrypto;if(Z!==void 0&&Z.getRandomValues){var Y=new Uint16Array(8);Z.getRandomValues(Y),Y[3]=Y[3]&4095|16384,Y[4]=Y[4]&16383|32768;var $=function(J){var X=J.toString(16);while(X.length<4)X="0"+X;return X};return $(Y[0])+$(Y[1])+$(Y[2])+$(Y[3])+$(Y[4])+$(Y[5])+$(Y[6])+$(Y[7])}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,function(J){var X=Math.random()*16|0,G=J==="x"?X:X&3|8;return G.toString(16)})}var b3=w(()=>{CV()});var c3=()=>{};var u3=()=>{};var p3;var l3=w(()=>{GW();p3=function(){function Q(Z){var Y=this;this._state=0,this._handlers=[],this._resolve=function($){Y._setResult(1,$)},this._reject=function($){Y._setResult(2,$)},this._setResult=function($,J){if(Y._state!==0)return;if(JW(J)){J.then(Y._resolve,Y._reject);return}Y._state=$,Y._value=J,Y._executeHandlers()},this._executeHandlers=function(){if(Y._state===0)return;var $=Y._handlers.slice();Y._handlers=[],$.forEach(function(J){if(J[0])return;if(Y._state===1)J[1](Y._value);if(Y._state===2)J[2](Y._value);J[0]=!0})};try{Z(this._resolve,this._reject)}catch($){this._reject($)}}return Q.prototype.then=function(Z,Y){var $=this;return new Q(function(J,X){$._handlers.push([!1,function(G){if(!Z)J(G);else try{J(Z(G))}catch(W){X(W)}},function(G){if(!Y)X(G);else try{J(Y(G))}catch(W){X(W)}}]),$._executeHandlers()})},Q.prototype.catch=function(Z){return this.then(function(Y){return Y},Z)},Q.prototype.finally=function(Z){var Y=this;return new Q(function($,J){var X,G;return Y.then(function(W){if(G=!1,X=W,Z)Z()},function(W){if(G=!0,X=W,Z)Z()}).then(function(){if(G){J(X);return}$(X)})})},Q}()});var m3=()=>{};var d3=()=>{};function di(){var Q=k$().performance;if(!Q||!Q.now)return;var Z=Date.now()-Q.now();return{now:function(){return Q.now()},timeOrigin:Z}}function ni(){try{var Q=M3(oi,"perf_hooks");return Q.performance}catch(Z){return}}var PH,EH,n3,qW,jH,VW,YA0;var o3=w(()=>{CV();YW();PH={nowSeconds:function(){return Date.now()/1000}};EH=BV()?ni():di(),n3=EH===void 0?PH:{nowSeconds:function(){return(EH.timeOrigin+EH.now())/1000}},qW=PH.nowSeconds.bind(PH),jH=n3.nowSeconds.bind(n3),YA0=function(){var Q=k$().performance;if(!Q||!Q.now){VW="none";return}var Z=3600000,Y=Q.now(),$=Date.now(),J=Q.timeOrigin?Math.abs(Q.timeOrigin+Y-$):Z,X=J<Z,G=Q.timing&&Q.timing.navigationStart,W=typeof G==="number",U=W?Math.abs(G+Y-$):Z,K=U<Z;if(X||K)if(J<=U)return VW="timeOrigin",Q.timeOrigin;else return VW="navigationStart",G;return VW="dateNow",$}()});var JA0;var s3=w(()=>{JA0=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$")});var i3=()=>{};var a3=()=>{};var r3=()=>{};var FW=w(()=>{T3();S3();w3();k3();CV();h3();GW();v3();b3();YW();c3();f3();u3();m3();d3();y3();x3();g3();l3();o3();s3();i3();a3();r3()});var AH;var t3=w(()=>{AH=typeof __SENTRY_DEBUG__>"u"?!0:__SENTRY_DEBUG__});function si(){return kV("globalEventProcessors",function(){return[]})}var e3=100,zW;var Qk=w(()=>{iG();FW();zW=function(){function Q(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={}}return Q.clone=function(Z){var Y=new Q;if(Z)Y._breadcrumbs=UJ(Z._breadcrumbs),Y._tags=MQ({},Z._tags),Y._extra=MQ({},Z._extra),Y._contexts=MQ({},Z._contexts),Y._user=Z._user,Y._level=Z._level,Y._span=Z._span,Y._session=Z._session,Y._transactionName=Z._transactionName,Y._fingerprint=Z._fingerprint,Y._eventProcessors=UJ(Z._eventProcessors),Y._requestSession=Z._requestSession;return Y},Q.prototype.addScopeListener=function(Z){this._scopeListeners.push(Z)},Q.prototype.addEventProcessor=function(Z){return this._eventProcessors.push(Z),this},Q.prototype.setUser=function(Z){if(this._user=Z||{},this._session)this._session.update({user:Z});return this._notifyScopeListeners(),this},Q.prototype.getUser=function(){return this._user},Q.prototype.getRequestSession=function(){return this._requestSession},Q.prototype.setRequestSession=function(Z){return this._requestSession=Z,this},Q.prototype.setTags=function(Z){return this._tags=MQ(MQ({},this._tags),Z),this._notifyScopeListeners(),this},Q.prototype.setTag=function(Z,Y){var $;return this._tags=MQ(MQ({},this._tags),($={},$[Z]=Y,$)),this._notifyScopeListeners(),this},Q.prototype.setExtras=function(Z){return this._extra=MQ(MQ({},this._extra),Z),this._notifyScopeListeners(),this},Q.prototype.setExtra=function(Z,Y){var $;return this._extra=MQ(MQ({},this._extra),($={},$[Z]=Y,$)),this._notifyScopeListeners(),this},Q.prototype.setFingerprint=function(Z){return this._fingerprint=Z,this._notifyScopeListeners(),this},Q.prototype.setLevel=function(Z){return this._level=Z,this._notifyScopeListeners(),this},Q.prototype.setTransactionName=function(Z){return this._transactionName=Z,this._notifyScopeListeners(),this},Q.prototype.setTransaction=function(Z){return this.setTransactionName(Z)},Q.prototype.setContext=function(Z,Y){var $;if(Y===null)delete this._contexts[Z];else this._contexts=MQ(MQ({},this._contexts),($={},$[Z]=Y,$));return this._notifyScopeListeners(),this},Q.prototype.setSpan=function(Z){return this._span=Z,this._notifyScopeListeners(),this},Q.prototype.getSpan=function(){return this._span},Q.prototype.getTransaction=function(){var Z=this.getSpan();return Z&&Z.transaction},Q.prototype.setSession=function(Z){if(!Z)delete this._session;else this._session=Z;return this._notifyScopeListeners(),this},Q.prototype.getSession=function(){return this._session},Q.prototype.update=function(Z){if(!Z)return this;if(typeof Z==="function"){var Y=Z(this);return Y instanceof Q?Y:this}if(Z instanceof Q){if(this._tags=MQ(MQ({},this._tags),Z._tags),this._extra=MQ(MQ({},this._extra),Z._extra),this._contexts=MQ(MQ({},this._contexts),Z._contexts),Z._user&&Object.keys(Z._user).length)this._user=Z._user;if(Z._level)this._level=Z._level;if(Z._fingerprint)this._fingerprint=Z._fingerprint;if(Z._requestSession)this._requestSession=Z._requestSession}else if($W(Z)){if(Z=Z,this._tags=MQ(MQ({},this._tags),Z.tags),this._extra=MQ(MQ({},this._extra),Z.extra),this._contexts=MQ(MQ({},this._contexts),Z.contexts),Z.user)this._user=Z.user;if(Z.level)this._level=Z.level;if(Z.fingerprint)this._fingerprint=Z.fingerprint;if(Z.requestSession)this._requestSession=Z.requestSession}return this},Q.prototype.clear=function(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._span=void 0,this._session=void 0,this._notifyScopeListeners(),this},Q.prototype.addBreadcrumb=function(Z,Y){var $=typeof Y==="number"?Math.min(Y,e3):e3;if($<=0)return this;var J=MQ({timestamp:qW()},Z);return this._breadcrumbs=UJ(this._breadcrumbs,[J]).slice(-$),this._notifyScopeListeners(),this},Q.prototype.clearBreadcrumbs=function(){return this._breadcrumbs=[],this._notifyScopeListeners(),this},Q.prototype.applyToEvent=function(Z,Y){if(this._extra&&Object.keys(this._extra).length)Z.extra=MQ(MQ({},this._extra),Z.extra);if(this._tags&&Object.keys(this._tags).length)Z.tags=MQ(MQ({},this._tags),Z.tags);if(this._user&&Object.keys(this._user).length)Z.user=MQ(MQ({},this._user),Z.user);if(this._contexts&&Object.keys(this._contexts).length)Z.contexts=MQ(MQ({},this._contexts),Z.contexts);if(this._level)Z.level=this._level;if(this._transactionName)Z.transaction=this._transactionName;if(this._span){Z.contexts=MQ({trace:this._span.getTraceContext()},Z.contexts);var $=this._span.transaction&&this._span.transaction.name;if($)Z.tags=MQ({transaction:$},Z.tags)}return this._applyFingerprint(Z),Z.breadcrumbs=UJ(Z.breadcrumbs||[],this._breadcrumbs),Z.breadcrumbs=Z.breadcrumbs.length>0?Z.breadcrumbs:void 0,Z.sdkProcessingMetadata=this._sdkProcessingMetadata,this._notifyEventProcessors(UJ(si(),this._eventProcessors),Z,Y)},Q.prototype.setSDKProcessingMetadata=function(Z){return this._sdkProcessingMetadata=MQ(MQ({},this._sdkProcessingMetadata),Z),this},Q.prototype._notifyEventProcessors=function(Z,Y,$,J){var X=this;if(J===void 0)J=0;return new p3(function(G,W){var U=Z[J];if(Y===null||typeof U!=="function")G(Y);else{var K=U(MQ({},Y),$);if(JW(K))K.then(function(O){return X._notifyEventProcessors(Z,O,$,J+1).then(G)}).then(null,W);else X._notifyEventProcessors(Z,K,$,J+1).then(G).then(null,W)}})},Q.prototype._notifyScopeListeners=function(){var Z=this;if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach(function(Y){Y(Z)}),this._notifyingListeners=!1},Q.prototype._applyFingerprint=function(Z){if(Z.fingerprint=Z.fingerprint?Array.isArray(Z.fingerprint)?Z.fingerprint:[Z.fingerprint]:[],this._fingerprint)Z.fingerprint=Z.fingerprint.concat(this._fingerprint);if(Z.fingerprint&&!Z.fingerprint.length)delete Z.fingerprint},Q}()});var Zk;var Yk=w(()=>{FW();Zk=function(){function Q(Z){this.errors=0,this.sid=aG(),this.duration=0,this.status="ok",this.init=!0,this.ignoreDuration=!1;var Y=jH();if(this.timestamp=Y,this.started=Y,Z)this.update(Z)}return Q.prototype.update=function(Z){if(Z===void 0)Z={};if(Z.user){if(!this.ipAddress&&Z.user.ip_address)this.ipAddress=Z.user.ip_address;if(!this.did&&!Z.did)this.did=Z.user.id||Z.user.email||Z.user.username}if(this.timestamp=Z.timestamp||jH(),Z.ignoreDuration)this.ignoreDuration=Z.ignoreDuration;if(Z.sid)this.sid=Z.sid.length===32?Z.sid:aG();if(Z.init!==void 0)this.init=Z.init;if(!this.did&&Z.did)this.did=""+Z.did;if(typeof Z.started==="number")this.started=Z.started;if(this.ignoreDuration)this.duration=void 0;else if(typeof Z.duration==="number")this.duration=Z.duration;else{var Y=this.timestamp-this.started;this.duration=Y>=0?Y:0}if(Z.release)this.release=Z.release;if(Z.environment)this.environment=Z.environment;if(!this.ipAddress&&Z.ipAddress)this.ipAddress=Z.ipAddress;if(!this.userAgent&&Z.userAgent)this.userAgent=Z.userAgent;if(typeof Z.errors==="number")this.errors=Z.errors;if(Z.status)this.status=Z.status},Q.prototype.close=function(Z){if(Z)this.update({status:Z});else if(this.status==="ok")this.update({status:"exited"});else this.update()},Q.prototype.toJSON=function(){return XW({sid:""+this.sid,init:this.init,started:new Date(this.started*1000).toISOString(),timestamp:new Date(this.timestamp*1000).toISOString(),status:this.status,errors:this.errors,did:typeof this.did==="number"||typeof this.did==="string"?""+this.did:void 0,duration:this.duration,attrs:{release:this.release,environment:this.environment,ip_address:this.ipAddress,user_agent:this.userAgent}})},Q}()});function f6(){var Q=k$();return Q.__SENTRY__=Q.__SENTRY__||{extensions:{},hub:void 0},Q}function MH(Q){var Z=f6(),Y=y1(Z);return KW(Z,Q),Y}function NH(){var Q=f6();if(!$k(Q)||y1(Q).isOlderThan(TH))KW(Q,new WW);if(BV())return ai(Q);return y1(Q)}function ai(Q){try{var Z=f6().__SENTRY__,Y=Z&&Z.extensions&&Z.extensions.domain&&Z.extensions.domain.active;if(!Y)return y1(Q);if(!$k(Y)||y1(Y).isOlderThan(TH)){var $=y1(Q).getStackTop();KW(Y,new WW($.client,zW.clone($.scope)))}return y1(Y)}catch(J){return y1(Q)}}function $k(Q){return!!(Q&&Q.__SENTRY__&&Q.__SENTRY__.hub)}function y1(Q){return kV("hub",function(){return new WW},Q)}function KW(Q,Z){if(!Q)return!1;var Y=Q.__SENTRY__=Q.__SENTRY__||{};return Y.hub=Z,!0}var TH=4,ii=100,WW;var Jk=w(()=>{iG();FW();t3();Qk();Yk();WW=function(){function Q(Z,Y,$){if(Y===void 0)Y=new zW;if($===void 0)$=TH;if(this._version=$,this._stack=[{}],this.getStackTop().scope=Y,Z)this.bindClient(Z)}return Q.prototype.isOlderThan=function(Z){return this._version<Z},Q.prototype.bindClient=function(Z){var Y=this.getStackTop();if(Y.client=Z,Z&&Z.setupIntegrations)Z.setupIntegrations()},Q.prototype.pushScope=function(){var Z=zW.clone(this.getScope());return this.getStack().push({client:this.getClient(),scope:Z}),Z},Q.prototype.popScope=function(){if(this.getStack().length<=1)return!1;return!!this.getStack().pop()},Q.prototype.withScope=function(Z){var Y=this.pushScope();try{Z(Y)}finally{this.popScope()}},Q.prototype.getClient=function(){return this.getStackTop().client},Q.prototype.getScope=function(){return this.getStackTop().scope},Q.prototype.getStack=function(){return this._stack},Q.prototype.getStackTop=function(){return this._stack[this._stack.length-1]},Q.prototype.captureException=function(Z,Y){var $=this._lastEventId=Y&&Y.event_id?Y.event_id:aG(),J=Y;if(!Y){var X=void 0;try{throw Error("Sentry syntheticException")}catch(G){X=G}J={originalException:Z,syntheticException:X}}return this._invokeClient("captureException",Z,MQ(MQ({},J),{event_id:$})),$},Q.prototype.captureMessage=function(Z,Y,$){var J=this._lastEventId=$&&$.event_id?$.event_id:aG(),X=$;if(!$){var G=void 0;try{throw Error(Z)}catch(W){G=W}X={originalException:Z,syntheticException:G}}return this._invokeClient("captureMessage",Z,Y,MQ(MQ({},X),{event_id:J})),J},Q.prototype.captureEvent=function(Z,Y){var $=Y&&Y.event_id?Y.event_id:aG();if(Z.type!=="transaction")this._lastEventId=$;return this._invokeClient("captureEvent",Z,MQ(MQ({},Y),{event_id:$})),$},Q.prototype.lastEventId=function(){return this._lastEventId},Q.prototype.addBreadcrumb=function(Z,Y){var $=this.getStackTop(),J=$.scope,X=$.client;if(!J||!X)return;var G=X.getOptions&&X.getOptions()||{},W=G.beforeBreadcrumb,U=W===void 0?null:W,K=G.maxBreadcrumbs,O=K===void 0?ii:K;if(O<=0)return;var I=qW(),L=MQ({timestamp:I},Z),A=U?LH(function(){return U(L,Y)}):L;if(A===null)return;J.addBreadcrumb(A,O)},Q.prototype.setUser=function(Z){var Y=this.getScope();if(Y)Y.setUser(Z)},Q.prototype.setTags=function(Z){var Y=this.getScope();if(Y)Y.setTags(Z)},Q.prototype.setExtras=function(Z){var Y=this.getScope();if(Y)Y.setExtras(Z)},Q.prototype.setTag=function(Z,Y){var $=this.getScope();if($)$.setTag(Z,Y)},Q.prototype.setExtra=function(Z,Y){var $=this.getScope();if($)$.setExtra(Z,Y)},Q.prototype.setContext=function(Z,Y){var $=this.getScope();if($)$.setContext(Z,Y)},Q.prototype.configureScope=function(Z){var Y=this.getStackTop(),$=Y.scope,J=Y.client;if($&&J)Z($)},Q.prototype.run=function(Z){var Y=MH(this);try{Z(this)}finally{MH(Y)}},Q.prototype.getIntegration=function(Z){var Y=this.getClient();if(!Y)return null;try{return Y.getIntegration(Z)}catch($){return AH&&x6.warn("Cannot retrieve integration "+Z.id+" from the current Hub"),null}},Q.prototype.startSpan=function(Z){return this._callExtensionMethod("startSpan",Z)},Q.prototype.startTransaction=function(Z,Y){return this._callExtensionMethod("startTransaction",Z,Y)},Q.prototype.traceHeaders=function(){return this._callExtensionMethod("traceHeaders")},Q.prototype.captureSession=function(Z){if(Z===void 0)Z=!1;if(Z)return this.endSession();this._sendSessionUpdate()},Q.prototype.endSession=function(){var Z=this.getStackTop(),Y=Z&&Z.scope,$=Y&&Y.getSession();if($)$.close();if(this._sendSessionUpdate(),Y)Y.setSession()},Q.prototype.startSession=function(Z){var Y=this.getStackTop(),$=Y.scope,J=Y.client,X=J&&J.getOptions()||{},G=X.release,W=X.environment,U=k$(),K=(U.navigator||{}).userAgent,O=new Zk(MQ(MQ(MQ({release:G,environment:W},$&&{user:$.getUser()}),K&&{userAgent:K}),Z));if($){var I=$.getSession&&$.getSession();if(I&&I.status==="ok")I.update({status:"exited"});this.endSession(),$.setSession(O)}return O},Q.prototype._sendSessionUpdate=function(){var Z=this.getStackTop(),Y=Z.scope,$=Z.client;if(!Y)return;var J=Y.getSession&&Y.getSession();if(J){if($&&$.captureSession)$.captureSession(J)}},Q.prototype._invokeClient=function(Z){var Y,$=[];for(var J=1;J<arguments.length;J++)$[J-1]=arguments[J];var X=this.getStackTop(),G=X.scope,W=X.client;if(W&&W[Z])(Y=W)[Z].apply(Y,UJ($,[G]))},Q.prototype._callExtensionMethod=function(Z){var Y=[];for(var $=1;$<arguments.length;$++)Y[$-1]=arguments[$];var J=f6(),X=J.__SENTRY__;if(X&&X.extensions&&typeof X.extensions[Z]==="function")return X.extensions[Z].apply(this,Y);AH&&x6.warn("Extension method "+Z+" couldn't be found, doing nothing.")},Q}()});var Xk=w(()=>{Jk()});function ei(Q){var Z=[];for(var Y=1;Y<arguments.length;Y++)Z[Y-1]=arguments[Y];var $=NH();if($&&$[Q])return $[Q].apply($,UJ(Z));throw Error("No hub defined or "+Q+" was not found on the hub, please open a bug report.")}function rG(Q,Z){var Y=Error("Sentry syntheticException");return ei("captureException",Q,{captureContext:Z,originalException:Q,syntheticException:Y})}var BH=w(()=>{iG();Xk()});var qk=64,Fk=6000;var kH=()=>{};class CH{dependencies;apduSender;apduReceiver;sendApduPromiseResolver;logger;constructor({dependencies:Q,apduSenderFactory:Z,apduReceiverFactory:Y},$){let J=q0.of(N$.numberToByteArray(Math.floor(Math.random()*65535),2));this.logger=$("WebHidApduSender"),this.apduSender=Z({frameSize:qk,channel:J,padding:!0}),this.apduReceiver=Y({channel:J}),this.sendApduPromiseResolver=YQ,this.dependencies=Q,this.logger.info("\uD83D\uDD0C Connected to device")}async sendApdu(Q,Z,Y){let $,J=new Promise((X)=>{this.sendApduPromiseResolver=q0.of((...G)=>($&&clearTimeout($),X(...G)))});for(let X of this.apduSender.getFrames(Q))try{await this.dependencies.device.sendReport(0,new Uint8Array(X.getRawData()))}catch(G){return this.logger.info("Error sending frame",{data:{error:G}}),Promise.resolve(a(new QW(G)))}return this.logger.debug(kz(Q)),Y&&($=setTimeout(()=>{this.logger.debug("[sendApdu] Abort timeout",{data:{abortTimeout:Y}}),this.sendApduPromiseResolver.map((X)=>X(a(new QV("Abort timeout"))))},Y)),J}receiveHidInputReport(Q){let Z=new Uint8Array(Q.data.buffer);this.apduReceiver.handleFrame(Z).map((Y)=>{Y.map(($)=>{this.logger.debug(P6($)),this.sendApduPromiseResolver.map((J)=>J(U0($)))})}).mapLeft((Y)=>{this.sendApduPromiseResolver.map(($)=>$(a(Y)))})}getDependencies(){return this.dependencies}setDependencies(Q){this.dependencies=Q}async setupConnection(){try{this.dependencies.device.oninputreport=(Q)=>this.receiveHidInputReport(Q),await this.dependencies.device.open()}catch(Q){if(Q instanceof DOMException&&Q.name==="InvalidStateError")this.logger.info("Device is already opened");else{let Z=new fG(Q);throw this.logger.error("Error while opening device",{data:{error:Q}}),rG(Z),Q}}}closeConnection(){this.logger.info("\uD83D\uDD1A Disconnect"),this.dependencies.device.close().catch((Q)=>{this.logger.error("Error while closing device",{data:{device:this.dependencies.device,error:Q}})})}}var zk=w(()=>{I0();BH();R0();kH();ZW()});class UW{constructor(Q,Z,Y,$,J=(G)=>new _6(G),X=(G,W)=>new CH(G,W)){this._deviceModelDataSource=Q,this._loggerServiceFactory=Z,this._apduSenderFactory=Y,this._apduReceiverFactory=$,this._deviceConnectionStateMachineFactory=J,this._deviceApduSenderFactory=X,this._logger=Z("WebWebHidTransport"),this.startListeningToConnectionEvents()}_transportDiscoveredDevices=new g1.BehaviorSubject([]);_deviceConnectionsByHidDevice=new Map;_deviceConnectionsPendingReconnection=new Set;_connectionListenersAbortController=new AbortController;_logger;connectionType="USB";identifier=SH;get hidApi(){return this.isSupported()?U0(navigator.hid):a(new ez("WebHID not supported"))}isSupported(){try{let Q=!!navigator?.hid;return this._logger.debug(`isSupported: ${Q}`),Q}catch(Q){return this._logger.error("isSupported: error",{data:{error:Q}}),!1}}getIdentifier(){return this.identifier}async getDevices(){return EQ.liftEither(this.hidApi).map(async(Q)=>{try{return(await Q.getDevices()).filter((Z)=>Z.vendorId===kq)}catch(Z){let Y=new eX(Z);throw this._logger.error("getDevices: error getting devices",{data:{error:Z}}),rG(Y),Y}})}mapHIDDeviceToTransportDiscoveredDevice(Q){let Z=this._transportDiscoveredDevices.getValue().find(($)=>$.hidDevice===Q);if(Z)return Z;let Y=this._deviceConnectionsByHidDevice.get(Q);return this.getDeviceModel(Q).caseOf({Just:($)=>{let J=Y?.getDeviceId()??_J(),X={id:J,deviceModel:$,hidDevice:Q,transport:this.identifier};return this._logger.debug(`Discovered device ${J} ${X.deviceModel.productName}`),X},Nothing:()=>{throw this._logger.warn(`Device not recognized: hidDevice.productId: 0x${Q.productId.toString(16)}`),new w9(`Device not recognized: hidDevice.productId: 0x${Q.productId.toString(16)}`)}})}listenToAvailableDevices(){return this.updateTransportDiscoveredDevices(),this._transportDiscoveredDevices.pipe(g1.map((Q)=>Q.map(({hidDevice:Z,...Y})=>Y)))}async updateTransportDiscoveredDevices(){(await this.getDevices()).caseOf({Left:(Q)=>{this._logger.error("Error while getting accessible device",{data:{error:Q}}),rG(Q)},Right:(Q)=>{this._transportDiscoveredDevices.next(Q.map((Z)=>this.mapHIDDeviceToTransportDiscoveredDevice(Z)))}})}async promptDeviceAccess(){return EQ.liftEither(this.hidApi).map(async(Q)=>{let Z=[];try{Z=await Q.requestDevice({filters:[{vendorId:kq}]}),await this.updateTransportDiscoveredDevices()}catch($){let J=new eX($);throw this._logger.error("promptDeviceAccess: error requesting device",{data:{error:$}}),rG(J),J}if(this._logger.debug(`promptDeviceAccess: hidDevices len ${Z.length}`),Z.length===0)throw this._logger.warn("No device was selected"),new eX("No selected device");let Y=[];for(let $ of Z)Y.push($),this._logger.debug("promptDeviceAccess: selected device",{data:{hidDevice:$}});return Y}).run()}startDiscovering(){return this._logger.debug("startDiscovering"),g1.from(this.promptDeviceAccess()).pipe(g1.switchMap((Q)=>Q.caseOf({Left:(Z)=>{throw this._logger.error("Error while getting accessible device",{data:{error:Z}}),rG(Z),Z},Right:(Z)=>{this._logger.info(`Got access to ${Z.length} HID devices`);let Y=Z.map(($)=>this.mapHIDDeviceToTransportDiscoveredDevice($));return g1.from(Y)}})))}stopDiscovering(){}startListeningToConnectionEvents(){this._logger.debug("startListeningToConnectionEvents"),this.hidApi.map((Q)=>{Q.addEventListener("connect",(Z)=>this.handleDeviceConnectionEvent(Z),{signal:this._connectionListenersAbortController.signal}),Q.addEventListener("disconnect",(Z)=>this.handleDeviceDisconnectionEvent(Z),{signal:this._connectionListenersAbortController.signal})})}stopListeningToConnectionEvents(){this._logger.debug("stopListeningToConnectionEvents"),this._connectionListenersAbortController.abort()}async connect({deviceId:Q,onDisconnect:Z}){this._logger.debug("connect",{data:{deviceId:Q}});let Y=this._transportDiscoveredDevices.getValue().find((U)=>U.id===Q);if(!Y)return this._logger.error(`Unknown device ${Q}`),a(new nq(`Unknown device ${Q}`));let{deviceModel:$}=Y,J=this._deviceConnectionsByHidDevice.get(Y.hidDevice);if(J)return U0(new w8({id:Q,deviceModel:$,type:this.connectionType,sendApdu:(...U)=>J.sendApdu(...U),transport:this.identifier}));let X=this._deviceApduSenderFactory({apduSenderFactory:this._apduSenderFactory,apduReceiverFactory:this._apduReceiverFactory,dependencies:{device:Y.hidDevice}},this._loggerServiceFactory),G=this._deviceConnectionStateMachineFactory({deviceId:Q,deviceApduSender:X,timeoutDuration:Fk,tryToReconnect:()=>{this._deviceConnectionsByHidDevice.forEach((U,K)=>{U.getDeviceId()===Q&&(this._deviceConnectionsPendingReconnection.add(U),this._deviceConnectionsByHidDevice.delete(K))})},onTerminated:()=>{this._deviceConnectionsPendingReconnection.forEach((U)=>{U.getDeviceId()===Q&&(this._deviceConnectionsPendingReconnection.delete(U),Z(U.getDeviceId()))}),this._deviceConnectionsByHidDevice.forEach((U,K)=>{U.getDeviceId()===Q&&(this._deviceConnectionsByHidDevice.delete(K),Z(U.getDeviceId()))})}});try{await X.setupConnection()}catch(U){return U instanceof fG?a(U):a(new fG(U))}this._deviceConnectionsByHidDevice.set(Y.hidDevice,G);let W=new w8({sendApdu:(...U)=>G.sendApdu(...U),deviceModel:$,id:Q,type:this.connectionType,transport:this.identifier});return U0(W)}getDeviceModel(Q){let{productId:Z}=Q,Y=this._deviceModelDataSource.getAllDeviceModels().find(($)=>$.usbProductId===Z>>8||$.bootloaderUsbProductId===Z);return Y?q0.of(Y):q0.zero()}getHidUsbProductId(Q){return this.getDeviceModel(Q).caseOf({Just:(Z)=>Z.usbProductId,Nothing:()=>Q.productId>>8})}async disconnect(Q){this._logger.debug("disconnect",{data:{connectedDevice:Q}});let Z=Array.from(this._deviceConnectionsByHidDevice.values()).find((Y)=>Y.getDeviceId()===Q.connectedDevice.id);return Z?(Z.closeConnection(),Promise.resolve(U0(void 0))):(this._logger.error("No matching device connection found",{data:{connectedDevice:Q}}),Promise.resolve(a(new nq(`Unknown device ${Q.connectedDevice.id}`))))}isHIDConnectionEvent(Q){return"device"in Q&&typeof Q.device=="object"&&Q.device!==null&&"productId"in Q.device&&typeof Q.device.productId=="number"}async handleDeviceDisconnectionEvent(Q){if(!this.isHIDConnectionEvent(Q)){this._logger.error("Invalid event",{data:{event:Q}});return}this._logger.info("[handleDeviceDisconnectionEvent] Device disconnected",{data:{event:Q}}),this.updateTransportDiscoveredDevices();try{await Q.device.close()}catch(Y){this._logger.error("Error while closing device ",{data:{event:Q,error:Y}})}let Z=this._deviceConnectionsByHidDevice.get(Q.device);Z&&Z.eventDeviceDisconnected()}async handleDeviceReconnection(Q,Z){this._deviceConnectionsPendingReconnection.delete(Q),this._deviceConnectionsByHidDevice.set(Z,Q);try{Q.setDependencies({device:Z}),await Q.setupConnection(),Q.eventDeviceConnected()}catch(Y){this._logger.error("Error while reconnecting to device",{data:{event,error:Y}}),Q.closeConnection()}}async handleDeviceConnectionEvent(Q){if(!this.isHIDConnectionEvent(Q)){this._logger.error("Invalid event",{data:{event:Q}});return}this._logger.info("[handleDeviceConnectionEvent] Device connected",{data:{event:Q}});let Z=Array.from(this._deviceConnectionsPendingReconnection).find((Y)=>this.getHidUsbProductId(Y.getDependencies().device)===this.getHidUsbProductId(Q.device));Z&&await this.handleDeviceReconnection(Z,Q.device),this.updateTransportDiscoveredDevices()}destroy(){this.stopListeningToConnectionEvents(),this._deviceConnectionsByHidDevice.forEach((Q)=>{Q.closeConnection()}),this._deviceConnectionsPendingReconnection.clear()}}var g1,SH="WEB-HID",Wk=({deviceModelDataSource:Q,loggerServiceFactory:Z,apduSenderServiceFactory:Y,apduReceiverServiceFactory:$})=>new UW(Q,Z,Y,$);var Kk=w(()=>{I0();BH();R0();IV();kH();ZW();zk();g1=require("rxjs")});var Uk=w(()=>{Kk();ZW()});var Ok={};j$(Ok,{webHidTransportFactory:()=>Wk,webHidIdentifier:()=>SH,WebHidTransportNotSupportedError:()=>ez,WebHidTransport:()=>UW,WebHidSendReportError:()=>QW});var Hk=w(()=>{Uk()});function SV(Q){let Z=new Map;return function($){let J=Z.get($);if(J)return J;let X=Q($);return Z.set($,X),X}}var Pk={};j$(Pk,{LedgerJsDmkTransport:()=>Ek});class Lk{apdu;name="ledgerJsRawApdu";constructor(Q){this.apdu=Q}getApdu(){return this.apdu}parseResponse({data:Q,statusCode:Z}){if(Z.length!==Va)return o({error:new sY(Error("Ledger returned an invalid APDU status code"))});let Y=new Uint8Array(Q.length+Z.length);return Y.set(Q),Y.set(Z,Q.length),o({data:{response:Y}})}}function Fa(Q){if(Q.length<5)throw new x8.TransportError("Ledger APDU must contain a five-byte short-APDU header","InvalidAPDU");let Z=Q[4];if(Z===void 0||Q.length!==Z+5)throw new x8.TransportError("Ledger APDU payload length does not match its short-APDU header","InvalidAPDU");let Y=Q[0],$=Q[1],J=Q[2],X=Q[3];if(Y===void 0||$===void 0||J===void 0||X===void 0)throw new x8.TransportError("Ledger APDU header is incomplete","InvalidAPDU");return{cla:Y,data:Q.subarray(5),ins:$,p1:J,p2:X}}var x8,Va=2,qa,Ek;var jk=w(()=>{I0();x8=JZ(require("@ledgerhq/hw-transport")),qa=typeof x8.default==="function"?x8.default:x8.default.default;Ek=class Ek extends qa{internalApi;constructor(Q){super();this.internalApi=Q}async exchange(Q,{abortTimeoutMs:Z}={}){let{cla:Y,data:$,ins:J,p1:X,p2:G}=Fa(Q),W=new Lk(new PG(Y,J,X,G,$)),U=await this.internalApi.sendCommand(W,Z);if(!N0(U))throw U.error;return Buffer.from(U.data.response)}close(){return Promise.resolve()}}});var bk={};j$(bk,{signLegacyPsbtTransaction:()=>y6,extractInputsFromPsbt:()=>HW,createLegacyPsbtSigner:()=>Da});async function HW(Q,Z){let{RawTx:Y}=await import("@swapkit/utxo-signer"),{getUtxoApi:$}=await import("@swapkit/toolboxes/utxo"),J=$(Z),X=SV((G)=>J.getRawTx(G));return Promise.all(Array.from({length:Q.inputsLength},async(G,W)=>{let U=Q.getInput(W);if(!U.txid||U.index===void 0)throw Error(`PSBT input ${W} is missing txid/index`);let K=OW.hex.encode(U.txid),O=U.nonWitnessUtxo?OW.hex.encode(Y.encode(U.nonWitnessUtxo)):await X(K);if(!O)throw new hk.SwapKitError("wallet_ledger_invalid_params",{chain:Z,inputIndex:W,reason:"Unable to resolve previous transaction hex for Ledger signing",txid:K});let I=U.witnessUtxo?{script:U.witnessUtxo.script,value:Number(U.witnessUtxo.amount)}:void 0,L=U.nonWitnessUtxo?.outputs?.[U.index],A=I?.value??(L?Number(L.amount):0);return{hash:K,index:U.index,txHex:O,value:A,witnessUtxo:I}}))}async function y6({chain:Q,inputUtxos:Z,legacyClient:Y,tx:$}){let J=Z??await HW($,Q);return Y.signTransaction($,J)}function Da({legacyClient:Q,chain:Z,address:Y}){return{getAddress:async()=>Y,signTransaction:async($)=>{let J=await y6({chain:Z,legacyClient:Q,tx:$}),{Transaction:X}=await import("@swapkit/utxo-signer");return X.fromRaw(OW.hex.decode(J),{allowUnknownOutputs:!0})}}}var OW,hk;var gH=w(()=>{OW=require("@scure/base"),hk=require("@swapkit/helpers")});var Z$;var hH=w(()=>{Z$={GetExtendedPublicKeyUseCase:Symbol.for("GetExtendedPublicKeyUseCase"),GetMasterFingerprintUseCase:Symbol.for("GetMasterFingerprintUseCase"),RegisterWalletUseCase:Symbol.for("RegisterWalletUseCase"),SignMessageUseCase:Symbol.for("SignMessageUseCase"),SignPsbtUseCase:Symbol.for("SignPsbtUseCase"),SignTransactionUseCase:Symbol.for("SignTransactionUseCase"),GetWalletAddressUseCase:Symbol.for("GetWalletAddressUseCase")}});var DW;var bH=w(()=>{DW={DataStoreService:Symbol.for("DataStoreService")}});var Y$;var tG=w(()=>{Y$={HasherService:Symbol.for("HasherService"),MerkleTreeBuilder:Symbol.for("MerkleTreeBuilder"),MerkleMapBuilder:Symbol.for("MerkleMapBuilder")}});var f8;var IW=w(()=>{f8={WalletBuilder:Symbol.for("WalletBuilder"),WalletSerializer:Symbol.for("WalletSerializer")}});var Ia,Ra,La=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ra(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ia(Z,Y,J),J},RW=(Q,Z)=>(Y,$)=>Z(Y,$,Q),LW=class{constructor(Q,Z,Y,$){this.merkleTreeBuilder=Q,this.merkleMapBuilder=Z,this.walletSerializer=Y,this.hasher=$}merklizeChunks(Q,Z){let Y=this.merkleTreeBuilder.build(Z);return Q.addMerkleTree(Y),Y.getRoot()}merklizeWallet(Q,Z){let Y=this.walletSerializer.serialize(Z);Q.addPreimage(this.hasher.hash(Y),Y),Q.addPreimage(this.hasher.hash(Z.descriptorBuffer),Z.descriptorBuffer),Q.addMerkleTree(Z.keysTree)}merklizePsbt(Q,Z){let Y=this.merklizePsbtMap(Z.globalMap).map((X)=>(Q.addMerkleMap(X),X.getCommitment())),$=Z.inputMaps.reduce((X,G)=>{let W=this.merklizePsbtMap(G);return X.chain((U)=>W.map((K)=>(Q.addMerkleMap(K),[...U,K.getCommitment()])))},U0([])),J=Z.outputMaps.reduce((X,G)=>{let W=this.merklizePsbtMap(G);return X.chain((U)=>W.map((K)=>(Q.addMerkleMap(K),[...U,K.getCommitment()])))},U0([]));return Y.chain((X)=>$.chain((G)=>J.map((W)=>{let U=this.merkleTreeBuilder.build(G),K=this.merkleTreeBuilder.build(W);return Q.addMerkleTree(U),Q.addMerkleTree(K),{globalCommitment:X,inputsRoot:U.getRoot(),outputsRoot:K.getRoot()}})))}merklizePsbtMap(Q){let Z=new Map(Array.from(Q.entries()).sort((J,X)=>J[0].localeCompare(X[0]))),Y=Array.from(Z.keys()).map((J)=>mQ(J)),$=Array.from(Z.values()).map((J)=>J.data);return this.merkleMapBuilder.build(Y,$)}};var ck=w(()=>{I0();W0();R0();tG();IW();Ia=Object.defineProperty,Ra=Object.getOwnPropertyDescriptor;LW=La([e(),RW(0,g(Y$.MerkleTreeBuilder)),RW(1,g(Y$.MerkleMapBuilder)),RW(2,g(f8.WalletSerializer)),RW(3,g(Y$.HasherService))],LW)});var uk=()=>new b0(({bind:Q})=>{Q(DW.DataStoreService).to(LW)});var pk=w(()=>{W0();bH();ck()});var y8;var cH=w(()=>{y8={Dmk:Symbol.for("Dmk"),SessionId:Symbol.for("SessionId"),DmkLoggerFactory:Symbol.for("DmkLoggerFactory")}});function C$(Q){let Z=Q.extract8BitUInt();return Z===void 0?YQ:Z<=252?HQ({value:Z,sizeInBytes:1}):Z===253?q0.fromNullable(Q.extract16BitUInt(!1)).map((Y)=>({value:Y,sizeInBytes:3})):Z===254?q0.fromNullable(Q.extract32BitUInt(!1)).map((Y)=>({value:Y,sizeInBytes:5})):q0.fromNullable(Q.extract64BitUInt(!1)).chain((Y)=>Y>Number.MAX_SAFE_INTEGER?YQ:HQ({value:Number(Y),sizeInBytes:9}))}function UZ(Q){let Z=new WQ;return Q<=252?Z.add8BitUIntToData(Q):Q<=65535?(Z.add8BitUIntToData(253),Z.add16BitUIntToData(Q,!1)):Q<=4294967295?(Z.add8BitUIntToData(254),Z.add32BitUIntToData(Q,!1)):(Z.add8BitUIntToData(255),Z.add64BitUIntToData(Q,!1)),q0.fromNullable(Z.tryBuild())}var H$=w(()=>{I0();R0()});class uH{constructor(Q,Z){this.keys=Q,this.values=Z}getCommitment(){let Q=UZ(this.keys.size()).unsafeCoerce();return Uint8Array.from([...Q,...this.keys.getRoot(),...this.values.getRoot()])}}var lk=w(()=>{H$()});var Ea,Pa,ja=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Pa(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ea(Z,Y,J),J},Aa=(Q,Z)=>(Y,$)=>Z(Y,$,Q),EW=class{constructor(Q){this.merkleTreeBuilder=Q}build(Q,Z){if(Q.length!=Z.length)return a(Error("Keys and values should have the same length"));for(let J=0;J<Q.length-1;J++)if(DQ(Q[J])>=DQ(Q[J+1]))return a(Error("Keys should be sorted and distinct"));let Y=this.merkleTreeBuilder.build(Q),$=this.merkleTreeBuilder.build(Z);return U0(new uH(Y,$))}};var mk=w(()=>{I0();W0();R0();tG();lk();Ea=Object.defineProperty,Pa=Object.getOwnPropertyDescriptor;EW=ja([e(),Aa(0,g(Y$.MerkleTreeBuilder))],EW)});class PW{constructor(Q,Z){this.value=Q,this.hash=Z}parent=YQ}var dk=w(()=>{R0()});class pH{constructor(Q,Z){this.root=Q,this.leaves=Z}getRoot(){return this.root.hash}size(){return this.leaves.length}getLeaves(){return this.leaves}getLeafHash(Q){return q0.fromNullable(this.leaves[Q]?.hash)}getProof(Q){return q0.fromNullable(this.leaves[Q]).map((Z)=>this.proveNode(Z))}proveNode(Q){return Q.parent.caseOf({Just:(Z)=>Z.leftChild===Q?[Z.rightChild.hash,...this.proveNode(Z)]:[Z.leftChild.hash,...this.proveNode(Z)],Nothing:()=>[]})}}var nk=w(()=>{R0()});class lH{constructor(Q,Z,Y){this.leftChild=Q,this.rightChild=Z,this.hash=Y}parent=YQ}var ok=w(()=>{R0()});var Ma,Ta,Na=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Ta(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Ma(Z,Y,J),J},Ba=(Q,Z)=>(Y,$)=>Z(Y,$,Q),ka=0,Ca=1,jW=class{constructor(Q){this.hasher=Q}build(Q){Q=Q.map((Y)=>Uint8Array.from([ka,...Y]));let Z=this.buildTree(Q.map((Y)=>new PW(Y,this.hasher.hash(Y))));return new pH(Z.root,Z.leaves)}buildTree(Q){if(Q.length==0)return{root:new PW(new Uint8Array,Uint8Array.from(Array(32).fill(0))),leaves:[]};if(Q.length==1)return{root:Q[0],leaves:Q};let Z=this.highestPowerOf2LessThan(Q.length),Y=this.buildTree(Q.slice(0,Z)),$=this.buildTree(Q.slice(Z)),J=Y.root,X=$.root,G=this.hasher.hash(Uint8Array.from([Ca,...J.hash,...X.hash])),W=new lH(J,X,G);return J.parent=HQ(W),X.parent=HQ(W),{root:W,leaves:[...Y.leaves,...$.leaves]}}highestPowerOf2LessThan(Q){if(Q<2)throw Error("Expected n >= 2");return this.isPowerOf2(Q)?Q/2:1<<Math.floor(Math.log2(Q))}isPowerOf2(Q){return(Q&Q-1)===0}};var sk=w(()=>{W0();R0();tG();dk();nk();ok();Ma=Object.defineProperty,Ta=Object.getOwnPropertyDescriptor;jW=Na([e(),Ba(0,g(Y$.HasherService))],jW)});var _Y={};j$(_Y,{transcode:()=>Or,resolveObjectURL:()=>Wr,kStringMaxLength:()=>$C,kMaxLength:()=>g6,isUtf8:()=>Kr,isAscii:()=>Ur,default:()=>Hr,constants:()=>ba,btoa:()=>fa,atob:()=>ya,INSPECT_MAX_BYTES:()=>YC,File:()=>ga,Buffer:()=>p0,Blob:()=>ha});function Sa(Q){var Z=Q.length;if(Z%4>0)throw Error("Invalid string. Length must be a multiple of 4");var Y=Q.indexOf("=");if(Y===-1)Y=Z;var $=Y===Z?0:4-Y%4;return[Y,$]}function wa(Q,Z){return(Q+Z)*3/4-Z}function _a(Q){var Z,Y=Sa(Q),$=Y[0],J=Y[1],X=new Uint8Array(wa($,J)),G=0,W=J>0?$-4:$,U;for(U=0;U<W;U+=4)Z=HJ[Q.charCodeAt(U)]<<18|HJ[Q.charCodeAt(U+1)]<<12|HJ[Q.charCodeAt(U+2)]<<6|HJ[Q.charCodeAt(U+3)],X[G++]=Z>>16&255,X[G++]=Z>>8&255,X[G++]=Z&255;if(J===2)Z=HJ[Q.charCodeAt(U)]<<2|HJ[Q.charCodeAt(U+1)]>>4,X[G++]=Z&255;if(J===1)Z=HJ[Q.charCodeAt(U)]<<10|HJ[Q.charCodeAt(U+1)]<<4|HJ[Q.charCodeAt(U+2)]>>2,X[G++]=Z>>8&255,X[G++]=Z&255;return X}function va(Q){return G1[Q>>18&63]+G1[Q>>12&63]+G1[Q>>6&63]+G1[Q&63]}function xa(Q,Z,Y){var $,J=[];for(var X=Z;X<Y;X+=3)$=(Q[X]<<16&16711680)+(Q[X+1]<<8&65280)+(Q[X+2]&255),J.push(va($));return J.join("")}function ak(Q){var Z,Y=Q.length,$=Y%3,J=[],X=16383;for(var G=0,W=Y-$;G<W;G+=X)J.push(xa(Q,G,G+X>W?W:G+X));if($===1)Z=Q[Y-1],J.push(G1[Z>>2]+G1[Z<<4&63]+"==");else if($===2)Z=(Q[Y-2]<<8)+Q[Y-1],J.push(G1[Z>>10]+G1[Z>>4&63]+G1[Z<<2&63]+"=");return J.join("")}function AW(Q,Z,Y,$,J){var X,G,W=J*8-$-1,U=(1<<W)-1,K=U>>1,O=-7,I=Y?J-1:0,L=Y?-1:1,A=Q[Z+I];I+=L,X=A&(1<<-O)-1,A>>=-O,O+=W;for(;O>0;X=X*256+Q[Z+I],I+=L,O-=8);G=X&(1<<-O)-1,X>>=-O,O+=$;for(;O>0;G=G*256+Q[Z+I],I+=L,O-=8);if(X===0)X=1-K;else if(X===U)return G?NaN:(A?-1:1)*(1/0);else G=G+Math.pow(2,$),X=X-K;return(A?-1:1)*G*Math.pow(2,X-$)}function ZC(Q,Z,Y,$,J,X){var G,W,U,K=X*8-J-1,O=(1<<K)-1,I=O>>1,L=J===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=$?0:X-1,M=$?1:-1,k=Z<0||Z===0&&1/Z<0?1:0;if(Z=Math.abs(Z),isNaN(Z)||Z===1/0)W=isNaN(Z)?1:0,G=O;else{if(G=Math.floor(Math.log(Z)/Math.LN2),Z*(U=Math.pow(2,-G))<1)G--,U*=2;if(G+I>=1)Z+=L/U;else Z+=L*Math.pow(2,1-I);if(Z*U>=2)G++,U/=2;if(G+I>=O)W=0,G=O;else if(G+I>=1)W=(Z*U-1)*Math.pow(2,J),G=G+I;else W=Z*Math.pow(2,I-1)*Math.pow(2,J),G=0}for(;J>=8;Q[Y+A]=W&255,A+=M,W/=256,J-=8);G=G<<J|W,K+=J;for(;K>0;Q[Y+A]=G&255,A+=M,G/=256,K-=8);Q[Y+A-M]|=k*128}function u1(Q){if(Q>g6)throw RangeError('The value "'+Q+'" is invalid for option "size"');let Z=new Uint8Array(Q);return Object.setPrototypeOf(Z,p0.prototype),Z}function iH(Q,Z,Y){return class extends Y{constructor(){super();Object.defineProperty(this,"message",{value:Z.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${Q}]`,this.stack,delete this.name}get code(){return Q}set code($){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:$,writable:!0})}toString(){return`${this.name} [${Q}]: ${this.message}`}}}function p0(Q,Z,Y){if(typeof Q==="number"){if(typeof Z==="string")throw TypeError('The "string" argument must be of type string. Received type number');return aH(Q)}return JC(Q,Z,Y)}function JC(Q,Z,Y){if(typeof Q==="string")return la(Q,Z);if(ArrayBuffer.isView(Q))return ma(Q);if(Q==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Q);if(X1(Q,ArrayBuffer)||Q&&X1(Q.buffer,ArrayBuffer))return oH(Q,Z,Y);if(typeof SharedArrayBuffer<"u"&&(X1(Q,SharedArrayBuffer)||Q&&X1(Q.buffer,SharedArrayBuffer)))return oH(Q,Z,Y);if(typeof Q==="number")throw TypeError('The "value" argument must not be of type number. Received type number');let $=Q.valueOf&&Q.valueOf();if($!=null&&$!==Q)return p0.from($,Z,Y);let J=da(Q);if(J)return J;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof Q[Symbol.toPrimitive]==="function")return p0.from(Q[Symbol.toPrimitive]("string"),Z,Y);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Q)}function GC(Q){if(typeof Q!=="number")throw TypeError('"size" argument must be of type number');else if(Q<0)throw RangeError('The value "'+Q+'" is invalid for option "size"')}function pa(Q,Z,Y){if(GC(Q),Q<=0)return u1(Q);if(Z!==void 0)return typeof Y==="string"?u1(Q).fill(Z,Y):u1(Q).fill(Z);return u1(Q)}function aH(Q){return GC(Q),u1(Q<0?0:rH(Q)|0)}function la(Q,Z){if(typeof Z!=="string"||Z==="")Z="utf8";if(!p0.isEncoding(Z))throw TypeError("Unknown encoding: "+Z);let Y=XC(Q,Z)|0,$=u1(Y),J=$.write(Q,Z);if(J!==Y)$=$.slice(0,J);return $}function nH(Q){let Z=Q.length<0?0:rH(Q.length)|0,Y=u1(Z);for(let $=0;$<Z;$+=1)Y[$]=Q[$]&255;return Y}function ma(Q){if(X1(Q,Uint8Array)){let Z=new Uint8Array(Q);return oH(Z.buffer,Z.byteOffset,Z.byteLength)}return nH(Q)}function oH(Q,Z,Y){if(Z<0||Q.byteLength<Z)throw RangeError('"offset" is outside of buffer bounds');if(Q.byteLength<Z+(Y||0))throw RangeError('"length" is outside of buffer bounds');let $;if(Z===void 0&&Y===void 0)$=new Uint8Array(Q);else if(Y===void 0)$=new Uint8Array(Q,Z);else $=new Uint8Array(Q,Z,Y);return Object.setPrototypeOf($,p0.prototype),$}function da(Q){if(p0.isBuffer(Q)){let Z=rH(Q.length)|0,Y=u1(Z);if(Y.length===0)return Y;return Q.copy(Y,0,0,Z),Y}if(Q.length!==void 0){if(typeof Q.length!=="number"||Number.isNaN(Q.length))return u1(0);return nH(Q)}if(Q.type==="Buffer"&&Array.isArray(Q.data))return nH(Q.data)}function rH(Q){if(Q>=g6)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+g6.toString(16)+" bytes");return Q|0}function XC(Q,Z){if(p0.isBuffer(Q))return Q.length;if(ArrayBuffer.isView(Q)||X1(Q,ArrayBuffer))return Q.byteLength;if(typeof Q!=="string")throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof Q);let Y=Q.length,$=arguments.length>2&&arguments[2]===!0;if(!$&&Y===0)return 0;let J=!1;for(;;)switch(Z){case"ascii":case"latin1":case"binary":return Y;case"utf8":case"utf-8":return sH(Q).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y*2;case"hex":return Y>>>1;case"base64":return HC(Q).length;default:if(J)return $?-1:sH(Q).length;Z=(""+Z).toLowerCase(),J=!0}}function na(Q,Z,Y){let $=!1;if(Z===void 0||Z<0)Z=0;if(Z>this.length)return"";if(Y===void 0||Y>this.length)Y=this.length;if(Y<=0)return"";if(Y>>>=0,Z>>>=0,Y<=Z)return"";if(!Q)Q="utf8";while(!0)switch(Q){case"hex":return Yr(this,Z,Y);case"utf8":case"utf-8":return qC(this,Z,Y);case"ascii":return Qr(this,Z,Y);case"latin1":case"binary":return Zr(this,Z,Y);case"base64":return ta(this,Z,Y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return $r(this,Z,Y);default:if($)throw TypeError("Unknown encoding: "+Q);Q=(Q+"").toLowerCase(),$=!0}}function QX(Q,Z,Y){let $=Q[Z];Q[Z]=Q[Y],Q[Y]=$}function VC(Q,Z,Y,$,J){if(Q.length===0)return-1;if(typeof Y==="string")$=Y,Y=0;else if(Y>2147483647)Y=2147483647;else if(Y<-2147483648)Y=-2147483648;if(Y=+Y,Number.isNaN(Y))Y=J?0:Q.length-1;if(Y<0)Y=Q.length+Y;if(Y>=Q.length)if(J)return-1;else Y=Q.length-1;else if(Y<0)if(J)Y=0;else return-1;if(typeof Z==="string")Z=p0.from(Z,$);if(p0.isBuffer(Z)){if(Z.length===0)return-1;return tk(Q,Z,Y,$,J)}else if(typeof Z==="number"){if(Z=Z&255,typeof Uint8Array.prototype.indexOf==="function")if(J)return Uint8Array.prototype.indexOf.call(Q,Z,Y);else return Uint8Array.prototype.lastIndexOf.call(Q,Z,Y);return tk(Q,[Z],Y,$,J)}throw TypeError("val must be string, number or Buffer")}function tk(Q,Z,Y,$,J){let X=1,G=Q.length,W=Z.length;if($!==void 0){if($=String($).toLowerCase(),$==="ucs2"||$==="ucs-2"||$==="utf16le"||$==="utf-16le"){if(Q.length<2||Z.length<2)return-1;X=2,G/=2,W/=2,Y/=2}}function U(O,I){if(X===1)return O[I];else return O.readUInt16BE(I*X)}let K;if(J){let O=-1;for(K=Y;K<G;K++)if(U(Q,K)===U(Z,O===-1?0:K-O)){if(O===-1)O=K;if(K-O+1===W)return O*X}else{if(O!==-1)K-=K-O;O=-1}}else{if(Y+W>G)Y=G-W;for(K=Y;K>=0;K--){let O=!0;for(let I=0;I<W;I++)if(U(Q,K+I)!==U(Z,I)){O=!1;break}if(O)return K}}return-1}function oa(Q,Z,Y,$){Y=Number(Y)||0;let J=Q.length-Y;if(!$)$=J;else if($=Number($),$>J)$=J;let X=Z.length;if($>X/2)$=X/2;let G;for(G=0;G<$;++G){let W=parseInt(Z.substr(G*2,2),16);if(Number.isNaN(W))return G;Q[Y+G]=W}return G}function sa(Q,Z,Y,$){return MW(sH(Z,Q.length-Y),Q,Y,$)}function ia(Q,Z,Y,$){return MW(Vr(Z),Q,Y,$)}function aa(Q,Z,Y,$){return MW(HC(Z),Q,Y,$)}function ra(Q,Z,Y,$){return MW(qr(Z,Q.length-Y),Q,Y,$)}function ta(Q,Z,Y){if(Z===0&&Y===Q.length)return ak(Q);else return ak(Q.slice(Z,Y))}function qC(Q,Z,Y){Y=Math.min(Q.length,Y);let $=[],J=Z;while(J<Y){let X=Q[J],G=null,W=X>239?4:X>223?3:X>191?2:1;if(J+W<=Y){let U,K,O,I;switch(W){case 1:if(X<128)G=X;break;case 2:if(U=Q[J+1],(U&192)===128){if(I=(X&31)<<6|U&63,I>127)G=I}break;case 3:if(U=Q[J+1],K=Q[J+2],(U&192)===128&&(K&192)===128){if(I=(X&15)<<12|(U&63)<<6|K&63,I>2047&&(I<55296||I>57343))G=I}break;case 4:if(U=Q[J+1],K=Q[J+2],O=Q[J+3],(U&192)===128&&(K&192)===128&&(O&192)===128){if(I=(X&15)<<18|(U&63)<<12|(K&63)<<6|O&63,I>65535&&I<1114112)G=I}}}if(G===null)G=65533,W=1;else if(G>65535)G-=65536,$.push(G>>>10&1023|55296),G=56320|G&1023;$.push(G),J+=W}return ea($)}function ea(Q){let Z=Q.length;if(Z<=ek)return String.fromCharCode.apply(String,Q);let Y="",$=0;while($<Z)Y+=String.fromCharCode.apply(String,Q.slice($,$+=ek));return Y}function Qr(Q,Z,Y){let $="";Y=Math.min(Q.length,Y);for(let J=Z;J<Y;++J)$+=String.fromCharCode(Q[J]&127);return $}function Zr(Q,Z,Y){let $="";Y=Math.min(Q.length,Y);for(let J=Z;J<Y;++J)$+=String.fromCharCode(Q[J]);return $}function Yr(Q,Z,Y){let $=Q.length;if(!Z||Z<0)Z=0;if(!Y||Y<0||Y>$)Y=$;let J="";for(let X=Z;X<Y;++X)J+=Fr[Q[X]];return J}function $r(Q,Z,Y){let $=Q.slice(Z,Y),J="";for(let X=0;X<$.length-1;X+=2)J+=String.fromCharCode($[X]+$[X+1]*256);return J}function wY(Q,Z,Y){if(Q%1!==0||Q<0)throw RangeError("offset is not uint");if(Q+Z>Y)throw RangeError("Trying to access beyond buffer length")}function S$(Q,Z,Y,$,J,X){if(!p0.isBuffer(Q))throw TypeError('"buffer" argument must be a Buffer instance');if(Z>J||Z<X)throw RangeError('"value" argument is out of bounds');if(Y+$>Q.length)throw RangeError("Index out of range")}function FC(Q,Z,Y,$,J){OC(Z,$,J,Q,Y,7);let X=Number(Z&BigInt(4294967295));Q[Y++]=X,X=X>>8,Q[Y++]=X,X=X>>8,Q[Y++]=X,X=X>>8,Q[Y++]=X;let G=Number(Z>>BigInt(32)&BigInt(4294967295));return Q[Y++]=G,G=G>>8,Q[Y++]=G,G=G>>8,Q[Y++]=G,G=G>>8,Q[Y++]=G,Y}function zC(Q,Z,Y,$,J){OC(Z,$,J,Q,Y,7);let X=Number(Z&BigInt(4294967295));Q[Y+7]=X,X=X>>8,Q[Y+6]=X,X=X>>8,Q[Y+5]=X,X=X>>8,Q[Y+4]=X;let G=Number(Z>>BigInt(32)&BigInt(4294967295));return Q[Y+3]=G,G=G>>8,Q[Y+2]=G,G=G>>8,Q[Y+1]=G,G=G>>8,Q[Y]=G,Y+8}function WC(Q,Z,Y,$,J,X){if(Y+$>Q.length)throw RangeError("Index out of range");if(Y<0)throw RangeError("Index out of range")}function KC(Q,Z,Y,$,J){if(Z=+Z,Y=Y>>>0,!J)WC(Q,Z,Y,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return ZC(Q,Z,Y,$,23,4),Y+4}function UC(Q,Z,Y,$,J){if(Z=+Z,Y=Y>>>0,!J)WC(Q,Z,Y,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return ZC(Q,Z,Y,$,52,8),Y+8}function QC(Q){let Z="",Y=Q.length,$=Q[0]==="-"?1:0;for(;Y>=$+4;Y-=3)Z=`_${Q.slice(Y-3,Y)}${Z}`;return`${Q.slice(0,Y)}${Z}`}function Jr(Q,Z,Y){if(_V(Z,"offset"),Q[Z]===void 0||Q[Z+Y]===void 0)h6(Z,Q.length-(Y+1))}function OC(Q,Z,Y,$,J,X){if(Q>Y||Q<Z){let G=typeof Z==="bigint"?"n":"",W;if(X>3)if(Z===0||Z===BigInt(0))W=`>= 0${G} and < 2${G} ** ${(X+1)*8}${G}`;else W=`>= -(2${G} ** ${(X+1)*8-1}${G}) and < 2 ** ${(X+1)*8-1}${G}`;else W=`>= ${Z}${G} and <= ${Y}${G}`;throw new dH("value",W,Q)}Jr($,J,X)}function _V(Q,Z){if(typeof Q!=="number")throw new ua(Z,"number",Q)}function h6(Q,Z,Y){if(Math.floor(Q)!==Q)throw _V(Q,Y),new dH(Y||"offset","an integer",Q);if(Z<0)throw new ca;throw new dH(Y||"offset",`>= ${Y?1:0} and <= ${Z}`,Q)}function Xr(Q){if(Q=Q.split("=")[0],Q=Q.trim().replace(Gr,""),Q.length<2)return"";while(Q.length%4!==0)Q=Q+"=";return Q}function sH(Q,Z){Z=Z||1/0;let Y,$=Q.length,J=null,X=[];for(let G=0;G<$;++G){if(Y=Q.charCodeAt(G),Y>55295&&Y<57344){if(!J){if(Y>56319){if((Z-=3)>-1)X.push(239,191,189);continue}else if(G+1===$){if((Z-=3)>-1)X.push(239,191,189);continue}J=Y;continue}if(Y<56320){if((Z-=3)>-1)X.push(239,191,189);J=Y;continue}Y=(J-55296<<10|Y-56320)+65536}else if(J){if((Z-=3)>-1)X.push(239,191,189)}if(J=null,Y<128){if((Z-=1)<0)break;X.push(Y)}else if(Y<2048){if((Z-=2)<0)break;X.push(Y>>6|192,Y&63|128)}else if(Y<65536){if((Z-=3)<0)break;X.push(Y>>12|224,Y>>6&63|128,Y&63|128)}else if(Y<1114112){if((Z-=4)<0)break;X.push(Y>>18|240,Y>>12&63|128,Y>>6&63|128,Y&63|128)}else throw Error("Invalid code point")}return X}function Vr(Q){let Z=[];for(let Y=0;Y<Q.length;++Y)Z.push(Q.charCodeAt(Y)&255);return Z}function qr(Q,Z){let Y,$,J,X=[];for(let G=0;G<Q.length;++G){if((Z-=2)<0)break;Y=Q.charCodeAt(G),$=Y>>8,J=Y%256,X.push(J),X.push($)}return X}function HC(Q){return _a(Xr(Q))}function MW(Q,Z,Y,$){let J;for(J=0;J<$;++J){if(J+Y>=Z.length||J>=Q.length)break;Z[J+Y]=Q[J]}return J}function X1(Q,Z){return Q instanceof Z||Q!=null&&Q.constructor!=null&&Q.constructor.name!=null&&Q.constructor.name===Z.name}function g8(Q){return typeof BigInt>"u"?zr:Q}function zr(){throw Error("BigInt not supported")}function tH(Q){return()=>{throw Error(Q+" is not implemented for node:buffer browser polyfill")}}var G1,HJ,mH="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",eG,ik,rk,YC=50,g6=2147483647,$C=536870888,fa,ya,ga,ha,ba,ca,ua,dH,ek=4096,Gr,Fr,Wr,Kr,Ur=(Q)=>{for(let Z of Q)if(Z.charCodeAt(0)>127)return!1;return!0},Or,Hr;var vY=w(()=>{G1=[],HJ=[];for(eG=0,ik=mH.length;eG<ik;++eG)G1[eG]=mH[eG],HJ[mH.charCodeAt(eG)]=eG;HJ[45]=62;HJ[95]=63;rk=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null,fa=globalThis.btoa,ya=globalThis.atob,ga=globalThis.File,ha=globalThis.Blob,ba={MAX_LENGTH:g6,MAX_STRING_LENGTH:$C};ca=iH("ERR_BUFFER_OUT_OF_BOUNDS",function(Q){if(Q)return`${Q} is outside of buffer bounds`;return"Attempt to access memory outside buffer bounds"},RangeError),ua=iH("ERR_INVALID_ARG_TYPE",function(Q,Z){return`The "${Q}" argument must be of type number. Received type ${typeof Z}`},TypeError),dH=iH("ERR_OUT_OF_RANGE",function(Q,Z,Y){let $=`The value of "${Q}" is out of range.`,J=Y;if(Number.isInteger(Y)&&Math.abs(Y)>4294967296)J=QC(String(Y));else if(typeof Y==="bigint"){if(J=String(Y),Y>BigInt(2)**BigInt(32)||Y<-(BigInt(2)**BigInt(32)))J=QC(J);J+="n"}return $+=` It must be ${Z}. Received ${J}`,$},RangeError);Object.defineProperty(p0.prototype,"parent",{enumerable:!0,get:function(){if(!p0.isBuffer(this))return;return this.buffer}});Object.defineProperty(p0.prototype,"offset",{enumerable:!0,get:function(){if(!p0.isBuffer(this))return;return this.byteOffset}});p0.poolSize=8192;p0.from=function(Q,Z,Y){return JC(Q,Z,Y)};Object.setPrototypeOf(p0.prototype,Uint8Array.prototype);Object.setPrototypeOf(p0,Uint8Array);p0.alloc=function(Q,Z,Y){return pa(Q,Z,Y)};p0.allocUnsafe=function(Q){return aH(Q)};p0.allocUnsafeSlow=function(Q){return aH(Q)};p0.isBuffer=function(Q){return Q!=null&&Q._isBuffer===!0&&Q!==p0.prototype};p0.compare=function(Q,Z){if(X1(Q,Uint8Array))Q=p0.from(Q,Q.offset,Q.byteLength);if(X1(Z,Uint8Array))Z=p0.from(Z,Z.offset,Z.byteLength);if(!p0.isBuffer(Q)||!p0.isBuffer(Z))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(Q===Z)return 0;let Y=Q.length,$=Z.length;for(let J=0,X=Math.min(Y,$);J<X;++J)if(Q[J]!==Z[J]){Y=Q[J],$=Z[J];break}if(Y<$)return-1;if($<Y)return 1;return 0};p0.isEncoding=function(Q){switch(String(Q).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};p0.concat=function(Q,Z){if(!Array.isArray(Q))throw TypeError('"list" argument must be an Array of Buffers');if(Q.length===0)return p0.alloc(0);let Y;if(Z===void 0){Z=0;for(Y=0;Y<Q.length;++Y)Z+=Q[Y].length}let $=p0.allocUnsafe(Z),J=0;for(Y=0;Y<Q.length;++Y){let X=Q[Y];if(X1(X,Uint8Array))if(J+X.length>$.length){if(!p0.isBuffer(X))X=p0.from(X);X.copy($,J)}else Uint8Array.prototype.set.call($,X,J);else if(!p0.isBuffer(X))throw TypeError('"list" argument must be an Array of Buffers');else X.copy($,J);J+=X.length}return $};p0.byteLength=XC;p0.prototype._isBuffer=!0;p0.prototype.swap16=function(){let Q=this.length;if(Q%2!==0)throw RangeError("Buffer size must be a multiple of 16-bits");for(let Z=0;Z<Q;Z+=2)QX(this,Z,Z+1);return this};p0.prototype.swap32=function(){let Q=this.length;if(Q%4!==0)throw RangeError("Buffer size must be a multiple of 32-bits");for(let Z=0;Z<Q;Z+=4)QX(this,Z,Z+3),QX(this,Z+1,Z+2);return this};p0.prototype.swap64=function(){let Q=this.length;if(Q%8!==0)throw RangeError("Buffer size must be a multiple of 64-bits");for(let Z=0;Z<Q;Z+=8)QX(this,Z,Z+7),QX(this,Z+1,Z+6),QX(this,Z+2,Z+5),QX(this,Z+3,Z+4);return this};p0.prototype.toString=function(){let Q=this.length;if(Q===0)return"";if(arguments.length===0)return qC(this,0,Q);return na.apply(this,arguments)};p0.prototype.toLocaleString=p0.prototype.toString;p0.prototype.equals=function(Q){if(!p0.isBuffer(Q))throw TypeError("Argument must be a Buffer");if(this===Q)return!0;return p0.compare(this,Q)===0};p0.prototype.inspect=function(){let Q="",Z=YC;if(Q=this.toString("hex",0,Z).replace(/(.{2})/g,"$1 ").trim(),this.length>Z)Q+=" ... ";return"<Buffer "+Q+">"};if(rk)p0.prototype[rk]=p0.prototype.inspect;p0.prototype.compare=function(Q,Z,Y,$,J){if(X1(Q,Uint8Array))Q=p0.from(Q,Q.offset,Q.byteLength);if(!p0.isBuffer(Q))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof Q);if(Z===void 0)Z=0;if(Y===void 0)Y=Q?Q.length:0;if($===void 0)$=0;if(J===void 0)J=this.length;if(Z<0||Y>Q.length||$<0||J>this.length)throw RangeError("out of range index");if($>=J&&Z>=Y)return 0;if($>=J)return-1;if(Z>=Y)return 1;if(Z>>>=0,Y>>>=0,$>>>=0,J>>>=0,this===Q)return 0;let X=J-$,G=Y-Z,W=Math.min(X,G),U=this.slice($,J),K=Q.slice(Z,Y);for(let O=0;O<W;++O)if(U[O]!==K[O]){X=U[O],G=K[O];break}if(X<G)return-1;if(G<X)return 1;return 0};p0.prototype.includes=function(Q,Z,Y){return this.indexOf(Q,Z,Y)!==-1};p0.prototype.indexOf=function(Q,Z,Y){return VC(this,Q,Z,Y,!0)};p0.prototype.lastIndexOf=function(Q,Z,Y){return VC(this,Q,Z,Y,!1)};p0.prototype.write=function(Q,Z,Y,$){if(Z===void 0)$="utf8",Y=this.length,Z=0;else if(Y===void 0&&typeof Z==="string")$=Z,Y=this.length,Z=0;else if(isFinite(Z))if(Z=Z>>>0,isFinite(Y)){if(Y=Y>>>0,$===void 0)$="utf8"}else $=Y,Y=void 0;else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let J=this.length-Z;if(Y===void 0||Y>J)Y=J;if(Q.length>0&&(Y<0||Z<0)||Z>this.length)throw RangeError("Attempt to write outside buffer bounds");if(!$)$="utf8";let X=!1;for(;;)switch($){case"hex":return oa(this,Q,Z,Y);case"utf8":case"utf-8":return sa(this,Q,Z,Y);case"ascii":case"latin1":case"binary":return ia(this,Q,Z,Y);case"base64":return aa(this,Q,Z,Y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ra(this,Q,Z,Y);default:if(X)throw TypeError("Unknown encoding: "+$);$=(""+$).toLowerCase(),X=!0}};p0.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};p0.prototype.slice=function(Q,Z){let Y=this.length;if(Q=~~Q,Z=Z===void 0?Y:~~Z,Q<0){if(Q+=Y,Q<0)Q=0}else if(Q>Y)Q=Y;if(Z<0){if(Z+=Y,Z<0)Z=0}else if(Z>Y)Z=Y;if(Z<Q)Z=Q;let $=this.subarray(Q,Z);return Object.setPrototypeOf($,p0.prototype),$};p0.prototype.readUintLE=p0.prototype.readUIntLE=function(Q,Z,Y){if(Q=Q>>>0,Z=Z>>>0,!Y)wY(Q,Z,this.length);let $=this[Q],J=1,X=0;while(++X<Z&&(J*=256))$+=this[Q+X]*J;return $};p0.prototype.readUintBE=p0.prototype.readUIntBE=function(Q,Z,Y){if(Q=Q>>>0,Z=Z>>>0,!Y)wY(Q,Z,this.length);let $=this[Q+--Z],J=1;while(Z>0&&(J*=256))$+=this[Q+--Z]*J;return $};p0.prototype.readUint8=p0.prototype.readUInt8=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,1,this.length);return this[Q]};p0.prototype.readUint16LE=p0.prototype.readUInt16LE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,2,this.length);return this[Q]|this[Q+1]<<8};p0.prototype.readUint16BE=p0.prototype.readUInt16BE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,2,this.length);return this[Q]<<8|this[Q+1]};p0.prototype.readUint32LE=p0.prototype.readUInt32LE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,4,this.length);return(this[Q]|this[Q+1]<<8|this[Q+2]<<16)+this[Q+3]*16777216};p0.prototype.readUint32BE=p0.prototype.readUInt32BE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,4,this.length);return this[Q]*16777216+(this[Q+1]<<16|this[Q+2]<<8|this[Q+3])};p0.prototype.readBigUInt64LE=g8(function(Q){Q=Q>>>0,_V(Q,"offset");let Z=this[Q],Y=this[Q+7];if(Z===void 0||Y===void 0)h6(Q,this.length-8);let $=Z+this[++Q]*256+this[++Q]*65536+this[++Q]*16777216,J=this[++Q]+this[++Q]*256+this[++Q]*65536+Y*16777216;return BigInt($)+(BigInt(J)<<BigInt(32))});p0.prototype.readBigUInt64BE=g8(function(Q){Q=Q>>>0,_V(Q,"offset");let Z=this[Q],Y=this[Q+7];if(Z===void 0||Y===void 0)h6(Q,this.length-8);let $=Z*16777216+this[++Q]*65536+this[++Q]*256+this[++Q],J=this[++Q]*16777216+this[++Q]*65536+this[++Q]*256+Y;return(BigInt($)<<BigInt(32))+BigInt(J)});p0.prototype.readIntLE=function(Q,Z,Y){if(Q=Q>>>0,Z=Z>>>0,!Y)wY(Q,Z,this.length);let $=this[Q],J=1,X=0;while(++X<Z&&(J*=256))$+=this[Q+X]*J;if(J*=128,$>=J)$-=Math.pow(2,8*Z);return $};p0.prototype.readIntBE=function(Q,Z,Y){if(Q=Q>>>0,Z=Z>>>0,!Y)wY(Q,Z,this.length);let $=Z,J=1,X=this[Q+--$];while($>0&&(J*=256))X+=this[Q+--$]*J;if(J*=128,X>=J)X-=Math.pow(2,8*Z);return X};p0.prototype.readInt8=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,1,this.length);if(!(this[Q]&128))return this[Q];return(255-this[Q]+1)*-1};p0.prototype.readInt16LE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,2,this.length);let Y=this[Q]|this[Q+1]<<8;return Y&32768?Y|4294901760:Y};p0.prototype.readInt16BE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,2,this.length);let Y=this[Q+1]|this[Q]<<8;return Y&32768?Y|4294901760:Y};p0.prototype.readInt32LE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,4,this.length);return this[Q]|this[Q+1]<<8|this[Q+2]<<16|this[Q+3]<<24};p0.prototype.readInt32BE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,4,this.length);return this[Q]<<24|this[Q+1]<<16|this[Q+2]<<8|this[Q+3]};p0.prototype.readBigInt64LE=g8(function(Q){Q=Q>>>0,_V(Q,"offset");let Z=this[Q],Y=this[Q+7];if(Z===void 0||Y===void 0)h6(Q,this.length-8);let $=this[Q+4]+this[Q+5]*256+this[Q+6]*65536+(Y<<24);return(BigInt($)<<BigInt(32))+BigInt(Z+this[++Q]*256+this[++Q]*65536+this[++Q]*16777216)});p0.prototype.readBigInt64BE=g8(function(Q){Q=Q>>>0,_V(Q,"offset");let Z=this[Q],Y=this[Q+7];if(Z===void 0||Y===void 0)h6(Q,this.length-8);let $=(Z<<24)+this[++Q]*65536+this[++Q]*256+this[++Q];return(BigInt($)<<BigInt(32))+BigInt(this[++Q]*16777216+this[++Q]*65536+this[++Q]*256+Y)});p0.prototype.readFloatLE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,4,this.length);return AW(this,Q,!0,23,4)};p0.prototype.readFloatBE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,4,this.length);return AW(this,Q,!1,23,4)};p0.prototype.readDoubleLE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,8,this.length);return AW(this,Q,!0,52,8)};p0.prototype.readDoubleBE=function(Q,Z){if(Q=Q>>>0,!Z)wY(Q,8,this.length);return AW(this,Q,!1,52,8)};p0.prototype.writeUintLE=p0.prototype.writeUIntLE=function(Q,Z,Y,$){if(Q=+Q,Z=Z>>>0,Y=Y>>>0,!$){let G=Math.pow(2,8*Y)-1;S$(this,Q,Z,Y,G,0)}let J=1,X=0;this[Z]=Q&255;while(++X<Y&&(J*=256))this[Z+X]=Q/J&255;return Z+Y};p0.prototype.writeUintBE=p0.prototype.writeUIntBE=function(Q,Z,Y,$){if(Q=+Q,Z=Z>>>0,Y=Y>>>0,!$){let G=Math.pow(2,8*Y)-1;S$(this,Q,Z,Y,G,0)}let J=Y-1,X=1;this[Z+J]=Q&255;while(--J>=0&&(X*=256))this[Z+J]=Q/X&255;return Z+Y};p0.prototype.writeUint8=p0.prototype.writeUInt8=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,1,255,0);return this[Z]=Q&255,Z+1};p0.prototype.writeUint16LE=p0.prototype.writeUInt16LE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,2,65535,0);return this[Z]=Q&255,this[Z+1]=Q>>>8,Z+2};p0.prototype.writeUint16BE=p0.prototype.writeUInt16BE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,2,65535,0);return this[Z]=Q>>>8,this[Z+1]=Q&255,Z+2};p0.prototype.writeUint32LE=p0.prototype.writeUInt32LE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,4,4294967295,0);return this[Z+3]=Q>>>24,this[Z+2]=Q>>>16,this[Z+1]=Q>>>8,this[Z]=Q&255,Z+4};p0.prototype.writeUint32BE=p0.prototype.writeUInt32BE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,4,4294967295,0);return this[Z]=Q>>>24,this[Z+1]=Q>>>16,this[Z+2]=Q>>>8,this[Z+3]=Q&255,Z+4};p0.prototype.writeBigUInt64LE=g8(function(Q,Z=0){return FC(this,Q,Z,BigInt(0),BigInt("0xffffffffffffffff"))});p0.prototype.writeBigUInt64BE=g8(function(Q,Z=0){return zC(this,Q,Z,BigInt(0),BigInt("0xffffffffffffffff"))});p0.prototype.writeIntLE=function(Q,Z,Y,$){if(Q=+Q,Z=Z>>>0,!$){let W=Math.pow(2,8*Y-1);S$(this,Q,Z,Y,W-1,-W)}let J=0,X=1,G=0;this[Z]=Q&255;while(++J<Y&&(X*=256)){if(Q<0&&G===0&&this[Z+J-1]!==0)G=1;this[Z+J]=(Q/X>>0)-G&255}return Z+Y};p0.prototype.writeIntBE=function(Q,Z,Y,$){if(Q=+Q,Z=Z>>>0,!$){let W=Math.pow(2,8*Y-1);S$(this,Q,Z,Y,W-1,-W)}let J=Y-1,X=1,G=0;this[Z+J]=Q&255;while(--J>=0&&(X*=256)){if(Q<0&&G===0&&this[Z+J+1]!==0)G=1;this[Z+J]=(Q/X>>0)-G&255}return Z+Y};p0.prototype.writeInt8=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,1,127,-128);if(Q<0)Q=255+Q+1;return this[Z]=Q&255,Z+1};p0.prototype.writeInt16LE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,2,32767,-32768);return this[Z]=Q&255,this[Z+1]=Q>>>8,Z+2};p0.prototype.writeInt16BE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,2,32767,-32768);return this[Z]=Q>>>8,this[Z+1]=Q&255,Z+2};p0.prototype.writeInt32LE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,4,2147483647,-2147483648);return this[Z]=Q&255,this[Z+1]=Q>>>8,this[Z+2]=Q>>>16,this[Z+3]=Q>>>24,Z+4};p0.prototype.writeInt32BE=function(Q,Z,Y){if(Q=+Q,Z=Z>>>0,!Y)S$(this,Q,Z,4,2147483647,-2147483648);if(Q<0)Q=4294967295+Q+1;return this[Z]=Q>>>24,this[Z+1]=Q>>>16,this[Z+2]=Q>>>8,this[Z+3]=Q&255,Z+4};p0.prototype.writeBigInt64LE=g8(function(Q,Z=0){return FC(this,Q,Z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});p0.prototype.writeBigInt64BE=g8(function(Q,Z=0){return zC(this,Q,Z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});p0.prototype.writeFloatLE=function(Q,Z,Y){return KC(this,Q,Z,!0,Y)};p0.prototype.writeFloatBE=function(Q,Z,Y){return KC(this,Q,Z,!1,Y)};p0.prototype.writeDoubleLE=function(Q,Z,Y){return UC(this,Q,Z,!0,Y)};p0.prototype.writeDoubleBE=function(Q,Z,Y){return UC(this,Q,Z,!1,Y)};p0.prototype.copy=function(Q,Z,Y,$){if(!p0.isBuffer(Q))throw TypeError("argument should be a Buffer");if(!Y)Y=0;if(!$&&$!==0)$=this.length;if(Z>=Q.length)Z=Q.length;if(!Z)Z=0;if($>0&&$<Y)$=Y;if($===Y)return 0;if(Q.length===0||this.length===0)return 0;if(Z<0)throw RangeError("targetStart out of bounds");if(Y<0||Y>=this.length)throw RangeError("Index out of range");if($<0)throw RangeError("sourceEnd out of bounds");if($>this.length)$=this.length;if(Q.length-Z<$-Y)$=Q.length-Z+Y;let J=$-Y;if(this===Q&&typeof Uint8Array.prototype.copyWithin==="function")this.copyWithin(Z,Y,$);else Uint8Array.prototype.set.call(Q,this.subarray(Y,$),Z);return J};p0.prototype.fill=function(Q,Z,Y,$){if(typeof Q==="string"){if(typeof Z==="string")$=Z,Z=0,Y=this.length;else if(typeof Y==="string")$=Y,Y=this.length;if($!==void 0&&typeof $!=="string")throw TypeError("encoding must be a string");if(typeof $==="string"&&!p0.isEncoding($))throw TypeError("Unknown encoding: "+$);if(Q.length===1){let X=Q.charCodeAt(0);if($==="utf8"&&X<128||$==="latin1")Q=X}}else if(typeof Q==="number")Q=Q&255;else if(typeof Q==="boolean")Q=Number(Q);if(Z<0||this.length<Z||this.length<Y)throw RangeError("Out of range index");if(Y<=Z)return this;if(Z=Z>>>0,Y=Y===void 0?this.length:Y>>>0,!Q)Q=0;let J;if(typeof Q==="number")for(J=Z;J<Y;++J)this[J]=Q;else{let X=p0.isBuffer(Q)?Q:p0.from(Q,$),G=X.length;if(G===0)throw TypeError('The value "'+Q+'" is invalid for argument "value"');for(J=0;J<Y-Z;++J)this[J+Z]=X[J%G]}return this};Gr=/[^+/0-9A-Za-z-_]/g;Fr=function(){let Q=Array(256);for(let Z=0;Z<16;++Z){let Y=Z*16;for(let $=0;$<16;++$)Q[Y+$]="0123456789abcdef"[Z]+"0123456789abcdef"[$]}return Q}();Wr=tH("resolveObjectURL"),Kr=tH("isUtf8"),Or=tH("transcode"),Hr=p0});var TC={};j$(TC,{types:()=>Tr,promisify:()=>PC,log:()=>RC,isUndefined:()=>vV,isSymbol:()=>Br,isString:()=>SW,isRegExp:()=>TW,isPrimitive:()=>kr,isObject:()=>xV,isNumber:()=>IC,isNullOrUndefined:()=>Nr,isNull:()=>CW,isFunction:()=>BW,isError:()=>NW,isDate:()=>YD,isBuffer:()=>Cr,isBoolean:()=>JD,isArray:()=>DC,inspect:()=>ZX,inherits:()=>LC,format:()=>$D,deprecate:()=>Ir,default:()=>_r,debuglog:()=>Rr,callbackifyOnRejected:()=>VD,callbackify:()=>jC,_extend:()=>XD,TextEncoder:()=>AC,TextDecoder:()=>MC});function $D(Q,...Z){if(!SW(Q)){var Y=[Q];for(var $=0;$<Z.length;$++)Y.push(ZX(Z[$]));return Y.join(" ")}var $=0,J=Z.length,X=String(Q).replace(Dr,function(W){if(W==="%%")return"%";if($>=J)return W;switch(W){case"%s":return String(Z[$++]);case"%d":return Number(Z[$++]);case"%j":try{return JSON.stringify(Z[$++])}catch(U){return"[Circular]"}default:return W}});for(var G=Z[$];$<J;G=Z[++$])if(CW(G)||!xV(G))X+=" "+G;else X+=" "+ZX(G);return X}function Ir(Q,Z){if(typeof process>"u"||process?.noDeprecation===!0)return Q;var Y=!1;function $(...J){if(!Y){if(process.throwDeprecation)throw Error(Z);else if(process.traceDeprecation)console.trace(Z);else console.error(Z);Y=!0}return Q.apply(this,...J)}return $}function Lr(Q,Z){var Y=ZX.styles[Z];if(Y)return"\x1B["+ZX.colors[Y][0]+"m"+Q+"\x1B["+ZX.colors[Y][1]+"m";else return Q}function Er(Q,Z){return Q}function Pr(Q){var Z={};return Q.forEach(function(Y,$){Z[Y]=!0}),Z}function kW(Q,Z,Y){if(Q.customInspect&&Z&&BW(Z.inspect)&&Z.inspect!==ZX&&!(Z.constructor&&Z.constructor.prototype===Z)){var $=Z.inspect(Y,Q);if(!SW($))$=kW(Q,$,Y);return $}var J=jr(Q,Z);if(J)return J;var X=Object.keys(Z),G=Pr(X);if(Q.showHidden)X=Object.getOwnPropertyNames(Z);if(NW(Z)&&(X.indexOf("message")>=0||X.indexOf("description")>=0))return eH(Z);if(X.length===0){if(BW(Z)){var W=Z.name?": "+Z.name:"";return Q.stylize("[Function"+W+"]","special")}if(TW(Z))return Q.stylize(RegExp.prototype.toString.call(Z),"regexp");if(YD(Z))return Q.stylize(Date.prototype.toString.call(Z),"date");if(NW(Z))return eH(Z)}var U="",K=!1,O=["{","}"];if(DC(Z))K=!0,O=["[","]"];if(BW(Z)){var I=Z.name?": "+Z.name:"";U=" [Function"+I+"]"}if(TW(Z))U=" "+RegExp.prototype.toString.call(Z);if(YD(Z))U=" "+Date.prototype.toUTCString.call(Z);if(NW(Z))U=" "+eH(Z);if(X.length===0&&(!K||Z.length==0))return O[0]+U+O[1];if(Y<0)if(TW(Z))return Q.stylize(RegExp.prototype.toString.call(Z),"regexp");else return Q.stylize("[Object]","special");Q.seen.push(Z);var L;if(K)L=Ar(Q,Z,Y,G,X);else L=X.map(function(A){return ZD(Q,Z,Y,G,A,K)});return Q.seen.pop(),Mr(L,U,O)}function jr(Q,Z){if(vV(Z))return Q.stylize("undefined","undefined");if(SW(Z)){var Y="'"+JSON.stringify(Z).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return Q.stylize(Y,"string")}if(IC(Z))return Q.stylize(""+Z,"number");if(JD(Z))return Q.stylize(""+Z,"boolean");if(CW(Z))return Q.stylize("null","null")}function eH(Q){return"["+Error.prototype.toString.call(Q)+"]"}function Ar(Q,Z,Y,$,J){var X=[];for(var G=0,W=Z.length;G<W;++G)if(EC(Z,String(G)))X.push(ZD(Q,Z,Y,$,String(G),!0));else X.push("");return J.forEach(function(U){if(!U.match(/^\d+$/))X.push(ZD(Q,Z,Y,$,U,!0))}),X}function ZD(Q,Z,Y,$,J,X){var G,W,U;if(U=Object.getOwnPropertyDescriptor(Z,J)||{value:Z[J]},U.get)if(U.set)W=Q.stylize("[Getter/Setter]","special");else W=Q.stylize("[Getter]","special");else if(U.set)W=Q.stylize("[Setter]","special");if(!EC($,J))G="["+J+"]";if(!W)if(Q.seen.indexOf(U.value)<0){if(CW(Y))W=kW(Q,U.value,null);else W=kW(Q,U.value,Y-1);if(W.indexOf(`
|
|
75
|
+
`)>-1)if(X)W=W.split(`
|
|
76
|
+
`).map(function(K){return" "+K}).join(`
|
|
77
|
+
`).slice(2);else W=`
|
|
78
|
+
`+W.split(`
|
|
79
|
+
`).map(function(K){return" "+K}).join(`
|
|
80
|
+
`)}else W=Q.stylize("[Circular]","special");if(vV(G)){if(X&&J.match(/^\d+$/))return W;if(G=JSON.stringify(""+J),G.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/))G=G.slice(1,-1),G=Q.stylize(G,"name");else G=G.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),G=Q.stylize(G,"string")}return G+": "+W}function Mr(Q,Z,Y){var $=0,J=Q.reduce(function(X,G){if($++,G.indexOf(`
|
|
81
|
+
`)>=0)$++;return X+G.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(J>60)return Y[0]+(Z===""?"":Z+`
|
|
82
|
+
`)+" "+Q.join(`,
|
|
83
|
+
`)+" "+Y[1];return Y[0]+Z+" "+Q.join(", ")+" "+Y[1]}function DC(Q){return Array.isArray(Q)}function JD(Q){return typeof Q==="boolean"}function CW(Q){return Q===null}function Nr(Q){return Q==null}function IC(Q){return typeof Q==="number"}function SW(Q){return typeof Q==="string"}function Br(Q){return typeof Q==="symbol"}function vV(Q){return Q===void 0}function TW(Q){return xV(Q)&&GD(Q)==="[object RegExp]"}function xV(Q){return typeof Q==="object"&&Q!==null}function YD(Q){return xV(Q)&&GD(Q)==="[object Date]"}function NW(Q){return xV(Q)&&(GD(Q)==="[object Error]"||Q instanceof Error)}function BW(Q){return typeof Q==="function"}function kr(Q){return Q===null||typeof Q==="boolean"||typeof Q==="number"||typeof Q==="string"||typeof Q==="symbol"||typeof Q>"u"}function Cr(Q){return Q instanceof Buffer}function GD(Q){return Object.prototype.toString.call(Q)}function QD(Q){return Q<10?"0"+Q.toString(10):Q.toString(10)}function wr(){var Q=new Date,Z=[QD(Q.getHours()),QD(Q.getMinutes()),QD(Q.getSeconds())].join(":");return[Q.getDate(),Sr[Q.getMonth()],Z].join(" ")}function RC(...Q){console.log("%s - %s",wr(),$D.apply(null,Q))}function LC(Q,Z){if(Z)Q.super_=Z,Q.prototype=Object.create(Z.prototype,{constructor:{value:Q,enumerable:!1,writable:!0,configurable:!0}})}function XD(Q,Z){if(!Z||!xV(Z))return Q;var Y=Object.keys(Z),$=Y.length;while($--)Q[Y[$]]=Z[Y[$]];return Q}function EC(Q,Z){return Object.prototype.hasOwnProperty.call(Q,Z)}function VD(Q,Z){if(!Q){var Y=Error("Promise was rejected with a falsy value");Y.reason=Q,Q=Y}return Z(Q)}function jC(Q){if(typeof Q!=="function")throw TypeError('The "original" argument must be of type Function');function Z(...Y){var $=Y.pop();if(typeof $!=="function")throw TypeError("The last argument must be of type Function");var J=this,X=function(...G){return $.apply(J,...G)};Q.apply(this,Y).then(function(G){process.nextTick(X.bind(null,null,G))},function(G){process.nextTick(VD.bind(null,G,X))})}return Object.setPrototypeOf(Z,Object.getPrototypeOf(Q)),Object.defineProperties(Z,Object.getOwnPropertyDescriptors(Q)),Z}var Dr,Rr,ZX,Tr=()=>{},Sr,PC,AC,MC,_r;var NC=w(()=>{Dr=/%[sdj%]/g;Rr=((Q={},Z={},Y)=>((Y=typeof process<"u"&&!1)&&(Y=Y.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase()),Z=new RegExp("^"+Y+"$","i"),($)=>{if($=$.toUpperCase(),!Q[$])if(Z.test($))Q[$]=function(...J){console.error("%s: %s",$,pid,$D.apply(null,...J))};else Q[$]=function(){};return Q[$]}))(),ZX=((Q)=>(Q.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},Q.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},Q.custom=Symbol.for("nodejs.util.inspect.custom"),Q))(function(Q,Z,...Y){var $={seen:[],stylize:Er};if(Y.length>=1)$.depth=Y[0];if(Y.length>=2)$.colors=Y[1];if(JD(Z))$.showHidden=Z;else if(Z)XD($,Z);if(vV($.showHidden))$.showHidden=!1;if(vV($.depth))$.depth=2;if(vV($.colors))$.colors=!1;if($.colors)$.stylize=Lr;return kW($,Q,$.depth)});Sr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];PC=((Q)=>(Q.custom=Symbol.for("nodejs.util.promisify.custom"),Q))(function(Q){if(typeof Q!=="function")throw TypeError('The "original" argument must be of type Function');if(kCustomPromisifiedSymbol&&Q[kCustomPromisifiedSymbol]){var Z=Q[kCustomPromisifiedSymbol];if(typeof Z!=="function")throw TypeError('The "nodejs.util.promisify.custom" argument must be of type Function');return Object.defineProperty(Z,kCustomPromisifiedSymbol,{value:Z,enumerable:!1,writable:!1,configurable:!0}),Z}function Z(...Y){var $,J,X=new Promise(function(G,W){$=G,J=W});Y.push(function(G,W){if(G)J(G);else $(W)});try{Q.apply(this,Y)}catch(G){J(G)}return X}if(Object.setPrototypeOf(Z,Object.getPrototypeOf(Q)),kCustomPromisifiedSymbol)Object.defineProperty(Z,kCustomPromisifiedSymbol,{value:Z,enumerable:!1,writable:!1,configurable:!0});return Object.defineProperties(Z,Object.getOwnPropertyDescriptors(Q))});({TextEncoder:AC,TextDecoder:MC}=globalThis),_r={TextEncoder:AC,TextDecoder:MC,promisify:PC,log:RC,inherits:LC,_extend:XD,callbackifyOnRejected:VD,callbackify:jC}});var c6={};j$(c6,{setMaxListeners:()=>gC,once:()=>fC,listenerCount:()=>hC,init:()=>h8,getMaxListeners:()=>cC,getEventListeners:()=>yC,default:()=>ur,captureRejectionSymbol:()=>wC,addAbortListener:()=>uC,EventEmitter:()=>h8});function _C(Q,Z){var{_events:Y}=Q;if(Z[0]??=Error("Unhandled error."),!Y)throw Z[0];var $=Y[SC];if($)for(var J of kC.call($))J.apply(Q,Z);var X=Y.error;if(!X)throw Z[0];for(var J of kC.call(X))J.apply(Q,Z);return!0}function fr(Q,Z,Y,$){Z.then(void 0,function(J){queueMicrotask(()=>yr(Q,J,Y,$))})}function yr(Q,Z,Y,$){if(typeof Q[BC]==="function")Q[BC](Z,Y,...$);else try{Q[YX]=!1,Q.emit("error",Z)}finally{Q[YX]=!0}}function vC(Q,Z,Y){Y.warned=!0;let $=Error(`Possible EventEmitter memory leak detected. ${Y.length} ${String(Z)} listeners added to [${Q.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);$.name="MaxListenersExceededWarning",$.emitter=Q,$.type=Z,$.count=Y.length,console.warn($)}function xC(Q,Z,...Y){this.removeListener(Q,Z),Z.apply(this,Y)}function fC(Q,Z,Y){var $=Y?.signal;if(bC($,"options.signal"),$?.aborted)throw new qD(void 0,{cause:$?.reason});let{resolve:J,reject:X,promise:G}=$newPromiseCapability(Promise),W=(O)=>{if(Q.removeListener(Z,U),$!=null)wW($,"abort",K);X(O)},U=(...O)=>{if(typeof Q.removeListener==="function")Q.removeListener("error",W);if($!=null)wW($,"abort",K);J(O)};if(CC(Q,Z,U,{once:!0}),Z!=="error"&&typeof Q.once==="function")Q.once("error",W);function K(){wW(Q,Z,U),wW(Q,"error",W),X(new qD(void 0,{cause:$?.reason}))}if($!=null)CC($,"abort",K,{once:!0});return G}function yC(Q,Z){return Q.listeners(Z)}function gC(Q,...Z){zD(Q,"setMaxListeners",0);var Y;if(Z&&(Y=Z.length))for(let $=0;$<Y;$++)Z[$].setMaxListeners(Q);else $X=Q}function hC(Q,Z){return Q.listenerCount(Z)}function wW(Q,Z,Y,$){if(typeof Q.removeListener==="function")Q.removeListener(Z,Y);else Q.removeEventListener(Z,Y,$)}function CC(Q,Z,Y,$){if(typeof Q.on==="function")if($.once)Q.once(Z,Y);else Q.on(Z,Y);else Q.addEventListener(Z,Y,$)}function fV(Q,Z,Y){let $=TypeError(`The "${Q}" argument must be of type ${Z}. Received ${Y}`);return $.code="ERR_INVALID_ARG_TYPE",$}function br(Q,Z,Y){let $=RangeError(`The "${Q}" argument is out of range. It must be ${Z}. Received ${Y}`);return $.code="ERR_OUT_OF_RANGE",$}function bC(Q,Z){if(Q!==void 0&&(Q===null||typeof Q!=="object"||!("aborted"in Q)))throw fV(Z,"AbortSignal",Q)}function zD(Q,Z,Y,$){if(typeof Q!=="number")throw fV(Z,"number",Q);if(Y!=null&&Q<Y||$!=null&&Q>$||(Y!=null||$!=null)&&Number.isNaN(Q))throw br(Z,`${Y!=null?`>= ${Y}`:""}${Y!=null&&$!=null?" && ":""}${$!=null?`<= ${$}`:""}`,Q)}function b6(Q){if(typeof Q!=="function")throw TypeError("The listener must be a function")}function cr(Q,Z){if(typeof Q!=="boolean")throw fV(Z,"boolean",Q)}function cC(Q){return Q?._maxListeners??$X}function uC(Q,Z){if(Q===void 0)throw fV("signal","AbortSignal",Q);if(bC(Q,"signal"),typeof Z!=="function")throw fV("listener","function",Z);let Y;if(Q.aborted)queueMicrotask(()=>Z());else Q.addEventListener("abort",Z,{__proto__:null,once:!0}),Y=()=>{Q.removeEventListener("abort",Z)};return{__proto__:null,[Symbol.dispose](){Y?.()}}}var FD,YX,SC,vr,xr,BC,wC,kC,$X=10,h8=function(Q){if(this._events===void 0||this._events===this.__proto__._events)this._events={__proto__:null},this._eventsCount=0;if(this._maxListeners??=void 0,this[YX]=Q?.captureRejections?Boolean(Q?.captureRejections):SZ[YX])this.emit=hr},SZ,gr=function(Q,...Z){if(Q==="error")return _C(this,Z);var{_events:Y}=this;if(Y===void 0)return!1;var $=Y[Q];if($===void 0)return!1;let J=$.length>1?$.slice():$;for(let X=0,{length:G}=J;X<G;X++){let W=J[X];switch(Z.length){case 0:W.call(this);break;case 1:W.call(this,Z[0]);break;case 2:W.call(this,Z[0],Z[1]);break;case 3:W.call(this,Z[0],Z[1],Z[2]);break;default:W.apply(this,Z);break}}return!0},hr=function(Q,...Z){if(Q==="error")return _C(this,Z);var{_events:Y}=this;if(Y===void 0)return!1;var $=Y[Q];if($===void 0)return!1;let J=$.length>1?$.slice():$;for(let X=0,{length:G}=J;X<G;X++){let W=J[X],U;switch(Z.length){case 0:U=W.call(this);break;case 1:U=W.call(this,Z[0]);break;case 2:U=W.call(this,Z[0],Z[1]);break;case 3:U=W.call(this,Z[0],Z[1],Z[2]);break;default:U=W.apply(this,Z);break}if(U!==void 0&&typeof U?.then==="function"&&U.then===Promise.prototype.then)fr(this,U,Q,Z)}return!0},qD,ur;var u6=w(()=>{FD=Symbol.for,YX=Symbol("kCapture"),SC=FD("events.errorMonitor"),vr=Symbol("events.maxEventTargetListeners"),xr=Symbol("events.maxEventTargetListenersWarned"),BC=FD("nodejs.rejection"),wC=FD("nodejs.rejection"),kC=Array.prototype.slice,SZ=h8.prototype={};SZ._events=void 0;SZ._eventsCount=0;SZ._maxListeners=void 0;SZ.setMaxListeners=function(Q){return zD(Q,"setMaxListeners",0),this._maxListeners=Q,this};SZ.constructor=h8;SZ.getMaxListeners=function(){return this?._maxListeners??$X};SZ.emit=gr;SZ.addListener=function(Q,Z){b6(Z);var Y=this._events;if(!Y)Y=this._events={__proto__:null},this._eventsCount=0;else if(Y.newListener)this.emit("newListener",Q,Z.listener??Z);var $=Y[Q];if(!$)Y[Q]=[Z],this._eventsCount++;else{$.push(Z);var J=this._maxListeners??$X;if(J>0&&$.length>J&&!$.warned)vC(this,Q,$)}return this};SZ.on=SZ.addListener;SZ.prependListener=function(Q,Z){b6(Z);var Y=this._events;if(!Y)Y=this._events={__proto__:null},this._eventsCount=0;else if(Y.newListener)this.emit("newListener",Q,Z.listener??Z);var $=Y[Q];if(!$)Y[Q]=[Z],this._eventsCount++;else{$.unshift(Z);var J=this._maxListeners??$X;if(J>0&&$.length>J&&!$.warned)vC(this,Q,$)}return this};SZ.once=function(Q,Z){b6(Z);let Y=xC.bind(this,Q,Z);return Y.listener=Z,this.addListener(Q,Y),this};SZ.prependOnceListener=function(Q,Z){b6(Z);let Y=xC.bind(this,Q,Z);return Y.listener=Z,this.prependListener(Q,Y),this};SZ.removeListener=function(Q,Z){b6(Z);var{_events:Y}=this;if(!Y)return this;var $=Y[Q];if(!$)return this;var J=$.length;let X=-1;for(let G=J-1;G>=0;G--)if($[G]===Z||$[G].listener===Z){X=G;break}if(X<0)return this;if(X===0)$.shift();else $.splice(X,1);if($.length===0)delete Y[Q],this._eventsCount--;return this};SZ.off=SZ.removeListener;SZ.removeAllListeners=function(Q){var{_events:Z}=this;if(Q&&Z){if(Z[Q])delete Z[Q],this._eventsCount--}else this._events={__proto__:null};return this};SZ.listeners=function(Q){var{_events:Z}=this;if(!Z)return[];var Y=Z[Q];if(!Y)return[];return Y.map(($)=>$.listener??$)};SZ.rawListeners=function(Q){var{_events:Z}=this;if(!Z)return[];var Y=Z[Q];if(!Y)return[];return Y.slice()};SZ.listenerCount=function(Q){var{_events:Z}=this;if(!Z)return 0;return Z[Q]?.length??0};SZ.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};SZ[YX]=!1;qD=class qD extends Error{constructor(Q="The operation was aborted",Z=void 0){if(Z!==void 0&&typeof Z!=="object")throw fV("options","Object",Z);super(Q,Z);this.code="ABORT_ERR",this.name="AbortError"}};Object.defineProperties(h8,{captureRejections:{get(){return SZ[YX]},set(Q){cr(Q,"EventEmitter.captureRejections"),SZ[YX]=Q},enumerable:!0},defaultMaxListeners:{enumerable:!0,get:()=>{return $X},set:(Q)=>{zD(Q,"defaultMaxListeners",0),$X=Q}},kMaxEventTargetListeners:{value:vr,enumerable:!1,configurable:!1,writable:!1},kMaxEventTargetListenersWarned:{value:xr,enumerable:!1,configurable:!1,writable:!1}});Object.assign(h8,{once:fC,getEventListeners:yC,getMaxListeners:cC,setMaxListeners:gC,EventEmitter:h8,usingDomains:!1,captureRejectionSymbol:wC,errorMonitor:SC,addAbortListener:uC,init:h8,listenerCount:hC});ur=h8});var OD=XQ((PT0,iC)=>{var FZ=(Q,Z)=>()=>(Z||Q((Z={exports:{}}).exports,Z),Z.exports),pZ=FZ((Q,Z)=>{class Y extends Error{constructor($){if(!Array.isArray($))throw TypeError(`Expected input to be an Array, got ${typeof $}`);let J="";for(let X=0;X<$.length;X++)J+=` ${$[X].stack}
|
|
84
|
+
`;super(J);this.name="AggregateError",this.errors=$}}Z.exports={AggregateError:Y,ArrayIsArray($){return Array.isArray($)},ArrayPrototypeIncludes($,J){return $.includes(J)},ArrayPrototypeIndexOf($,J){return $.indexOf(J)},ArrayPrototypeJoin($,J){return $.join(J)},ArrayPrototypeMap($,J){return $.map(J)},ArrayPrototypePop($,J){return $.pop(J)},ArrayPrototypePush($,J){return $.push(J)},ArrayPrototypeSlice($,J,X){return $.slice(J,X)},Error,FunctionPrototypeCall($,J,...X){return $.call(J,...X)},FunctionPrototypeSymbolHasInstance($,J){return Function.prototype[Symbol.hasInstance].call($,J)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties($,J){return Object.defineProperties($,J)},ObjectDefineProperty($,J,X){return Object.defineProperty($,J,X)},ObjectGetOwnPropertyDescriptor($,J){return Object.getOwnPropertyDescriptor($,J)},ObjectKeys($){return Object.keys($)},ObjectSetPrototypeOf($,J){return Object.setPrototypeOf($,J)},Promise,PromisePrototypeCatch($,J){return $.catch(J)},PromisePrototypeThen($,J,X){return $.then(J,X)},PromiseReject($){return Promise.reject($)},PromiseResolve($){return Promise.resolve($)},ReflectApply:Reflect.apply,RegExpPrototypeTest($,J){return $.test(J)},SafeSet:Set,String,StringPrototypeSlice($,J,X){return $.slice(J,X)},StringPrototypeToLowerCase($){return $.toLowerCase()},StringPrototypeToUpperCase($){return $.toUpperCase()},StringPrototypeTrim($){return $.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet($,J,X){return $.set(J,X)},Boolean,Uint8Array}}),pC=FZ((Q,Z)=>{Z.exports={format(Y,...$){return Y.replace(/%([sdifj])/g,function(...[J,X]){let G=$.shift();if(X==="f")return G.toFixed(6);else if(X==="j")return JSON.stringify(G);else if(X==="s"&&typeof G==="object")return`${G.constructor!==Object?G.constructor.name:""} {}`.trim();else return G.toString()})},inspect(Y){switch(typeof Y){case"string":if(Y.includes("'")){if(!Y.includes('"'))return`"${Y}"`;else if(!Y.includes("`")&&!Y.includes("${"))return`\`${Y}\``}return`'${Y}'`;case"number":if(isNaN(Y))return"NaN";else if(Object.is(Y,-0))return String(Y);return Y;case"bigint":return`${String(Y)}n`;case"boolean":case"undefined":return String(Y);case"object":return"{}"}}}}),D$=FZ((Q,Z)=>{var{format:Y,inspect:$}=pC(),{AggregateError:J}=pZ(),X=globalThis.AggregateError||J,G=Symbol("kIsNodeError"),W=["string","function","number","object","Function","Object","boolean","bigint","symbol"],U=/^([A-Z][a-z0-9]*)+$/,K={};function O(C,S){if(!C)throw new K.ERR_INTERNAL_ASSERTION(S)}function I(C){let S="",_=C.length,x=C[0]==="-"?1:0;for(;_>=x+4;_-=3)S=`_${C.slice(_-3,_)}${S}`;return`${C.slice(0,_)}${S}`}function L(C,S,_){if(typeof S==="function")return O(S.length<=_.length,`Code: ${C}; The provided arguments length (${_.length}) does not match the required ones (${S.length}).`),S(..._);let x=(S.match(/%[dfijoOs]/g)||[]).length;if(O(x===_.length,`Code: ${C}; The provided arguments length (${_.length}) does not match the required ones (${x}).`),_.length===0)return S;return Y(S,..._)}function A(C,S,_){if(!_)_=Error;class x extends _{constructor(...f){super(L(C,S,f))}toString(){return`${this.name} [${C}]: ${this.message}`}}Object.defineProperties(x.prototype,{name:{value:_.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${C}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),x.prototype.code=C,x.prototype[G]=!0,K[C]=x}function M(C){let S="__node_internal_"+C.name;return Object.defineProperty(C,"name",{value:S}),C}function k(C,S){if(C&&S&&C!==S){if(Array.isArray(S.errors))return S.errors.push(C),S;let _=new X([S,C],S.message);return _.code=S.code,_}return C||S}class B extends Error{constructor(C="The operation was aborted",S=void 0){if(S!==void 0&&typeof S!=="object")throw new K.ERR_INVALID_ARG_TYPE("options","Object",S);super(C,S);this.code="ABORT_ERR",this.name="AbortError"}}A("ERR_ASSERTION","%s",Error),A("ERR_INVALID_ARG_TYPE",(C,S,_)=>{if(O(typeof C==="string","'name' must be a string"),!Array.isArray(S))S=[S];let x="The ";if(C.endsWith(" argument"))x+=`${C} `;else x+=`"${C}" ${C.includes(".")?"property":"argument"} `;x+="must be ";let f=[],h=[],i=[];for(let t of S)if(O(typeof t==="string","All expected entries have to be of type string"),W.includes(t))f.push(t.toLowerCase());else if(U.test(t))h.push(t);else O(t!=="object",'The value "object" should be written as "Object"'),i.push(t);if(h.length>0){let t=f.indexOf("object");if(t!==-1)f.splice(f,t,1),h.push("Object")}if(f.length>0){switch(f.length){case 1:x+=`of type ${f[0]}`;break;case 2:x+=`one of type ${f[0]} or ${f[1]}`;break;default:{let t=f.pop();x+=`one of type ${f.join(", ")}, or ${t}`}}if(h.length>0||i.length>0)x+=" or "}if(h.length>0){switch(h.length){case 1:x+=`an instance of ${h[0]}`;break;case 2:x+=`an instance of ${h[0]} or ${h[1]}`;break;default:{let t=h.pop();x+=`an instance of ${h.join(", ")}, or ${t}`}}if(i.length>0)x+=" or "}switch(i.length){case 0:break;case 1:if(i[0].toLowerCase()!==i[0])x+="an ";x+=`${i[0]}`;break;case 2:x+=`one of ${i[0]} or ${i[1]}`;break;default:{let t=i.pop();x+=`one of ${i.join(", ")}, or ${t}`}}if(_==null)x+=`. Received ${_}`;else if(typeof _==="function"&&_.name)x+=`. Received function ${_.name}`;else if(typeof _==="object"){var Z0;if((Z0=_.constructor)!==null&&Z0!==void 0&&Z0.name)x+=`. Received an instance of ${_.constructor.name}`;else{let t=$(_,{depth:-1});x+=`. Received ${t}`}}else{let t=$(_,{colors:!1});if(t.length>25)t=`${t.slice(0,25)}...`;x+=`. Received type ${typeof _} (${t})`}return x},TypeError),A("ERR_INVALID_ARG_VALUE",(C,S,_="is invalid")=>{let x=$(S);if(x.length>128)x=x.slice(0,128)+"...";return`The ${C.includes(".")?"property":"argument"} '${C}' ${_}. Received ${x}`},TypeError),A("ERR_INVALID_RETURN_VALUE",(C,S,_)=>{var x;let f=_!==null&&_!==void 0&&(x=_.constructor)!==null&&x!==void 0&&x.name?`instance of ${_.constructor.name}`:`type ${typeof _}`;return`Expected ${C} to be returned from the "${S}" function but got ${f}.`},TypeError),A("ERR_MISSING_ARGS",(...C)=>{O(C.length>0,"At least one arg needs to be specified");let S,_=C.length;switch(C=(Array.isArray(C)?C:[C]).map((x)=>`"${x}"`).join(" or "),_){case 1:S+=`The ${C[0]} argument`;break;case 2:S+=`The ${C[0]} and ${C[1]} arguments`;break;default:{let x=C.pop();S+=`The ${C.join(", ")}, and ${x} arguments`}break}return`${S} must be specified`},TypeError),A("ERR_OUT_OF_RANGE",(C,S,_)=>{O(S,'Missing "range" argument');let x;if(Number.isInteger(_)&&Math.abs(_)>4294967296)x=I(String(_));else if(typeof _==="bigint"){x=String(_);let f=BigInt(2)**BigInt(32);if(_>f||_<-f)x=I(x);x+="n"}else x=$(_);return`The value of "${C}" is out of range. It must be ${S}. Received ${x}`},RangeError),A("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),A("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),A("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),A("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),A("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),A("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),A("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),A("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),A("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),A("ERR_STREAM_WRITE_AFTER_END","write after end",Error),A("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),Z.exports={AbortError:B,aggregateTwoErrors:M(k),hideStackFrames:M,codes:K}}),pr=FZ((Q,Z)=>{Object.defineProperty(Q,"__esModule",{value:!0});var Y=new WeakMap,$=new WeakMap;function J(c){let l=Y.get(c);return console.assert(l!=null,"'this' is expected an Event object, but got",c),l}function X(c){if(c.passiveListener!=null){if(typeof console<"u"&&typeof console.error==="function")console.error("Unable to preventDefault inside passive event listener invocation.",c.passiveListener);return}if(!c.event.cancelable)return;if(c.canceled=!0,typeof c.event.preventDefault==="function")c.event.preventDefault()}function G(c,l){Y.set(this,{eventTarget:c,event:l,eventPhase:2,currentTarget:c,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:l.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let V=Object.keys(l);for(let z=0;z<V.length;++z){let H=V[z];if(!(H in this))Object.defineProperty(this,H,W(H))}}if(G.prototype={get type(){return J(this).event.type},get target(){return J(this).eventTarget},get currentTarget(){return J(this).currentTarget},composedPath(){let c=J(this).currentTarget;if(c==null)return[];return[c]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return J(this).eventPhase},stopPropagation(){let c=J(this);if(c.stopped=!0,typeof c.event.stopPropagation==="function")c.event.stopPropagation()},stopImmediatePropagation(){let c=J(this);if(c.stopped=!0,c.immediateStopped=!0,typeof c.event.stopImmediatePropagation==="function")c.event.stopImmediatePropagation()},get bubbles(){return Boolean(J(this).event.bubbles)},get cancelable(){return Boolean(J(this).event.cancelable)},preventDefault(){X(J(this))},get defaultPrevented(){return J(this).canceled},get composed(){return Boolean(J(this).event.composed)},get timeStamp(){return J(this).timeStamp},get srcElement(){return J(this).eventTarget},get cancelBubble(){return J(this).stopped},set cancelBubble(c){if(!c)return;let l=J(this);if(l.stopped=!0,typeof l.event.cancelBubble==="boolean")l.event.cancelBubble=!0},get returnValue(){return!J(this).canceled},set returnValue(c){if(!c)X(J(this))},initEvent(){}},Object.defineProperty(G.prototype,"constructor",{value:G,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u")Object.setPrototypeOf(G.prototype,window.Event.prototype),$.set(window.Event.prototype,G);function W(c){return{get(){return J(this).event[c]},set(l){J(this).event[c]=l},configurable:!0,enumerable:!0}}function U(c){return{value(){let l=J(this).event;return l[c].apply(l,arguments)},configurable:!0,enumerable:!0}}function K(c,l){let V=Object.keys(l);if(V.length===0)return c;function z(H,F){c.call(this,H,F)}z.prototype=Object.create(c.prototype,{constructor:{value:z,configurable:!0,writable:!0}});for(let H=0;H<V.length;++H){let F=V[H];if(!(F in c.prototype)){let D=typeof Object.getOwnPropertyDescriptor(l,F).value==="function";Object.defineProperty(z.prototype,F,D?U(F):W(F))}}return z}function O(c){if(c==null||c===Object.prototype)return G;let l=$.get(c);if(l==null)l=K(O(Object.getPrototypeOf(c)),c),$.set(c,l);return l}function I(c,l){return new(O(Object.getPrototypeOf(l)))(c,l)}function L(c){return J(c).immediateStopped}function A(c,l){J(c).eventPhase=l}function M(c,l){J(c).currentTarget=l}function k(c,l){J(c).passiveListener=l}var B=new WeakMap,C=1,S=2,_=3;function x(c){return c!==null&&typeof c==="object"}function f(c){let l=B.get(c);if(l==null)throw TypeError("'this' is expected an EventTarget object, but got another value.");return l}function h(c){return{get(){let l=f(this).get(c);while(l!=null){if(l.listenerType===_)return l.listener;l=l.next}return null},set(l){if(typeof l!=="function"&&!x(l))l=null;let V=f(this),z=null,H=V.get(c);while(H!=null){if(H.listenerType===_)if(z!==null)z.next=H.next;else if(H.next!==null)V.set(c,H.next);else V.delete(c);else z=H;H=H.next}if(l!==null){let F={listener:l,listenerType:_,passive:!1,once:!1,next:null};if(z===null)V.set(c,F);else z.next=F}},configurable:!0,enumerable:!0}}function i(c,l){Object.defineProperty(c,`on${l}`,h(l))}function Z0(c){function l(){t.call(this)}l.prototype=Object.create(t.prototype,{constructor:{value:l,configurable:!0,writable:!0}});for(let V=0;V<c.length;++V)i(l.prototype,c[V]);return l}function t(){if(this instanceof t){B.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return Z0(arguments[0]);if(arguments.length>0){let c=Array(arguments.length);for(let l=0;l<arguments.length;++l)c[l]=arguments[l];return Z0(c)}throw TypeError("Cannot call a class as a function")}if(t.prototype={addEventListener(c,l,V){if(l==null)return;if(typeof l!=="function"&&!x(l))throw TypeError("'listener' should be a function or an object.");let z=f(this),H=x(V),F=(H?Boolean(V.capture):Boolean(V))?C:S,D={listener:l,listenerType:F,passive:H&&Boolean(V.passive),once:H&&Boolean(V.once),next:null},P=z.get(c);if(P===void 0){z.set(c,D);return}let j=null;while(P!=null){if(P.listener===l&&P.listenerType===F)return;j=P,P=P.next}j.next=D},removeEventListener(c,l,V){if(l==null)return;let z=f(this),H=(x(V)?Boolean(V.capture):Boolean(V))?C:S,F=null,D=z.get(c);while(D!=null){if(D.listener===l&&D.listenerType===H){if(F!==null)F.next=D.next;else if(D.next!==null)z.set(c,D.next);else z.delete(c);return}F=D,D=D.next}},dispatchEvent(c){if(c==null||typeof c.type!=="string")throw TypeError('"event.type" should be a string.');let l=f(this),V=c.type,z=l.get(V);if(z==null)return!0;let H=I(this,c),F=null;while(z!=null){if(z.once)if(F!==null)F.next=z.next;else if(z.next!==null)l.set(V,z.next);else l.delete(V);else F=z;if(k(H,z.passive?z.listener:null),typeof z.listener==="function")try{z.listener.call(this,H)}catch(D){if(typeof console<"u"&&typeof console.error==="function")console.error(D)}else if(z.listenerType!==_&&typeof z.listener.handleEvent==="function")z.listener.handleEvent(H);if(L(H))break;z=z.next}return k(H,null),A(H,0),M(H,null),!H.defaultPrevented}},Object.defineProperty(t.prototype,"constructor",{value:t,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u")Object.setPrototypeOf(t.prototype,window.EventTarget.prototype);Q.defineEventAttribute=i,Q.EventTarget=t,Q.default=t,Z.exports=t,Z.exports.EventTarget=Z.exports.default=t,Z.exports.defineEventAttribute=i}),p6=FZ((Q,Z)=>{Object.defineProperty(Q,"__esModule",{value:!0});var Y=pr();class $ extends Y.EventTarget{constructor(){super();throw TypeError("AbortSignal cannot be constructed directly")}get aborted(){let O=G.get(this);if(typeof O!=="boolean")throw TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return O}}Y.defineEventAttribute($.prototype,"abort");function J(){let O=Object.create($.prototype);return Y.EventTarget.call(O),G.set(O,!1),O}function X(O){if(G.get(O)!==!1)return;G.set(O,!0),O.dispatchEvent({type:"abort"})}var G=new WeakMap;if(Object.defineProperties($.prototype,{aborted:{enumerable:!0}}),typeof Symbol==="function"&&typeof Symbol.toStringTag==="symbol")Object.defineProperty($.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});class W{constructor(){U.set(this,J())}get signal(){return K(this)}abort(){X(K(this))}}var U=new WeakMap;function K(O){let I=U.get(O);if(I==null)throw TypeError(`Expected 'this' to be an 'AbortController' object, but got ${O===null?"null":typeof O}`);return I}if(Object.defineProperties(W.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol==="function"&&typeof Symbol.toStringTag==="symbol")Object.defineProperty(W.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});Q.AbortController=W,Q.AbortSignal=$,Q.default=W,Z.exports=W,Z.exports.AbortController=Z.exports.default=W,Z.exports.AbortSignal=$}),w$=FZ((Q,Z)=>{var Y=(vY(),oQ(_Y)),{format:$,inspect:J}=pC(),{codes:{ERR_INVALID_ARG_TYPE:X}}=D$(),{kResistStopPropagation:G,AggregateError:W,SymbolDispose:U}=pZ(),K=globalThis.AbortSignal||p6().AbortSignal,O=globalThis.AbortController||p6().AbortController,I=Object.getPrototypeOf(async function(){}).constructor,L=globalThis.Blob||Y.Blob,A=typeof L<"u"?function(B){return B instanceof L}:function(B){return!1},M=(B,C)=>{if(B!==void 0&&(B===null||typeof B!=="object"||!("aborted"in B)))throw new X(C,"AbortSignal",B)},k=(B,C)=>{if(typeof B!=="function")throw new X(C,"Function",B)};Z.exports={AggregateError:W,kEmptyObject:Object.freeze({}),once(B){let C=!1;return function(...S){if(C)return;C=!0,B.apply(this,S)}},createDeferredPromise:function(){let B,C;return{promise:new Promise((S,_)=>{B=S,C=_}),resolve:B,reject:C}},promisify(B){return new Promise((C,S)=>{B((_,...x)=>{if(_)return S(_);return C(...x)})})},debuglog(){return function(){}},format:$,inspect:J,types:{isAsyncFunction(B){return B instanceof I},isArrayBufferView(B){return ArrayBuffer.isView(B)}},isBlob:A,deprecate(B,C){return B},addAbortListener:(u6(),oQ(c6)).addAbortListener||function(B,C){if(B===void 0)throw new X("signal","AbortSignal",B);M(B,"signal"),k(C,"listener");let S;if(B.aborted)queueMicrotask(()=>C());else B.addEventListener("abort",C,{__proto__:null,once:!0,[G]:!0}),S=()=>{B.removeEventListener("abort",C)};return{__proto__:null,[U](){var _;(_=S)===null||_===void 0||_()}}},AbortSignalAny:K.any||function(B){if(B.length===1)return B[0];let C=new O,S=()=>C.abort();return B.forEach((_)=>{M(_,"signals"),_.addEventListener("abort",S,{once:!0})}),C.signal.addEventListener("abort",()=>{B.forEach((_)=>_.removeEventListener("abort",S))},{once:!0}),C.signal}},Z.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),l6=FZ((Q,Z)=>{var{ArrayIsArray:Y,ArrayPrototypeIncludes:$,ArrayPrototypeJoin:J,ArrayPrototypeMap:X,NumberIsInteger:G,NumberIsNaN:W,NumberMAX_SAFE_INTEGER:U,NumberMIN_SAFE_INTEGER:K,NumberParseInt:O,ObjectPrototypeHasOwnProperty:I,RegExpPrototypeExec:L,String:A,StringPrototypeToUpperCase:M,StringPrototypeTrim:k}=pZ(),{hideStackFrames:B,codes:{ERR_SOCKET_BAD_PORT:C,ERR_INVALID_ARG_TYPE:S,ERR_INVALID_ARG_VALUE:_,ERR_OUT_OF_RANGE:x,ERR_UNKNOWN_SIGNAL:f}}=D$(),{normalizeEncoding:h}=w$(),{isAsyncFunction:i,isArrayBufferView:Z0}=w$().types,t={};function c(d){return d===(d|0)}function l(d){return d===d>>>0}var V=/^[0-7]+$/,z="must be a 32-bit unsigned integer or an octal string";function H(d,X0,QQ){if(typeof d>"u")d=QQ;if(typeof d==="string"){if(L(V,d)===null)throw new _(X0,d,z);d=O(d,8)}return P(d,X0),d}var F=B((d,X0,QQ=K,V0=U)=>{if(typeof d!=="number")throw new S(X0,"number",d);if(!G(d))throw new x(X0,"an integer",d);if(d<QQ||d>V0)throw new x(X0,`>= ${QQ} && <= ${V0}`,d)}),D=B((d,X0,QQ=-2147483648,V0=2147483647)=>{if(typeof d!=="number")throw new S(X0,"number",d);if(!G(d))throw new x(X0,"an integer",d);if(d<QQ||d>V0)throw new x(X0,`>= ${QQ} && <= ${V0}`,d)}),P=B((d,X0,QQ=!1)=>{if(typeof d!=="number")throw new S(X0,"number",d);if(!G(d))throw new x(X0,"an integer",d);let V0=QQ?1:0,P0=4294967295;if(d<V0||d>P0)throw new x(X0,`>= ${V0} && <= ${P0}`,d)});function j(d,X0){if(typeof d!=="string")throw new S(X0,"string",d)}function R(d,X0,QQ=void 0,V0){if(typeof d!=="number")throw new S(X0,"number",d);if(QQ!=null&&d<QQ||V0!=null&&d>V0||(QQ!=null||V0!=null)&&W(d))throw new x(X0,`${QQ!=null?`>= ${QQ}`:""}${QQ!=null&&V0!=null?" && ":""}${V0!=null?`<= ${V0}`:""}`,d)}var q=B((d,X0,QQ)=>{if(!$(QQ,d)){let V0="must be one of: "+J(X(QQ,(P0)=>typeof P0==="string"?`'${P0}'`:A(P0)),", ");throw new _(X0,d,V0)}});function E(d,X0){if(typeof d!=="boolean")throw new S(X0,"boolean",d)}function N(d,X0,QQ){return d==null||!I(d,X0)?QQ:d[X0]}var T=B((d,X0,QQ=null)=>{let V0=N(QQ,"allowArray",!1),P0=N(QQ,"allowFunction",!1);if(!N(QQ,"nullable",!1)&&d===null||!V0&&Y(d)||typeof d!=="object"&&(!P0||typeof d!=="function"))throw new S(X0,"Object",d)}),v=B((d,X0)=>{if(d!=null&&typeof d!=="object"&&typeof d!=="function")throw new S(X0,"a dictionary",d)}),y=B((d,X0,QQ=0)=>{if(!Y(d))throw new S(X0,"Array",d);if(d.length<QQ){let V0=`must be longer than ${QQ}`;throw new _(X0,d,V0)}});function p(d,X0){y(d,X0);for(let QQ=0;QQ<d.length;QQ++)j(d[QQ],`${X0}[${QQ}]`)}function J0(d,X0){y(d,X0);for(let QQ=0;QQ<d.length;QQ++)E(d[QQ],`${X0}[${QQ}]`)}function x0(d,X0){y(d,X0);for(let QQ=0;QQ<d.length;QQ++){let V0=d[QQ],P0=`${X0}[${QQ}]`;if(V0==null)throw new S(P0,"AbortSignal",V0);D0(V0,P0)}}function K0(d,X0="signal"){if(j(d,X0),t[d]===void 0){if(t[M(d)]!==void 0)throw new f(d+" (signals must use all capital letters)");throw new f(d)}}var Y0=B((d,X0="buffer")=>{if(!Z0(d))throw new S(X0,["Buffer","TypedArray","DataView"],d)});function j0(d,X0){let QQ=h(X0),V0=d.length;if(QQ==="hex"&&V0%2!==0)throw new _("encoding",X0,`is invalid for data of length ${V0}`)}function $0(d,X0="Port",QQ=!0){if(typeof d!=="number"&&typeof d!=="string"||typeof d==="string"&&k(d).length===0||+d!==+d>>>0||d>65535||d===0&&!QQ)throw new C(X0,d,QQ);return d|0}var D0=B((d,X0)=>{if(d!==void 0&&(d===null||typeof d!=="object"||!("aborted"in d)))throw new S(X0,"AbortSignal",d)}),$Q=B((d,X0)=>{if(typeof d!=="function")throw new S(X0,"Function",d)}),m=B((d,X0)=>{if(typeof d!=="function"||i(d))throw new S(X0,"Function",d)}),n=B((d,X0)=>{if(d!==void 0)throw new S(X0,"undefined",d)});function B0(d,X0,QQ){if(!$(QQ,d))throw new S(X0,`('${J(QQ,"|")}')`,d)}var F0=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function z0(d,X0){if(typeof d>"u"||!L(F0,d))throw new _(X0,d,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function l0(d){if(typeof d==="string")return z0(d,"hints"),d;else if(Y(d)){let X0=d.length,QQ="";if(X0===0)return QQ;for(let V0=0;V0<X0;V0++){let P0=d[V0];if(z0(P0,"hints"),QQ+=P0,V0!==X0-1)QQ+=", "}return QQ}throw new _("hints",d,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}Z.exports={isInt32:c,isUint32:l,parseFileMode:H,validateArray:y,validateStringArray:p,validateBooleanArray:J0,validateAbortSignalArray:x0,validateBoolean:E,validateBuffer:Y0,validateDictionary:v,validateEncoding:j0,validateFunction:$Q,validateInt32:D,validateInteger:F,validateNumber:R,validateObject:T,validateOneOf:q,validatePlainFunction:m,validatePort:$0,validateSignalName:K0,validateString:j,validateUint32:P,validateUndefined:n,validateUnion:B0,validateAbortSignal:D0,validateLinkHeaderValue:l0}}),JX=FZ((Q,Z)=>{Z.exports=globalThis.process}),l1=FZ((Q,Z)=>{var{SymbolAsyncIterator:Y,SymbolIterator:$,SymbolFor:J}=pZ(),X=J("nodejs.stream.destroyed"),G=J("nodejs.stream.errored"),W=J("nodejs.stream.readable"),U=J("nodejs.stream.writable"),K=J("nodejs.stream.disturbed"),O=J("nodejs.webstream.isClosedPromise"),I=J("nodejs.webstream.controllerErrorFunction");function L(N,T=!1){var v;return!!(N&&typeof N.pipe==="function"&&typeof N.on==="function"&&(!T||typeof N.pause==="function"&&typeof N.resume==="function")&&(!N._writableState||((v=N._readableState)===null||v===void 0?void 0:v.readable)!==!1)&&(!N._writableState||N._readableState))}function A(N){var T;return!!(N&&typeof N.write==="function"&&typeof N.on==="function"&&(!N._readableState||((T=N._writableState)===null||T===void 0?void 0:T.writable)!==!1))}function M(N){return!!(N&&typeof N.pipe==="function"&&N._readableState&&typeof N.on==="function"&&typeof N.write==="function")}function k(N){return N&&(N._readableState||N._writableState||typeof N.write==="function"&&typeof N.on==="function"||typeof N.pipe==="function"&&typeof N.on==="function")}function B(N){return!!(N&&!k(N)&&typeof N.pipeThrough==="function"&&typeof N.getReader==="function"&&typeof N.cancel==="function")}function C(N){return!!(N&&!k(N)&&typeof N.getWriter==="function"&&typeof N.abort==="function")}function S(N){return!!(N&&!k(N)&&typeof N.readable==="object"&&typeof N.writable==="object")}function _(N){return B(N)||C(N)||S(N)}function x(N,T){if(N==null)return!1;if(T===!0)return typeof N[Y]==="function";if(T===!1)return typeof N[$]==="function";return typeof N[Y]==="function"||typeof N[$]==="function"}function f(N){if(!k(N))return null;let{_writableState:T,_readableState:v}=N,y=T||v;return!!(N.destroyed||N[X]||y!==null&&y!==void 0&&y.destroyed)}function h(N){if(!A(N))return null;if(N.writableEnded===!0)return!0;let T=N._writableState;if(T!==null&&T!==void 0&&T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function i(N,T){if(!A(N))return null;if(N.writableFinished===!0)return!0;let v=N._writableState;if(v!==null&&v!==void 0&&v.errored)return!1;if(typeof(v===null||v===void 0?void 0:v.finished)!=="boolean")return null;return!!(v.finished||T===!1&&v.ended===!0&&v.length===0)}function Z0(N){if(!L(N))return null;if(N.readableEnded===!0)return!0;let T=N._readableState;if(!T||T.errored)return!1;if(typeof(T===null||T===void 0?void 0:T.ended)!=="boolean")return null;return T.ended}function t(N,T){if(!L(N))return null;let v=N._readableState;if(v!==null&&v!==void 0&&v.errored)return!1;if(typeof(v===null||v===void 0?void 0:v.endEmitted)!=="boolean")return null;return!!(v.endEmitted||T===!1&&v.ended===!0&&v.length===0)}function c(N){if(N&&N[W]!=null)return N[W];if(typeof(N===null||N===void 0?void 0:N.readable)!=="boolean")return null;if(f(N))return!1;return L(N)&&N.readable&&!t(N)}function l(N){if(N&&N[U]!=null)return N[U];if(typeof(N===null||N===void 0?void 0:N.writable)!=="boolean")return null;if(f(N))return!1;return A(N)&&N.writable&&!h(N)}function V(N,T){if(!k(N))return null;if(f(N))return!0;if((T===null||T===void 0?void 0:T.readable)!==!1&&c(N))return!1;if((T===null||T===void 0?void 0:T.writable)!==!1&&l(N))return!1;return!0}function z(N){var T,v;if(!k(N))return null;if(N.writableErrored)return N.writableErrored;return(T=(v=N._writableState)===null||v===void 0?void 0:v.errored)!==null&&T!==void 0?T:null}function H(N){var T,v;if(!k(N))return null;if(N.readableErrored)return N.readableErrored;return(T=(v=N._readableState)===null||v===void 0?void 0:v.errored)!==null&&T!==void 0?T:null}function F(N){if(!k(N))return null;if(typeof N.closed==="boolean")return N.closed;let{_writableState:T,_readableState:v}=N;if(typeof(T===null||T===void 0?void 0:T.closed)==="boolean"||typeof(v===null||v===void 0?void 0:v.closed)==="boolean")return(T===null||T===void 0?void 0:T.closed)||(v===null||v===void 0?void 0:v.closed);if(typeof N._closed==="boolean"&&D(N))return N._closed;return null}function D(N){return typeof N._closed==="boolean"&&typeof N._defaultKeepAlive==="boolean"&&typeof N._removedConnection==="boolean"&&typeof N._removedContLen==="boolean"}function P(N){return typeof N._sent100==="boolean"&&D(N)}function j(N){var T;return typeof N._consuming==="boolean"&&typeof N._dumped==="boolean"&&((T=N.req)===null||T===void 0?void 0:T.upgradeOrConnect)===void 0}function R(N){if(!k(N))return null;let{_writableState:T,_readableState:v}=N,y=T||v;return!y&&P(N)||!!(y&&y.autoDestroy&&y.emitClose&&y.closed===!1)}function q(N){var T;return!!(N&&((T=N[K])!==null&&T!==void 0?T:N.readableDidRead||N.readableAborted))}function E(N){var T,v,y,p,J0,x0,K0,Y0,j0,$0;return!!(N&&((T=(v=(y=(p=(J0=(x0=N[G])!==null&&x0!==void 0?x0:N.readableErrored)!==null&&J0!==void 0?J0:N.writableErrored)!==null&&p!==void 0?p:(K0=N._readableState)===null||K0===void 0?void 0:K0.errorEmitted)!==null&&y!==void 0?y:(Y0=N._writableState)===null||Y0===void 0?void 0:Y0.errorEmitted)!==null&&v!==void 0?v:(j0=N._readableState)===null||j0===void 0?void 0:j0.errored)!==null&&T!==void 0?T:($0=N._writableState)===null||$0===void 0?void 0:$0.errored))}Z.exports={isDestroyed:f,kIsDestroyed:X,isDisturbed:q,kIsDisturbed:K,isErrored:E,kIsErrored:G,isReadable:c,kIsReadable:W,kIsClosedPromise:O,kControllerErrorFunction:I,kIsWritable:U,isClosed:F,isDuplexNodeStream:M,isFinished:V,isIterable:x,isReadableNodeStream:L,isReadableStream:B,isReadableEnded:Z0,isReadableFinished:t,isReadableErrored:H,isNodeStream:k,isWebStream:_,isWritable:l,isWritableNodeStream:A,isWritableStream:C,isWritableEnded:h,isWritableFinished:i,isWritableErrored:z,isServerRequest:j,isServerResponse:P,willEmitClose:R,isTransformStream:S}}),b8=FZ((Q,Z)=>{var Y=JX(),{AbortError:$,codes:J}=D$(),{ERR_INVALID_ARG_TYPE:X,ERR_STREAM_PREMATURE_CLOSE:G}=J,{kEmptyObject:W,once:U}=w$(),{validateAbortSignal:K,validateFunction:O,validateObject:I,validateBoolean:L}=l6(),{Promise:A,PromisePrototypeThen:M,SymbolDispose:k}=pZ(),{isClosed:B,isReadable:C,isReadableNodeStream:S,isReadableStream:_,isReadableFinished:x,isReadableErrored:f,isWritable:h,isWritableNodeStream:i,isWritableStream:Z0,isWritableFinished:t,isWritableErrored:c,isNodeStream:l,willEmitClose:V,kIsClosedPromise:z}=l1(),H;function F(q){return q.setHeader&&typeof q.abort==="function"}var D=()=>{};function P(q,E,N){var T,v;if(arguments.length===2)N=E,E=W;else if(E==null)E=W;else I(E,"options");if(O(N,"callback"),K(E.signal,"options.signal"),N=U(N),_(q)||Z0(q))return j(q,E,N);if(!l(q))throw new X("stream",["ReadableStream","WritableStream","Stream"],q);let y=(T=E.readable)!==null&&T!==void 0?T:S(q),p=(v=E.writable)!==null&&v!==void 0?v:i(q),J0=q._writableState,x0=q._readableState,K0=()=>{if(!q.writable)$0()},Y0=V(q)&&S(q)===y&&i(q)===p,j0=t(q,!1),$0=()=>{if(j0=!0,q.destroyed)Y0=!1;if(Y0&&(!q.readable||y))return;if(!y||D0)N.call(q)},D0=x(q,!1),$Q=()=>{if(D0=!0,q.destroyed)Y0=!1;if(Y0&&(!q.writable||p))return;if(!p||j0)N.call(q)},m=(d)=>{N.call(q,d)},n=B(q),B0=()=>{n=!0;let d=c(q)||f(q);if(d&&typeof d!=="boolean")return N.call(q,d);if(y&&!D0&&S(q,!0)){if(!x(q,!1))return N.call(q,new G)}if(p&&!j0){if(!t(q,!1))return N.call(q,new G)}N.call(q)},F0=()=>{n=!0;let d=c(q)||f(q);if(d&&typeof d!=="boolean")return N.call(q,d);N.call(q)},z0=()=>{q.req.on("finish",$0)};if(F(q)){if(q.on("complete",$0),!Y0)q.on("abort",B0);if(q.req)z0();else q.on("request",z0)}else if(p&&!J0)q.on("end",K0),q.on("close",K0);if(!Y0&&typeof q.aborted==="boolean")q.on("aborted",B0);if(q.on("end",$Q),q.on("finish",$0),E.error!==!1)q.on("error",m);if(q.on("close",B0),n)Y.nextTick(B0);else if(J0!==null&&J0!==void 0&&J0.errorEmitted||x0!==null&&x0!==void 0&&x0.errorEmitted){if(!Y0)Y.nextTick(F0)}else if(!y&&(!Y0||C(q))&&(j0||h(q)===!1))Y.nextTick(F0);else if(!p&&(!Y0||h(q))&&(D0||C(q)===!1))Y.nextTick(F0);else if(x0&&q.req&&q.aborted)Y.nextTick(F0);let l0=()=>{if(N=D,q.removeListener("aborted",B0),q.removeListener("complete",$0),q.removeListener("abort",B0),q.removeListener("request",z0),q.req)q.req.removeListener("finish",$0);q.removeListener("end",K0),q.removeListener("close",K0),q.removeListener("finish",$0),q.removeListener("end",$Q),q.removeListener("error",m),q.removeListener("close",B0)};if(E.signal&&!n){let d=()=>{let X0=N;l0(),X0.call(q,new $(void 0,{cause:E.signal.reason}))};if(E.signal.aborted)Y.nextTick(d);else{H=H||w$().addAbortListener;let X0=H(E.signal,d),QQ=N;N=U((...V0)=>{X0[k](),QQ.apply(q,V0)})}}return l0}function j(q,E,N){let T=!1,v=D;if(E.signal)if(v=()=>{T=!0,N.call(q,new $(void 0,{cause:E.signal.reason}))},E.signal.aborted)Y.nextTick(v);else{H=H||w$().addAbortListener;let p=H(E.signal,v),J0=N;N=U((...x0)=>{p[k](),J0.apply(q,x0)})}let y=(...p)=>{if(!T)Y.nextTick(()=>N.apply(q,p))};return M(q[z].promise,y,y),D}function R(q,E){var N;let T=!1;if(E===null)E=W;if((N=E)!==null&&N!==void 0&&N.cleanup)L(E.cleanup,"cleanup"),T=E.cleanup;return new A((v,y)=>{let p=P(q,E,(J0)=>{if(T)p();if(J0)y(J0);else v()})})}Z.exports=P,Z.exports.finished=R}),yV=FZ((Q,Z)=>{var Y=JX(),{aggregateTwoErrors:$,codes:{ERR_MULTIPLE_CALLBACK:J},AbortError:X}=D$(),{Symbol:G}=pZ(),{kIsDestroyed:W,isDestroyed:U,isFinished:K,isServerRequest:O}=l1(),I=G("kDestroy"),L=G("kConstruct");function A(V,z,H){if(V){if(V.stack,z&&!z.errored)z.errored=V;if(H&&!H.errored)H.errored=V}}function M(V,z){let H=this._readableState,F=this._writableState,D=F||H;if(F!==null&&F!==void 0&&F.destroyed||H!==null&&H!==void 0&&H.destroyed){if(typeof z==="function")z();return this}if(A(V,F,H),F)F.destroyed=!0;if(H)H.destroyed=!0;if(!D.constructed)this.once(I,function(P){k(this,$(P,V),z)});else k(this,V,z);return this}function k(V,z,H){let F=!1;function D(P){if(F)return;F=!0;let{_readableState:j,_writableState:R}=V;if(A(P,R,j),R)R.closed=!0;if(j)j.closed=!0;if(typeof H==="function")H(P);if(P)Y.nextTick(B,V,P);else Y.nextTick(C,V)}try{V._destroy(z||null,D)}catch(P){D(P)}}function B(V,z){S(V,z),C(V)}function C(V){let{_readableState:z,_writableState:H}=V;if(H)H.closeEmitted=!0;if(z)z.closeEmitted=!0;if(H!==null&&H!==void 0&&H.emitClose||z!==null&&z!==void 0&&z.emitClose)V.emit("close")}function S(V,z){let{_readableState:H,_writableState:F}=V;if(F!==null&&F!==void 0&&F.errorEmitted||H!==null&&H!==void 0&&H.errorEmitted)return;if(F)F.errorEmitted=!0;if(H)H.errorEmitted=!0;V.emit("error",z)}function _(){let V=this._readableState,z=this._writableState;if(V)V.constructed=!0,V.closed=!1,V.closeEmitted=!1,V.destroyed=!1,V.errored=null,V.errorEmitted=!1,V.reading=!1,V.ended=V.readable===!1,V.endEmitted=V.readable===!1;if(z)z.constructed=!0,z.destroyed=!1,z.closed=!1,z.closeEmitted=!1,z.errored=null,z.errorEmitted=!1,z.finalCalled=!1,z.prefinished=!1,z.ended=z.writable===!1,z.ending=z.writable===!1,z.finished=z.writable===!1}function x(V,z,H){let{_readableState:F,_writableState:D}=V;if(D!==null&&D!==void 0&&D.destroyed||F!==null&&F!==void 0&&F.destroyed)return this;if(F!==null&&F!==void 0&&F.autoDestroy||D!==null&&D!==void 0&&D.autoDestroy)V.destroy(z);else if(z){if(z.stack,D&&!D.errored)D.errored=z;if(F&&!F.errored)F.errored=z;if(H)Y.nextTick(S,V,z);else S(V,z)}}function f(V,z){if(typeof V._construct!=="function")return;let{_readableState:H,_writableState:F}=V;if(H)H.constructed=!1;if(F)F.constructed=!1;if(V.once(L,z),V.listenerCount(L)>1)return;Y.nextTick(h,V)}function h(V){let z=!1;function H(F){if(z){x(V,F!==null&&F!==void 0?F:new J);return}z=!0;let{_readableState:D,_writableState:P}=V,j=P||D;if(D)D.constructed=!0;if(P)P.constructed=!0;if(j.destroyed)V.emit(I,F);else if(F)x(V,F,!0);else Y.nextTick(i,V)}try{V._construct((F)=>{Y.nextTick(H,F)})}catch(F){Y.nextTick(H,F)}}function i(V){V.emit(L)}function Z0(V){return(V===null||V===void 0?void 0:V.setHeader)&&typeof V.abort==="function"}function t(V){V.emit("close")}function c(V,z){V.emit("error",z),Y.nextTick(t,V)}function l(V,z){if(!V||U(V))return;if(!z&&!K(V))z=new X;if(O(V))V.socket=null,V.destroy(z);else if(Z0(V))V.abort();else if(Z0(V.req))V.req.abort();else if(typeof V.destroy==="function")V.destroy(z);else if(typeof V.close==="function")V.close();else if(z)Y.nextTick(c,V,z);else Y.nextTick(t,V);if(!V.destroyed)V[W]=!0}Z.exports={construct:f,destroyer:l,destroy:M,undestroy:_,errorOrDestroy:x}}),WD=FZ((Q,Z)=>{var{ArrayIsArray:Y,ObjectSetPrototypeOf:$}=pZ(),{EventEmitter:J}=(u6(),oQ(c6));function X(W){J.call(this,W)}$(X.prototype,J.prototype),$(X,J),X.prototype.pipe=function(W,U){let K=this;function O(C){if(W.writable&&W.write(C)===!1&&K.pause)K.pause()}K.on("data",O);function I(){if(K.readable&&K.resume)K.resume()}if(W.on("drain",I),!W._isStdio&&(!U||U.end!==!1))K.on("end",A),K.on("close",M);let L=!1;function A(){if(L)return;L=!0,W.end()}function M(){if(L)return;if(L=!0,typeof W.destroy==="function")W.destroy()}function k(C){if(B(),J.listenerCount(this,"error")===0)this.emit("error",C)}G(K,"error",k),G(W,"error",k);function B(){K.removeListener("data",O),W.removeListener("drain",I),K.removeListener("end",A),K.removeListener("close",M),K.removeListener("error",k),W.removeListener("error",k),K.removeListener("end",B),K.removeListener("close",B),W.removeListener("close",B)}return K.on("end",B),K.on("close",B),W.on("close",B),W.emit("pipe",K),W};function G(W,U,K){if(typeof W.prependListener==="function")return W.prependListener(U,K);if(!W._events||!W._events[U])W.on(U,K);else if(Y(W._events[U]))W._events[U].unshift(K);else W._events[U]=[K,W._events[U]]}Z.exports={Stream:X,prependListener:G}}),_W=FZ((Q,Z)=>{var{SymbolDispose:Y}=pZ(),{AbortError:$,codes:J}=D$(),{isNodeStream:X,isWebStream:G,kControllerErrorFunction:W}=l1(),U=b8(),{ERR_INVALID_ARG_TYPE:K}=J,O,I=(L,A)=>{if(typeof L!=="object"||!("aborted"in L))throw new K(A,"AbortSignal",L)};Z.exports.addAbortSignal=function(L,A){if(I(L,"signal"),!X(A)&&!G(A))throw new K("stream",["ReadableStream","WritableStream","Stream"],A);return Z.exports.addAbortSignalNoValidate(L,A)},Z.exports.addAbortSignalNoValidate=function(L,A){if(typeof L!=="object"||!("aborted"in L))return A;let M=X(A)?()=>{A.destroy(new $(void 0,{cause:L.reason}))}:()=>{A[W](new $(void 0,{cause:L.reason}))};if(L.aborted)M();else{O=O||w$().addAbortListener;let k=O(L,M);U(A,k[Y])}return A}}),lr=FZ((Q,Z)=>{var{StringPrototypeSlice:Y,SymbolIterator:$,TypedArrayPrototypeSet:J,Uint8Array:X}=pZ(),{Buffer:G}=(vY(),oQ(_Y)),{inspect:W}=w$();Z.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(U){let K={data:U,next:null};if(this.length>0)this.tail.next=K;else this.head=K;this.tail=K,++this.length}unshift(U){let K={data:U,next:this.head};if(this.length===0)this.tail=K;this.head=K,++this.length}shift(){if(this.length===0)return;let U=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,U}clear(){this.head=this.tail=null,this.length=0}join(U){if(this.length===0)return"";let K=this.head,O=""+K.data;while((K=K.next)!==null)O+=U+K.data;return O}concat(U){if(this.length===0)return G.alloc(0);let K=G.allocUnsafe(U>>>0),O=this.head,I=0;while(O)J(K,O.data,I),I+=O.data.length,O=O.next;return K}consume(U,K){let O=this.head.data;if(U<O.length){let I=O.slice(0,U);return this.head.data=O.slice(U),I}if(U===O.length)return this.shift();return K?this._getString(U):this._getBuffer(U)}first(){return this.head.data}*[$](){for(let U=this.head;U;U=U.next)yield U.data}_getString(U){let K="",O=this.head,I=0;do{let L=O.data;if(U>L.length)K+=L,U-=L.length;else{if(U===L.length)if(K+=L,++I,O.next)this.head=O.next;else this.head=this.tail=null;else K+=Y(L,0,U),this.head=O,O.data=Y(L,U);break}++I}while((O=O.next)!==null);return this.length-=I,K}_getBuffer(U){let K=G.allocUnsafe(U),O=U,I=this.head,L=0;do{let A=I.data;if(U>A.length)J(K,A,O-U),U-=A.length;else{if(U===A.length)if(J(K,A,O-U),++L,I.next)this.head=I.next;else this.head=this.tail=null;else J(K,new X(A.buffer,A.byteOffset,U),O-U),this.head=I,I.data=A.slice(U);break}++L}while((I=I.next)!==null);return this.length-=L,K}[Symbol.for("nodejs.util.inspect.custom")](U,K){return W(this,{...K,depth:0,customInspect:!1})}}}),vW=FZ((Q,Z)=>{var{MathFloor:Y,NumberIsInteger:$}=pZ(),{validateInteger:J}=l6(),{ERR_INVALID_ARG_VALUE:X}=D$().codes,G=16384,W=16;function U(L,A,M){return L.highWaterMark!=null?L.highWaterMark:A?L[M]:null}function K(L){return L?W:G}function O(L,A){if(J(A,"value",0),L)W=A;else G=A}function I(L,A,M,k){let B=U(A,k,M);if(B!=null){if(!$(B)||B<0){let C=k?`options.${M}`:"options.highWaterMark";throw new X(C,B)}return Y(B)}return K(L.objectMode)}Z.exports={getHighWaterMark:I,getDefaultHighWaterMark:K,setDefaultHighWaterMark:O}}),mr=FZ((Q,Z)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var Y=(vY(),oQ(_Y)),$=Y.Buffer;function J(G,W){for(var U in G)W[U]=G[U]}if($.from&&$.alloc&&$.allocUnsafe&&$.allocUnsafeSlow)Z.exports=Y;else J(Y,Q),Q.Buffer=X;function X(G,W,U){return $(G,W,U)}X.prototype=Object.create($.prototype),J($,X),X.from=function(G,W,U){if(typeof G==="number")throw TypeError("Argument must not be a number");return $(G,W,U)},X.alloc=function(G,W,U){if(typeof G!=="number")throw TypeError("Argument must be a number");var K=$(G);if(W!==void 0)if(typeof U==="string")K.fill(W,U);else K.fill(W);else K.fill(0);return K},X.allocUnsafe=function(G){if(typeof G!=="number")throw TypeError("Argument must be a number");return $(G)},X.allocUnsafeSlow=function(G){if(typeof G!=="number")throw TypeError("Argument must be a number");return Y.SlowBuffer(G)}}),dr=FZ((Q)=>{var Z=mr().Buffer,Y=Z.isEncoding||function(S){switch(S=""+S,S&&S.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function $(S){if(!S)return"utf8";var _;while(!0)switch(S){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return S;default:if(_)return;S=(""+S).toLowerCase(),_=!0}}function J(S){var _=$(S);if(typeof _!=="string"&&(Z.isEncoding===Y||!Y(S)))throw Error("Unknown encoding: "+S);return _||S}Q.StringDecoder=X;function X(S){this.encoding=J(S);var _;switch(this.encoding){case"utf16le":this.text=L,this.end=A,_=4;break;case"utf8":this.fillLast=K,_=4;break;case"base64":this.text=M,this.end=k,_=3;break;default:this.write=B,this.end=C;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Z.allocUnsafe(_)}X.prototype.write=function(S){if(S.length===0)return"";var _,x;if(this.lastNeed){if(_=this.fillLast(S),_===void 0)return"";x=this.lastNeed,this.lastNeed=0}else x=0;if(x<S.length)return _?_+this.text(S,x):this.text(S,x);return _||""},X.prototype.end=I,X.prototype.text=O,X.prototype.fillLast=function(S){if(this.lastNeed<=S.length)return S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,S.length),this.lastNeed-=S.length};function G(S){if(S<=127)return 0;else if(S>>5===6)return 2;else if(S>>4===14)return 3;else if(S>>3===30)return 4;return S>>6===2?-1:-2}function W(S,_,x){var f=_.length-1;if(f<x)return 0;var h=G(_[f]);if(h>=0){if(h>0)S.lastNeed=h-1;return h}if(--f<x||h===-2)return 0;if(h=G(_[f]),h>=0){if(h>0)S.lastNeed=h-2;return h}if(--f<x||h===-2)return 0;if(h=G(_[f]),h>=0){if(h>0)if(h===2)h=0;else S.lastNeed=h-3;return h}return 0}function U(S,_,x){if((_[0]&192)!==128)return S.lastNeed=0,"�";if(S.lastNeed>1&&_.length>1){if((_[1]&192)!==128)return S.lastNeed=1,"�";if(S.lastNeed>2&&_.length>2){if((_[2]&192)!==128)return S.lastNeed=2,"�"}}}function K(S){var _=this.lastTotal-this.lastNeed,x=U(this,S,_);if(x!==void 0)return x;if(this.lastNeed<=S.length)return S.copy(this.lastChar,_,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);S.copy(this.lastChar,_,0,S.length),this.lastNeed-=S.length}function O(S,_){var x=W(this,S,_);if(!this.lastNeed)return S.toString("utf8",_);this.lastTotal=x;var f=S.length-(x-this.lastNeed);return S.copy(this.lastChar,0,f),S.toString("utf8",_,f)}function I(S){var _=S&&S.length?this.write(S):"";if(this.lastNeed)return _+"�";return _}function L(S,_){if((S.length-_)%2===0){var x=S.toString("utf16le",_);if(x){var f=x.charCodeAt(x.length-1);if(f>=55296&&f<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1],x.slice(0,-1)}return x}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=S[S.length-1],S.toString("utf16le",_,S.length-1)}function A(S){var _=S&&S.length?this.write(S):"";if(this.lastNeed){var x=this.lastTotal-this.lastNeed;return _+this.lastChar.toString("utf16le",0,x)}return _}function M(S,_){var x=(S.length-_)%3;if(x===0)return S.toString("base64",_);if(this.lastNeed=3-x,this.lastTotal=3,x===1)this.lastChar[0]=S[S.length-1];else this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1];return S.toString("base64",_,S.length-x)}function k(S){var _=S&&S.length?this.write(S):"";if(this.lastNeed)return _+this.lastChar.toString("base64",0,3-this.lastNeed);return _}function B(S){return S.toString(this.encoding)}function C(S){return S&&S.length?this.write(S):""}}),lC=FZ((Q,Z)=>{var Y=JX(),{PromisePrototypeThen:$,SymbolAsyncIterator:J,SymbolIterator:X}=pZ(),{Buffer:G}=(vY(),oQ(_Y)),{ERR_INVALID_ARG_TYPE:W,ERR_STREAM_NULL_VALUES:U}=D$().codes;function K(O,I,L){let A;if(typeof I==="string"||I instanceof G)return new O({objectMode:!0,...L,read(){this.push(I),this.push(null)}});let M;if(I&&I[J])M=!0,A=I[J]();else if(I&&I[X])M=!1,A=I[X]();else throw new W("iterable",["Iterable"],I);let k=new O({objectMode:!0,highWaterMark:1,...L}),B=!1;k._read=function(){if(!B)B=!0,S()},k._destroy=function(_,x){$(C(_),()=>Y.nextTick(x,_),(f)=>Y.nextTick(x,f||_))};async function C(_){let x=_!==void 0&&_!==null,f=typeof A.throw==="function";if(x&&f){let{value:h,done:i}=await A.throw(_);if(await h,i)return}if(typeof A.return==="function"){let{value:h}=await A.return();await h}}async function S(){for(;;){try{let{value:_,done:x}=M?await A.next():A.next();if(x)k.push(null);else{let f=_&&typeof _.then==="function"?await _:_;if(f===null)throw B=!1,new U;else if(k.push(f))continue;else B=!1}}catch(_){k.destroy(_)}break}}return k}Z.exports=K}),xW=FZ((Q,Z)=>{var Y=JX(),{ArrayPrototypeIndexOf:$,NumberIsInteger:J,NumberIsNaN:X,NumberParseInt:G,ObjectDefineProperties:W,ObjectKeys:U,ObjectSetPrototypeOf:K,Promise:O,SafeSet:I,SymbolAsyncDispose:L,SymbolAsyncIterator:A,Symbol:M}=pZ();Z.exports=V0,V0.ReadableState=QQ;var{EventEmitter:k}=(u6(),oQ(c6)),{Stream:B,prependListener:C}=WD(),{Buffer:S}=(vY(),oQ(_Y)),{addAbortSignal:_}=_W(),x=b8(),f=w$().debuglog("stream",(b)=>{f=b}),h=lr(),i=yV(),{getHighWaterMark:Z0,getDefaultHighWaterMark:t}=vW(),{aggregateTwoErrors:c,codes:{ERR_INVALID_ARG_TYPE:l,ERR_METHOD_NOT_IMPLEMENTED:V,ERR_OUT_OF_RANGE:z,ERR_STREAM_PUSH_AFTER_EOF:H,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:F},AbortError:D}=D$(),{validateObject:P}=l6(),j=M("kPaused"),{StringDecoder:R}=dr(),q=lC();K(V0.prototype,B.prototype),K(V0,B);var E=()=>{},{errorOrDestroy:N}=i,T=1,v=2,y=4,p=8,J0=16,x0=32,K0=64,Y0=128,j0=256,$0=512,D0=1024,$Q=2048,m=4096,n=8192,B0=16384,F0=32768,z0=65536,l0=131072,d=262144;function X0(b){return{enumerable:!1,get(){return(this.state&b)!==0},set(Q0){if(Q0)this.state|=b;else this.state&=~b}}}W(QQ.prototype,{objectMode:X0(T),ended:X0(v),endEmitted:X0(y),reading:X0(p),constructed:X0(J0),sync:X0(x0),needReadable:X0(K0),emittedReadable:X0(Y0),readableListening:X0(j0),resumeScheduled:X0($0),errorEmitted:X0(D0),emitClose:X0($Q),autoDestroy:X0(m),destroyed:X0(n),closed:X0(B0),closeEmitted:X0(F0),multiAwaitDrain:X0(z0),readingMore:X0(l0),dataEmitted:X0(d)});function QQ(b,Q0,O0){if(typeof O0!=="boolean")O0=Q0 instanceof p1();if(this.state=$Q|m|J0|x0,b&&b.objectMode)this.state|=T;if(O0&&b&&b.readableObjectMode)this.state|=T;if(this.highWaterMark=b?Z0(this,b,"readableHighWaterMark",O0):t(!1),this.buffer=new h,this.length=0,this.pipes=[],this.flowing=null,this[j]=null,b&&b.emitClose===!1)this.state&=~$Q;if(b&&b.autoDestroy===!1)this.state&=~m;if(this.errored=null,this.defaultEncoding=b&&b.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,b&&b.encoding)this.decoder=new R(b.encoding),this.encoding=b.encoding}function V0(b){if(!(this instanceof V0))return new V0(b);let Q0=this instanceof p1();if(this._readableState=new QQ(b,this,Q0),b){if(typeof b.read==="function")this._read=b.read;if(typeof b.destroy==="function")this._destroy=b.destroy;if(typeof b.construct==="function")this._construct=b.construct;if(b.signal&&!Q0)_(b.signal,this)}B.call(this,b),i.construct(this,()=>{if(this._readableState.needReadable)G0(this,this._readableState)})}V0.prototype.destroy=i.destroy,V0.prototype._undestroy=i.undestroy,V0.prototype._destroy=function(b,Q0){Q0(b)},V0.prototype[k.captureRejectionSymbol]=function(b){this.destroy(b)},V0.prototype[L]=function(){let b;if(!this.destroyed)b=this.readableEnded?null:new D,this.destroy(b);return new O((Q0,O0)=>x(this,(L0)=>L0&&L0!==b?O0(L0):Q0(null)))},V0.prototype.push=function(b,Q0){return P0(this,b,Q0,!1)},V0.prototype.unshift=function(b,Q0){return P0(this,b,Q0,!0)};function P0(b,Q0,O0,L0){f("readableAddChunk",Q0);let qQ=b._readableState,m0;if((qQ.state&T)===0){if(typeof Q0==="string"){if(O0=O0||qQ.defaultEncoding,qQ.encoding!==O0)if(L0&&qQ.encoding)Q0=S.from(Q0,O0).toString(qQ.encoding);else Q0=S.from(Q0,O0),O0=""}else if(Q0 instanceof S)O0="";else if(B._isUint8Array(Q0))Q0=B._uint8ArrayToBuffer(Q0),O0="";else if(Q0!=null)m0=new l("chunk",["string","Buffer","Uint8Array"],Q0)}if(m0)N(b,m0);else if(Q0===null)qQ.state&=~p,y0(b,qQ);else if((qQ.state&T)!==0||Q0&&Q0.length>0)if(L0)if((qQ.state&y)!==0)N(b,new F);else if(qQ.destroyed||qQ.errored)return!1;else jQ(b,qQ,Q0,!0);else if(qQ.ended)N(b,new H);else if(qQ.destroyed||qQ.errored)return!1;else if(qQ.state&=~p,qQ.decoder&&!O0)if(Q0=qQ.decoder.write(Q0),qQ.objectMode||Q0.length!==0)jQ(b,qQ,Q0,!1);else G0(b,qQ);else jQ(b,qQ,Q0,!1);else if(!L0)qQ.state&=~p,G0(b,qQ);return!qQ.ended&&(qQ.length<qQ.highWaterMark||qQ.length===0)}function jQ(b,Q0,O0,L0){if(Q0.flowing&&Q0.length===0&&!Q0.sync&&b.listenerCount("data")>0){if((Q0.state&z0)!==0)Q0.awaitDrainWriters.clear();else Q0.awaitDrainWriters=null;Q0.dataEmitted=!0,b.emit("data",O0)}else{if(Q0.length+=Q0.objectMode?1:O0.length,L0)Q0.buffer.unshift(O0);else Q0.buffer.push(O0);if((Q0.state&K0)!==0)s(b)}G0(b,Q0)}V0.prototype.isPaused=function(){let b=this._readableState;return b[j]===!0||b.flowing===!1},V0.prototype.setEncoding=function(b){let Q0=new R(b);this._readableState.decoder=Q0,this._readableState.encoding=this._readableState.decoder.encoding;let O0=this._readableState.buffer,L0="";for(let qQ of O0)L0+=Q0.write(qQ);if(O0.clear(),L0!=="")O0.push(L0);return this._readableState.length=L0.length,this};var c0=1073741824;function u0(b){if(b>c0)throw new z("size","<= 1GiB",b);else b--,b|=b>>>1,b|=b>>>2,b|=b>>>4,b|=b>>>8,b|=b>>>16,b++;return b}function $Z(b,Q0){if(b<=0||Q0.length===0&&Q0.ended)return 0;if((Q0.state&T)!==0)return 1;if(X(b)){if(Q0.flowing&&Q0.length)return Q0.buffer.first().length;return Q0.length}if(b<=Q0.length)return b;return Q0.ended?Q0.length:0}V0.prototype.read=function(b){if(f("read",b),b===void 0)b=NaN;else if(!J(b))b=G(b,10);let Q0=this._readableState,O0=b;if(b>Q0.highWaterMark)Q0.highWaterMark=u0(b);if(b!==0)Q0.state&=~Y0;if(b===0&&Q0.needReadable&&((Q0.highWaterMark!==0?Q0.length>=Q0.highWaterMark:Q0.length>0)||Q0.ended)){if(f("read: emitReadable",Q0.length,Q0.ended),Q0.length===0&&Q0.ended)gQ(this);else s(this);return null}if(b=$Z(b,Q0),b===0&&Q0.ended){if(Q0.length===0)gQ(this);return null}let L0=(Q0.state&K0)!==0;if(f("need readable",L0),Q0.length===0||Q0.length-b<Q0.highWaterMark)L0=!0,f("length less than watermark",L0);if(Q0.ended||Q0.reading||Q0.destroyed||Q0.errored||!Q0.constructed)L0=!1,f("reading, ended or constructing",L0);else if(L0){if(f("do read"),Q0.state|=p|x0,Q0.length===0)Q0.state|=K0;try{this._read(Q0.highWaterMark)}catch(m0){N(this,m0)}if(Q0.state&=~x0,!Q0.reading)b=$Z(O0,Q0)}let qQ;if(b>0)qQ=S0(b,Q0);else qQ=null;if(qQ===null)Q0.needReadable=Q0.length<=Q0.highWaterMark,b=0;else if(Q0.length-=b,Q0.multiAwaitDrain)Q0.awaitDrainWriters.clear();else Q0.awaitDrainWriters=null;if(Q0.length===0){if(!Q0.ended)Q0.needReadable=!0;if(O0!==b&&Q0.ended)gQ(this)}if(qQ!==null&&!Q0.errorEmitted&&!Q0.closeEmitted)Q0.dataEmitted=!0,this.emit("data",qQ);return qQ};function y0(b,Q0){if(f("onEofChunk"),Q0.ended)return;if(Q0.decoder){let O0=Q0.decoder.end();if(O0&&O0.length)Q0.buffer.push(O0),Q0.length+=Q0.objectMode?1:O0.length}if(Q0.ended=!0,Q0.sync)s(b);else Q0.needReadable=!1,Q0.emittedReadable=!0,M0(b)}function s(b){let Q0=b._readableState;if(f("emitReadable",Q0.needReadable,Q0.emittedReadable),Q0.needReadable=!1,!Q0.emittedReadable)f("emitReadable",Q0.flowing),Q0.emittedReadable=!0,Y.nextTick(M0,b)}function M0(b){let Q0=b._readableState;if(f("emitReadable_",Q0.destroyed,Q0.length,Q0.ended),!Q0.destroyed&&!Q0.errored&&(Q0.length||Q0.ended))b.emit("readable"),Q0.emittedReadable=!1;Q0.needReadable=!Q0.flowing&&!Q0.ended&&Q0.length<=Q0.highWaterMark,A0(b)}function G0(b,Q0){if(!Q0.readingMore&&Q0.constructed)Q0.readingMore=!0,Y.nextTick(H0,b,Q0)}function H0(b,Q0){while(!Q0.reading&&!Q0.ended&&(Q0.length<Q0.highWaterMark||Q0.flowing&&Q0.length===0)){let O0=Q0.length;if(f("maybeReadMore read 0"),b.read(0),O0===Q0.length)break}Q0.readingMore=!1}V0.prototype._read=function(b){throw new V("_read()")},V0.prototype.pipe=function(b,Q0){let O0=this,L0=this._readableState;if(L0.pipes.length===1){if(!L0.multiAwaitDrain)L0.multiAwaitDrain=!0,L0.awaitDrainWriters=new I(L0.awaitDrainWriters?[L0.awaitDrainWriters]:[])}L0.pipes.push(b),f("pipe count=%d opts=%j",L0.pipes.length,Q0);let qQ=(!Q0||Q0.end!==!1)&&b!==Y.stdout&&b!==Y.stderr?n0:pQ;if(L0.endEmitted)Y.nextTick(qQ);else O0.once("end",qQ);b.on("unpipe",m0);function m0(IZ,zZ){if(f("onunpipe"),IZ===O0){if(zZ&&zZ.hasUnpiped===!1)zZ.hasUnpiped=!0,e0()}}function n0(){f("onend"),b.end()}let lZ,r0=!1;function e0(){if(f("cleanup"),b.removeListener("close",mZ),b.removeListener("finish",lQ),lZ)b.removeListener("drain",lZ);if(b.removeListener("error",a0),b.removeListener("unpipe",m0),O0.removeListener("end",n0),O0.removeListener("end",pQ),O0.removeListener("data",t0),r0=!0,lZ&&L0.awaitDrainWriters&&(!b._writableState||b._writableState.needDrain))lZ()}function bY(){if(!r0){if(L0.pipes.length===1&&L0.pipes[0]===b)f("false write response, pause",0),L0.awaitDrainWriters=b,L0.multiAwaitDrain=!1;else if(L0.pipes.length>1&&L0.pipes.includes(b))f("false write response, pause",L0.awaitDrainWriters.size),L0.awaitDrainWriters.add(b);O0.pause()}if(!lZ)lZ=KQ(O0,b),b.on("drain",lZ)}O0.on("data",t0);function t0(IZ){f("ondata");let zZ=b.write(IZ);if(f("dest.write",zZ),zZ===!1)bY()}function a0(IZ){if(f("onerror",IZ),pQ(),b.removeListener("error",a0),b.listenerCount("error")===0){let zZ=b._writableState||b._readableState;if(zZ&&!zZ.errorEmitted)N(b,IZ);else b.emit("error",IZ)}}C(b,"error",a0);function mZ(){b.removeListener("finish",lQ),pQ()}b.once("close",mZ);function lQ(){f("onfinish"),b.removeListener("close",mZ),pQ()}b.once("finish",lQ);function pQ(){f("unpipe"),O0.unpipe(b)}if(b.emit("pipe",O0),b.writableNeedDrain===!0)bY();else if(!L0.flowing)f("pipe resume"),O0.resume();return b};function KQ(b,Q0){return function(){let O0=b._readableState;if(O0.awaitDrainWriters===Q0)f("pipeOnDrain",1),O0.awaitDrainWriters=null;else if(O0.multiAwaitDrain)f("pipeOnDrain",O0.awaitDrainWriters.size),O0.awaitDrainWriters.delete(Q0);if((!O0.awaitDrainWriters||O0.awaitDrainWriters.size===0)&&b.listenerCount("data"))b.resume()}}V0.prototype.unpipe=function(b){let Q0=this._readableState,O0={hasUnpiped:!1};if(Q0.pipes.length===0)return this;if(!b){let qQ=Q0.pipes;Q0.pipes=[],this.pause();for(let m0=0;m0<qQ.length;m0++)qQ[m0].emit("unpipe",this,{hasUnpiped:!1});return this}let L0=$(Q0.pipes,b);if(L0===-1)return this;if(Q0.pipes.splice(L0,1),Q0.pipes.length===0)this.pause();return b.emit("unpipe",this,O0),this},V0.prototype.on=function(b,Q0){let O0=B.prototype.on.call(this,b,Q0),L0=this._readableState;if(b==="data"){if(L0.readableListening=this.listenerCount("readable")>0,L0.flowing!==!1)this.resume()}else if(b==="readable"){if(!L0.endEmitted&&!L0.readableListening){if(L0.readableListening=L0.needReadable=!0,L0.flowing=!1,L0.emittedReadable=!1,f("on readable",L0.length,L0.reading),L0.length)s(this);else if(!L0.reading)Y.nextTick(h0,this)}}return O0},V0.prototype.addListener=V0.prototype.on,V0.prototype.removeListener=function(b,Q0){let O0=B.prototype.removeListener.call(this,b,Q0);if(b==="readable")Y.nextTick(f0,this);return O0},V0.prototype.off=V0.prototype.removeListener,V0.prototype.removeAllListeners=function(b){let Q0=B.prototype.removeAllListeners.apply(this,arguments);if(b==="readable"||b===void 0)Y.nextTick(f0,this);return Q0};function f0(b){let Q0=b._readableState;if(Q0.readableListening=b.listenerCount("readable")>0,Q0.resumeScheduled&&Q0[j]===!1)Q0.flowing=!0;else if(b.listenerCount("data")>0)b.resume();else if(!Q0.readableListening)Q0.flowing=null}function h0(b){f("readable nexttick read 0"),b.read(0)}V0.prototype.resume=function(){let b=this._readableState;if(!b.flowing)f("resume"),b.flowing=!b.readableListening,LQ(this,b);return b[j]=!1,this};function LQ(b,Q0){if(!Q0.resumeScheduled)Q0.resumeScheduled=!0,Y.nextTick(E0,b,Q0)}function E0(b,Q0){if(f("resume",Q0.reading),!Q0.reading)b.read(0);if(Q0.resumeScheduled=!1,b.emit("resume"),A0(b),Q0.flowing&&!Q0.reading)b.read(0)}V0.prototype.pause=function(){if(f("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1)f("pause"),this._readableState.flowing=!1,this.emit("pause");return this._readableState[j]=!0,this};function A0(b){let Q0=b._readableState;f("flow",Q0.flowing);while(Q0.flowing&&b.read()!==null);}V0.prototype.wrap=function(b){let Q0=!1;b.on("data",(L0)=>{if(!this.push(L0)&&b.pause)Q0=!0,b.pause()}),b.on("end",()=>{this.push(null)}),b.on("error",(L0)=>{N(this,L0)}),b.on("close",()=>{this.destroy()}),b.on("destroy",()=>{this.destroy()}),this._read=()=>{if(Q0&&b.resume)Q0=!1,b.resume()};let O0=U(b);for(let L0=1;L0<O0.length;L0++){let qQ=O0[L0];if(this[qQ]===void 0&&typeof b[qQ]==="function")this[qQ]=b[qQ].bind(b)}return this},V0.prototype[A]=function(){return GQ(this)},V0.prototype.iterator=function(b){if(b!==void 0)P(b,"options");return GQ(this,b)};function GQ(b,Q0){if(typeof b.read!=="function")b=V0.wrap(b,{objectMode:!0});let O0=T0(b,Q0);return O0.stream=b,O0}async function*T0(b,Q0){let O0=E;function L0(n0){if(this===b)O0(),O0=E;else O0=n0}b.on("readable",L0);let qQ,m0=x(b,{writable:!1},(n0)=>{qQ=n0?c(qQ,n0):null,O0(),O0=E});try{while(!0){let n0=b.destroyed?null:b.read();if(n0!==null)yield n0;else if(qQ)throw qQ;else if(qQ===null)return;else await new O(L0)}}catch(n0){throw qQ=c(qQ,n0),qQ}finally{if((qQ||(Q0===null||Q0===void 0?void 0:Q0.destroyOnReturn)!==!1)&&(qQ===void 0||b._readableState.autoDestroy))i.destroyer(b,null);else b.off("readable",L0),m0()}}W(V0.prototype,{readable:{__proto__:null,get(){let b=this._readableState;return!!b&&b.readable!==!1&&!b.destroyed&&!b.errorEmitted&&!b.endEmitted},set(b){if(this._readableState)this._readableState.readable=!!b}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(b){if(this._readableState)this._readableState.flowing=b}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(b){if(!this._readableState)return;this._readableState.destroyed=b}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),W(QQ.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[j]!==!1},set(b){this[j]=!!b}}}),V0._fromList=S0;function S0(b,Q0){if(Q0.length===0)return null;let O0;if(Q0.objectMode)O0=Q0.buffer.shift();else if(!b||b>=Q0.length){if(Q0.decoder)O0=Q0.buffer.join("");else if(Q0.buffer.length===1)O0=Q0.buffer.first();else O0=Q0.buffer.concat(Q0.length);Q0.buffer.clear()}else O0=Q0.buffer.consume(b,Q0.decoder);return O0}function gQ(b){let Q0=b._readableState;if(f("endReadable",Q0.endEmitted),!Q0.endEmitted)Q0.ended=!0,Y.nextTick(g0,Q0,b)}function g0(b,Q0){if(f("endReadableNT",b.endEmitted,b.length),!b.errored&&!b.closeEmitted&&!b.endEmitted&&b.length===0){if(b.endEmitted=!0,Q0.emit("end"),Q0.writable&&Q0.allowHalfOpen===!1)Y.nextTick(d0,Q0);else if(b.autoDestroy){let O0=Q0._writableState;if(!O0||O0.autoDestroy&&(O0.finished||O0.writable===!1))Q0.destroy()}}}function d0(b){if(b.writable&&!b.writableEnded&&!b.destroyed)b.end()}V0.from=function(b,Q0){return q(V0,b,Q0)};var _Z;function o0(){if(_Z===void 0)_Z={};return _Z}V0.fromWeb=function(b,Q0){return o0().newStreamReadableFromReadableStream(b,Q0)},V0.toWeb=function(b,Q0){return o0().newReadableStreamFromStreamReadable(b,Q0)},V0.wrap=function(b,Q0){var O0,L0;return new V0({objectMode:(O0=(L0=b.readableObjectMode)!==null&&L0!==void 0?L0:b.objectMode)!==null&&O0!==void 0?O0:!0,...Q0,destroy(qQ,m0){i.destroyer(b,qQ),m0(qQ)}}).wrap(b)}}),KD=FZ((Q,Z)=>{var Y=JX(),{ArrayPrototypeSlice:$,Error:J,FunctionPrototypeSymbolHasInstance:X,ObjectDefineProperty:G,ObjectDefineProperties:W,ObjectSetPrototypeOf:U,StringPrototypeToLowerCase:K,Symbol:O,SymbolHasInstance:I}=pZ();Z.exports=P,P.WritableState=F;var{EventEmitter:L}=(u6(),oQ(c6)),A=WD().Stream,{Buffer:M}=(vY(),oQ(_Y)),k=yV(),{addAbortSignal:B}=_W(),{getHighWaterMark:C,getDefaultHighWaterMark:S}=vW(),{ERR_INVALID_ARG_TYPE:_,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_MULTIPLE_CALLBACK:f,ERR_STREAM_CANNOT_PIPE:h,ERR_STREAM_DESTROYED:i,ERR_STREAM_ALREADY_FINISHED:Z0,ERR_STREAM_NULL_VALUES:t,ERR_STREAM_WRITE_AFTER_END:c,ERR_UNKNOWN_ENCODING:l}=D$().codes,{errorOrDestroy:V}=k;U(P.prototype,A.prototype),U(P,A);function z(){}var H=O("kOnFinished");function F(m,n,B0){if(typeof B0!=="boolean")B0=n instanceof p1();if(this.objectMode=!!(m&&m.objectMode),B0)this.objectMode=this.objectMode||!!(m&&m.writableObjectMode);this.highWaterMark=m?C(this,m,"writableHighWaterMark",B0):S(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let F0=!!(m&&m.decodeStrings===!1);this.decodeStrings=!F0,this.defaultEncoding=m&&m.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=N.bind(void 0,n),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,D(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!m||m.emitClose!==!1,this.autoDestroy=!m||m.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[H]=[]}function D(m){m.buffered=[],m.bufferedIndex=0,m.allBuffers=!0,m.allNoop=!0}F.prototype.getBuffer=function(){return $(this.buffered,this.bufferedIndex)},G(F.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function P(m){let n=this instanceof p1();if(!n&&!X(P,this))return new P(m);if(this._writableState=new F(m,this,n),m){if(typeof m.write==="function")this._write=m.write;if(typeof m.writev==="function")this._writev=m.writev;if(typeof m.destroy==="function")this._destroy=m.destroy;if(typeof m.final==="function")this._final=m.final;if(typeof m.construct==="function")this._construct=m.construct;if(m.signal)B(m.signal,this)}A.call(this,m),k.construct(this,()=>{let B0=this._writableState;if(!B0.writing)p(this,B0);Y0(this,B0)})}G(P,I,{__proto__:null,value:function(m){if(X(this,m))return!0;if(this!==P)return!1;return m&&m._writableState instanceof F}}),P.prototype.pipe=function(){V(this,new h)};function j(m,n,B0,F0){let z0=m._writableState;if(typeof B0==="function")F0=B0,B0=z0.defaultEncoding;else{if(!B0)B0=z0.defaultEncoding;else if(B0!=="buffer"&&!M.isEncoding(B0))throw new l(B0);if(typeof F0!=="function")F0=z}if(n===null)throw new t;else if(!z0.objectMode)if(typeof n==="string"){if(z0.decodeStrings!==!1)n=M.from(n,B0),B0="buffer"}else if(n instanceof M)B0="buffer";else if(A._isUint8Array(n))n=A._uint8ArrayToBuffer(n),B0="buffer";else throw new _("chunk",["string","Buffer","Uint8Array"],n);let l0;if(z0.ending)l0=new c;else if(z0.destroyed)l0=new i("write");if(l0)return Y.nextTick(F0,l0),V(m,l0,!0),l0;return z0.pendingcb++,R(m,z0,n,B0,F0)}P.prototype.write=function(m,n,B0){return j(this,m,n,B0)===!0},P.prototype.cork=function(){this._writableState.corked++},P.prototype.uncork=function(){let m=this._writableState;if(m.corked){if(m.corked--,!m.writing)p(this,m)}},P.prototype.setDefaultEncoding=function(m){if(typeof m==="string")m=K(m);if(!M.isEncoding(m))throw new l(m);return this._writableState.defaultEncoding=m,this};function R(m,n,B0,F0,z0){let l0=n.objectMode?1:B0.length;n.length+=l0;let d=n.length<n.highWaterMark;if(!d)n.needDrain=!0;if(n.writing||n.corked||n.errored||!n.constructed){if(n.buffered.push({chunk:B0,encoding:F0,callback:z0}),n.allBuffers&&F0!=="buffer")n.allBuffers=!1;if(n.allNoop&&z0!==z)n.allNoop=!1}else n.writelen=l0,n.writecb=z0,n.writing=!0,n.sync=!0,m._write(B0,F0,n.onwrite),n.sync=!1;return d&&!n.errored&&!n.destroyed}function q(m,n,B0,F0,z0,l0,d){if(n.writelen=F0,n.writecb=d,n.writing=!0,n.sync=!0,n.destroyed)n.onwrite(new i("write"));else if(B0)m._writev(z0,n.onwrite);else m._write(z0,l0,n.onwrite);n.sync=!1}function E(m,n,B0,F0){--n.pendingcb,F0(B0),y(n),V(m,B0)}function N(m,n){let B0=m._writableState,F0=B0.sync,z0=B0.writecb;if(typeof z0!=="function"){V(m,new f);return}if(B0.writing=!1,B0.writecb=null,B0.length-=B0.writelen,B0.writelen=0,n){if(n.stack,!B0.errored)B0.errored=n;if(m._readableState&&!m._readableState.errored)m._readableState.errored=n;if(F0)Y.nextTick(E,m,B0,n,z0);else E(m,B0,n,z0)}else{if(B0.buffered.length>B0.bufferedIndex)p(m,B0);if(F0)if(B0.afterWriteTickInfo!==null&&B0.afterWriteTickInfo.cb===z0)B0.afterWriteTickInfo.count++;else B0.afterWriteTickInfo={count:1,cb:z0,stream:m,state:B0},Y.nextTick(T,B0.afterWriteTickInfo);else v(m,B0,1,z0)}}function T({stream:m,state:n,count:B0,cb:F0}){return n.afterWriteTickInfo=null,v(m,n,B0,F0)}function v(m,n,B0,F0){if(!n.ending&&!m.destroyed&&n.length===0&&n.needDrain)n.needDrain=!1,m.emit("drain");while(B0-- >0)n.pendingcb--,F0();if(n.destroyed)y(n);Y0(m,n)}function y(m){if(m.writing)return;for(let z0=m.bufferedIndex;z0<m.buffered.length;++z0){var n;let{chunk:l0,callback:d}=m.buffered[z0],X0=m.objectMode?1:l0.length;m.length-=X0,d((n=m.errored)!==null&&n!==void 0?n:new i("write"))}let B0=m[H].splice(0);for(let z0=0;z0<B0.length;z0++){var F0;B0[z0]((F0=m.errored)!==null&&F0!==void 0?F0:new i("end"))}D(m)}function p(m,n){if(n.corked||n.bufferProcessing||n.destroyed||!n.constructed)return;let{buffered:B0,bufferedIndex:F0,objectMode:z0}=n,l0=B0.length-F0;if(!l0)return;let d=F0;if(n.bufferProcessing=!0,l0>1&&m._writev){n.pendingcb-=l0-1;let X0=n.allNoop?z:(V0)=>{for(let P0=d;P0<B0.length;++P0)B0[P0].callback(V0)},QQ=n.allNoop&&d===0?B0:$(B0,d);QQ.allBuffers=n.allBuffers,q(m,n,!0,n.length,QQ,"",X0),D(n)}else{do{let{chunk:X0,encoding:QQ,callback:V0}=B0[d];B0[d++]=null;let P0=z0?1:X0.length;q(m,n,!1,P0,X0,QQ,V0)}while(d<B0.length&&!n.writing);if(d===B0.length)D(n);else if(d>256)B0.splice(0,d),n.bufferedIndex=0;else n.bufferedIndex=d}n.bufferProcessing=!1}P.prototype._write=function(m,n,B0){if(this._writev)this._writev([{chunk:m,encoding:n}],B0);else throw new x("_write()")},P.prototype._writev=null,P.prototype.end=function(m,n,B0){let F0=this._writableState;if(typeof m==="function")B0=m,m=null,n=null;else if(typeof n==="function")B0=n,n=null;let z0;if(m!==null&&m!==void 0){let l0=j(this,m,n);if(l0 instanceof J)z0=l0}if(F0.corked)F0.corked=1,this.uncork();if(z0);else if(!F0.errored&&!F0.ending)F0.ending=!0,Y0(this,F0,!0),F0.ended=!0;else if(F0.finished)z0=new Z0("end");else if(F0.destroyed)z0=new i("end");if(typeof B0==="function")if(z0||F0.finished)Y.nextTick(B0,z0);else F0[H].push(B0);return this};function J0(m){return m.ending&&!m.destroyed&&m.constructed&&m.length===0&&!m.errored&&m.buffered.length===0&&!m.finished&&!m.writing&&!m.errorEmitted&&!m.closeEmitted}function x0(m,n){let B0=!1;function F0(z0){if(B0){V(m,z0!==null&&z0!==void 0?z0:f());return}if(B0=!0,n.pendingcb--,z0){let l0=n[H].splice(0);for(let d=0;d<l0.length;d++)l0[d](z0);V(m,z0,n.sync)}else if(J0(n))n.prefinished=!0,m.emit("prefinish"),n.pendingcb++,Y.nextTick(j0,m,n)}n.sync=!0,n.pendingcb++;try{m._final(F0)}catch(z0){F0(z0)}n.sync=!1}function K0(m,n){if(!n.prefinished&&!n.finalCalled)if(typeof m._final==="function"&&!n.destroyed)n.finalCalled=!0,x0(m,n);else n.prefinished=!0,m.emit("prefinish")}function Y0(m,n,B0){if(J0(n)){if(K0(m,n),n.pendingcb===0){if(B0)n.pendingcb++,Y.nextTick((F0,z0)=>{if(J0(z0))j0(F0,z0);else z0.pendingcb--},m,n);else if(J0(n))n.pendingcb++,j0(m,n)}}}function j0(m,n){n.pendingcb--,n.finished=!0;let B0=n[H].splice(0);for(let F0=0;F0<B0.length;F0++)B0[F0]();if(m.emit("finish"),n.autoDestroy){let F0=m._readableState;if(!F0||F0.autoDestroy&&(F0.endEmitted||F0.readable===!1))m.destroy()}}W(P.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(m){if(this._writableState)this._writableState.destroyed=m}},writable:{__proto__:null,get(){let m=this._writableState;return!!m&&m.writable!==!1&&!m.destroyed&&!m.errored&&!m.ending&&!m.ended},set(m){if(this._writableState)this._writableState.writable=!!m}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let m=this._writableState;if(!m)return!1;return!m.destroyed&&!m.ending&&m.needDrain}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var $0=k.destroy;P.prototype.destroy=function(m,n){let B0=this._writableState;if(!B0.destroyed&&(B0.bufferedIndex<B0.buffered.length||B0[H].length))Y.nextTick(y,B0);return $0.call(this,m,n),this},P.prototype._undestroy=k.undestroy,P.prototype._destroy=function(m,n){n(m)},P.prototype[L.captureRejectionSymbol]=function(m){this.destroy(m)};var D0;function $Q(){if(D0===void 0)D0={};return D0}P.fromWeb=function(m,n){return $Q().newStreamWritableFromWritableStream(m,n)},P.toWeb=function(m){return $Q().newWritableStreamFromStreamWritable(m)}}),nr=FZ((Q,Z)=>{var Y=JX(),$=(vY(),oQ(_Y)),{isReadable:J,isWritable:X,isIterable:G,isNodeStream:W,isReadableNodeStream:U,isWritableNodeStream:K,isDuplexNodeStream:O,isReadableStream:I,isWritableStream:L}=l1(),A=b8(),{AbortError:M,codes:{ERR_INVALID_ARG_TYPE:k,ERR_INVALID_RETURN_VALUE:B}}=D$(),{destroyer:C}=yV(),S=p1(),_=xW(),x=KD(),{createDeferredPromise:f}=w$(),h=lC(),i=globalThis.Blob||$.Blob,Z0=typeof i<"u"?function(H){return H instanceof i}:function(H){return!1},t=globalThis.AbortController||p6().AbortController,{FunctionPrototypeCall:c}=pZ();class l extends S{constructor(H){super(H);if((H===null||H===void 0?void 0:H.readable)===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if((H===null||H===void 0?void 0:H.writable)===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}}Z.exports=function H(F,D){if(O(F))return F;if(U(F))return z({readable:F});if(K(F))return z({writable:F});if(W(F))return z({writable:!1,readable:!1});if(I(F))return z({readable:_.fromWeb(F)});if(L(F))return z({writable:x.fromWeb(F)});if(typeof F==="function"){let{value:j,write:R,final:q,destroy:E}=V(F);if(G(j))return h(l,j,{objectMode:!0,write:R,final:q,destroy:E});let N=j===null||j===void 0?void 0:j.then;if(typeof N==="function"){let T,v=c(N,j,(y)=>{if(y!=null)throw new B("nully","body",y)},(y)=>{C(T,y)});return T=new l({objectMode:!0,readable:!1,write:R,final(y){q(async()=>{try{await v,Y.nextTick(y,null)}catch(p){Y.nextTick(y,p)}})},destroy:E})}throw new B("Iterable, AsyncIterable or AsyncFunction",D,j)}if(Z0(F))return H(F.arrayBuffer());if(G(F))return h(l,F,{objectMode:!0,writable:!1});if(I(F===null||F===void 0?void 0:F.readable)&&L(F===null||F===void 0?void 0:F.writable))return l.fromWeb(F);if(typeof(F===null||F===void 0?void 0:F.writable)==="object"||typeof(F===null||F===void 0?void 0:F.readable)==="object"){let j=F!==null&&F!==void 0&&F.readable?U(F===null||F===void 0?void 0:F.readable)?F===null||F===void 0?void 0:F.readable:H(F.readable):void 0,R=F!==null&&F!==void 0&&F.writable?K(F===null||F===void 0?void 0:F.writable)?F===null||F===void 0?void 0:F.writable:H(F.writable):void 0;return z({readable:j,writable:R})}let P=F===null||F===void 0?void 0:F.then;if(typeof P==="function"){let j;return c(P,F,(R)=>{if(R!=null)j.push(R);j.push(null)},(R)=>{C(j,R)}),j=new l({objectMode:!0,writable:!1,read(){}})}throw new k(D,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],F)};function V(H){let{promise:F,resolve:D}=f(),P=new t,j=P.signal;return{value:H(async function*(){while(!0){let R=F;F=null;let{chunk:q,done:E,cb:N}=await R;if(Y.nextTick(N),E)return;if(j.aborted)throw new M(void 0,{cause:j.reason});({promise:F,resolve:D}=f()),yield q}}(),{signal:j}),write(R,q,E){let N=D;D=null,N({chunk:R,done:!1,cb:E})},final(R){let q=D;D=null,q({done:!0,cb:R})},destroy(R,q){P.abort(),q(R)}}}function z(H){let F=H.readable&&typeof H.readable.read!=="function"?_.wrap(H.readable):H.readable,D=H.writable,P=!!J(F),j=!!X(D),R,q,E,N,T;function v(y){let p=N;if(N=null,p)p(y);else if(y)T.destroy(y)}if(T=new l({readableObjectMode:!!(F!==null&&F!==void 0&&F.readableObjectMode),writableObjectMode:!!(D!==null&&D!==void 0&&D.writableObjectMode),readable:P,writable:j}),j)A(D,(y)=>{if(j=!1,y)C(F,y);v(y)}),T._write=function(y,p,J0){if(D.write(y,p))J0();else R=J0},T._final=function(y){D.end(),q=y},D.on("drain",function(){if(R){let y=R;R=null,y()}}),D.on("finish",function(){if(q){let y=q;q=null,y()}});if(P)A(F,(y)=>{if(P=!1,y)C(F,y);v(y)}),F.on("readable",function(){if(E){let y=E;E=null,y()}}),F.on("end",function(){T.push(null)}),T._read=function(){while(!0){let y=F.read();if(y===null){E=T._read;return}if(!T.push(y))return}};return T._destroy=function(y,p){if(!y&&N!==null)y=new M;if(E=null,R=null,q=null,N===null)p(y);else N=p,C(D,y),C(F,y)},T}}),p1=FZ((Q,Z)=>{var{ObjectDefineProperties:Y,ObjectGetOwnPropertyDescriptor:$,ObjectKeys:J,ObjectSetPrototypeOf:X}=pZ();Z.exports=U;var G=xW(),W=KD();X(U.prototype,G.prototype),X(U,G);{let L=J(W.prototype);for(let A=0;A<L.length;A++){let M=L[A];if(!U.prototype[M])U.prototype[M]=W.prototype[M]}}function U(L){if(!(this instanceof U))return new U(L);if(G.call(this,L),W.call(this,L),L){if(this.allowHalfOpen=L.allowHalfOpen!==!1,L.readable===!1)this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0;if(L.writable===!1)this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0}else this.allowHalfOpen=!0}Y(U.prototype,{writable:{__proto__:null,...$(W.prototype,"writable")},writableHighWaterMark:{__proto__:null,...$(W.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...$(W.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...$(W.prototype,"writableBuffer")},writableLength:{__proto__:null,...$(W.prototype,"writableLength")},writableFinished:{__proto__:null,...$(W.prototype,"writableFinished")},writableCorked:{__proto__:null,...$(W.prototype,"writableCorked")},writableEnded:{__proto__:null,...$(W.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...$(W.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){if(this._readableState===void 0||this._writableState===void 0)return!1;return this._readableState.destroyed&&this._writableState.destroyed},set(L){if(this._readableState&&this._writableState)this._readableState.destroyed=L,this._writableState.destroyed=L}}});var K;function O(){if(K===void 0)K={};return K}U.fromWeb=function(L,A){return O().newStreamDuplexFromReadableWritablePair(L,A)},U.toWeb=function(L){return O().newReadableWritablePairFromDuplex(L)};var I;U.from=function(L){if(!I)I=nr();return I(L,"body")}}),mC=FZ((Q,Z)=>{var{ObjectSetPrototypeOf:Y,Symbol:$}=pZ();Z.exports=U;var{ERR_METHOD_NOT_IMPLEMENTED:J}=D$().codes,X=p1(),{getHighWaterMark:G}=vW();Y(U.prototype,X.prototype),Y(U,X);var W=$("kCallback");function U(I){if(!(this instanceof U))return new U(I);let L=I?G(this,I,"readableHighWaterMark",!0):null;if(L===0)I={...I,highWaterMark:null,readableHighWaterMark:L,writableHighWaterMark:I.writableHighWaterMark||0};if(X.call(this,I),this._readableState.sync=!1,this[W]=null,I){if(typeof I.transform==="function")this._transform=I.transform;if(typeof I.flush==="function")this._flush=I.flush}this.on("prefinish",O)}function K(I){if(typeof this._flush==="function"&&!this.destroyed)this._flush((L,A)=>{if(L){if(I)I(L);else this.destroy(L);return}if(A!=null)this.push(A);if(this.push(null),I)I()});else if(this.push(null),I)I()}function O(){if(this._final!==K)K.call(this)}U.prototype._final=K,U.prototype._transform=function(I,L,A){throw new J("_transform()")},U.prototype._write=function(I,L,A){let M=this._readableState,k=this._writableState,B=M.length;this._transform(I,L,(C,S)=>{if(C){A(C);return}if(S!=null)this.push(S);if(k.ended||B===M.length||M.length<M.highWaterMark)A();else this[W]=A})},U.prototype._read=function(){if(this[W]){let I=this[W];this[W]=null,I()}}}),dC=FZ((Q,Z)=>{var{ObjectSetPrototypeOf:Y}=pZ();Z.exports=J;var $=mC();Y(J.prototype,$.prototype),Y(J,$);function J(X){if(!(this instanceof J))return new J(X);$.call(this,X)}J.prototype._transform=function(X,G,W){W(null,X)}}),UD=FZ((Q,Z)=>{var Y=JX(),{ArrayIsArray:$,Promise:J,SymbolAsyncIterator:X,SymbolDispose:G}=pZ(),W=b8(),{once:U}=w$(),K=yV(),O=p1(),{aggregateTwoErrors:I,codes:{ERR_INVALID_ARG_TYPE:L,ERR_INVALID_RETURN_VALUE:A,ERR_MISSING_ARGS:M,ERR_STREAM_DESTROYED:k,ERR_STREAM_PREMATURE_CLOSE:B},AbortError:C}=D$(),{validateFunction:S,validateAbortSignal:_}=l6(),{isIterable:x,isReadable:f,isReadableNodeStream:h,isNodeStream:i,isTransformStream:Z0,isWebStream:t,isReadableStream:c,isReadableFinished:l}=l1(),V=globalThis.AbortController||p6().AbortController,z,H,F;function D(y,p,J0){let x0=!1;y.on("close",()=>{x0=!0});let K0=W(y,{readable:p,writable:J0},(Y0)=>{x0=!Y0});return{destroy:(Y0)=>{if(x0)return;x0=!0,K.destroyer(y,Y0||new k("pipe"))},cleanup:K0}}function P(y){return S(y[y.length-1],"streams[stream.length - 1]"),y.pop()}function j(y){if(x(y))return y;else if(h(y))return R(y);throw new L("val",["Readable","Iterable","AsyncIterable"],y)}async function*R(y){if(!H)H=xW();yield*H.prototype[X].call(y)}async function q(y,p,J0,{end:x0}){let K0,Y0=null,j0=($Q)=>{if($Q)K0=$Q;if(Y0){let m=Y0;Y0=null,m()}},$0=()=>new J(($Q,m)=>{if(K0)m(K0);else Y0=()=>{if(K0)m(K0);else $Q()}});p.on("drain",j0);let D0=W(p,{readable:!1},j0);try{if(p.writableNeedDrain)await $0();for await(let $Q of y)if(!p.write($Q))await $0();if(x0)p.end(),await $0();J0()}catch($Q){J0(K0!==$Q?I(K0,$Q):$Q)}finally{D0(),p.off("drain",j0)}}async function E(y,p,J0,{end:x0}){if(Z0(p))p=p.writable;let K0=p.getWriter();try{for await(let Y0 of y)await K0.ready,K0.write(Y0).catch(()=>{});if(await K0.ready,x0)await K0.close();J0()}catch(Y0){try{await K0.abort(Y0),J0(Y0)}catch(j0){J0(j0)}}}function N(...y){return T(y,U(P(y)))}function T(y,p,J0){if(y.length===1&&$(y[0]))y=y[0];if(y.length<2)throw new M("streams");let x0=new V,K0=x0.signal,Y0=J0===null||J0===void 0?void 0:J0.signal,j0=[];_(Y0,"options.signal");function $0(){z0(new C)}F=F||w$().addAbortListener;let D0;if(Y0)D0=F(Y0,$0);let $Q,m,n=[],B0=0;function F0(V0){z0(V0,--B0===0)}function z0(V0,P0){var jQ;if(V0&&(!$Q||$Q.code==="ERR_STREAM_PREMATURE_CLOSE"))$Q=V0;if(!$Q&&!P0)return;while(n.length)n.shift()($Q);if((jQ=D0)===null||jQ===void 0||jQ[G](),x0.abort(),P0){if(!$Q)j0.forEach((c0)=>c0());Y.nextTick(p,$Q,m)}}let l0;for(let V0=0;V0<y.length;V0++){let P0=y[V0],jQ=V0<y.length-1,c0=V0>0,u0=jQ||(J0===null||J0===void 0?void 0:J0.end)!==!1,$Z=V0===y.length-1;if(i(P0)){let y0=function(s){if(s&&s.name!=="AbortError"&&s.code!=="ERR_STREAM_PREMATURE_CLOSE")F0(s)};var d=y0;if(u0){let{destroy:s,cleanup:M0}=D(P0,jQ,c0);if(n.push(s),f(P0)&&$Z)j0.push(M0)}if(P0.on("error",y0),f(P0)&&$Z)j0.push(()=>{P0.removeListener("error",y0)})}if(V0===0)if(typeof P0==="function"){if(l0=P0({signal:K0}),!x(l0))throw new A("Iterable, AsyncIterable or Stream","source",l0)}else if(x(P0)||h(P0)||Z0(P0))l0=P0;else l0=O.from(P0);else if(typeof P0==="function"){if(Z0(l0)){var X0;l0=j((X0=l0)===null||X0===void 0?void 0:X0.readable)}else l0=j(l0);if(l0=P0(l0,{signal:K0}),jQ){if(!x(l0,!0))throw new A("AsyncIterable",`transform[${V0-1}]`,l0)}else{var QQ;if(!z)z=dC();let y0=new z({objectMode:!0}),s=(QQ=l0)===null||QQ===void 0?void 0:QQ.then;if(typeof s==="function")B0++,s.call(l0,(H0)=>{if(m=H0,H0!=null)y0.write(H0);if(u0)y0.end();Y.nextTick(F0)},(H0)=>{y0.destroy(H0),Y.nextTick(F0,H0)});else if(x(l0,!0))B0++,q(l0,y0,F0,{end:u0});else if(c(l0)||Z0(l0)){let H0=l0.readable||l0;B0++,q(H0,y0,F0,{end:u0})}else throw new A("AsyncIterable or Promise","destination",l0);l0=y0;let{destroy:M0,cleanup:G0}=D(l0,!1,!0);if(n.push(M0),$Z)j0.push(G0)}}else if(i(P0)){if(h(l0)){B0+=2;let y0=v(l0,P0,F0,{end:u0});if(f(P0)&&$Z)j0.push(y0)}else if(Z0(l0)||c(l0)){let y0=l0.readable||l0;B0++,q(y0,P0,F0,{end:u0})}else if(x(l0))B0++,q(l0,P0,F0,{end:u0});else throw new L("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],l0);l0=P0}else if(t(P0)){if(h(l0))B0++,E(j(l0),P0,F0,{end:u0});else if(c(l0)||x(l0))B0++,E(l0,P0,F0,{end:u0});else if(Z0(l0))B0++,E(l0.readable,P0,F0,{end:u0});else throw new L("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],l0);l0=P0}else l0=O.from(P0)}if(K0!==null&&K0!==void 0&&K0.aborted||Y0!==null&&Y0!==void 0&&Y0.aborted)Y.nextTick($0);return l0}function v(y,p,J0,{end:x0}){let K0=!1;if(p.on("close",()=>{if(!K0)J0(new B)}),y.pipe(p,{end:!1}),x0){let j0=function(){K0=!0,p.end()};var Y0=j0;if(l(y))Y.nextTick(j0);else y.once("end",j0)}else J0();return W(y,{readable:!0,writable:!1},(j0)=>{let $0=y._readableState;if(j0&&j0.code==="ERR_STREAM_PREMATURE_CLOSE"&&$0&&$0.ended&&!$0.errored&&!$0.errorEmitted)y.once("end",J0).once("error",J0);else J0(j0)}),W(p,{readable:!1,writable:!0},J0)}Z.exports={pipelineImpl:T,pipeline:N}}),nC=FZ((Q,Z)=>{var{pipeline:Y}=UD(),$=p1(),{destroyer:J}=yV(),{isNodeStream:X,isReadable:G,isWritable:W,isWebStream:U,isTransformStream:K,isWritableStream:O,isReadableStream:I}=l1(),{AbortError:L,codes:{ERR_INVALID_ARG_VALUE:A,ERR_MISSING_ARGS:M}}=D$(),k=b8();Z.exports=function(...B){if(B.length===0)throw new M("streams");if(B.length===1)return $.from(B[0]);let C=[...B];if(typeof B[0]==="function")B[0]=$.from(B[0]);if(typeof B[B.length-1]==="function"){let V=B.length-1;B[V]=$.from(B[V])}for(let V=0;V<B.length;++V){if(!X(B[V])&&!U(B[V]))continue;if(V<B.length-1&&!(G(B[V])||I(B[V])||K(B[V])))throw new A(`streams[${V}]`,C[V],"must be readable");if(V>0&&!(W(B[V])||O(B[V])||K(B[V])))throw new A(`streams[${V}]`,C[V],"must be writable")}let S,_,x,f,h;function i(V){let z=f;if(f=null,z)z(V);else if(V)h.destroy(V);else if(!l&&!c)h.destroy()}let Z0=B[0],t=Y(B,i),c=!!(W(Z0)||O(Z0)||K(Z0)),l=!!(G(t)||I(t)||K(t));if(h=new $({writableObjectMode:!!(Z0!==null&&Z0!==void 0&&Z0.writableObjectMode),readableObjectMode:!!(t!==null&&t!==void 0&&t.readableObjectMode),writable:c,readable:l}),c){if(X(Z0))h._write=function(z,H,F){if(Z0.write(z,H))F();else S=F},h._final=function(z){Z0.end(),_=z},Z0.on("drain",function(){if(S){let z=S;S=null,z()}});else if(U(Z0)){let z=(K(Z0)?Z0.writable:Z0).getWriter();h._write=async function(H,F,D){try{await z.ready,z.write(H).catch(()=>{}),D()}catch(P){D(P)}},h._final=async function(H){try{await z.ready,z.close().catch(()=>{}),_=H}catch(F){H(F)}}}let V=K(t)?t.readable:t;k(V,()=>{if(_){let z=_;_=null,z()}})}if(l){if(X(t))t.on("readable",function(){if(x){let V=x;x=null,V()}}),t.on("end",function(){h.push(null)}),h._read=function(){while(!0){let V=t.read();if(V===null){x=h._read;return}if(!h.push(V))return}};else if(U(t)){let V=(K(t)?t.readable:t).getReader();h._read=async function(){while(!0)try{let{value:z,done:H}=await V.read();if(!h.push(z))return;if(H){h.push(null);return}}catch{return}}}}return h._destroy=function(V,z){if(!V&&f!==null)V=new L;if(x=null,S=null,_=null,f===null)z(V);else if(f=z,X(t))J(t,V)},h}}),or=FZ((Q,Z)=>{var Y=globalThis.AbortController||p6().AbortController,{codes:{ERR_INVALID_ARG_VALUE:$,ERR_INVALID_ARG_TYPE:J,ERR_MISSING_ARGS:X,ERR_OUT_OF_RANGE:G},AbortError:W}=D$(),{validateAbortSignal:U,validateInteger:K,validateObject:O}=l6(),I=pZ().Symbol("kWeak"),L=pZ().Symbol("kResistStopPropagation"),{finished:A}=b8(),M=nC(),{addAbortSignalNoValidate:k}=_W(),{isWritable:B,isNodeStream:C}=l1(),{deprecate:S}=w$(),{ArrayPrototypePush:_,Boolean:x,MathFloor:f,Number:h,NumberIsNaN:i,Promise:Z0,PromiseReject:t,PromiseResolve:c,PromisePrototypeThen:l,Symbol:V}=pZ(),z=V("kEmpty"),H=V("kEof");function F(Y0,j0){if(j0!=null)O(j0,"options");if((j0===null||j0===void 0?void 0:j0.signal)!=null)U(j0.signal,"options.signal");if(C(Y0)&&!B(Y0))throw new $("stream",Y0,"must be writable");let $0=M(this,Y0);if(j0!==null&&j0!==void 0&&j0.signal)k(j0.signal,$0);return $0}function D(Y0,j0){if(typeof Y0!=="function")throw new J("fn",["Function","AsyncFunction"],Y0);if(j0!=null)O(j0,"options");if((j0===null||j0===void 0?void 0:j0.signal)!=null)U(j0.signal,"options.signal");let $0=1;if((j0===null||j0===void 0?void 0:j0.concurrency)!=null)$0=f(j0.concurrency);let D0=$0-1;if((j0===null||j0===void 0?void 0:j0.highWaterMark)!=null)D0=f(j0.highWaterMark);return K($0,"options.concurrency",1),K(D0,"options.highWaterMark",0),D0+=$0,async function*(){let $Q=w$().AbortSignalAny([j0===null||j0===void 0?void 0:j0.signal].filter(x)),m=this,n=[],B0={signal:$Q},F0,z0,l0=!1,d=0;function X0(){l0=!0,QQ()}function QQ(){d-=1,V0()}function V0(){if(z0&&!l0&&d<$0&&n.length<D0)z0(),z0=null}async function P0(){try{for await(let jQ of m){if(l0)return;if($Q.aborted)throw new W;try{if(jQ=Y0(jQ,B0),jQ===z)continue;jQ=c(jQ)}catch(c0){jQ=t(c0)}if(d+=1,l(jQ,QQ,X0),n.push(jQ),F0)F0(),F0=null;if(!l0&&(n.length>=D0||d>=$0))await new Z0((c0)=>{z0=c0})}n.push(H)}catch(jQ){let c0=t(jQ);l(c0,QQ,X0),n.push(c0)}finally{if(l0=!0,F0)F0(),F0=null}}P0();try{while(!0){while(n.length>0){let jQ=await n[0];if(jQ===H)return;if($Q.aborted)throw new W;if(jQ!==z)yield jQ;n.shift(),V0()}await new Z0((jQ)=>{F0=jQ})}}finally{if(l0=!0,z0)z0(),z0=null}}.call(this)}function P(Y0=void 0){if(Y0!=null)O(Y0,"options");if((Y0===null||Y0===void 0?void 0:Y0.signal)!=null)U(Y0.signal,"options.signal");return async function*(){let j0=0;for await(let D0 of this){var $0;if(Y0!==null&&Y0!==void 0&&($0=Y0.signal)!==null&&$0!==void 0&&$0.aborted)throw new W({cause:Y0.signal.reason});yield[j0++,D0]}}.call(this)}async function j(Y0,j0=void 0){for await(let $0 of N.call(this,Y0,j0))return!0;return!1}async function R(Y0,j0=void 0){if(typeof Y0!=="function")throw new J("fn",["Function","AsyncFunction"],Y0);return!await j.call(this,async(...$0)=>{return!await Y0(...$0)},j0)}async function q(Y0,j0){for await(let $0 of N.call(this,Y0,j0))return $0;return}async function E(Y0,j0){if(typeof Y0!=="function")throw new J("fn",["Function","AsyncFunction"],Y0);async function $0(D0,$Q){return await Y0(D0,$Q),z}for await(let D0 of D.call(this,$0,j0));}function N(Y0,j0){if(typeof Y0!=="function")throw new J("fn",["Function","AsyncFunction"],Y0);async function $0(D0,$Q){if(await Y0(D0,$Q))return D0;return z}return D.call(this,$0,j0)}class T extends X{constructor(){super("reduce");this.message="Reduce of an empty stream requires an initial value"}}async function v(Y0,j0,$0){var D0;if(typeof Y0!=="function")throw new J("reducer",["Function","AsyncFunction"],Y0);if($0!=null)O($0,"options");if(($0===null||$0===void 0?void 0:$0.signal)!=null)U($0.signal,"options.signal");let $Q=arguments.length>1;if($0!==null&&$0!==void 0&&(D0=$0.signal)!==null&&D0!==void 0&&D0.aborted){let z0=new W(void 0,{cause:$0.signal.reason});throw this.once("error",()=>{}),await A(this.destroy(z0)),z0}let m=new Y,n=m.signal;if($0!==null&&$0!==void 0&&$0.signal){let z0={once:!0,[I]:this,[L]:!0};$0.signal.addEventListener("abort",()=>m.abort(),z0)}let B0=!1;try{for await(let z0 of this){var F0;if(B0=!0,$0!==null&&$0!==void 0&&(F0=$0.signal)!==null&&F0!==void 0&&F0.aborted)throw new W;if(!$Q)j0=z0,$Q=!0;else j0=await Y0(j0,z0,{signal:n})}if(!B0&&!$Q)throw new T}finally{m.abort()}return j0}async function y(Y0){if(Y0!=null)O(Y0,"options");if((Y0===null||Y0===void 0?void 0:Y0.signal)!=null)U(Y0.signal,"options.signal");let j0=[];for await(let D0 of this){var $0;if(Y0!==null&&Y0!==void 0&&($0=Y0.signal)!==null&&$0!==void 0&&$0.aborted)throw new W(void 0,{cause:Y0.signal.reason});_(j0,D0)}return j0}function p(Y0,j0){let $0=D.call(this,Y0,j0);return async function*(){for await(let D0 of $0)yield*D0}.call(this)}function J0(Y0){if(Y0=h(Y0),i(Y0))return 0;if(Y0<0)throw new G("number",">= 0",Y0);return Y0}function x0(Y0,j0=void 0){if(j0!=null)O(j0,"options");if((j0===null||j0===void 0?void 0:j0.signal)!=null)U(j0.signal,"options.signal");return Y0=J0(Y0),async function*(){var $0;if(j0!==null&&j0!==void 0&&($0=j0.signal)!==null&&$0!==void 0&&$0.aborted)throw new W;for await(let $Q of this){var D0;if(j0!==null&&j0!==void 0&&(D0=j0.signal)!==null&&D0!==void 0&&D0.aborted)throw new W;if(Y0--<=0)yield $Q}}.call(this)}function K0(Y0,j0=void 0){if(j0!=null)O(j0,"options");if((j0===null||j0===void 0?void 0:j0.signal)!=null)U(j0.signal,"options.signal");return Y0=J0(Y0),async function*(){var $0;if(j0!==null&&j0!==void 0&&($0=j0.signal)!==null&&$0!==void 0&&$0.aborted)throw new W;for await(let $Q of this){var D0;if(j0!==null&&j0!==void 0&&(D0=j0.signal)!==null&&D0!==void 0&&D0.aborted)throw new W;if(Y0-- >0)yield $Q;if(Y0<=0)return}}.call(this)}Z.exports.streamReturningOperators={asIndexedPairs:S(P,"readable.asIndexedPairs will be removed in a future version."),drop:x0,filter:N,flatMap:p,map:D,take:K0,compose:F},Z.exports.promiseReturningOperators={every:R,forEach:E,reduce:v,toArray:y,some:j,find:q}}),oC=FZ((Q,Z)=>{var{ArrayPrototypePop:Y,Promise:$}=pZ(),{isIterable:J,isNodeStream:X,isWebStream:G}=l1(),{pipelineImpl:W}=UD(),{finished:U}=b8();sC();function K(...O){return new $((I,L)=>{let A,M,k=O[O.length-1];if(k&&typeof k==="object"&&!X(k)&&!J(k)&&!G(k)){let B=Y(O);A=B.signal,M=B.end}W(O,(B,C)=>{if(B)L(B);else I(C)},{signal:A,end:M})})}Z.exports={finished:U,pipeline:K}}),sC=FZ((Q,Z)=>{var{Buffer:Y}=(vY(),oQ(_Y)),{ObjectDefineProperty:$,ObjectKeys:J,ReflectApply:X}=pZ(),{promisify:{custom:G}}=w$(),{streamReturningOperators:W,promiseReturningOperators:U}=or(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:K}}=D$(),O=nC(),{setDefaultHighWaterMark:I,getDefaultHighWaterMark:L}=vW(),{pipeline:A}=UD(),{destroyer:M}=yV(),k=b8(),B=oC(),C=l1(),S=Z.exports=WD().Stream;S.isDestroyed=C.isDestroyed,S.isDisturbed=C.isDisturbed,S.isErrored=C.isErrored,S.isReadable=C.isReadable,S.isWritable=C.isWritable,S.Readable=xW();for(let x of J(W)){let f=function(...i){if(new.target)throw K();return S.Readable.from(X(h,this,i))},h=W[x];$(f,"name",{__proto__:null,value:h.name}),$(f,"length",{__proto__:null,value:h.length}),$(S.Readable.prototype,x,{__proto__:null,value:f,enumerable:!1,configurable:!0,writable:!0})}for(let x of J(U)){let f=function(...i){if(new.target)throw K();return X(h,this,i)},h=U[x];$(f,"name",{__proto__:null,value:h.name}),$(f,"length",{__proto__:null,value:h.length}),$(S.Readable.prototype,x,{__proto__:null,value:f,enumerable:!1,configurable:!0,writable:!0})}S.Writable=KD(),S.Duplex=p1(),S.Transform=mC(),S.PassThrough=dC(),S.pipeline=A;var{addAbortSignal:_}=_W();S.addAbortSignal=_,S.finished=k,S.destroy=M,S.compose=O,S.setDefaultHighWaterMark=I,S.getDefaultHighWaterMark=L,$(S,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return B}}),$(A,G,{__proto__:null,enumerable:!0,get(){return B.pipeline}}),$(k,G,{__proto__:null,enumerable:!0,get(){return B.finished}}),S.Stream=S,S._isUint8Array=function(x){return x instanceof Uint8Array},S._uint8ArrayToBuffer=function(x){return Y.from(x.buffer,x.byteOffset,x.byteLength)}}),sr=FZ((Q,Z)=>{var Y=OD();{let $=sC(),J=oC(),X=$.Readable.destroy;Z.exports=$.Readable,Z.exports._uint8ArrayToBuffer=$._uint8ArrayToBuffer,Z.exports._isUint8Array=$._isUint8Array,Z.exports.isDisturbed=$.isDisturbed,Z.exports.isErrored=$.isErrored,Z.exports.isReadable=$.isReadable,Z.exports.Readable=$.Readable,Z.exports.Writable=$.Writable,Z.exports.Duplex=$.Duplex,Z.exports.Transform=$.Transform,Z.exports.PassThrough=$.PassThrough,Z.exports.addAbortSignal=$.addAbortSignal,Z.exports.finished=$.finished,Z.exports.destroy=$.destroy,Z.exports.destroy=X,Z.exports.pipeline=$.pipeline,Z.exports.compose=$.compose,Object.defineProperty($,"promises",{configurable:!0,enumerable:!0,get(){return J}}),Z.exports.Stream=$.Stream}Z.exports.default=Z.exports});iC.exports=sr()});var _$={};j$(_$,{webcrypto:()=>P00,rng:()=>ve,randomUUID:()=>R00,randomFillSync:()=>U00,randomFill:()=>K00,randomBytes:()=>xe,publicEncrypt:()=>q00,publicDecrypt:()=>z00,pseudoRandomBytes:()=>_e,prng:()=>we,privateEncrypt:()=>F00,privateDecrypt:()=>W00,pbkdf2Sync:()=>ue,pbkdf2:()=>ce,listCiphers:()=>re,getRandomValues:()=>I00,getHashes:()=>be,getDiffieHellman:()=>Q00,getCurves:()=>E00,getCiphers:()=>ae,default:()=>j00,createVerify:()=>G00,createSign:()=>$00,createHmac:()=>he,createHash:()=>ye,createECDH:()=>V00,createDiffieHellmanGroup:()=>ee,createDiffieHellman:()=>Z00,createDecipheriv:()=>ie,createDecipher:()=>oe,createCredentials:()=>O00,createCipheriv:()=>de,createCipher:()=>le,constants:()=>H00,Verify:()=>X00,Sign:()=>J00,Hmac:()=>ge,Hash:()=>fe,DiffieHellmanGroup:()=>te,DiffieHellman:()=>Y00,Decipheriv:()=>se,Decipher:()=>ne,DEFAULT_ENCODING:()=>D00,Cipheriv:()=>me,Cipher:()=>pe});function E00(){return L00}var ir,ar,aC,rr,tr,er=(Q,Z,Y)=>{Y=Q!=null?ir(ar(Q)):{};let $=Z||!Q||!Q.__esModule?aC(Y,"default",{value:Q,enumerable:!0}):Y;for(let J of rr(Q))if(!tr.call($,J))aC($,J,{get:()=>Q[J],enumerable:!0});return $},v0=(Q,Z)=>()=>(Z||Q((Z={exports:{}}).exports,Z),Z.exports),fW,yW,tC,Qt,DD,ID,I$,Zt,d6,eC,Yt,$t,Jt,Gt,QS,Xt,Vt,qt,Ft,zt,Wt,Kt,Ut,Ot,Ht,n6,gW,ZS,Dt,YS,$S,It,o6,RD,LD,Rt,JS,ED,Lt,GS,Et,XS,VS,Pt,jt,At,Mt,Tt,Nt,Bt,kt,Ct,St,wt,_t,vt,xt,PD,qS,ft,FS,yt,gt,ht,bt,m1,c8,zS,DJ,WS,hW,ct,YJ,ut,pt,lt,KS,V1,s6,US,mt,OS,dt,HS,nt,ot,st,it,jD,at,AD,rt,tt,et,Qe,Ze,Ye,$e,Je,Ge,Xe,Ve,qe,Fe,ze,rC,We,m6,Ke,DS,IS,Ue,Oe,RS,He,De,i6,Ie,Re,Le,Ee,Pe,je,LS,Ae,ES,PS,jS,MD,AS,Me,MS,Te,Ne,HD,Be,ke,Ce,Se,nQ,we,_e,ve,xe,fe,ye,ge,he,be,ce,ue,pe,le,me,de,ne,oe,se,ie,ae,re,te,ee,Q00,Z00,Y00,$00,J00,G00,X00,V00,q00,F00,z00,W00,K00,U00,O00,H00,D00="buffer",I00=(Q)=>{return crypto.getRandomValues(Q)},R00=()=>{return crypto.randomUUID()},L00,P00,j00;var v$=w(()=>{ir=Object.create,{getPrototypeOf:ar,defineProperty:aC,getOwnPropertyNames:rr}=Object,tr=Object.prototype.hasOwnProperty,fW=v0((Q,Z)=>{Z.exports=(v$(),oQ(_$)).randomBytes}),yW=v0((Q,Z)=>{Z.exports=(v$(),oQ(_$)).createHash}),tC=v0((Q,Z)=>{Z.exports=(v$(),oQ(_$)).createHmac}),Qt=v0((Q,Z)=>{Z.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}}),DD=v0((Q,Z)=>{var Y=isFinite,$=Math.pow(2,30)-1;Z.exports=function(J,X){if(typeof J!=="number")throw TypeError("Iterations not a number");if(J<0||!Y(J))throw TypeError("Bad iterations");if(typeof X!=="number")throw TypeError("Key length not a number");if(X<0||X>$||X!==X)throw TypeError("Bad key length")}}),ID=v0((Q,Z)=>{var Y;if(globalThis.process&&globalThis.process.browser)Y="utf-8";else if(globalThis.process&&globalThis.process.version)$=parseInt(process.version.split(".")[0].slice(1),10),Y=$>=6?"utf-8":"binary";else Y="utf-8";var $;Z.exports=Y}),I$=v0((Q,Z)=>{/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var Y=(vY(),oQ(_Y)),$=Y.Buffer;function J(G,W){for(var U in G)W[U]=G[U]}if($.from&&$.alloc&&$.allocUnsafe&&$.allocUnsafeSlow)Z.exports=Y;else J(Y,Q),Q.Buffer=X;function X(G,W,U){return $(G,W,U)}X.prototype=Object.create($.prototype),J($,X),X.from=function(G,W,U){if(typeof G==="number")throw TypeError("Argument must not be a number");return $(G,W,U)},X.alloc=function(G,W,U){if(typeof G!=="number")throw TypeError("Argument must be a number");var K=$(G);if(W!==void 0)if(typeof U==="string")K.fill(W,U);else K.fill(W);else K.fill(0);return K},X.allocUnsafe=function(G){if(typeof G!=="number")throw TypeError("Argument must be a number");return $(G)},X.allocUnsafeSlow=function(G){if(typeof G!=="number")throw TypeError("Argument must be a number");return Y.SlowBuffer(G)}}),Zt=v0((Q,Z)=>{var Y={}.toString;Z.exports=Array.isArray||function($){return Y.call($)=="[object Array]"}}),d6=v0((Q,Z)=>{Z.exports=TypeError}),eC=v0((Q,Z)=>{Z.exports=Object}),Yt=v0((Q,Z)=>{Z.exports=Error}),$t=v0((Q,Z)=>{Z.exports=EvalError}),Jt=v0((Q,Z)=>{Z.exports=RangeError}),Gt=v0((Q,Z)=>{Z.exports=ReferenceError}),QS=v0((Q,Z)=>{Z.exports=SyntaxError}),Xt=v0((Q,Z)=>{Z.exports=URIError}),Vt=v0((Q,Z)=>{Z.exports=Math.abs}),qt=v0((Q,Z)=>{Z.exports=Math.floor}),Ft=v0((Q,Z)=>{Z.exports=Math.max}),zt=v0((Q,Z)=>{Z.exports=Math.min}),Wt=v0((Q,Z)=>{Z.exports=Math.pow}),Kt=v0((Q,Z)=>{Z.exports=Math.round}),Ut=v0((Q,Z)=>{Z.exports=Number.isNaN||function(Y){return Y!==Y}}),Ot=v0((Q,Z)=>{var Y=Ut();Z.exports=function($){if(Y($)||$===0)return $;return $<0?-1:1}}),Ht=v0((Q,Z)=>{Z.exports=Object.getOwnPropertyDescriptor}),n6=v0((Q,Z)=>{var Y=Ht();if(Y)try{Y([],"length")}catch($){Y=null}Z.exports=Y}),gW=v0((Q,Z)=>{var Y=Object.defineProperty||!1;if(Y)try{Y({},"a",{value:1})}catch($){Y=!1}Z.exports=Y}),ZS=v0((Q,Z)=>{Z.exports=function(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function")return!1;if(typeof Symbol.iterator==="symbol")return!0;var Y={},$=Symbol("test"),J=Object($);if(typeof $==="string")return!1;if(Object.prototype.toString.call($)!=="[object Symbol]")return!1;if(Object.prototype.toString.call(J)!=="[object Symbol]")return!1;var X=42;Y[$]=X;for(var G in Y)return!1;if(typeof Object.keys==="function"&&Object.keys(Y).length!==0)return!1;if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(Y).length!==0)return!1;var W=Object.getOwnPropertySymbols(Y);if(W.length!==1||W[0]!==$)return!1;if(!Object.prototype.propertyIsEnumerable.call(Y,$))return!1;if(typeof Object.getOwnPropertyDescriptor==="function"){var U=Object.getOwnPropertyDescriptor(Y,$);if(U.value!==X||U.enumerable!==!0)return!1}return!0}}),Dt=v0((Q,Z)=>{var Y=typeof Symbol<"u"&&Symbol,$=ZS();Z.exports=function(){if(typeof Y!=="function")return!1;if(typeof Symbol!=="function")return!1;if(typeof Y("foo")!=="symbol")return!1;if(typeof Symbol("bar")!=="symbol")return!1;return $()}}),YS=v0((Q,Z)=>{Z.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null}),$S=v0((Q,Z)=>{var Y=eC();Z.exports=Y.getPrototypeOf||null}),It=v0((Q,Z)=>{var Y="Function.prototype.bind called on incompatible ",$=Object.prototype.toString,J=Math.max,X="[object Function]",G=function(K,O){var I=[];for(var L=0;L<K.length;L+=1)I[L]=K[L];for(var A=0;A<O.length;A+=1)I[A+K.length]=O[A];return I},W=function(K,O){var I=[];for(var L=O||0,A=0;L<K.length;L+=1,A+=1)I[A]=K[L];return I},U=function(K,O){var I="";for(var L=0;L<K.length;L+=1)if(I+=K[L],L+1<K.length)I+=O;return I};Z.exports=function(K){var O=this;if(typeof O!=="function"||$.apply(O)!==X)throw TypeError(Y+O);var I=W(arguments,1),L,A=function(){if(this instanceof L){var S=O.apply(this,G(I,arguments));if(Object(S)===S)return S;return this}return O.apply(K,G(I,arguments))},M=J(0,O.length-I.length),k=[];for(var B=0;B<M;B++)k[B]="$"+B;if(L=Function("binder","return function ("+U(k,",")+"){ return binder.apply(this,arguments); }")(A),O.prototype){var C=function(){};C.prototype=O.prototype,L.prototype=new C,C.prototype=null}return L}}),o6=v0((Q,Z)=>{var Y=It();Z.exports=Function.prototype.bind||Y}),RD=v0((Q,Z)=>{Z.exports=Function.prototype.call}),LD=v0((Q,Z)=>{Z.exports=Function.prototype.apply}),Rt=v0((Q,Z)=>{Z.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply}),JS=v0((Q,Z)=>{var Y=o6(),$=LD(),J=RD(),X=Rt();Z.exports=X||Y.call(J,$)}),ED=v0((Q,Z)=>{var Y=o6(),$=d6(),J=RD(),X=JS();Z.exports=function(G){if(G.length<1||typeof G[0]!=="function")throw new $("a function is required");return X(Y,J,G)}}),Lt=v0((Q,Z)=>{var Y=ED(),$=n6(),J;try{J=[].__proto__===Array.prototype}catch(U){if(!U||typeof U!=="object"||!("code"in U)||U.code!=="ERR_PROTO_ACCESS")throw U}var X=!!J&&$&&$(Object.prototype,"__proto__"),G=Object,W=G.getPrototypeOf;Z.exports=X&&typeof X.get==="function"?Y([X.get]):typeof W==="function"?function(U){return W(U==null?U:G(U))}:!1}),GS=v0((Q,Z)=>{var Y=YS(),$=$S(),J=Lt();Z.exports=Y?function(X){return Y(X)}:$?function(X){if(!X||typeof X!=="object"&&typeof X!=="function")throw TypeError("getProto: not an object");return $(X)}:J?function(X){return J(X)}:null}),Et=v0((Q,Z)=>{var Y=Function.prototype.call,$=Object.prototype.hasOwnProperty,J=o6();Z.exports=J.call(Y,$)}),XS=v0((Q,Z)=>{var Y,$=eC(),J=Yt(),X=$t(),G=Jt(),W=Gt(),U=QS(),K=d6(),O=Xt(),I=Vt(),L=qt(),A=Ft(),M=zt(),k=Wt(),B=Kt(),C=Ot(),S=Function,_=function(j0){try{return S('"use strict"; return ('+j0+").constructor;")()}catch($0){}},x=n6(),f=gW(),h=function(){throw new K},i=x?function(){try{return arguments.callee,h}catch(j0){try{return x(arguments,"callee").get}catch($0){return h}}}():h,Z0=Dt()(),t=GS(),c=$S(),l=YS(),V=LD(),z=RD(),H={},F=typeof Uint8Array>"u"||!t?Y:t(Uint8Array),D={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?Y:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?Y:ArrayBuffer,"%ArrayIteratorPrototype%":Z0&&t?t([][Symbol.iterator]()):Y,"%AsyncFromSyncIteratorPrototype%":Y,"%AsyncFunction%":H,"%AsyncGenerator%":H,"%AsyncGeneratorFunction%":H,"%AsyncIteratorPrototype%":H,"%Atomics%":typeof Atomics>"u"?Y:Atomics,"%BigInt%":typeof BigInt>"u"?Y:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?Y:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?Y:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?Y:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":J,"%eval%":eval,"%EvalError%":X,"%Float16Array%":typeof Float16Array>"u"?Y:Float16Array,"%Float32Array%":typeof Float32Array>"u"?Y:Float32Array,"%Float64Array%":typeof Float64Array>"u"?Y:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?Y:FinalizationRegistry,"%Function%":S,"%GeneratorFunction%":H,"%Int8Array%":typeof Int8Array>"u"?Y:Int8Array,"%Int16Array%":typeof Int16Array>"u"?Y:Int16Array,"%Int32Array%":typeof Int32Array>"u"?Y:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Z0&&t?t(t([][Symbol.iterator]())):Y,"%JSON%":typeof JSON==="object"?JSON:Y,"%Map%":typeof Map>"u"?Y:Map,"%MapIteratorPrototype%":typeof Map>"u"||!Z0||!t?Y:t(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":$,"%Object.getOwnPropertyDescriptor%":x,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?Y:Promise,"%Proxy%":typeof Proxy>"u"?Y:Proxy,"%RangeError%":G,"%ReferenceError%":W,"%Reflect%":typeof Reflect>"u"?Y:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?Y:Set,"%SetIteratorPrototype%":typeof Set>"u"||!Z0||!t?Y:t(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?Y:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Z0&&t?t(""[Symbol.iterator]()):Y,"%Symbol%":Z0?Symbol:Y,"%SyntaxError%":U,"%ThrowTypeError%":i,"%TypedArray%":F,"%TypeError%":K,"%Uint8Array%":typeof Uint8Array>"u"?Y:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?Y:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?Y:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?Y:Uint32Array,"%URIError%":O,"%WeakMap%":typeof WeakMap>"u"?Y:WeakMap,"%WeakRef%":typeof WeakRef>"u"?Y:WeakRef,"%WeakSet%":typeof WeakSet>"u"?Y:WeakSet,"%Function.prototype.call%":z,"%Function.prototype.apply%":V,"%Object.defineProperty%":f,"%Object.getPrototypeOf%":c,"%Math.abs%":I,"%Math.floor%":L,"%Math.max%":A,"%Math.min%":M,"%Math.pow%":k,"%Math.round%":B,"%Math.sign%":C,"%Reflect.getPrototypeOf%":l};if(t)try{null.error}catch(j0){P=t(t(j0)),D["%Error.prototype%"]=P}var P,j=function j0($0){var D0;if($0==="%AsyncFunction%")D0=_("async function () {}");else if($0==="%GeneratorFunction%")D0=_("function* () {}");else if($0==="%AsyncGeneratorFunction%")D0=_("async function* () {}");else if($0==="%AsyncGenerator%"){var $Q=j0("%AsyncGeneratorFunction%");if($Q)D0=$Q.prototype}else if($0==="%AsyncIteratorPrototype%"){var m=j0("%AsyncGenerator%");if(m&&t)D0=t(m.prototype)}return D[$0]=D0,D0},R={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},q=o6(),E=Et(),N=q.call(z,Array.prototype.concat),T=q.call(V,Array.prototype.splice),v=q.call(z,String.prototype.replace),y=q.call(z,String.prototype.slice),p=q.call(z,RegExp.prototype.exec),J0=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,x0=/\\(\\)?/g,K0=function(j0){var $0=y(j0,0,1),D0=y(j0,-1);if($0==="%"&&D0!=="%")throw new U("invalid intrinsic syntax, expected closing `%`");else if(D0==="%"&&$0!=="%")throw new U("invalid intrinsic syntax, expected opening `%`");var $Q=[];return v(j0,J0,function(m,n,B0,F0){$Q[$Q.length]=B0?v(F0,x0,"$1"):n||m}),$Q},Y0=function(j0,$0){var D0=j0,$Q;if(E(R,D0))$Q=R[D0],D0="%"+$Q[0]+"%";if(E(D,D0)){var m=D[D0];if(m===H)m=j(D0);if(typeof m>"u"&&!$0)throw new K("intrinsic "+j0+" exists, but is not available. Please file an issue!");return{alias:$Q,name:D0,value:m}}throw new U("intrinsic "+j0+" does not exist!")};Z.exports=function(j0,$0){if(typeof j0!=="string"||j0.length===0)throw new K("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof $0!=="boolean")throw new K('"allowMissing" argument must be a boolean');if(p(/^%?[^%]*%?$/,j0)===null)throw new U("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var D0=K0(j0),$Q=D0.length>0?D0[0]:"",m=Y0("%"+$Q+"%",$0),n=m.name,B0=m.value,F0=!1,z0=m.alias;if(z0)$Q=z0[0],T(D0,N([0,1],z0));for(var l0=1,d=!0;l0<D0.length;l0+=1){var X0=D0[l0],QQ=y(X0,0,1),V0=y(X0,-1);if((QQ==='"'||QQ==="'"||QQ==="`"||(V0==='"'||V0==="'"||V0==="`"))&&QQ!==V0)throw new U("property names with quotes must have matching quotes");if(X0==="constructor"||!d)F0=!0;if($Q+="."+X0,n="%"+$Q+"%",E(D,n))B0=D[n];else if(B0!=null){if(!(X0 in B0)){if(!$0)throw new K("base intrinsic for "+j0+" exists, but the property is not available.");return}if(x&&l0+1>=D0.length){var P0=x(B0,X0);if(d=!!P0,d&&"get"in P0&&!("originalValue"in P0.get))B0=P0.get;else B0=B0[X0]}else d=E(B0,X0),B0=B0[X0];if(d&&!F0)D[n]=B0}}return B0}}),VS=v0((Q,Z)=>{var Y=XS(),$=ED(),J=$([Y("%String.prototype.indexOf%")]);Z.exports=function(X,G){var W=Y(X,!!G);if(typeof W==="function"&&J(X,".prototype.")>-1)return $([W]);return W}}),Pt=v0((Q,Z)=>{var Y=Function.prototype.toString,$=typeof Reflect==="object"&&Reflect!==null&&Reflect.apply,J,X;if(typeof $==="function"&&typeof Object.defineProperty==="function")try{J=Object.defineProperty({},"length",{get:function(){throw X}}),X={},$(function(){throw 42},null,J)}catch(x){if(x!==X)$=null}else $=null;var G=/^\s*class\b/,W=function(x){try{var f=Y.call(x);return G.test(f)}catch(h){return!1}},U=function(x){try{if(W(x))return!1;return Y.call(x),!0}catch(f){return!1}},K=Object.prototype.toString,O="[object Object]",I="[object Function]",L="[object GeneratorFunction]",A="[object HTMLAllCollection]",M="[object HTML document.all class]",k="[object HTMLCollection]",B=typeof Symbol==="function"&&!!Symbol.toStringTag,C=!(0 in[,]),S=function(){return!1};if(typeof document==="object"){if(_=document.all,K.call(_)===K.call(document.all))S=function(x){if((C||!x)&&(typeof x>"u"||typeof x==="object"))try{var f=K.call(x);return(f===A||f===M||f===k||f===O)&&x("")==null}catch(h){}return!1}}var _;Z.exports=$?function(x){if(S(x))return!0;if(!x)return!1;if(typeof x!=="function"&&typeof x!=="object")return!1;try{$(x,null,J)}catch(f){if(f!==X)return!1}return!W(x)&&U(x)}:function(x){if(S(x))return!0;if(!x)return!1;if(typeof x!=="function"&&typeof x!=="object")return!1;if(B)return U(x);if(W(x))return!1;var f=K.call(x);if(f!==I&&f!==L&&!/^\[object HTML/.test(f))return!1;return U(x)}}),jt=v0((Q,Z)=>{var Y=Pt(),$=Object.prototype.toString,J=Object.prototype.hasOwnProperty,X=function(K,O,I){for(var L=0,A=K.length;L<A;L++)if(J.call(K,L))if(I==null)O(K[L],L,K);else O.call(I,K[L],L,K)},G=function(K,O,I){for(var L=0,A=K.length;L<A;L++)if(I==null)O(K.charAt(L),L,K);else O.call(I,K.charAt(L),L,K)},W=function(K,O,I){for(var L in K)if(J.call(K,L))if(I==null)O(K[L],L,K);else O.call(I,K[L],L,K)};function U(K){return $.call(K)==="[object Array]"}Z.exports=function(K,O,I){if(!Y(O))throw TypeError("iterator must be a function");var L;if(arguments.length>=3)L=I;if(U(K))X(K,O,L);else if(typeof K==="string")G(K,O,L);else W(K,O,L)}}),At=v0((Q,Z)=>{Z.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]}),Mt=v0((Q,Z)=>{var Y=At(),$=typeof globalThis>"u"?globalThis:globalThis;Z.exports=function(){var J=[];for(var X=0;X<Y.length;X++)if(typeof $[Y[X]]==="function")J[J.length]=Y[X];return J}}),Tt=v0((Q,Z)=>{var Y=gW(),$=QS(),J=d6(),X=n6();Z.exports=function(G,W,U){if(!G||typeof G!=="object"&&typeof G!=="function")throw new J("`obj` must be an object or a function`");if(typeof W!=="string"&&typeof W!=="symbol")throw new J("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=="boolean"&&arguments[3]!==null)throw new J("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=="boolean"&&arguments[4]!==null)throw new J("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=="boolean"&&arguments[5]!==null)throw new J("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=="boolean")throw new J("`loose`, if provided, must be a boolean");var K=arguments.length>3?arguments[3]:null,O=arguments.length>4?arguments[4]:null,I=arguments.length>5?arguments[5]:null,L=arguments.length>6?arguments[6]:!1,A=!!X&&X(G,W);if(Y)Y(G,W,{configurable:I===null&&A?A.configurable:!I,enumerable:K===null&&A?A.enumerable:!K,value:U,writable:O===null&&A?A.writable:!O});else if(L||!K&&!O&&!I)G[W]=U;else throw new $("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}}),Nt=v0((Q,Z)=>{var Y=gW(),$=function(){return!!Y};$.hasArrayLengthDefineBug=function(){if(!Y)return null;try{return Y([],"length",{value:1}).length!==1}catch(J){return!0}},Z.exports=$}),Bt=v0((Q,Z)=>{var Y=XS(),$=Tt(),J=Nt()(),X=n6(),G=d6(),W=Y("%Math.floor%");Z.exports=function(U,K){if(typeof U!=="function")throw new G("`fn` is not a function");if(typeof K!=="number"||K<0||K>4294967295||W(K)!==K)throw new G("`length` must be a positive 32-bit integer");var O=arguments.length>2&&!!arguments[2],I=!0,L=!0;if("length"in U&&X){var A=X(U,"length");if(A&&!A.configurable)I=!1;if(A&&!A.writable)L=!1}if(I||L||!O)if(J)$(U,"length",K,!0,!0);else $(U,"length",K);return U}}),kt=v0((Q,Z)=>{var Y=o6(),$=LD(),J=JS();Z.exports=function(){return J(Y,$,arguments)}}),Ct=v0((Q,Z)=>{var Y=Bt(),$=gW(),J=ED(),X=kt();if(Z.exports=function(G){var W=J(arguments),U=G.length-(arguments.length-1);return Y(W,1+(U>0?U:0),!0)},$)$(Z.exports,"apply",{value:X});else Z.exports.apply=X}),St=v0((Q,Z)=>{var Y=ZS();Z.exports=function(){return Y()&&!!Symbol.toStringTag}}),wt=v0((Q,Z)=>{var Y=jt(),$=Mt(),J=Ct(),X=VS(),G=n6(),W=GS(),U=X("Object.prototype.toString"),K=St()(),O=typeof globalThis>"u"?globalThis:globalThis,I=$(),L=X("String.prototype.slice"),A=X("Array.prototype.indexOf",!0)||function(C,S){for(var _=0;_<C.length;_+=1)if(C[_]===S)return _;return-1},M={__proto__:null};if(K&&G&&W)Y(I,function(C){var S=new O[C];if(Symbol.toStringTag in S&&W){var _=W(S),x=G(_,Symbol.toStringTag);if(!x&&_){var f=W(_);x=G(f,Symbol.toStringTag)}M["$"+C]=J(x.get)}});else Y(I,function(C){var S=new O[C],_=S.slice||S.set;if(_)M["$"+C]=J(_)});var k=function(C){var S=!1;return Y(M,function(_,x){if(!S)try{if("$"+_(C)===x)S=L(x,1)}catch(f){}}),S},B=function(C){var S=!1;return Y(M,function(_,x){if(!S)try{_(C),S=L(x,1)}catch(f){}}),S};Z.exports=function(C){if(!C||typeof C!=="object")return!1;if(!K){var S=L(U(C),8,-1);if(A(I,S)>-1)return S;if(S!=="Object")return!1;return B(C)}if(!G)return null;return k(C)}}),_t=v0((Q,Z)=>{var Y=wt();Z.exports=function($){return!!Y($)}}),vt=v0((Q,Z)=>{var Y=d6(),$=VS(),J=$("TypedArray.prototype.buffer",!0),X=_t();Z.exports=J||function(G){if(!X(G))throw new Y("Not a Typed Array");return G.buffer}}),xt=v0((Q,Z)=>{var Y=I$().Buffer,$=Zt(),J=vt(),X=ArrayBuffer.isView||function(K){try{return J(K),!0}catch(O){return!1}},G=typeof Uint8Array<"u",W=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",U=W&&(Y.prototype instanceof Uint8Array||Y.TYPED_ARRAY_SUPPORT);Z.exports=function(K,O){if(Y.isBuffer(K)){if(K.constructor&&!("isBuffer"in K))return Y.from(K);return K}if(typeof K==="string")return Y.from(K,O);if(W&&X(K)){if(K.byteLength===0)return Y.alloc(0);if(U){var I=Y.from(K.buffer,K.byteOffset,K.byteLength);if(I.byteLength===K.byteLength)return I}var L=K instanceof Uint8Array?K:new Uint8Array(K.buffer,K.byteOffset,K.byteLength),A=Y.from(L);if(A.length===K.byteLength)return A}if(G&&K instanceof Uint8Array)return Y.from(K);var M=$(K);if(M)for(var k=0;k<K.length;k+=1){var B=K[k];if(typeof B!=="number"||B<0||B>255||~~B!==B)throw RangeError("Array items must be numbers in the range 0-255.")}if(M||Y.isBuffer(K)&&K.constructor&&typeof K.constructor.isBuffer==="function"&&K.constructor.isBuffer(K))return Y.from(K);throw TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')}}),PD=v0((Q,Z)=>{var Y=I$().Buffer,$=xt(),J=typeof Uint8Array<"u",X=J&&typeof ArrayBuffer<"u",G=X&&ArrayBuffer.isView;Z.exports=function(W,U,K){if(typeof W==="string"||Y.isBuffer(W)||J&&W instanceof Uint8Array||G&&G(W))return $(W,U);throw TypeError(K+" must be a string, a Buffer, a Uint8Array, or a DataView")}}),qS=v0((Q,Z)=>{var Y={__proto__:null,md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,"sha512-256":32,rmd160:20,ripemd160:20},$={__proto__:null,"sha-1":"sha1","sha-224":"sha224","sha-256":"sha256","sha-384":"sha384","sha-512":"sha512","ripemd-160":"ripemd160"},J=tC(),X=I$().Buffer,G=DD(),W=ID(),U=PD();function K(O,I,L,A,M){G(L,A),O=U(O,W,"Password"),I=U(I,W,"Salt");var k=(M||"sha1").toLowerCase(),B=$[k]||k,C=Y[B];if(typeof C!=="number"||!C)throw TypeError("Digest algorithm not supported: "+M);var S=X.allocUnsafe(A),_=X.allocUnsafe(I.length+4);I.copy(_,0,0,I.length);var x=0,f=C,h=Math.ceil(A/f);for(var i=1;i<=h;i++){_.writeUInt32BE(i,I.length);var Z0=J(B,O).update(_).digest(),t=Z0;for(var c=1;c<L;c++){t=J(B,O).update(t).digest();for(var l=0;l<f;l++)Z0[l]^=t[l]}Z0.copy(S,x),x+=f}return S}Z.exports=K}),ft=v0((Q,Z)=>{var Y=I$().Buffer,$=DD(),J=ID(),X=qS(),G=PD(),W,U=globalThis.crypto&&globalThis.crypto.subtle,K={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},O=[],I;function L(){if(I)return I;if(globalThis.process&&globalThis.process.nextTick)I=globalThis.process.nextTick;else if(globalThis.queueMicrotask)I=globalThis.queueMicrotask;else if(globalThis.setImmediate)I=globalThis.setImmediate;else I=globalThis.setTimeout;return I}function A(B,C,S,_,x){return U.importKey("raw",B,{name:"PBKDF2"},!1,["deriveBits"]).then(function(f){return U.deriveBits({name:"PBKDF2",salt:C,iterations:S,hash:{name:x}},f,_<<3)}).then(function(f){return Y.from(f)})}function M(B){if(globalThis.process&&!globalThis.process.browser)return Promise.resolve(!1);if(!U||!U.importKey||!U.deriveBits)return Promise.resolve(!1);if(O[B]!==void 0)return O[B];W=W||Y.alloc(8);var C=A(W,W,10,128,B).then(function(){return!0},function(){return!1});return O[B]=C,C}function k(B,C){B.then(function(S){L()(function(){C(null,S)})},function(S){L()(function(){C(S)})})}Z.exports=function(B,C,S,_,x,f){if(typeof x==="function")f=x,x=void 0;if($(S,_),B=G(B,J,"Password"),C=G(C,J,"Salt"),typeof f!=="function")throw Error("No callback provided to pbkdf2");x=x||"sha1";var h=K[x.toLowerCase()];if(!h||typeof globalThis.Promise!=="function"){L()(function(){var i;try{i=X(B,C,S,_,x)}catch(Z0){f(Z0);return}f(null,i)});return}k(M(h).then(function(i){if(i)return A(B,C,S,_,h);return X(B,C,S,_,x)}),f)}}),FS=v0((Q)=>{var Z=(v$(),oQ(_$)),Y=DD(),$=ID(),J=PD();function X(W,U,K,O,I,L){if(Y(K,O),W=J(W,$,"Password"),U=J(U,$,"Salt"),typeof I==="function")L=I,I="sha1";if(typeof L!=="function")throw Error("No callback provided to pbkdf2");return Z.pbkdf2(W,U,K,O,I,L)}function G(W,U,K,O,I){return Y(K,O),W=J(W,$,"Password"),U=J(U,$,"Salt"),I=I||"sha1",Z.pbkdf2Sync(W,U,K,O,I)}if(!Z.pbkdf2Sync||Z.pbkdf2Sync.toString().indexOf("keylen, digest")===-1)Q.pbkdf2Sync=qS(),Q.pbkdf2=ft();else Q.pbkdf2Sync=G,Q.pbkdf2=X}),yt=v0((Q)=>{var Z=(v$(),oQ(_$));Q.createCipher=Q.Cipher=Z.createCipher,Q.createCipheriv=Q.Cipheriv=Z.createCipheriv,Q.createDecipher=Q.Decipher=Z.createDecipher,Q.createDecipheriv=Q.Decipheriv=Z.createDecipheriv,Q.listCiphers=Q.getCiphers=Z.getCiphers}),gt=v0((Q)=>{var Z=(v$(),oQ(_$));Q.DiffieHellmanGroup=Z.DiffieHellmanGroup,Q.createDiffieHellmanGroup=Z.createDiffieHellmanGroup,Q.getDiffieHellman=Z.getDiffieHellman,Q.createDiffieHellman=Z.createDiffieHellman,Q.DiffieHellman=Z.DiffieHellman}),ht=v0((Q)=>{var Z=(v$(),oQ(_$));Q.createSign=Z.createSign,Q.Sign=Z.Sign,Q.createVerify=Z.createVerify,Q.Verify=Z.Verify}),bt=v0((Q,Z)=>{Z.exports={name:"elliptic",version:"6.6.1",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny <fedor@indutny.com>",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"}}}),m1=v0((Q,Z)=>{(function(Y,$){function J(V,z){if(!V)throw Error(z||"Assertion failed")}function X(V,z){V.super_=z;var H=function(){};H.prototype=z.prototype,V.prototype=new H,V.prototype.constructor=V}function G(V,z,H){if(G.isBN(V))return V;if(this.negative=0,this.words=null,this.length=0,this.red=null,V!==null){if(z==="le"||z==="be")H=z,z=10;this._init(V||0,z||10,H||"be")}}if(typeof Y==="object")Y.exports=G;else $.BN=G;G.BN=G,G.wordSize=26;var W;try{if(typeof window<"u"&&typeof window.Buffer<"u")W=window.Buffer;else W=(vY(),oQ(_Y)).Buffer}catch(V){}G.isBN=function(V){if(V instanceof G)return!0;return V!==null&&typeof V==="object"&&V.constructor.wordSize===G.wordSize&&Array.isArray(V.words)},G.max=function(V,z){if(V.cmp(z)>0)return V;return z},G.min=function(V,z){if(V.cmp(z)<0)return V;return z},G.prototype._init=function(V,z,H){if(typeof V==="number")return this._initNumber(V,z,H);if(typeof V==="object")return this._initArray(V,z,H);if(z==="hex")z=16;J(z===(z|0)&&z>=2&&z<=36),V=V.toString().replace(/\s+/g,"");var F=0;if(V[0]==="-")F++,this.negative=1;if(F<V.length){if(z===16)this._parseHex(V,F,H);else if(this._parseBase(V,z,F),H==="le")this._initArray(this.toArray(),z,H)}},G.prototype._initNumber=function(V,z,H){if(V<0)this.negative=1,V=-V;if(V<67108864)this.words=[V&67108863],this.length=1;else if(V<4503599627370496)this.words=[V&67108863,V/67108864&67108863],this.length=2;else J(V<9007199254740992),this.words=[V&67108863,V/67108864&67108863,1],this.length=3;if(H!=="le")return;this._initArray(this.toArray(),z,H)},G.prototype._initArray=function(V,z,H){if(J(typeof V.length==="number"),V.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(V.length/3),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D,P,j=0;if(H==="be"){for(F=V.length-1,D=0;F>=0;F-=3)if(P=V[F]|V[F-1]<<8|V[F-2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}else if(H==="le"){for(F=0,D=0;F<V.length;F+=3)if(P=V[F]|V[F+1]<<8|V[F+2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}return this.strip()};function U(V,z){var H=V.charCodeAt(z);if(H>=65&&H<=70)return H-55;else if(H>=97&&H<=102)return H-87;else return H-48&15}function K(V,z,H){var F=U(V,H);if(H-1>=z)F|=U(V,H-1)<<4;return F}G.prototype._parseHex=function(V,z,H){this.length=Math.ceil((V.length-z)/6),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D=0,P=0,j;if(H==="be")for(F=V.length-1;F>=z;F-=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8;else{var R=V.length-z;for(F=R%2===0?z+1:z;F<V.length;F+=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8}this.strip()};function O(V,z,H,F){var D=0,P=Math.min(V.length,H);for(var j=z;j<P;j++){var R=V.charCodeAt(j)-48;if(D*=F,R>=49)D+=R-49+10;else if(R>=17)D+=R-17+10;else D+=R}return D}G.prototype._parseBase=function(V,z,H){this.words=[0],this.length=1;for(var F=0,D=1;D<=67108863;D*=z)F++;F--,D=D/z|0;var P=V.length-H,j=P%F,R=Math.min(P,P-j)+H,q=0;for(var E=H;E<R;E+=F)if(q=O(V,E,E+F,z),this.imuln(D),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q);if(j!==0){var N=1;q=O(V,E,V.length,z);for(E=0;E<j;E++)N*=z;if(this.imuln(N),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q)}this.strip()},G.prototype.copy=function(V){V.words=Array(this.length);for(var z=0;z<this.length;z++)V.words[z]=this.words[z];V.length=this.length,V.negative=this.negative,V.red=this.red},G.prototype.clone=function(){var V=new G(null);return this.copy(V),V},G.prototype._expand=function(V){while(this.length<V)this.words[this.length++]=0;return this},G.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},G.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],L=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(G.prototype.toString=function(V,z){V=V||10,z=z|0||1;var H;if(V===16||V==="hex"){H="";var F=0,D=0;for(var P=0;P<this.length;P++){var j=this.words[P],R=((j<<F|D)&16777215).toString(16);if(D=j>>>24-F&16777215,F+=2,F>=26)F-=26,P--;if(D!==0||P!==this.length-1)H=I[6-R.length]+R+H;else H=R+H}if(D!==0)H=D.toString(16)+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}if(V===(V|0)&&V>=2&&V<=36){var q=L[V],E=A[V];H="";var N=this.clone();N.negative=0;while(!N.isZero()){var T=N.modn(E).toString(V);if(N=N.idivn(E),!N.isZero())H=I[q-T.length]+T+H;else H=T+H}if(this.isZero())H="0"+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}J(!1,"Base should be between 2 and 36")},G.prototype.toNumber=function(){var V=this.words[0];if(this.length===2)V+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)V+=4503599627370496+this.words[1]*67108864;else if(this.length>2)J(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-V:V},G.prototype.toJSON=function(){return this.toString(16)},G.prototype.toBuffer=function(V,z){return J(typeof W<"u"),this.toArrayLike(W,V,z)},G.prototype.toArray=function(V,z){return this.toArrayLike(Array,V,z)},G.prototype.toArrayLike=function(V,z,H){var F=this.byteLength(),D=H||Math.max(1,F);J(F<=D,"byte array longer than desired length"),J(D>0,"Requested array length <= 0"),this.strip();var P=z==="le",j=new V(D),R,q,E=this.clone();if(!P){for(q=0;q<D-F;q++)j[q]=0;for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[D-q-1]=R}else{for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[q]=R;for(;q<D;q++)j[q]=0}return j},Math.clz32)G.prototype._countBits=function(V){return 32-Math.clz32(V)};else G.prototype._countBits=function(V){var z=V,H=0;if(z>=4096)H+=13,z>>>=13;if(z>=64)H+=7,z>>>=7;if(z>=8)H+=4,z>>>=4;if(z>=2)H+=2,z>>>=2;return H+z};G.prototype._zeroBits=function(V){if(V===0)return 26;var z=V,H=0;if((z&8191)===0)H+=13,z>>>=13;if((z&127)===0)H+=7,z>>>=7;if((z&15)===0)H+=4,z>>>=4;if((z&3)===0)H+=2,z>>>=2;if((z&1)===0)H++;return H},G.prototype.bitLength=function(){var V=this.words[this.length-1],z=this._countBits(V);return(this.length-1)*26+z};function M(V){var z=Array(V.bitLength());for(var H=0;H<z.length;H++){var F=H/26|0,D=H%26;z[H]=(V.words[F]&1<<D)>>>D}return z}G.prototype.zeroBits=function(){if(this.isZero())return 0;var V=0;for(var z=0;z<this.length;z++){var H=this._zeroBits(this.words[z]);if(V+=H,H!==26)break}return V},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(V){if(this.negative!==0)return this.abs().inotn(V).iaddn(1);return this.clone()},G.prototype.fromTwos=function(V){if(this.testn(V-1))return this.notn(V).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(V){while(this.length<V.length)this.words[this.length++]=0;for(var z=0;z<V.length;z++)this.words[z]=this.words[z]|V.words[z];return this.strip()},G.prototype.ior=function(V){return J((this.negative|V.negative)===0),this.iuor(V)},G.prototype.or=function(V){if(this.length>V.length)return this.clone().ior(V);return V.clone().ior(this)},G.prototype.uor=function(V){if(this.length>V.length)return this.clone().iuor(V);return V.clone().iuor(this)},G.prototype.iuand=function(V){var z;if(this.length>V.length)z=V;else z=this;for(var H=0;H<z.length;H++)this.words[H]=this.words[H]&V.words[H];return this.length=z.length,this.strip()},G.prototype.iand=function(V){return J((this.negative|V.negative)===0),this.iuand(V)},G.prototype.and=function(V){if(this.length>V.length)return this.clone().iand(V);return V.clone().iand(this)},G.prototype.uand=function(V){if(this.length>V.length)return this.clone().iuand(V);return V.clone().iuand(this)},G.prototype.iuxor=function(V){var z,H;if(this.length>V.length)z=this,H=V;else z=V,H=this;for(var F=0;F<H.length;F++)this.words[F]=z.words[F]^H.words[F];if(this!==z)for(;F<z.length;F++)this.words[F]=z.words[F];return this.length=z.length,this.strip()},G.prototype.ixor=function(V){return J((this.negative|V.negative)===0),this.iuxor(V)},G.prototype.xor=function(V){if(this.length>V.length)return this.clone().ixor(V);return V.clone().ixor(this)},G.prototype.uxor=function(V){if(this.length>V.length)return this.clone().iuxor(V);return V.clone().iuxor(this)},G.prototype.inotn=function(V){J(typeof V==="number"&&V>=0);var z=Math.ceil(V/26)|0,H=V%26;if(this._expand(z),H>0)z--;for(var F=0;F<z;F++)this.words[F]=~this.words[F]&67108863;if(H>0)this.words[F]=~this.words[F]&67108863>>26-H;return this.strip()},G.prototype.notn=function(V){return this.clone().inotn(V)},G.prototype.setn=function(V,z){J(typeof V==="number"&&V>=0);var H=V/26|0,F=V%26;if(this._expand(H+1),z)this.words[H]=this.words[H]|1<<F;else this.words[H]=this.words[H]&~(1<<F);return this.strip()},G.prototype.iadd=function(V){var z;if(this.negative!==0&&V.negative===0)return this.negative=0,z=this.isub(V),this.negative^=1,this._normSign();else if(this.negative===0&&V.negative!==0)return V.negative=0,z=this.isub(V),V.negative=1,z._normSign();var H,F;if(this.length>V.length)H=this,F=V;else H=V,F=this;var D=0;for(var P=0;P<F.length;P++)z=(H.words[P]|0)+(F.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;for(;D!==0&&P<H.length;P++)z=(H.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;if(this.length=H.length,D!==0)this.words[this.length]=D,this.length++;else if(H!==this)for(;P<H.length;P++)this.words[P]=H.words[P];return this},G.prototype.add=function(V){var z;if(V.negative!==0&&this.negative===0)return V.negative=0,z=this.sub(V),V.negative^=1,z;else if(V.negative===0&&this.negative!==0)return this.negative=0,z=V.sub(this),this.negative=1,z;if(this.length>V.length)return this.clone().iadd(V);return V.clone().iadd(this)},G.prototype.isub=function(V){if(V.negative!==0){V.negative=0;var z=this.iadd(V);return V.negative=1,z._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(V),this.negative=1,this._normSign();var H=this.cmp(V);if(H===0)return this.negative=0,this.length=1,this.words[0]=0,this;var F,D;if(H>0)F=this,D=V;else F=V,D=this;var P=0;for(var j=0;j<D.length;j++)z=(F.words[j]|0)-(D.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;for(;P!==0&&j<F.length;j++)z=(F.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;if(P===0&&j<F.length&&F!==this)for(;j<F.length;j++)this.words[j]=F.words[j];if(this.length=Math.max(this.length,j),F!==this)this.negative=1;return this.strip()},G.prototype.sub=function(V){return this.clone().isub(V)};function k(V,z,H){H.negative=z.negative^V.negative;var F=V.length+z.length|0;H.length=F,F=F-1|0;var D=V.words[0]|0,P=z.words[0]|0,j=D*P,R=j&67108863,q=j/67108864|0;H.words[0]=R;for(var E=1;E<F;E++){var N=q>>>26,T=q&67108863,v=Math.min(E,z.length-1);for(var y=Math.max(0,E-V.length+1);y<=v;y++){var p=E-y|0;D=V.words[p]|0,P=z.words[y]|0,j=D*P+T,N+=j/67108864|0,T=j&67108863}H.words[E]=T|0,q=N|0}if(q!==0)H.words[E]=q|0;else H.length--;return H.strip()}var B=function(V,z,H){var F=V.words,D=z.words,P=H.words,j=0,R,q,E,N=F[0]|0,T=N&8191,v=N>>>13,y=F[1]|0,p=y&8191,J0=y>>>13,x0=F[2]|0,K0=x0&8191,Y0=x0>>>13,j0=F[3]|0,$0=j0&8191,D0=j0>>>13,$Q=F[4]|0,m=$Q&8191,n=$Q>>>13,B0=F[5]|0,F0=B0&8191,z0=B0>>>13,l0=F[6]|0,d=l0&8191,X0=l0>>>13,QQ=F[7]|0,V0=QQ&8191,P0=QQ>>>13,jQ=F[8]|0,c0=jQ&8191,u0=jQ>>>13,$Z=F[9]|0,y0=$Z&8191,s=$Z>>>13,M0=D[0]|0,G0=M0&8191,H0=M0>>>13,KQ=D[1]|0,f0=KQ&8191,h0=KQ>>>13,LQ=D[2]|0,E0=LQ&8191,A0=LQ>>>13,GQ=D[3]|0,T0=GQ&8191,S0=GQ>>>13,gQ=D[4]|0,g0=gQ&8191,d0=gQ>>>13,_Z=D[5]|0,o0=_Z&8191,b=_Z>>>13,Q0=D[6]|0,O0=Q0&8191,L0=Q0>>>13,qQ=D[7]|0,m0=qQ&8191,n0=qQ>>>13,lZ=D[8]|0,r0=lZ&8191,e0=lZ>>>13,bY=D[9]|0,t0=bY&8191,a0=bY>>>13;H.negative=V.negative^z.negative,H.length=19,R=Math.imul(T,G0),q=Math.imul(T,H0),q=q+Math.imul(v,G0)|0,E=Math.imul(v,H0);var mZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(mZ>>>26)|0,mZ&=67108863,R=Math.imul(p,G0),q=Math.imul(p,H0),q=q+Math.imul(J0,G0)|0,E=Math.imul(J0,H0),R=R+Math.imul(T,f0)|0,q=q+Math.imul(T,h0)|0,q=q+Math.imul(v,f0)|0,E=E+Math.imul(v,h0)|0;var lQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(lQ>>>26)|0,lQ&=67108863,R=Math.imul(K0,G0),q=Math.imul(K0,H0),q=q+Math.imul(Y0,G0)|0,E=Math.imul(Y0,H0),R=R+Math.imul(p,f0)|0,q=q+Math.imul(p,h0)|0,q=q+Math.imul(J0,f0)|0,E=E+Math.imul(J0,h0)|0,R=R+Math.imul(T,E0)|0,q=q+Math.imul(T,A0)|0,q=q+Math.imul(v,E0)|0,E=E+Math.imul(v,A0)|0;var pQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(pQ>>>26)|0,pQ&=67108863,R=Math.imul($0,G0),q=Math.imul($0,H0),q=q+Math.imul(D0,G0)|0,E=Math.imul(D0,H0),R=R+Math.imul(K0,f0)|0,q=q+Math.imul(K0,h0)|0,q=q+Math.imul(Y0,f0)|0,E=E+Math.imul(Y0,h0)|0,R=R+Math.imul(p,E0)|0,q=q+Math.imul(p,A0)|0,q=q+Math.imul(J0,E0)|0,E=E+Math.imul(J0,A0)|0,R=R+Math.imul(T,T0)|0,q=q+Math.imul(T,S0)|0,q=q+Math.imul(v,T0)|0,E=E+Math.imul(v,S0)|0;var IZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,R=Math.imul(m,G0),q=Math.imul(m,H0),q=q+Math.imul(n,G0)|0,E=Math.imul(n,H0),R=R+Math.imul($0,f0)|0,q=q+Math.imul($0,h0)|0,q=q+Math.imul(D0,f0)|0,E=E+Math.imul(D0,h0)|0,R=R+Math.imul(K0,E0)|0,q=q+Math.imul(K0,A0)|0,q=q+Math.imul(Y0,E0)|0,E=E+Math.imul(Y0,A0)|0,R=R+Math.imul(p,T0)|0,q=q+Math.imul(p,S0)|0,q=q+Math.imul(J0,T0)|0,E=E+Math.imul(J0,S0)|0,R=R+Math.imul(T,g0)|0,q=q+Math.imul(T,d0)|0,q=q+Math.imul(v,g0)|0,E=E+Math.imul(v,d0)|0;var zZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,R=Math.imul(F0,G0),q=Math.imul(F0,H0),q=q+Math.imul(z0,G0)|0,E=Math.imul(z0,H0),R=R+Math.imul(m,f0)|0,q=q+Math.imul(m,h0)|0,q=q+Math.imul(n,f0)|0,E=E+Math.imul(n,h0)|0,R=R+Math.imul($0,E0)|0,q=q+Math.imul($0,A0)|0,q=q+Math.imul(D0,E0)|0,E=E+Math.imul(D0,A0)|0,R=R+Math.imul(K0,T0)|0,q=q+Math.imul(K0,S0)|0,q=q+Math.imul(Y0,T0)|0,E=E+Math.imul(Y0,S0)|0,R=R+Math.imul(p,g0)|0,q=q+Math.imul(p,d0)|0,q=q+Math.imul(J0,g0)|0,E=E+Math.imul(J0,d0)|0,R=R+Math.imul(T,o0)|0,q=q+Math.imul(T,b)|0,q=q+Math.imul(v,o0)|0,E=E+Math.imul(v,b)|0;var $Y=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+($Y>>>26)|0,$Y&=67108863,R=Math.imul(d,G0),q=Math.imul(d,H0),q=q+Math.imul(X0,G0)|0,E=Math.imul(X0,H0),R=R+Math.imul(F0,f0)|0,q=q+Math.imul(F0,h0)|0,q=q+Math.imul(z0,f0)|0,E=E+Math.imul(z0,h0)|0,R=R+Math.imul(m,E0)|0,q=q+Math.imul(m,A0)|0,q=q+Math.imul(n,E0)|0,E=E+Math.imul(n,A0)|0,R=R+Math.imul($0,T0)|0,q=q+Math.imul($0,S0)|0,q=q+Math.imul(D0,T0)|0,E=E+Math.imul(D0,S0)|0,R=R+Math.imul(K0,g0)|0,q=q+Math.imul(K0,d0)|0,q=q+Math.imul(Y0,g0)|0,E=E+Math.imul(Y0,d0)|0,R=R+Math.imul(p,o0)|0,q=q+Math.imul(p,b)|0,q=q+Math.imul(J0,o0)|0,E=E+Math.imul(J0,b)|0,R=R+Math.imul(T,O0)|0,q=q+Math.imul(T,L0)|0,q=q+Math.imul(v,O0)|0,E=E+Math.imul(v,L0)|0;var JY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(JY>>>26)|0,JY&=67108863,R=Math.imul(V0,G0),q=Math.imul(V0,H0),q=q+Math.imul(P0,G0)|0,E=Math.imul(P0,H0),R=R+Math.imul(d,f0)|0,q=q+Math.imul(d,h0)|0,q=q+Math.imul(X0,f0)|0,E=E+Math.imul(X0,h0)|0,R=R+Math.imul(F0,E0)|0,q=q+Math.imul(F0,A0)|0,q=q+Math.imul(z0,E0)|0,E=E+Math.imul(z0,A0)|0,R=R+Math.imul(m,T0)|0,q=q+Math.imul(m,S0)|0,q=q+Math.imul(n,T0)|0,E=E+Math.imul(n,S0)|0,R=R+Math.imul($0,g0)|0,q=q+Math.imul($0,d0)|0,q=q+Math.imul(D0,g0)|0,E=E+Math.imul(D0,d0)|0,R=R+Math.imul(K0,o0)|0,q=q+Math.imul(K0,b)|0,q=q+Math.imul(Y0,o0)|0,E=E+Math.imul(Y0,b)|0,R=R+Math.imul(p,O0)|0,q=q+Math.imul(p,L0)|0,q=q+Math.imul(J0,O0)|0,E=E+Math.imul(J0,L0)|0,R=R+Math.imul(T,m0)|0,q=q+Math.imul(T,n0)|0,q=q+Math.imul(v,m0)|0,E=E+Math.imul(v,n0)|0;var GY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(GY>>>26)|0,GY&=67108863,R=Math.imul(c0,G0),q=Math.imul(c0,H0),q=q+Math.imul(u0,G0)|0,E=Math.imul(u0,H0),R=R+Math.imul(V0,f0)|0,q=q+Math.imul(V0,h0)|0,q=q+Math.imul(P0,f0)|0,E=E+Math.imul(P0,h0)|0,R=R+Math.imul(d,E0)|0,q=q+Math.imul(d,A0)|0,q=q+Math.imul(X0,E0)|0,E=E+Math.imul(X0,A0)|0,R=R+Math.imul(F0,T0)|0,q=q+Math.imul(F0,S0)|0,q=q+Math.imul(z0,T0)|0,E=E+Math.imul(z0,S0)|0,R=R+Math.imul(m,g0)|0,q=q+Math.imul(m,d0)|0,q=q+Math.imul(n,g0)|0,E=E+Math.imul(n,d0)|0,R=R+Math.imul($0,o0)|0,q=q+Math.imul($0,b)|0,q=q+Math.imul(D0,o0)|0,E=E+Math.imul(D0,b)|0,R=R+Math.imul(K0,O0)|0,q=q+Math.imul(K0,L0)|0,q=q+Math.imul(Y0,O0)|0,E=E+Math.imul(Y0,L0)|0,R=R+Math.imul(p,m0)|0,q=q+Math.imul(p,n0)|0,q=q+Math.imul(J0,m0)|0,E=E+Math.imul(J0,n0)|0,R=R+Math.imul(T,r0)|0,q=q+Math.imul(T,e0)|0,q=q+Math.imul(v,r0)|0,E=E+Math.imul(v,e0)|0;var XY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(XY>>>26)|0,XY&=67108863,R=Math.imul(y0,G0),q=Math.imul(y0,H0),q=q+Math.imul(s,G0)|0,E=Math.imul(s,H0),R=R+Math.imul(c0,f0)|0,q=q+Math.imul(c0,h0)|0,q=q+Math.imul(u0,f0)|0,E=E+Math.imul(u0,h0)|0,R=R+Math.imul(V0,E0)|0,q=q+Math.imul(V0,A0)|0,q=q+Math.imul(P0,E0)|0,E=E+Math.imul(P0,A0)|0,R=R+Math.imul(d,T0)|0,q=q+Math.imul(d,S0)|0,q=q+Math.imul(X0,T0)|0,E=E+Math.imul(X0,S0)|0,R=R+Math.imul(F0,g0)|0,q=q+Math.imul(F0,d0)|0,q=q+Math.imul(z0,g0)|0,E=E+Math.imul(z0,d0)|0,R=R+Math.imul(m,o0)|0,q=q+Math.imul(m,b)|0,q=q+Math.imul(n,o0)|0,E=E+Math.imul(n,b)|0,R=R+Math.imul($0,O0)|0,q=q+Math.imul($0,L0)|0,q=q+Math.imul(D0,O0)|0,E=E+Math.imul(D0,L0)|0,R=R+Math.imul(K0,m0)|0,q=q+Math.imul(K0,n0)|0,q=q+Math.imul(Y0,m0)|0,E=E+Math.imul(Y0,n0)|0,R=R+Math.imul(p,r0)|0,q=q+Math.imul(p,e0)|0,q=q+Math.imul(J0,r0)|0,E=E+Math.imul(J0,e0)|0,R=R+Math.imul(T,t0)|0,q=q+Math.imul(T,a0)|0,q=q+Math.imul(v,t0)|0,E=E+Math.imul(v,a0)|0;var VY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(VY>>>26)|0,VY&=67108863,R=Math.imul(y0,f0),q=Math.imul(y0,h0),q=q+Math.imul(s,f0)|0,E=Math.imul(s,h0),R=R+Math.imul(c0,E0)|0,q=q+Math.imul(c0,A0)|0,q=q+Math.imul(u0,E0)|0,E=E+Math.imul(u0,A0)|0,R=R+Math.imul(V0,T0)|0,q=q+Math.imul(V0,S0)|0,q=q+Math.imul(P0,T0)|0,E=E+Math.imul(P0,S0)|0,R=R+Math.imul(d,g0)|0,q=q+Math.imul(d,d0)|0,q=q+Math.imul(X0,g0)|0,E=E+Math.imul(X0,d0)|0,R=R+Math.imul(F0,o0)|0,q=q+Math.imul(F0,b)|0,q=q+Math.imul(z0,o0)|0,E=E+Math.imul(z0,b)|0,R=R+Math.imul(m,O0)|0,q=q+Math.imul(m,L0)|0,q=q+Math.imul(n,O0)|0,E=E+Math.imul(n,L0)|0,R=R+Math.imul($0,m0)|0,q=q+Math.imul($0,n0)|0,q=q+Math.imul(D0,m0)|0,E=E+Math.imul(D0,n0)|0,R=R+Math.imul(K0,r0)|0,q=q+Math.imul(K0,e0)|0,q=q+Math.imul(Y0,r0)|0,E=E+Math.imul(Y0,e0)|0,R=R+Math.imul(p,t0)|0,q=q+Math.imul(p,a0)|0,q=q+Math.imul(J0,t0)|0,E=E+Math.imul(J0,a0)|0;var qY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(qY>>>26)|0,qY&=67108863,R=Math.imul(y0,E0),q=Math.imul(y0,A0),q=q+Math.imul(s,E0)|0,E=Math.imul(s,A0),R=R+Math.imul(c0,T0)|0,q=q+Math.imul(c0,S0)|0,q=q+Math.imul(u0,T0)|0,E=E+Math.imul(u0,S0)|0,R=R+Math.imul(V0,g0)|0,q=q+Math.imul(V0,d0)|0,q=q+Math.imul(P0,g0)|0,E=E+Math.imul(P0,d0)|0,R=R+Math.imul(d,o0)|0,q=q+Math.imul(d,b)|0,q=q+Math.imul(X0,o0)|0,E=E+Math.imul(X0,b)|0,R=R+Math.imul(F0,O0)|0,q=q+Math.imul(F0,L0)|0,q=q+Math.imul(z0,O0)|0,E=E+Math.imul(z0,L0)|0,R=R+Math.imul(m,m0)|0,q=q+Math.imul(m,n0)|0,q=q+Math.imul(n,m0)|0,E=E+Math.imul(n,n0)|0,R=R+Math.imul($0,r0)|0,q=q+Math.imul($0,e0)|0,q=q+Math.imul(D0,r0)|0,E=E+Math.imul(D0,e0)|0,R=R+Math.imul(K0,t0)|0,q=q+Math.imul(K0,a0)|0,q=q+Math.imul(Y0,t0)|0,E=E+Math.imul(Y0,a0)|0;var FY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(FY>>>26)|0,FY&=67108863,R=Math.imul(y0,T0),q=Math.imul(y0,S0),q=q+Math.imul(s,T0)|0,E=Math.imul(s,S0),R=R+Math.imul(c0,g0)|0,q=q+Math.imul(c0,d0)|0,q=q+Math.imul(u0,g0)|0,E=E+Math.imul(u0,d0)|0,R=R+Math.imul(V0,o0)|0,q=q+Math.imul(V0,b)|0,q=q+Math.imul(P0,o0)|0,E=E+Math.imul(P0,b)|0,R=R+Math.imul(d,O0)|0,q=q+Math.imul(d,L0)|0,q=q+Math.imul(X0,O0)|0,E=E+Math.imul(X0,L0)|0,R=R+Math.imul(F0,m0)|0,q=q+Math.imul(F0,n0)|0,q=q+Math.imul(z0,m0)|0,E=E+Math.imul(z0,n0)|0,R=R+Math.imul(m,r0)|0,q=q+Math.imul(m,e0)|0,q=q+Math.imul(n,r0)|0,E=E+Math.imul(n,e0)|0,R=R+Math.imul($0,t0)|0,q=q+Math.imul($0,a0)|0,q=q+Math.imul(D0,t0)|0,E=E+Math.imul(D0,a0)|0;var zY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zY>>>26)|0,zY&=67108863,R=Math.imul(y0,g0),q=Math.imul(y0,d0),q=q+Math.imul(s,g0)|0,E=Math.imul(s,d0),R=R+Math.imul(c0,o0)|0,q=q+Math.imul(c0,b)|0,q=q+Math.imul(u0,o0)|0,E=E+Math.imul(u0,b)|0,R=R+Math.imul(V0,O0)|0,q=q+Math.imul(V0,L0)|0,q=q+Math.imul(P0,O0)|0,E=E+Math.imul(P0,L0)|0,R=R+Math.imul(d,m0)|0,q=q+Math.imul(d,n0)|0,q=q+Math.imul(X0,m0)|0,E=E+Math.imul(X0,n0)|0,R=R+Math.imul(F0,r0)|0,q=q+Math.imul(F0,e0)|0,q=q+Math.imul(z0,r0)|0,E=E+Math.imul(z0,e0)|0,R=R+Math.imul(m,t0)|0,q=q+Math.imul(m,a0)|0,q=q+Math.imul(n,t0)|0,E=E+Math.imul(n,a0)|0;var WY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(WY>>>26)|0,WY&=67108863,R=Math.imul(y0,o0),q=Math.imul(y0,b),q=q+Math.imul(s,o0)|0,E=Math.imul(s,b),R=R+Math.imul(c0,O0)|0,q=q+Math.imul(c0,L0)|0,q=q+Math.imul(u0,O0)|0,E=E+Math.imul(u0,L0)|0,R=R+Math.imul(V0,m0)|0,q=q+Math.imul(V0,n0)|0,q=q+Math.imul(P0,m0)|0,E=E+Math.imul(P0,n0)|0,R=R+Math.imul(d,r0)|0,q=q+Math.imul(d,e0)|0,q=q+Math.imul(X0,r0)|0,E=E+Math.imul(X0,e0)|0,R=R+Math.imul(F0,t0)|0,q=q+Math.imul(F0,a0)|0,q=q+Math.imul(z0,t0)|0,E=E+Math.imul(z0,a0)|0;var KY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(KY>>>26)|0,KY&=67108863,R=Math.imul(y0,O0),q=Math.imul(y0,L0),q=q+Math.imul(s,O0)|0,E=Math.imul(s,L0),R=R+Math.imul(c0,m0)|0,q=q+Math.imul(c0,n0)|0,q=q+Math.imul(u0,m0)|0,E=E+Math.imul(u0,n0)|0,R=R+Math.imul(V0,r0)|0,q=q+Math.imul(V0,e0)|0,q=q+Math.imul(P0,r0)|0,E=E+Math.imul(P0,e0)|0,R=R+Math.imul(d,t0)|0,q=q+Math.imul(d,a0)|0,q=q+Math.imul(X0,t0)|0,E=E+Math.imul(X0,a0)|0;var UY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(UY>>>26)|0,UY&=67108863,R=Math.imul(y0,m0),q=Math.imul(y0,n0),q=q+Math.imul(s,m0)|0,E=Math.imul(s,n0),R=R+Math.imul(c0,r0)|0,q=q+Math.imul(c0,e0)|0,q=q+Math.imul(u0,r0)|0,E=E+Math.imul(u0,e0)|0,R=R+Math.imul(V0,t0)|0,q=q+Math.imul(V0,a0)|0,q=q+Math.imul(P0,t0)|0,E=E+Math.imul(P0,a0)|0;var OY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(OY>>>26)|0,OY&=67108863,R=Math.imul(y0,r0),q=Math.imul(y0,e0),q=q+Math.imul(s,r0)|0,E=Math.imul(s,e0),R=R+Math.imul(c0,t0)|0,q=q+Math.imul(c0,a0)|0,q=q+Math.imul(u0,t0)|0,E=E+Math.imul(u0,a0)|0;var HY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(HY>>>26)|0,HY&=67108863,R=Math.imul(y0,t0),q=Math.imul(y0,a0),q=q+Math.imul(s,t0)|0,E=Math.imul(s,a0);var DY=(j+R|0)+((q&8191)<<13)|0;if(j=(E+(q>>>13)|0)+(DY>>>26)|0,DY&=67108863,P[0]=mZ,P[1]=lQ,P[2]=pQ,P[3]=IZ,P[4]=zZ,P[5]=$Y,P[6]=JY,P[7]=GY,P[8]=XY,P[9]=VY,P[10]=qY,P[11]=FY,P[12]=zY,P[13]=WY,P[14]=KY,P[15]=UY,P[16]=OY,P[17]=HY,P[18]=DY,j!==0)P[19]=j,H.length++;return H};if(!Math.imul)B=k;function C(V,z,H){H.negative=z.negative^V.negative,H.length=V.length+z.length;var F=0,D=0;for(var P=0;P<H.length-1;P++){var j=D;D=0;var R=F&67108863,q=Math.min(P,z.length-1);for(var E=Math.max(0,P-V.length+1);E<=q;E++){var N=P-E,T=V.words[N]|0,v=z.words[E]|0,y=T*v,p=y&67108863;j=j+(y/67108864|0)|0,p=p+R|0,R=p&67108863,j=j+(p>>>26)|0,D+=j>>>26,j&=67108863}H.words[P]=R,F=j,j=D}if(F!==0)H.words[P]=F;else H.length--;return H.strip()}function S(V,z,H){var F=new _;return F.mulp(V,z,H)}G.prototype.mulTo=function(V,z){var H,F=this.length+V.length;if(this.length===10&&V.length===10)H=B(this,V,z);else if(F<63)H=k(this,V,z);else if(F<1024)H=C(this,V,z);else H=S(this,V,z);return H};function _(V,z){this.x=V,this.y=z}_.prototype.makeRBT=function(V){var z=Array(V),H=G.prototype._countBits(V)-1;for(var F=0;F<V;F++)z[F]=this.revBin(F,H,V);return z},_.prototype.revBin=function(V,z,H){if(V===0||V===H-1)return V;var F=0;for(var D=0;D<z;D++)F|=(V&1)<<z-D-1,V>>=1;return F},_.prototype.permute=function(V,z,H,F,D,P){for(var j=0;j<P;j++)F[j]=z[V[j]],D[j]=H[V[j]]},_.prototype.transform=function(V,z,H,F,D,P){this.permute(P,V,z,H,F,D);for(var j=1;j<D;j<<=1){var R=j<<1,q=Math.cos(2*Math.PI/R),E=Math.sin(2*Math.PI/R);for(var N=0;N<D;N+=R){var T=q,v=E;for(var y=0;y<j;y++){var p=H[N+y],J0=F[N+y],x0=H[N+y+j],K0=F[N+y+j],Y0=T*x0-v*K0;if(K0=T*K0+v*x0,x0=Y0,H[N+y]=p+x0,F[N+y]=J0+K0,H[N+y+j]=p-x0,F[N+y+j]=J0-K0,y!==R)Y0=q*T-E*v,v=q*v+E*T,T=Y0}}}},_.prototype.guessLen13b=function(V,z){var H=Math.max(z,V)|1,F=H&1,D=0;for(H=H/2|0;H;H=H>>>1)D++;return 1<<D+1+F},_.prototype.conjugate=function(V,z,H){if(H<=1)return;for(var F=0;F<H/2;F++){var D=V[F];V[F]=V[H-F-1],V[H-F-1]=D,D=z[F],z[F]=-z[H-F-1],z[H-F-1]=-D}},_.prototype.normalize13b=function(V,z){var H=0;for(var F=0;F<z/2;F++){var D=Math.round(V[2*F+1]/z)*8192+Math.round(V[2*F]/z)+H;if(V[F]=D&67108863,D<67108864)H=0;else H=D/67108864|0}return V},_.prototype.convert13b=function(V,z,H,F){var D=0;for(var P=0;P<z;P++)D=D+(V[P]|0),H[2*P]=D&8191,D=D>>>13,H[2*P+1]=D&8191,D=D>>>13;for(P=2*z;P<F;++P)H[P]=0;J(D===0),J((D&-8192)===0)},_.prototype.stub=function(V){var z=Array(V);for(var H=0;H<V;H++)z[H]=0;return z},_.prototype.mulp=function(V,z,H){var F=2*this.guessLen13b(V.length,z.length),D=this.makeRBT(F),P=this.stub(F),j=Array(F),R=Array(F),q=Array(F),E=Array(F),N=Array(F),T=Array(F),v=H.words;v.length=F,this.convert13b(V.words,V.length,j,F),this.convert13b(z.words,z.length,E,F),this.transform(j,P,R,q,F,D),this.transform(E,P,N,T,F,D);for(var y=0;y<F;y++){var p=R[y]*N[y]-q[y]*T[y];q[y]=R[y]*T[y]+q[y]*N[y],R[y]=p}return this.conjugate(R,q,F),this.transform(R,q,v,P,F,D),this.conjugate(v,P,F),this.normalize13b(v,F),H.negative=V.negative^z.negative,H.length=V.length+z.length,H.strip()},G.prototype.mul=function(V){var z=new G(null);return z.words=Array(this.length+V.length),this.mulTo(V,z)},G.prototype.mulf=function(V){var z=new G(null);return z.words=Array(this.length+V.length),S(this,V,z)},G.prototype.imul=function(V){return this.clone().mulTo(V,this)},G.prototype.imuln=function(V){J(typeof V==="number"),J(V<67108864);var z=0;for(var H=0;H<this.length;H++){var F=(this.words[H]|0)*V,D=(F&67108863)+(z&67108863);z>>=26,z+=F/67108864|0,z+=D>>>26,this.words[H]=D&67108863}if(z!==0)this.words[H]=z,this.length++;return this.length=V===0?1:this.length,this},G.prototype.muln=function(V){return this.clone().imuln(V)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(V){var z=M(V);if(z.length===0)return new G(1);var H=this;for(var F=0;F<z.length;F++,H=H.sqr())if(z[F]!==0)break;if(++F<z.length)for(var D=H.sqr();F<z.length;F++,D=D.sqr()){if(z[F]===0)continue;H=H.mul(D)}return H},G.prototype.iushln=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=67108863>>>26-z<<26-z,D;if(z!==0){var P=0;for(D=0;D<this.length;D++){var j=this.words[D]&F,R=(this.words[D]|0)-j<<z;this.words[D]=R|P,P=j>>>26-z}if(P)this.words[D]=P,this.length++}if(H!==0){for(D=this.length-1;D>=0;D--)this.words[D+H]=this.words[D];for(D=0;D<H;D++)this.words[D]=0;this.length+=H}return this.strip()},G.prototype.ishln=function(V){return J(this.negative===0),this.iushln(V)},G.prototype.iushrn=function(V,z,H){J(typeof V==="number"&&V>=0);var F;if(z)F=(z-z%26)/26;else F=0;var D=V%26,P=Math.min((V-D)/26,this.length),j=67108863^67108863>>>D<<D,R=H;if(F-=P,F=Math.max(0,F),R){for(var q=0;q<P;q++)R.words[q]=this.words[q];R.length=P}if(P===0);else if(this.length>P){this.length-=P;for(q=0;q<this.length;q++)this.words[q]=this.words[q+P]}else this.words[0]=0,this.length=1;var E=0;for(q=this.length-1;q>=0&&(E!==0||q>=F);q--){var N=this.words[q]|0;this.words[q]=E<<26-D|N>>>D,E=N&j}if(R&&E!==0)R.words[R.length++]=E;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},G.prototype.ishrn=function(V,z,H){return J(this.negative===0),this.iushrn(V,z,H)},G.prototype.shln=function(V){return this.clone().ishln(V)},G.prototype.ushln=function(V){return this.clone().iushln(V)},G.prototype.shrn=function(V){return this.clone().ishrn(V)},G.prototype.ushrn=function(V){return this.clone().iushrn(V)},G.prototype.testn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return!1;var D=this.words[H];return!!(D&F)},G.prototype.imaskn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26;if(J(this.negative===0,"imaskn works only with positive numbers"),this.length<=H)return this;if(z!==0)H++;if(this.length=Math.min(H,this.length),z!==0){var F=67108863^67108863>>>z<<z;this.words[this.length-1]&=F}return this.strip()},G.prototype.maskn=function(V){return this.clone().imaskn(V)},G.prototype.iaddn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.isubn(-V);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<V)return this.words[0]=V-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(V),this.negative=1,this}return this._iaddn(V)},G.prototype._iaddn=function(V){this.words[0]+=V;for(var z=0;z<this.length&&this.words[z]>=67108864;z++)if(this.words[z]-=67108864,z===this.length-1)this.words[z+1]=1;else this.words[z+1]++;return this.length=Math.max(this.length,z+1),this},G.prototype.isubn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.iaddn(-V);if(this.negative!==0)return this.negative=0,this.iaddn(V),this.negative=1,this;if(this.words[0]-=V,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var z=0;z<this.length&&this.words[z]<0;z++)this.words[z]+=67108864,this.words[z+1]-=1;return this.strip()},G.prototype.addn=function(V){return this.clone().iaddn(V)},G.prototype.subn=function(V){return this.clone().isubn(V)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(V,z,H){var F=V.length+H,D;this._expand(F);var P,j=0;for(D=0;D<V.length;D++){P=(this.words[D+H]|0)+j;var R=(V.words[D]|0)*z;P-=R&67108863,j=(P>>26)-(R/67108864|0),this.words[D+H]=P&67108863}for(;D<this.length-H;D++)P=(this.words[D+H]|0)+j,j=P>>26,this.words[D+H]=P&67108863;if(j===0)return this.strip();J(j===-1),j=0;for(D=0;D<this.length;D++)P=-(this.words[D]|0)+j,j=P>>26,this.words[D]=P&67108863;return this.negative=1,this.strip()},G.prototype._wordDiv=function(V,z){var H=this.length-V.length,F=this.clone(),D=V,P=D.words[D.length-1]|0,j=this._countBits(P);if(H=26-j,H!==0)D=D.ushln(H),F.iushln(H),P=D.words[D.length-1]|0;var R=F.length-D.length,q;if(z!=="mod"){q=new G(null),q.length=R+1,q.words=Array(q.length);for(var E=0;E<q.length;E++)q.words[E]=0}var N=F.clone()._ishlnsubmul(D,1,R);if(N.negative===0){if(F=N,q)q.words[R]=1}for(var T=R-1;T>=0;T--){var v=(F.words[D.length+T]|0)*67108864+(F.words[D.length+T-1]|0);v=Math.min(v/P|0,67108863),F._ishlnsubmul(D,v,T);while(F.negative!==0)if(v--,F.negative=0,F._ishlnsubmul(D,1,T),!F.isZero())F.negative^=1;if(q)q.words[T]=v}if(q)q.strip();if(F.strip(),z!=="div"&&H!==0)F.iushrn(H);return{div:q||null,mod:F}},G.prototype.divmod=function(V,z,H){if(J(!V.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var F,D,P;if(this.negative!==0&&V.negative===0){if(P=this.neg().divmod(V,z),z!=="mod")F=P.div.neg();if(z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.iadd(V)}return{div:F,mod:D}}if(this.negative===0&&V.negative!==0){if(P=this.divmod(V.neg(),z),z!=="mod")F=P.div.neg();return{div:F,mod:P.mod}}if((this.negative&V.negative)!==0){if(P=this.neg().divmod(V.neg(),z),z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.isub(V)}return{div:P.div,mod:D}}if(V.length>this.length||this.cmp(V)<0)return{div:new G(0),mod:this};if(V.length===1){if(z==="div")return{div:this.divn(V.words[0]),mod:null};if(z==="mod")return{div:null,mod:new G(this.modn(V.words[0]))};return{div:this.divn(V.words[0]),mod:new G(this.modn(V.words[0]))}}return this._wordDiv(V,z)},G.prototype.div=function(V){return this.divmod(V,"div",!1).div},G.prototype.mod=function(V){return this.divmod(V,"mod",!1).mod},G.prototype.umod=function(V){return this.divmod(V,"mod",!0).mod},G.prototype.divRound=function(V){var z=this.divmod(V);if(z.mod.isZero())return z.div;var H=z.div.negative!==0?z.mod.isub(V):z.mod,F=V.ushrn(1),D=V.andln(1),P=H.cmp(F);if(P<0||D===1&&P===0)return z.div;return z.div.negative!==0?z.div.isubn(1):z.div.iaddn(1)},G.prototype.modn=function(V){J(V<=67108863);var z=67108864%V,H=0;for(var F=this.length-1;F>=0;F--)H=(z*H+(this.words[F]|0))%V;return H},G.prototype.idivn=function(V){J(V<=67108863);var z=0;for(var H=this.length-1;H>=0;H--){var F=(this.words[H]|0)+z*67108864;this.words[H]=F/V|0,z=F%V}return this.strip()},G.prototype.divn=function(V){return this.clone().idivn(V)},G.prototype.egcd=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=new G(0),j=new G(1),R=0;while(z.isEven()&&H.isEven())z.iushrn(1),H.iushrn(1),++R;var q=H.clone(),E=z.clone();while(!z.isZero()){for(var N=0,T=1;(z.words[0]&T)===0&&N<26;++N,T<<=1);if(N>0){z.iushrn(N);while(N-- >0){if(F.isOdd()||D.isOdd())F.iadd(q),D.isub(E);F.iushrn(1),D.iushrn(1)}}for(var v=0,y=1;(H.words[0]&y)===0&&v<26;++v,y<<=1);if(v>0){H.iushrn(v);while(v-- >0){if(P.isOdd()||j.isOdd())P.iadd(q),j.isub(E);P.iushrn(1),j.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(P),D.isub(j);else H.isub(z),P.isub(F),j.isub(D)}return{a:P,b:j,gcd:H.iushln(R)}},G.prototype._invmp=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=H.clone();while(z.cmpn(1)>0&&H.cmpn(1)>0){for(var j=0,R=1;(z.words[0]&R)===0&&j<26;++j,R<<=1);if(j>0){z.iushrn(j);while(j-- >0){if(F.isOdd())F.iadd(P);F.iushrn(1)}}for(var q=0,E=1;(H.words[0]&E)===0&&q<26;++q,E<<=1);if(q>0){H.iushrn(q);while(q-- >0){if(D.isOdd())D.iadd(P);D.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(D);else H.isub(z),D.isub(F)}var N;if(z.cmpn(1)===0)N=F;else N=D;if(N.cmpn(0)<0)N.iadd(V);return N},G.prototype.gcd=function(V){if(this.isZero())return V.abs();if(V.isZero())return this.abs();var z=this.clone(),H=V.clone();z.negative=0,H.negative=0;for(var F=0;z.isEven()&&H.isEven();F++)z.iushrn(1),H.iushrn(1);do{while(z.isEven())z.iushrn(1);while(H.isEven())H.iushrn(1);var D=z.cmp(H);if(D<0){var P=z;z=H,H=P}else if(D===0||H.cmpn(1)===0)break;z.isub(H)}while(!0);return H.iushln(F)},G.prototype.invm=function(V){return this.egcd(V).a.umod(V)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(V){return this.words[0]&V},G.prototype.bincn=function(V){J(typeof V==="number");var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return this._expand(H+1),this.words[H]|=F,this;var D=F;for(var P=H;D!==0&&P<this.length;P++){var j=this.words[P]|0;j+=D,D=j>>>26,j&=67108863,this.words[P]=j}if(D!==0)this.words[P]=D,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(V){var z=V<0;if(this.negative!==0&&!z)return-1;if(this.negative===0&&z)return 1;this.strip();var H;if(this.length>1)H=1;else{if(z)V=-V;J(V<=67108863,"Number is too big");var F=this.words[0]|0;H=F===V?0:F<V?-1:1}if(this.negative!==0)return-H|0;return H},G.prototype.cmp=function(V){if(this.negative!==0&&V.negative===0)return-1;if(this.negative===0&&V.negative!==0)return 1;var z=this.ucmp(V);if(this.negative!==0)return-z|0;return z},G.prototype.ucmp=function(V){if(this.length>V.length)return 1;if(this.length<V.length)return-1;var z=0;for(var H=this.length-1;H>=0;H--){var F=this.words[H]|0,D=V.words[H]|0;if(F===D)continue;if(F<D)z=-1;else if(F>D)z=1;break}return z},G.prototype.gtn=function(V){return this.cmpn(V)===1},G.prototype.gt=function(V){return this.cmp(V)===1},G.prototype.gten=function(V){return this.cmpn(V)>=0},G.prototype.gte=function(V){return this.cmp(V)>=0},G.prototype.ltn=function(V){return this.cmpn(V)===-1},G.prototype.lt=function(V){return this.cmp(V)===-1},G.prototype.lten=function(V){return this.cmpn(V)<=0},G.prototype.lte=function(V){return this.cmp(V)<=0},G.prototype.eqn=function(V){return this.cmpn(V)===0},G.prototype.eq=function(V){return this.cmp(V)===0},G.red=function(V){return new c(V)},G.prototype.toRed=function(V){return J(!this.red,"Already a number in reduction context"),J(this.negative===0,"red works only with positives"),V.convertTo(this)._forceRed(V)},G.prototype.fromRed=function(){return J(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(V){return this.red=V,this},G.prototype.forceRed=function(V){return J(!this.red,"Already a number in reduction context"),this._forceRed(V)},G.prototype.redAdd=function(V){return J(this.red,"redAdd works only with red numbers"),this.red.add(this,V)},G.prototype.redIAdd=function(V){return J(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,V)},G.prototype.redSub=function(V){return J(this.red,"redSub works only with red numbers"),this.red.sub(this,V)},G.prototype.redISub=function(V){return J(this.red,"redISub works only with red numbers"),this.red.isub(this,V)},G.prototype.redShl=function(V){return J(this.red,"redShl works only with red numbers"),this.red.shl(this,V)},G.prototype.redMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.mul(this,V)},G.prototype.redIMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.imul(this,V)},G.prototype.redSqr=function(){return J(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return J(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return J(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return J(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return J(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(V){return J(this.red&&!V.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,V)};var x={k256:null,p224:null,p192:null,p25519:null};function f(V,z){this.name=V,this.p=new G(z,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}f.prototype._tmp=function(){var V=new G(null);return V.words=Array(Math.ceil(this.n/13)),V},f.prototype.ireduce=function(V){var z=V,H;do this.split(z,this.tmp),z=this.imulK(z),z=z.iadd(this.tmp),H=z.bitLength();while(H>this.n);var F=H<this.n?-1:z.ucmp(this.p);if(F===0)z.words[0]=0,z.length=1;else if(F>0)z.isub(this.p);else if(z.strip!==void 0)z.strip();else z._strip();return z},f.prototype.split=function(V,z){V.iushrn(this.n,0,z)},f.prototype.imulK=function(V){return V.imul(this.k)};function h(){f.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,f),h.prototype.split=function(V,z){var H=4194303,F=Math.min(V.length,9);for(var D=0;D<F;D++)z.words[D]=V.words[D];if(z.length=F,V.length<=9){V.words[0]=0,V.length=1;return}var P=V.words[9];z.words[z.length++]=P&H;for(D=10;D<V.length;D++){var j=V.words[D]|0;V.words[D-10]=(j&H)<<4|P>>>22,P=j}if(P>>>=22,V.words[D-10]=P,P===0&&V.length>10)V.length-=10;else V.length-=9},h.prototype.imulK=function(V){V.words[V.length]=0,V.words[V.length+1]=0,V.length+=2;var z=0;for(var H=0;H<V.length;H++){var F=V.words[H]|0;z+=F*977,V.words[H]=z&67108863,z=F*64+(z/67108864|0)}if(V.words[V.length-1]===0){if(V.length--,V.words[V.length-1]===0)V.length--}return V};function i(){f.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(i,f);function Z0(){f.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(Z0,f);function t(){f.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(t,f),t.prototype.imulK=function(V){var z=0;for(var H=0;H<V.length;H++){var F=(V.words[H]|0)*19+z,D=F&67108863;F>>>=26,V.words[H]=D,z=F}if(z!==0)V.words[V.length++]=z;return V},G._prime=function(V){if(x[V])return x[V];var z;if(V==="k256")z=new h;else if(V==="p224")z=new i;else if(V==="p192")z=new Z0;else if(V==="p25519")z=new t;else throw Error("Unknown prime "+V);return x[V]=z,z};function c(V){if(typeof V==="string"){var z=G._prime(V);this.m=z.p,this.prime=z}else J(V.gtn(1),"modulus must be greater than 1"),this.m=V,this.prime=null}c.prototype._verify1=function(V){J(V.negative===0,"red works only with positives"),J(V.red,"red works only with red numbers")},c.prototype._verify2=function(V,z){J((V.negative|z.negative)===0,"red works only with positives"),J(V.red&&V.red===z.red,"red works only with red numbers")},c.prototype.imod=function(V){if(this.prime)return this.prime.ireduce(V)._forceRed(this);return V.umod(this.m)._forceRed(this)},c.prototype.neg=function(V){if(V.isZero())return V.clone();return this.m.sub(V)._forceRed(this)},c.prototype.add=function(V,z){this._verify2(V,z);var H=V.add(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H._forceRed(this)},c.prototype.iadd=function(V,z){this._verify2(V,z);var H=V.iadd(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H},c.prototype.sub=function(V,z){this._verify2(V,z);var H=V.sub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H._forceRed(this)},c.prototype.isub=function(V,z){this._verify2(V,z);var H=V.isub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H},c.prototype.shl=function(V,z){return this._verify1(V),this.imod(V.ushln(z))},c.prototype.imul=function(V,z){return this._verify2(V,z),this.imod(V.imul(z))},c.prototype.mul=function(V,z){return this._verify2(V,z),this.imod(V.mul(z))},c.prototype.isqr=function(V){return this.imul(V,V.clone())},c.prototype.sqr=function(V){return this.mul(V,V)},c.prototype.sqrt=function(V){if(V.isZero())return V.clone();var z=this.m.andln(3);if(J(z%2===1),z===3){var H=this.m.add(new G(1)).iushrn(2);return this.pow(V,H)}var F=this.m.subn(1),D=0;while(!F.isZero()&&F.andln(1)===0)D++,F.iushrn(1);J(!F.isZero());var P=new G(1).toRed(this),j=P.redNeg(),R=this.m.subn(1).iushrn(1),q=this.m.bitLength();q=new G(2*q*q).toRed(this);while(this.pow(q,R).cmp(j)!==0)q.redIAdd(j);var E=this.pow(q,F),N=this.pow(V,F.addn(1).iushrn(1)),T=this.pow(V,F),v=D;while(T.cmp(P)!==0){var y=T;for(var p=0;y.cmp(P)!==0;p++)y=y.redSqr();J(p<v);var J0=this.pow(E,new G(1).iushln(v-p-1));N=N.redMul(J0),E=J0.redSqr(),T=T.redMul(E),v=p}return N},c.prototype.invm=function(V){var z=V._invmp(this.m);if(z.negative!==0)return z.negative=0,this.imod(z).redNeg();else return this.imod(z)},c.prototype.pow=function(V,z){if(z.isZero())return new G(1).toRed(this);if(z.cmpn(1)===0)return V.clone();var H=4,F=Array(1<<H);F[0]=new G(1).toRed(this),F[1]=V;for(var D=2;D<F.length;D++)F[D]=this.mul(F[D-1],V);var P=F[0],j=0,R=0,q=z.bitLength()%26;if(q===0)q=26;for(D=z.length-1;D>=0;D--){var E=z.words[D];for(var N=q-1;N>=0;N--){var T=E>>N&1;if(P!==F[0])P=this.sqr(P);if(T===0&&j===0){R=0;continue}if(j<<=1,j|=T,R++,R!==H&&(D!==0||N!==0))continue;P=this.mul(P,F[j]),R=0,j=0}q=26}return P},c.prototype.convertTo=function(V){var z=V.umod(this.m);return z===V?z.clone():z},c.prototype.convertFrom=function(V){var z=V.clone();return z.red=null,z},G.mont=function(V){return new l(V)};function l(V){if(c.call(this,V),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(l,c),l.prototype.convertTo=function(V){return this.imod(V.ushln(this.shift))},l.prototype.convertFrom=function(V){var z=this.imod(V.mul(this.rinv));return z.red=null,z},l.prototype.imul=function(V,z){if(V.isZero()||z.isZero())return V.words[0]=0,V.length=1,V;var H=V.imul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.mul=function(V,z){if(V.isZero()||z.isZero())return new G(0)._forceRed(this);var H=V.mul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.invm=function(V){var z=this.imod(V._invmp(this.m).mul(this.r2));return z._forceRed(this)}})(typeof Z>"u"||Z,Q)}),c8=v0((Q,Z)=>{Z.exports=Y;function Y($,J){if(!$)throw Error(J||"Assertion failed")}Y.equal=function($,J,X){if($!=J)throw Error(X||"Assertion failed: "+$+" != "+J)}}),zS=v0((Q)=>{var Z=Q;function Y(X,G){if(Array.isArray(X))return X.slice();if(!X)return[];var W=[];if(typeof X!=="string"){for(var U=0;U<X.length;U++)W[U]=X[U]|0;return W}if(G==="hex"){if(X=X.replace(/[^a-z0-9]+/ig,""),X.length%2!==0)X="0"+X;for(var U=0;U<X.length;U+=2)W.push(parseInt(X[U]+X[U+1],16))}else for(var U=0;U<X.length;U++){var K=X.charCodeAt(U),O=K>>8,I=K&255;if(O)W.push(O,I);else W.push(I)}return W}Z.toArray=Y;function $(X){if(X.length===1)return"0"+X;else return X}Z.zero2=$;function J(X){var G="";for(var W=0;W<X.length;W++)G+=$(X[W].toString(16));return G}Z.toHex=J,Z.encode=function(X,G){if(G==="hex")return J(X);else return X}}),DJ=v0((Q)=>{var Z=Q,Y=m1(),$=c8(),J=zS();Z.assert=$,Z.toArray=J.toArray,Z.zero2=J.zero2,Z.toHex=J.toHex,Z.encode=J.encode;function X(O,I,L){var A=Array(Math.max(O.bitLength(),L)+1),M;for(M=0;M<A.length;M+=1)A[M]=0;var k=1<<I+1,B=O.clone();for(M=0;M<A.length;M++){var C,S=B.andln(k-1);if(B.isOdd()){if(S>(k>>1)-1)C=(k>>1)-S;else C=S;B.isubn(C)}else C=0;A[M]=C,B.iushrn(1)}return A}Z.getNAF=X;function G(O,I){var L=[[],[]];O=O.clone(),I=I.clone();var A=0,M=0,k;while(O.cmpn(-A)>0||I.cmpn(-M)>0){var B=O.andln(3)+A&3,C=I.andln(3)+M&3;if(B===3)B=-1;if(C===3)C=-1;var S;if((B&1)===0)S=0;else if(k=O.andln(7)+A&7,(k===3||k===5)&&C===2)S=-B;else S=B;L[0].push(S);var _;if((C&1)===0)_=0;else if(k=I.andln(7)+M&7,(k===3||k===5)&&B===2)_=-C;else _=C;if(L[1].push(_),2*A===S+1)A=1-A;if(2*M===_+1)M=1-M;O.iushrn(1),I.iushrn(1)}return L}Z.getJSF=G;function W(O,I,L){var A="_"+I;O.prototype[I]=function(){return this[A]!==void 0?this[A]:this[A]=L.call(this)}}Z.cachedProperty=W;function U(O){return typeof O==="string"?Z.toArray(O,"hex"):O}Z.parseBytes=U;function K(O){return new Y(O,"hex","le")}Z.intFromLE=K}),WS=v0((Q,Z)=>{var Y;Z.exports=function(X){if(!Y)Y=new $(null);return Y.generate(X)};function $(X){this.rand=X}if(Z.exports.Rand=$,$.prototype.generate=function(X){return this._rand(X)},$.prototype._rand=function(X){if(this.rand.getBytes)return this.rand.getBytes(X);var G=new Uint8Array(X);for(var W=0;W<G.length;W++)G[W]=this.rand.getByte();return G},typeof self==="object"){if(self.crypto&&self.crypto.getRandomValues)$.prototype._rand=function(X){var G=new Uint8Array(X);return self.crypto.getRandomValues(G),G};else if(self.msCrypto&&self.msCrypto.getRandomValues)$.prototype._rand=function(X){var G=new Uint8Array(X);return self.msCrypto.getRandomValues(G),G};else if(typeof window==="object")$.prototype._rand=function(){throw Error("Not implemented yet")}}else try{if(J=(v$(),oQ(_$)),typeof J.randomBytes!=="function")throw Error("Not supported");$.prototype._rand=function(X){return J.randomBytes(X)}}catch(X){}var J}),hW=v0((Q,Z)=>{var Y=m1(),$=DJ(),J=$.getNAF,X=$.getJSF,G=$.assert;function W(K,O){this.type=K,this.p=new Y(O.p,16),this.red=O.prime?Y.red(O.prime):Y.mont(this.p),this.zero=new Y(0).toRed(this.red),this.one=new Y(1).toRed(this.red),this.two=new Y(2).toRed(this.red),this.n=O.n&&new Y(O.n,16),this.g=O.g&&this.pointFromJSON(O.g,O.gRed),this._wnafT1=[,,,,],this._wnafT2=[,,,,],this._wnafT3=[,,,,],this._wnafT4=[,,,,],this._bitLength=this.n?this.n.bitLength():0;var I=this.n&&this.p.div(this.n);if(!I||I.cmpn(100)>0)this.redN=null;else this._maxwellTrick=!0,this.redN=this.n.toRed(this.red)}Z.exports=W,W.prototype.point=function(){throw Error("Not implemented")},W.prototype.validate=function(){throw Error("Not implemented")},W.prototype._fixedNafMul=function(K,O){G(K.precomputed);var I=K._getDoubles(),L=J(O,1,this._bitLength),A=(1<<I.step+1)-(I.step%2===0?2:1);A/=3;var M=[],k,B;for(k=0;k<L.length;k+=I.step){B=0;for(var C=k+I.step-1;C>=k;C--)B=(B<<1)+L[C];M.push(B)}var S=this.jpoint(null,null,null),_=this.jpoint(null,null,null);for(var x=A;x>0;x--){for(k=0;k<M.length;k++)if(B=M[k],B===x)_=_.mixedAdd(I.points[k]);else if(B===-x)_=_.mixedAdd(I.points[k].neg());S=S.add(_)}return S.toP()},W.prototype._wnafMul=function(K,O){var I=4,L=K._getNAFPoints(I);I=L.wnd;var A=L.points,M=J(O,I,this._bitLength),k=this.jpoint(null,null,null);for(var B=M.length-1;B>=0;B--){for(var C=0;B>=0&&M[B]===0;B--)C++;if(B>=0)C++;if(k=k.dblp(C),B<0)break;var S=M[B];if(G(S!==0),K.type==="affine")if(S>0)k=k.mixedAdd(A[S-1>>1]);else k=k.mixedAdd(A[-S-1>>1].neg());else if(S>0)k=k.add(A[S-1>>1]);else k=k.add(A[-S-1>>1].neg())}return K.type==="affine"?k.toP():k},W.prototype._wnafMulAdd=function(K,O,I,L,A){var M=this._wnafT1,k=this._wnafT2,B=this._wnafT3,C=0,S,_,x;for(S=0;S<L;S++){x=O[S];var f=x._getNAFPoints(K);M[S]=f.wnd,k[S]=f.points}for(S=L-1;S>=1;S-=2){var h=S-1,i=S;if(M[h]!==1||M[i]!==1){B[h]=J(I[h],M[h],this._bitLength),B[i]=J(I[i],M[i],this._bitLength),C=Math.max(B[h].length,C),C=Math.max(B[i].length,C);continue}var Z0=[O[h],null,null,O[i]];if(O[h].y.cmp(O[i].y)===0)Z0[1]=O[h].add(O[i]),Z0[2]=O[h].toJ().mixedAdd(O[i].neg());else if(O[h].y.cmp(O[i].y.redNeg())===0)Z0[1]=O[h].toJ().mixedAdd(O[i]),Z0[2]=O[h].add(O[i].neg());else Z0[1]=O[h].toJ().mixedAdd(O[i]),Z0[2]=O[h].toJ().mixedAdd(O[i].neg());var t=[-3,-1,-5,-7,0,7,5,1,3],c=X(I[h],I[i]);C=Math.max(c[0].length,C),B[h]=Array(C),B[i]=Array(C);for(_=0;_<C;_++){var l=c[0][_]|0,V=c[1][_]|0;B[h][_]=t[(l+1)*3+(V+1)],B[i][_]=0,k[h]=Z0}}var z=this.jpoint(null,null,null),H=this._wnafT4;for(S=C;S>=0;S--){var F=0;while(S>=0){var D=!0;for(_=0;_<L;_++)if(H[_]=B[_][S]|0,H[_]!==0)D=!1;if(!D)break;F++,S--}if(S>=0)F++;if(z=z.dblp(F),S<0)break;for(_=0;_<L;_++){var P=H[_];if(P===0)continue;else if(P>0)x=k[_][P-1>>1];else if(P<0)x=k[_][-P-1>>1].neg();if(x.type==="affine")z=z.mixedAdd(x);else z=z.add(x)}}for(S=0;S<L;S++)k[S]=null;if(A)return z;else return z.toP()};function U(K,O){this.curve=K,this.type=O,this.precomputed=null}W.BasePoint=U,U.prototype.eq=function(){throw Error("Not implemented")},U.prototype.validate=function(){return this.curve.validate(this)},W.prototype.decodePoint=function(K,O){K=$.toArray(K,O);var I=this.p.byteLength();if((K[0]===4||K[0]===6||K[0]===7)&&K.length-1===2*I){if(K[0]===6)G(K[K.length-1]%2===0);else if(K[0]===7)G(K[K.length-1]%2===1);var L=this.point(K.slice(1,1+I),K.slice(1+I,1+2*I));return L}else if((K[0]===2||K[0]===3)&&K.length-1===I)return this.pointFromX(K.slice(1,1+I),K[0]===3);throw Error("Unknown point format")},U.prototype.encodeCompressed=function(K){return this.encode(K,!0)},U.prototype._encode=function(K){var O=this.curve.p.byteLength(),I=this.getX().toArray("be",O);if(K)return[this.getY().isEven()?2:3].concat(I);return[4].concat(I,this.getY().toArray("be",O))},U.prototype.encode=function(K,O){return $.encode(this._encode(O),K)},U.prototype.precompute=function(K){if(this.precomputed)return this;var O={doubles:null,naf:null,beta:null};return O.naf=this._getNAFPoints(8),O.doubles=this._getDoubles(4,K),O.beta=this._getBeta(),this.precomputed=O,this},U.prototype._hasDoubles=function(K){if(!this.precomputed)return!1;var O=this.precomputed.doubles;if(!O)return!1;return O.points.length>=Math.ceil((K.bitLength()+1)/O.step)},U.prototype._getDoubles=function(K,O){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;var I=[this],L=this;for(var A=0;A<O;A+=K){for(var M=0;M<K;M++)L=L.dbl();I.push(L)}return{step:K,points:I}},U.prototype._getNAFPoints=function(K){if(this.precomputed&&this.precomputed.naf)return this.precomputed.naf;var O=[this],I=(1<<K)-1,L=I===1?null:this.dbl();for(var A=1;A<I;A++)O[A]=O[A-1].add(L);return{wnd:K,points:O}},U.prototype._getBeta=function(){return null},U.prototype.dblp=function(K){var O=this;for(var I=0;I<K;I++)O=O.dbl();return O}}),ct=v0((Q,Z)=>{if(typeof Object.create==="function")Z.exports=function(Y,$){if($)Y.super_=$,Y.prototype=Object.create($.prototype,{constructor:{value:Y,enumerable:!1,writable:!0,configurable:!0}})};else Z.exports=function(Y,$){if($){Y.super_=$;var J=function(){};J.prototype=$.prototype,Y.prototype=new J,Y.prototype.constructor=Y}}}),YJ=v0((Q,Z)=>{try{if(Y=(NC(),oQ(TC)),typeof Y.inherits!=="function")throw"";Z.exports=Y.inherits}catch($){Z.exports=ct()}var Y}),ut=v0((Q,Z)=>{var Y=DJ(),$=m1(),J=YJ(),X=hW(),G=Y.assert;function W(O){X.call(this,"short",O),this.a=new $(O.a,16).toRed(this.red),this.b=new $(O.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=this.a.fromRed().cmpn(0)===0,this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0,this.endo=this._getEndomorphism(O),this._endoWnafT1=[,,,,],this._endoWnafT2=[,,,,]}J(W,X),Z.exports=W,W.prototype._getEndomorphism=function(O){if(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)return;var I,L;if(O.beta)I=new $(O.beta,16).toRed(this.red);else{var A=this._getEndoRoots(this.p);I=A[0].cmp(A[1])<0?A[0]:A[1],I=I.toRed(this.red)}if(O.lambda)L=new $(O.lambda,16);else{var M=this._getEndoRoots(this.n);if(this.g.mul(M[0]).x.cmp(this.g.x.redMul(I))===0)L=M[0];else L=M[1],G(this.g.mul(L).x.cmp(this.g.x.redMul(I))===0)}var k;if(O.basis)k=O.basis.map(function(B){return{a:new $(B.a,16),b:new $(B.b,16)}});else k=this._getEndoBasis(L);return{beta:I,lambda:L,basis:k}},W.prototype._getEndoRoots=function(O){var I=O===this.p?this.red:$.mont(O),L=new $(2).toRed(I).redInvm(),A=L.redNeg(),M=new $(3).toRed(I).redNeg().redSqrt().redMul(L),k=A.redAdd(M).fromRed(),B=A.redSub(M).fromRed();return[k,B]},W.prototype._getEndoBasis=function(O){var I=this.n.ushrn(Math.floor(this.n.bitLength()/2)),L=O,A=this.n.clone(),M=new $(1),k=new $(0),B=new $(0),C=new $(1),S,_,x,f,h,i,Z0,t=0,c,l;while(L.cmpn(0)!==0){var V=A.div(L);c=A.sub(V.mul(L)),l=B.sub(V.mul(M));var z=C.sub(V.mul(k));if(!x&&c.cmp(I)<0)S=Z0.neg(),_=M,x=c.neg(),f=l;else if(x&&++t===2)break;Z0=c,A=L,L=c,B=M,M=l,C=k,k=z}h=c.neg(),i=l;var H=x.sqr().add(f.sqr()),F=h.sqr().add(i.sqr());if(F.cmp(H)>=0)h=S,i=_;if(x.negative)x=x.neg(),f=f.neg();if(h.negative)h=h.neg(),i=i.neg();return[{a:x,b:f},{a:h,b:i}]},W.prototype._endoSplit=function(O){var I=this.endo.basis,L=I[0],A=I[1],M=A.b.mul(O).divRound(this.n),k=L.b.neg().mul(O).divRound(this.n),B=M.mul(L.a),C=k.mul(A.a),S=M.mul(L.b),_=k.mul(A.b),x=O.sub(B).sub(C),f=S.add(_).neg();return{k1:x,k2:f}},W.prototype.pointFromX=function(O,I){if(O=new $(O,16),!O.red)O=O.toRed(this.red);var L=O.redSqr().redMul(O).redIAdd(O.redMul(this.a)).redIAdd(this.b),A=L.redSqrt();if(A.redSqr().redSub(L).cmp(this.zero)!==0)throw Error("invalid point");var M=A.fromRed().isOdd();if(I&&!M||!I&&M)A=A.redNeg();return this.point(O,A)},W.prototype.validate=function(O){if(O.inf)return!0;var{x:I,y:L}=O,A=this.a.redMul(I),M=I.redSqr().redMul(I).redIAdd(A).redIAdd(this.b);return L.redSqr().redISub(M).cmpn(0)===0},W.prototype._endoWnafMulAdd=function(O,I,L){var A=this._endoWnafT1,M=this._endoWnafT2;for(var k=0;k<O.length;k++){var B=this._endoSplit(I[k]),C=O[k],S=C._getBeta();if(B.k1.negative)B.k1.ineg(),C=C.neg(!0);if(B.k2.negative)B.k2.ineg(),S=S.neg(!0);A[k*2]=C,A[k*2+1]=S,M[k*2]=B.k1,M[k*2+1]=B.k2}var _=this._wnafMulAdd(1,A,M,k*2,L);for(var x=0;x<k*2;x++)A[x]=null,M[x]=null;return _};function U(O,I,L,A){if(X.BasePoint.call(this,O,"affine"),I===null&&L===null)this.x=null,this.y=null,this.inf=!0;else{if(this.x=new $(I,16),this.y=new $(L,16),A)this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);this.inf=!1}}J(U,X.BasePoint),W.prototype.point=function(O,I,L){return new U(this,O,I,L)},W.prototype.pointFromJSON=function(O,I){return U.fromJSON(this,O,I)},U.prototype._getBeta=function(){if(!this.curve.endo)return;var O=this.precomputed;if(O&&O.beta)return O.beta;var I=this.curve.point(this.x.redMul(this.curve.endo.beta),this.y);if(O){var L=this.curve,A=function(M){return L.point(M.x.redMul(L.endo.beta),M.y)};O.beta=I,I.precomputed={beta:null,naf:O.naf&&{wnd:O.naf.wnd,points:O.naf.points.map(A)},doubles:O.doubles&&{step:O.doubles.step,points:O.doubles.points.map(A)}}}return I},U.prototype.toJSON=function(){if(!this.precomputed)return[this.x,this.y];return[this.x,this.y,this.precomputed&&{doubles:this.precomputed.doubles&&{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:this.precomputed.naf&&{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}]},U.fromJSON=function(O,I,L){if(typeof I==="string")I=JSON.parse(I);var A=O.point(I[0],I[1],L);if(!I[2])return A;function M(B){return O.point(B[0],B[1],L)}var k=I[2];return A.precomputed={beta:null,doubles:k.doubles&&{step:k.doubles.step,points:[A].concat(k.doubles.points.map(M))},naf:k.naf&&{wnd:k.naf.wnd,points:[A].concat(k.naf.points.map(M))}},A},U.prototype.inspect=function(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+">"},U.prototype.isInfinity=function(){return this.inf},U.prototype.add=function(O){if(this.inf)return O;if(O.inf)return this;if(this.eq(O))return this.dbl();if(this.neg().eq(O))return this.curve.point(null,null);if(this.x.cmp(O.x)===0)return this.curve.point(null,null);var I=this.y.redSub(O.y);if(I.cmpn(0)!==0)I=I.redMul(this.x.redSub(O.x).redInvm());var L=I.redSqr().redISub(this.x).redISub(O.x),A=I.redMul(this.x.redSub(L)).redISub(this.y);return this.curve.point(L,A)},U.prototype.dbl=function(){if(this.inf)return this;var O=this.y.redAdd(this.y);if(O.cmpn(0)===0)return this.curve.point(null,null);var I=this.curve.a,L=this.x.redSqr(),A=O.redInvm(),M=L.redAdd(L).redIAdd(L).redIAdd(I).redMul(A),k=M.redSqr().redISub(this.x.redAdd(this.x)),B=M.redMul(this.x.redSub(k)).redISub(this.y);return this.curve.point(k,B)},U.prototype.getX=function(){return this.x.fromRed()},U.prototype.getY=function(){return this.y.fromRed()},U.prototype.mul=function(O){if(O=new $(O,16),this.isInfinity())return this;else if(this._hasDoubles(O))return this.curve._fixedNafMul(this,O);else if(this.curve.endo)return this.curve._endoWnafMulAdd([this],[O]);else return this.curve._wnafMul(this,O)},U.prototype.mulAdd=function(O,I,L){var A=[this,I],M=[O,L];if(this.curve.endo)return this.curve._endoWnafMulAdd(A,M);else return this.curve._wnafMulAdd(1,A,M,2)},U.prototype.jmulAdd=function(O,I,L){var A=[this,I],M=[O,L];if(this.curve.endo)return this.curve._endoWnafMulAdd(A,M,!0);else return this.curve._wnafMulAdd(1,A,M,2,!0)},U.prototype.eq=function(O){return this===O||this.inf===O.inf&&(this.inf||this.x.cmp(O.x)===0&&this.y.cmp(O.y)===0)},U.prototype.neg=function(O){if(this.inf)return this;var I=this.curve.point(this.x,this.y.redNeg());if(O&&this.precomputed){var L=this.precomputed,A=function(M){return M.neg()};I.precomputed={naf:L.naf&&{wnd:L.naf.wnd,points:L.naf.points.map(A)},doubles:L.doubles&&{step:L.doubles.step,points:L.doubles.points.map(A)}}}return I},U.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var O=this.curve.jpoint(this.x,this.y,this.curve.one);return O};function K(O,I,L,A){if(X.BasePoint.call(this,O,"jacobian"),I===null&&L===null&&A===null)this.x=this.curve.one,this.y=this.curve.one,this.z=new $(0);else this.x=new $(I,16),this.y=new $(L,16),this.z=new $(A,16);if(!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);this.zOne=this.z===this.curve.one}J(K,X.BasePoint),W.prototype.jpoint=function(O,I,L){return new K(this,O,I,L)},K.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var O=this.z.redInvm(),I=O.redSqr(),L=this.x.redMul(I),A=this.y.redMul(I).redMul(O);return this.curve.point(L,A)},K.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},K.prototype.add=function(O){if(this.isInfinity())return O;if(O.isInfinity())return this;var I=O.z.redSqr(),L=this.z.redSqr(),A=this.x.redMul(I),M=O.x.redMul(L),k=this.y.redMul(I.redMul(O.z)),B=O.y.redMul(L.redMul(this.z)),C=A.redSub(M),S=k.redSub(B);if(C.cmpn(0)===0)if(S.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl();var _=C.redSqr(),x=_.redMul(C),f=A.redMul(_),h=S.redSqr().redIAdd(x).redISub(f).redISub(f),i=S.redMul(f.redISub(h)).redISub(k.redMul(x)),Z0=this.z.redMul(O.z).redMul(C);return this.curve.jpoint(h,i,Z0)},K.prototype.mixedAdd=function(O){if(this.isInfinity())return O.toJ();if(O.isInfinity())return this;var I=this.z.redSqr(),L=this.x,A=O.x.redMul(I),M=this.y,k=O.y.redMul(I).redMul(this.z),B=L.redSub(A),C=M.redSub(k);if(B.cmpn(0)===0)if(C.cmpn(0)!==0)return this.curve.jpoint(null,null,null);else return this.dbl();var S=B.redSqr(),_=S.redMul(B),x=L.redMul(S),f=C.redSqr().redIAdd(_).redISub(x).redISub(x),h=C.redMul(x.redISub(f)).redISub(M.redMul(_)),i=this.z.redMul(B);return this.curve.jpoint(f,h,i)},K.prototype.dblp=function(O){if(O===0)return this;if(this.isInfinity())return this;if(!O)return this.dbl();var I;if(this.curve.zeroA||this.curve.threeA){var L=this;for(I=0;I<O;I++)L=L.dbl();return L}var A=this.curve.a,M=this.curve.tinv,k=this.x,B=this.y,C=this.z,S=C.redSqr().redSqr(),_=B.redAdd(B);for(I=0;I<O;I++){var x=k.redSqr(),f=_.redSqr(),h=f.redSqr(),i=x.redAdd(x).redIAdd(x).redIAdd(A.redMul(S)),Z0=k.redMul(f),t=i.redSqr().redISub(Z0.redAdd(Z0)),c=Z0.redISub(t),l=i.redMul(c);l=l.redIAdd(l).redISub(h);var V=_.redMul(C);if(I+1<O)S=S.redMul(h);k=t,C=V,_=l}return this.curve.jpoint(k,_.redMul(M),C)},K.prototype.dbl=function(){if(this.isInfinity())return this;if(this.curve.zeroA)return this._zeroDbl();else if(this.curve.threeA)return this._threeDbl();else return this._dbl()},K.prototype._zeroDbl=function(){var O,I,L;if(this.zOne){var A=this.x.redSqr(),M=this.y.redSqr(),k=M.redSqr(),B=this.x.redAdd(M).redSqr().redISub(A).redISub(k);B=B.redIAdd(B);var C=A.redAdd(A).redIAdd(A),S=C.redSqr().redISub(B).redISub(B),_=k.redIAdd(k);_=_.redIAdd(_),_=_.redIAdd(_),O=S,I=C.redMul(B.redISub(S)).redISub(_),L=this.y.redAdd(this.y)}else{var x=this.x.redSqr(),f=this.y.redSqr(),h=f.redSqr(),i=this.x.redAdd(f).redSqr().redISub(x).redISub(h);i=i.redIAdd(i);var Z0=x.redAdd(x).redIAdd(x),t=Z0.redSqr(),c=h.redIAdd(h);c=c.redIAdd(c),c=c.redIAdd(c),O=t.redISub(i).redISub(i),I=Z0.redMul(i.redISub(O)).redISub(c),L=this.y.redMul(this.z),L=L.redIAdd(L)}return this.curve.jpoint(O,I,L)},K.prototype._threeDbl=function(){var O,I,L;if(this.zOne){var A=this.x.redSqr(),M=this.y.redSqr(),k=M.redSqr(),B=this.x.redAdd(M).redSqr().redISub(A).redISub(k);B=B.redIAdd(B);var C=A.redAdd(A).redIAdd(A).redIAdd(this.curve.a),S=C.redSqr().redISub(B).redISub(B);O=S;var _=k.redIAdd(k);_=_.redIAdd(_),_=_.redIAdd(_),I=C.redMul(B.redISub(S)).redISub(_),L=this.y.redAdd(this.y)}else{var x=this.z.redSqr(),f=this.y.redSqr(),h=this.x.redMul(f),i=this.x.redSub(x).redMul(this.x.redAdd(x));i=i.redAdd(i).redIAdd(i);var Z0=h.redIAdd(h);Z0=Z0.redIAdd(Z0);var t=Z0.redAdd(Z0);O=i.redSqr().redISub(t),L=this.y.redAdd(this.z).redSqr().redISub(f).redISub(x);var c=f.redSqr();c=c.redIAdd(c),c=c.redIAdd(c),c=c.redIAdd(c),I=i.redMul(Z0.redISub(O)).redISub(c)}return this.curve.jpoint(O,I,L)},K.prototype._dbl=function(){var O=this.curve.a,I=this.x,L=this.y,A=this.z,M=A.redSqr().redSqr(),k=I.redSqr(),B=L.redSqr(),C=k.redAdd(k).redIAdd(k).redIAdd(O.redMul(M)),S=I.redAdd(I);S=S.redIAdd(S);var _=S.redMul(B),x=C.redSqr().redISub(_.redAdd(_)),f=_.redISub(x),h=B.redSqr();h=h.redIAdd(h),h=h.redIAdd(h),h=h.redIAdd(h);var i=C.redMul(f).redISub(h),Z0=L.redAdd(L).redMul(A);return this.curve.jpoint(x,i,Z0)},K.prototype.trpl=function(){if(!this.curve.zeroA)return this.dbl().add(this);var O=this.x.redSqr(),I=this.y.redSqr(),L=this.z.redSqr(),A=I.redSqr(),M=O.redAdd(O).redIAdd(O),k=M.redSqr(),B=this.x.redAdd(I).redSqr().redISub(O).redISub(A);B=B.redIAdd(B),B=B.redAdd(B).redIAdd(B),B=B.redISub(k);var C=B.redSqr(),S=A.redIAdd(A);S=S.redIAdd(S),S=S.redIAdd(S),S=S.redIAdd(S);var _=M.redIAdd(B).redSqr().redISub(k).redISub(C).redISub(S),x=I.redMul(_);x=x.redIAdd(x),x=x.redIAdd(x);var f=this.x.redMul(C).redISub(x);f=f.redIAdd(f),f=f.redIAdd(f);var h=this.y.redMul(_.redMul(S.redISub(_)).redISub(B.redMul(C)));h=h.redIAdd(h),h=h.redIAdd(h),h=h.redIAdd(h);var i=this.z.redAdd(B).redSqr().redISub(L).redISub(C);return this.curve.jpoint(f,h,i)},K.prototype.mul=function(O,I){return O=new $(O,I),this.curve._wnafMul(this,O)},K.prototype.eq=function(O){if(O.type==="affine")return this.eq(O.toJ());if(this===O)return!0;var I=this.z.redSqr(),L=O.z.redSqr();if(this.x.redMul(L).redISub(O.x.redMul(I)).cmpn(0)!==0)return!1;var A=I.redMul(this.z),M=L.redMul(O.z);return this.y.redMul(M).redISub(O.y.redMul(A)).cmpn(0)===0},K.prototype.eqXToP=function(O){var I=this.z.redSqr(),L=O.toRed(this.curve.red).redMul(I);if(this.x.cmp(L)===0)return!0;var A=O.clone(),M=this.curve.redN.redMul(I);for(;;){if(A.iadd(this.curve.n),A.cmp(this.curve.p)>=0)return!1;if(L.redIAdd(M),this.x.cmp(L)===0)return!0}},K.prototype.inspect=function(){if(this.isInfinity())return"<EC JPoint Infinity>";return"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"},K.prototype.isInfinity=function(){return this.z.cmpn(0)===0}}),pt=v0((Q,Z)=>{var Y=m1(),$=YJ(),J=hW(),X=DJ();function G(U){J.call(this,"mont",U),this.a=new Y(U.a,16).toRed(this.red),this.b=new Y(U.b,16).toRed(this.red),this.i4=new Y(4).toRed(this.red).redInvm(),this.two=new Y(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}$(G,J),Z.exports=G,G.prototype.validate=function(U){var K=U.normalize().x,O=K.redSqr(),I=O.redMul(K).redAdd(O.redMul(this.a)).redAdd(K),L=I.redSqrt();return L.redSqr().cmp(I)===0};function W(U,K,O){if(J.BasePoint.call(this,U,"projective"),K===null&&O===null)this.x=this.curve.one,this.z=this.curve.zero;else{if(this.x=new Y(K,16),this.z=new Y(O,16),!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red)}}$(W,J.BasePoint),G.prototype.decodePoint=function(U,K){return this.point(X.toArray(U,K),1)},G.prototype.point=function(U,K){return new W(this,U,K)},G.prototype.pointFromJSON=function(U){return W.fromJSON(this,U)},W.prototype.precompute=function(){},W.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},W.fromJSON=function(U,K){return new W(U,K[0],K[1]||U.one)},W.prototype.inspect=function(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"},W.prototype.isInfinity=function(){return this.z.cmpn(0)===0},W.prototype.dbl=function(){var U=this.x.redAdd(this.z),K=U.redSqr(),O=this.x.redSub(this.z),I=O.redSqr(),L=K.redSub(I),A=K.redMul(I),M=L.redMul(I.redAdd(this.curve.a24.redMul(L)));return this.curve.point(A,M)},W.prototype.add=function(){throw Error("Not supported on Montgomery curve")},W.prototype.diffAdd=function(U,K){var O=this.x.redAdd(this.z),I=this.x.redSub(this.z),L=U.x.redAdd(U.z),A=U.x.redSub(U.z),M=A.redMul(O),k=L.redMul(I),B=K.z.redMul(M.redAdd(k).redSqr()),C=K.x.redMul(M.redISub(k).redSqr());return this.curve.point(B,C)},W.prototype.mul=function(U){var K=U.clone(),O=this,I=this.curve.point(null,null),L=this;for(var A=[];K.cmpn(0)!==0;K.iushrn(1))A.push(K.andln(1));for(var M=A.length-1;M>=0;M--)if(A[M]===0)O=O.diffAdd(I,L),I=I.dbl();else I=O.diffAdd(I,L),O=O.dbl();return I},W.prototype.mulAdd=function(){throw Error("Not supported on Montgomery curve")},W.prototype.jumlAdd=function(){throw Error("Not supported on Montgomery curve")},W.prototype.eq=function(U){return this.getX().cmp(U.getX())===0},W.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},W.prototype.getX=function(){return this.normalize(),this.x.fromRed()}}),lt=v0((Q,Z)=>{var Y=DJ(),$=m1(),J=YJ(),X=hW(),G=Y.assert;function W(K){this.twisted=(K.a|0)!==1,this.mOneA=this.twisted&&(K.a|0)===-1,this.extended=this.mOneA,X.call(this,"edwards",K),this.a=new $(K.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new $(K.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new $(K.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),G(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(K.c|0)===1}J(W,X),Z.exports=W,W.prototype._mulA=function(K){if(this.mOneA)return K.redNeg();else return this.a.redMul(K)},W.prototype._mulC=function(K){if(this.oneC)return K;else return this.c.redMul(K)},W.prototype.jpoint=function(K,O,I,L){return this.point(K,O,I,L)},W.prototype.pointFromX=function(K,O){if(K=new $(K,16),!K.red)K=K.toRed(this.red);var I=K.redSqr(),L=this.c2.redSub(this.a.redMul(I)),A=this.one.redSub(this.c2.redMul(this.d).redMul(I)),M=L.redMul(A.redInvm()),k=M.redSqrt();if(k.redSqr().redSub(M).cmp(this.zero)!==0)throw Error("invalid point");var B=k.fromRed().isOdd();if(O&&!B||!O&&B)k=k.redNeg();return this.point(K,k)},W.prototype.pointFromY=function(K,O){if(K=new $(K,16),!K.red)K=K.toRed(this.red);var I=K.redSqr(),L=I.redSub(this.c2),A=I.redMul(this.d).redMul(this.c2).redSub(this.a),M=L.redMul(A.redInvm());if(M.cmp(this.zero)===0)if(O)throw Error("invalid point");else return this.point(this.zero,K);var k=M.redSqrt();if(k.redSqr().redSub(M).cmp(this.zero)!==0)throw Error("invalid point");if(k.fromRed().isOdd()!==O)k=k.redNeg();return this.point(k,K)},W.prototype.validate=function(K){if(K.isInfinity())return!0;K.normalize();var O=K.x.redSqr(),I=K.y.redSqr(),L=O.redMul(this.a).redAdd(I),A=this.c2.redMul(this.one.redAdd(this.d.redMul(O).redMul(I)));return L.cmp(A)===0};function U(K,O,I,L,A){if(X.BasePoint.call(this,K,"projective"),O===null&&I===null&&L===null)this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0;else{if(this.x=new $(O,16),this.y=new $(I,16),this.z=L?new $(L,16):this.curve.one,this.t=A&&new $(A,16),!this.x.red)this.x=this.x.toRed(this.curve.red);if(!this.y.red)this.y=this.y.toRed(this.curve.red);if(!this.z.red)this.z=this.z.toRed(this.curve.red);if(this.t&&!this.t.red)this.t=this.t.toRed(this.curve.red);if(this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t){if(this.t=this.x.redMul(this.y),!this.zOne)this.t=this.t.redMul(this.z.redInvm())}}}J(U,X.BasePoint),W.prototype.pointFromJSON=function(K){return U.fromJSON(this,K)},W.prototype.point=function(K,O,I,L){return new U(this,K,O,I,L)},U.fromJSON=function(K,O){return new U(K,O[0],O[1],O[2])},U.prototype.inspect=function(){if(this.isInfinity())return"<EC Point Infinity>";return"<EC Point x: "+this.x.fromRed().toString(16,2)+" y: "+this.y.fromRed().toString(16,2)+" z: "+this.z.fromRed().toString(16,2)+">"},U.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},U.prototype._extDbl=function(){var K=this.x.redSqr(),O=this.y.redSqr(),I=this.z.redSqr();I=I.redIAdd(I);var L=this.curve._mulA(K),A=this.x.redAdd(this.y).redSqr().redISub(K).redISub(O),M=L.redAdd(O),k=M.redSub(I),B=L.redSub(O),C=A.redMul(k),S=M.redMul(B),_=A.redMul(B),x=k.redMul(M);return this.curve.point(C,S,x,_)},U.prototype._projDbl=function(){var K=this.x.redAdd(this.y).redSqr(),O=this.x.redSqr(),I=this.y.redSqr(),L,A,M,k,B,C;if(this.curve.twisted){k=this.curve._mulA(O);var S=k.redAdd(I);if(this.zOne)L=K.redSub(O).redSub(I).redMul(S.redSub(this.curve.two)),A=S.redMul(k.redSub(I)),M=S.redSqr().redSub(S).redSub(S);else B=this.z.redSqr(),C=S.redSub(B).redISub(B),L=K.redSub(O).redISub(I).redMul(C),A=S.redMul(k.redSub(I)),M=S.redMul(C)}else k=O.redAdd(I),B=this.curve._mulC(this.z).redSqr(),C=k.redSub(B).redSub(B),L=this.curve._mulC(K.redISub(k)).redMul(C),A=this.curve._mulC(k).redMul(O.redISub(I)),M=k.redMul(C);return this.curve.point(L,A,M)},U.prototype.dbl=function(){if(this.isInfinity())return this;if(this.curve.extended)return this._extDbl();else return this._projDbl()},U.prototype._extAdd=function(K){var O=this.y.redSub(this.x).redMul(K.y.redSub(K.x)),I=this.y.redAdd(this.x).redMul(K.y.redAdd(K.x)),L=this.t.redMul(this.curve.dd).redMul(K.t),A=this.z.redMul(K.z.redAdd(K.z)),M=I.redSub(O),k=A.redSub(L),B=A.redAdd(L),C=I.redAdd(O),S=M.redMul(k),_=B.redMul(C),x=M.redMul(C),f=k.redMul(B);return this.curve.point(S,_,f,x)},U.prototype._projAdd=function(K){var O=this.z.redMul(K.z),I=O.redSqr(),L=this.x.redMul(K.x),A=this.y.redMul(K.y),M=this.curve.d.redMul(L).redMul(A),k=I.redSub(M),B=I.redAdd(M),C=this.x.redAdd(this.y).redMul(K.x.redAdd(K.y)).redISub(L).redISub(A),S=O.redMul(k).redMul(C),_,x;if(this.curve.twisted)_=O.redMul(B).redMul(A.redSub(this.curve._mulA(L))),x=k.redMul(B);else _=O.redMul(B).redMul(A.redSub(L)),x=this.curve._mulC(k).redMul(B);return this.curve.point(S,_,x)},U.prototype.add=function(K){if(this.isInfinity())return K;if(K.isInfinity())return this;if(this.curve.extended)return this._extAdd(K);else return this._projAdd(K)},U.prototype.mul=function(K){if(this._hasDoubles(K))return this.curve._fixedNafMul(this,K);else return this.curve._wnafMul(this,K)},U.prototype.mulAdd=function(K,O,I){return this.curve._wnafMulAdd(1,[this,O],[K,I],2,!1)},U.prototype.jmulAdd=function(K,O,I){return this.curve._wnafMulAdd(1,[this,O],[K,I],2,!0)},U.prototype.normalize=function(){if(this.zOne)return this;var K=this.z.redInvm();if(this.x=this.x.redMul(K),this.y=this.y.redMul(K),this.t)this.t=this.t.redMul(K);return this.z=this.curve.one,this.zOne=!0,this},U.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},U.prototype.getX=function(){return this.normalize(),this.x.fromRed()},U.prototype.getY=function(){return this.normalize(),this.y.fromRed()},U.prototype.eq=function(K){return this===K||this.getX().cmp(K.getX())===0&&this.getY().cmp(K.getY())===0},U.prototype.eqXToP=function(K){var O=K.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(O)===0)return!0;var I=K.clone(),L=this.curve.redN.redMul(this.z);for(;;){if(I.iadd(this.curve.n),I.cmp(this.curve.p)>=0)return!1;if(O.redIAdd(L),this.x.cmp(O)===0)return!0}},U.prototype.toP=U.prototype.normalize,U.prototype.mixedAdd=U.prototype.add}),KS=v0((Q)=>{var Z=Q;Z.base=hW(),Z.short=ut(),Z.mont=pt(),Z.edwards=lt()}),V1=v0((Q)=>{var Z=c8(),Y=YJ();Q.inherits=Y;function $(z,H){if((z.charCodeAt(H)&64512)!==55296)return!1;if(H<0||H+1>=z.length)return!1;return(z.charCodeAt(H+1)&64512)===56320}function J(z,H){if(Array.isArray(z))return z.slice();if(!z)return[];var F=[];if(typeof z==="string"){if(!H){var D=0;for(var P=0;P<z.length;P++){var j=z.charCodeAt(P);if(j<128)F[D++]=j;else if(j<2048)F[D++]=j>>6|192,F[D++]=j&63|128;else if($(z,P))j=65536+((j&1023)<<10)+(z.charCodeAt(++P)&1023),F[D++]=j>>18|240,F[D++]=j>>12&63|128,F[D++]=j>>6&63|128,F[D++]=j&63|128;else F[D++]=j>>12|224,F[D++]=j>>6&63|128,F[D++]=j&63|128}}else if(H==="hex"){if(z=z.replace(/[^a-z0-9]+/ig,""),z.length%2!==0)z="0"+z;for(P=0;P<z.length;P+=2)F.push(parseInt(z[P]+z[P+1],16))}}else for(P=0;P<z.length;P++)F[P]=z[P]|0;return F}Q.toArray=J;function X(z){var H="";for(var F=0;F<z.length;F++)H+=U(z[F].toString(16));return H}Q.toHex=X;function G(z){var H=z>>>24|z>>>8&65280|z<<8&16711680|(z&255)<<24;return H>>>0}Q.htonl=G;function W(z,H){var F="";for(var D=0;D<z.length;D++){var P=z[D];if(H==="little")P=G(P);F+=K(P.toString(16))}return F}Q.toHex32=W;function U(z){if(z.length===1)return"0"+z;else return z}Q.zero2=U;function K(z){if(z.length===7)return"0"+z;else if(z.length===6)return"00"+z;else if(z.length===5)return"000"+z;else if(z.length===4)return"0000"+z;else if(z.length===3)return"00000"+z;else if(z.length===2)return"000000"+z;else if(z.length===1)return"0000000"+z;else return z}Q.zero8=K;function O(z,H,F,D){var P=F-H;Z(P%4===0);var j=Array(P/4);for(var R=0,q=H;R<j.length;R++,q+=4){var E;if(D==="big")E=z[q]<<24|z[q+1]<<16|z[q+2]<<8|z[q+3];else E=z[q+3]<<24|z[q+2]<<16|z[q+1]<<8|z[q];j[R]=E>>>0}return j}Q.join32=O;function I(z,H){var F=Array(z.length*4);for(var D=0,P=0;D<z.length;D++,P+=4){var j=z[D];if(H==="big")F[P]=j>>>24,F[P+1]=j>>>16&255,F[P+2]=j>>>8&255,F[P+3]=j&255;else F[P+3]=j>>>24,F[P+2]=j>>>16&255,F[P+1]=j>>>8&255,F[P]=j&255}return F}Q.split32=I;function L(z,H){return z>>>H|z<<32-H}Q.rotr32=L;function A(z,H){return z<<H|z>>>32-H}Q.rotl32=A;function M(z,H){return z+H>>>0}Q.sum32=M;function k(z,H,F){return z+H+F>>>0}Q.sum32_3=k;function B(z,H,F,D){return z+H+F+D>>>0}Q.sum32_4=B;function C(z,H,F,D,P){return z+H+F+D+P>>>0}Q.sum32_5=C;function S(z,H,F,D){var P=z[H],j=z[H+1],R=D+j>>>0,q=(R<D?1:0)+F+P;z[H]=q>>>0,z[H+1]=R}Q.sum64=S;function _(z,H,F,D){var P=H+D>>>0,j=(P<H?1:0)+z+F;return j>>>0}Q.sum64_hi=_;function x(z,H,F,D){var P=H+D;return P>>>0}Q.sum64_lo=x;function f(z,H,F,D,P,j,R,q){var E=0,N=H;N=N+D>>>0,E+=N<H?1:0,N=N+j>>>0,E+=N<j?1:0,N=N+q>>>0,E+=N<q?1:0;var T=z+F+P+R+E;return T>>>0}Q.sum64_4_hi=f;function h(z,H,F,D,P,j,R,q){var E=H+D+j+q;return E>>>0}Q.sum64_4_lo=h;function i(z,H,F,D,P,j,R,q,E,N){var T=0,v=H;v=v+D>>>0,T+=v<H?1:0,v=v+j>>>0,T+=v<j?1:0,v=v+q>>>0,T+=v<q?1:0,v=v+N>>>0,T+=v<N?1:0;var y=z+F+P+R+E+T;return y>>>0}Q.sum64_5_hi=i;function Z0(z,H,F,D,P,j,R,q,E,N){var T=H+D+j+q+N;return T>>>0}Q.sum64_5_lo=Z0;function t(z,H,F){var D=H<<32-F|z>>>F;return D>>>0}Q.rotr64_hi=t;function c(z,H,F){var D=z<<32-F|H>>>F;return D>>>0}Q.rotr64_lo=c;function l(z,H,F){return z>>>F}Q.shr64_hi=l;function V(z,H,F){var D=z<<32-F|H>>>F;return D>>>0}Q.shr64_lo=V}),s6=v0((Q)=>{var Z=V1(),Y=c8();function $(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}Q.BlockHash=$,$.prototype.update=function(J,X){if(J=Z.toArray(J,X),!this.pending)this.pending=J;else this.pending=this.pending.concat(J);if(this.pendingTotal+=J.length,this.pending.length>=this._delta8){J=this.pending;var G=J.length%this._delta8;if(this.pending=J.slice(J.length-G,J.length),this.pending.length===0)this.pending=null;J=Z.join32(J,0,J.length-G,this.endian);for(var W=0;W<J.length;W+=this._delta32)this._update(J,W,W+this._delta32)}return this},$.prototype.digest=function(J){return this.update(this._pad()),Y(this.pending===null),this._digest(J)},$.prototype._pad=function(){var J=this.pendingTotal,X=this._delta8,G=X-(J+this.padLength)%X,W=Array(G+this.padLength);W[0]=128;for(var U=1;U<G;U++)W[U]=0;if(J<<=3,this.endian==="big"){for(var K=8;K<this.padLength;K++)W[U++]=0;W[U++]=0,W[U++]=0,W[U++]=0,W[U++]=0,W[U++]=J>>>24&255,W[U++]=J>>>16&255,W[U++]=J>>>8&255,W[U++]=J&255}else{W[U++]=J&255,W[U++]=J>>>8&255,W[U++]=J>>>16&255,W[U++]=J>>>24&255,W[U++]=0,W[U++]=0,W[U++]=0,W[U++]=0;for(K=8;K<this.padLength;K++)W[U++]=0}return W}}),US=v0((Q)=>{var Z=V1(),Y=Z.rotr32;function $(I,L,A,M){if(I===0)return J(L,A,M);if(I===1||I===3)return G(L,A,M);if(I===2)return X(L,A,M)}Q.ft_1=$;function J(I,L,A){return I&L^~I&A}Q.ch32=J;function X(I,L,A){return I&L^I&A^L&A}Q.maj32=X;function G(I,L,A){return I^L^A}Q.p32=G;function W(I){return Y(I,2)^Y(I,13)^Y(I,22)}Q.s0_256=W;function U(I){return Y(I,6)^Y(I,11)^Y(I,25)}Q.s1_256=U;function K(I){return Y(I,7)^Y(I,18)^I>>>3}Q.g0_256=K;function O(I){return Y(I,17)^Y(I,19)^I>>>10}Q.g1_256=O}),mt=v0((Q,Z)=>{var Y=V1(),$=s6(),J=US(),X=Y.rotl32,G=Y.sum32,W=Y.sum32_5,U=J.ft_1,K=$.BlockHash,O=[1518500249,1859775393,2400959708,3395469782];function I(){if(!(this instanceof I))return new I;K.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=Array(80)}Y.inherits(I,K),Z.exports=I,I.blockSize=512,I.outSize=160,I.hmacStrength=80,I.padLength=64,I.prototype._update=function(L,A){var M=this.W;for(var k=0;k<16;k++)M[k]=L[A+k];for(;k<M.length;k++)M[k]=X(M[k-3]^M[k-8]^M[k-14]^M[k-16],1);var B=this.h[0],C=this.h[1],S=this.h[2],_=this.h[3],x=this.h[4];for(k=0;k<M.length;k++){var f=~~(k/20),h=W(X(B,5),U(f,C,S,_),x,M[k],O[f]);x=_,_=S,S=X(C,30),C=B,B=h}this.h[0]=G(this.h[0],B),this.h[1]=G(this.h[1],C),this.h[2]=G(this.h[2],S),this.h[3]=G(this.h[3],_),this.h[4]=G(this.h[4],x)},I.prototype._digest=function(L){if(L==="hex")return Y.toHex32(this.h,"big");else return Y.split32(this.h,"big")}}),OS=v0((Q,Z)=>{var Y=V1(),$=s6(),J=US(),X=c8(),G=Y.sum32,W=Y.sum32_4,U=Y.sum32_5,K=J.ch32,O=J.maj32,I=J.s0_256,L=J.s1_256,A=J.g0_256,M=J.g1_256,k=$.BlockHash,B=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function C(){if(!(this instanceof C))return new C;k.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=B,this.W=Array(64)}Y.inherits(C,k),Z.exports=C,C.blockSize=512,C.outSize=256,C.hmacStrength=192,C.padLength=64,C.prototype._update=function(S,_){var x=this.W;for(var f=0;f<16;f++)x[f]=S[_+f];for(;f<x.length;f++)x[f]=W(M(x[f-2]),x[f-7],A(x[f-15]),x[f-16]);var h=this.h[0],i=this.h[1],Z0=this.h[2],t=this.h[3],c=this.h[4],l=this.h[5],V=this.h[6],z=this.h[7];X(this.k.length===x.length);for(f=0;f<x.length;f++){var H=U(z,L(c),K(c,l,V),this.k[f],x[f]),F=G(I(h),O(h,i,Z0));z=V,V=l,l=c,c=G(t,H),t=Z0,Z0=i,i=h,h=G(H,F)}this.h[0]=G(this.h[0],h),this.h[1]=G(this.h[1],i),this.h[2]=G(this.h[2],Z0),this.h[3]=G(this.h[3],t),this.h[4]=G(this.h[4],c),this.h[5]=G(this.h[5],l),this.h[6]=G(this.h[6],V),this.h[7]=G(this.h[7],z)},C.prototype._digest=function(S){if(S==="hex")return Y.toHex32(this.h,"big");else return Y.split32(this.h,"big")}}),dt=v0((Q,Z)=>{var Y=V1(),$=OS();function J(){if(!(this instanceof J))return new J;$.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}Y.inherits(J,$),Z.exports=J,J.blockSize=512,J.outSize=224,J.hmacStrength=192,J.padLength=64,J.prototype._digest=function(X){if(X==="hex")return Y.toHex32(this.h.slice(0,7),"big");else return Y.split32(this.h.slice(0,7),"big")}}),HS=v0((Q,Z)=>{var Y=V1(),$=s6(),J=c8(),X=Y.rotr64_hi,G=Y.rotr64_lo,W=Y.shr64_hi,U=Y.shr64_lo,K=Y.sum64,O=Y.sum64_hi,I=Y.sum64_lo,L=Y.sum64_4_hi,A=Y.sum64_4_lo,M=Y.sum64_5_hi,k=Y.sum64_5_lo,B=$.BlockHash,C=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function S(){if(!(this instanceof S))return new S;B.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=C,this.W=Array(160)}Y.inherits(S,B),Z.exports=S,S.blockSize=1024,S.outSize=512,S.hmacStrength=192,S.padLength=128,S.prototype._prepareBlock=function(F,D){var P=this.W;for(var j=0;j<32;j++)P[j]=F[D+j];for(;j<P.length;j+=2){var R=z(P[j-4],P[j-3]),q=H(P[j-4],P[j-3]),E=P[j-14],N=P[j-13],T=l(P[j-30],P[j-29]),v=V(P[j-30],P[j-29]),y=P[j-32],p=P[j-31];P[j]=L(R,q,E,N,T,v,y,p),P[j+1]=A(R,q,E,N,T,v,y,p)}},S.prototype._update=function(F,D){this._prepareBlock(F,D);var P=this.W,j=this.h[0],R=this.h[1],q=this.h[2],E=this.h[3],N=this.h[4],T=this.h[5],v=this.h[6],y=this.h[7],p=this.h[8],J0=this.h[9],x0=this.h[10],K0=this.h[11],Y0=this.h[12],j0=this.h[13],$0=this.h[14],D0=this.h[15];J(this.k.length===P.length);for(var $Q=0;$Q<P.length;$Q+=2){var m=$0,n=D0,B0=t(p,J0),F0=c(p,J0),z0=_(p,J0,x0,K0,Y0,j0),l0=x(p,J0,x0,K0,Y0,j0),d=this.k[$Q],X0=this.k[$Q+1],QQ=P[$Q],V0=P[$Q+1],P0=M(m,n,B0,F0,z0,l0,d,X0,QQ,V0),jQ=k(m,n,B0,F0,z0,l0,d,X0,QQ,V0);m=i(j,R),n=Z0(j,R),B0=f(j,R,q,E,N,T),F0=h(j,R,q,E,N,T);var c0=O(m,n,B0,F0),u0=I(m,n,B0,F0);$0=Y0,D0=j0,Y0=x0,j0=K0,x0=p,K0=J0,p=O(v,y,P0,jQ),J0=I(y,y,P0,jQ),v=N,y=T,N=q,T=E,q=j,E=R,j=O(P0,jQ,c0,u0),R=I(P0,jQ,c0,u0)}K(this.h,0,j,R),K(this.h,2,q,E),K(this.h,4,N,T),K(this.h,6,v,y),K(this.h,8,p,J0),K(this.h,10,x0,K0),K(this.h,12,Y0,j0),K(this.h,14,$0,D0)},S.prototype._digest=function(F){if(F==="hex")return Y.toHex32(this.h,"big");else return Y.split32(this.h,"big")};function _(F,D,P,j,R){var q=F&P^~F&R;if(q<0)q+=4294967296;return q}function x(F,D,P,j,R,q){var E=D&j^~D&q;if(E<0)E+=4294967296;return E}function f(F,D,P,j,R){var q=F&P^F&R^P&R;if(q<0)q+=4294967296;return q}function h(F,D,P,j,R,q){var E=D&j^D&q^j&q;if(E<0)E+=4294967296;return E}function i(F,D){var P=X(F,D,28),j=X(D,F,2),R=X(D,F,7),q=P^j^R;if(q<0)q+=4294967296;return q}function Z0(F,D){var P=G(F,D,28),j=G(D,F,2),R=G(D,F,7),q=P^j^R;if(q<0)q+=4294967296;return q}function t(F,D){var P=X(F,D,14),j=X(F,D,18),R=X(D,F,9),q=P^j^R;if(q<0)q+=4294967296;return q}function c(F,D){var P=G(F,D,14),j=G(F,D,18),R=G(D,F,9),q=P^j^R;if(q<0)q+=4294967296;return q}function l(F,D){var P=X(F,D,1),j=X(F,D,8),R=W(F,D,7),q=P^j^R;if(q<0)q+=4294967296;return q}function V(F,D){var P=G(F,D,1),j=G(F,D,8),R=U(F,D,7),q=P^j^R;if(q<0)q+=4294967296;return q}function z(F,D){var P=X(F,D,19),j=X(D,F,29),R=W(F,D,6),q=P^j^R;if(q<0)q+=4294967296;return q}function H(F,D){var P=G(F,D,19),j=G(D,F,29),R=U(F,D,6),q=P^j^R;if(q<0)q+=4294967296;return q}}),nt=v0((Q,Z)=>{var Y=V1(),$=HS();function J(){if(!(this instanceof J))return new J;$.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}Y.inherits(J,$),Z.exports=J,J.blockSize=1024,J.outSize=384,J.hmacStrength=192,J.padLength=128,J.prototype._digest=function(X){if(X==="hex")return Y.toHex32(this.h.slice(0,12),"big");else return Y.split32(this.h.slice(0,12),"big")}}),ot=v0((Q)=>{Q.sha1=mt(),Q.sha224=dt(),Q.sha256=OS(),Q.sha384=nt(),Q.sha512=HS()}),st=v0((Q)=>{var Z=V1(),Y=s6(),$=Z.rotl32,J=Z.sum32,X=Z.sum32_3,G=Z.sum32_4,W=Y.BlockHash;function U(){if(!(this instanceof U))return new U;W.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}Z.inherits(U,W),Q.ripemd160=U,U.blockSize=512,U.outSize=160,U.hmacStrength=192,U.padLength=64,U.prototype._update=function(B,C){var S=this.h[0],_=this.h[1],x=this.h[2],f=this.h[3],h=this.h[4],i=S,Z0=_,t=x,c=f,l=h;for(var V=0;V<80;V++){var z=J($(G(S,K(V,_,x,f),B[L[V]+C],O(V)),M[V]),h);S=h,h=f,f=$(x,10),x=_,_=z,z=J($(G(i,K(79-V,Z0,t,c),B[A[V]+C],I(V)),k[V]),l),i=l,l=c,c=$(t,10),t=Z0,Z0=z}z=X(this.h[1],x,c),this.h[1]=X(this.h[2],f,l),this.h[2]=X(this.h[3],h,i),this.h[3]=X(this.h[4],S,Z0),this.h[4]=X(this.h[0],_,t),this.h[0]=z},U.prototype._digest=function(B){if(B==="hex")return Z.toHex32(this.h,"little");else return Z.split32(this.h,"little")};function K(B,C,S,_){if(B<=15)return C^S^_;else if(B<=31)return C&S|~C&_;else if(B<=47)return(C|~S)^_;else if(B<=63)return C&_|S&~_;else return C^(S|~_)}function O(B){if(B<=15)return 0;else if(B<=31)return 1518500249;else if(B<=47)return 1859775393;else if(B<=63)return 2400959708;else return 2840853838}function I(B){if(B<=15)return 1352829926;else if(B<=31)return 1548603684;else if(B<=47)return 1836072691;else if(B<=63)return 2053994217;else return 0}var L=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],A=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],M=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],k=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]}),it=v0((Q,Z)=>{var Y=V1(),$=c8();function J(X,G,W){if(!(this instanceof J))return new J(X,G,W);this.Hash=X,this.blockSize=X.blockSize/8,this.outSize=X.outSize/8,this.inner=null,this.outer=null,this._init(Y.toArray(G,W))}Z.exports=J,J.prototype._init=function(X){if(X.length>this.blockSize)X=new this.Hash().update(X).digest();$(X.length<=this.blockSize);for(var G=X.length;G<this.blockSize;G++)X.push(0);for(G=0;G<X.length;G++)X[G]^=54;this.inner=new this.Hash().update(X);for(G=0;G<X.length;G++)X[G]^=106;this.outer=new this.Hash().update(X)},J.prototype.update=function(X,G){return this.inner.update(X,G),this},J.prototype.digest=function(X){return this.outer.update(this.inner.digest()),this.outer.digest(X)}}),jD=v0((Q)=>{var Z=Q;Z.utils=V1(),Z.common=s6(),Z.sha=ot(),Z.ripemd=st(),Z.hmac=it(),Z.sha1=Z.sha.sha1,Z.sha256=Z.sha.sha256,Z.sha224=Z.sha.sha224,Z.sha384=Z.sha.sha384,Z.sha512=Z.sha.sha512,Z.ripemd160=Z.ripemd.ripemd160}),at=v0((Q,Z)=>{Z.exports={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}}),AD=v0((Q)=>{var Z=Q,Y=jD(),$=KS(),J=DJ(),X=J.assert;function G(K){if(K.type==="short")this.curve=new $.short(K);else if(K.type==="edwards")this.curve=new $.edwards(K);else this.curve=new $.mont(K);this.g=this.curve.g,this.n=this.curve.n,this.hash=K.hash,X(this.g.validate(),"Invalid curve"),X(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}Z.PresetCurve=G;function W(K,O){Object.defineProperty(Z,K,{configurable:!0,enumerable:!0,get:function(){var I=new G(O);return Object.defineProperty(Z,K,{configurable:!0,enumerable:!0,value:I}),I}})}W("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:Y.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),W("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:Y.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),W("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:Y.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),W("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:Y.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),W("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:Y.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),W("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Y.sha256,gRed:!1,g:["9"]}),W("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:Y.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var U;try{U=at()}catch(K){U=void 0}W("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:Y.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",U]})}),rt=v0((Q,Z)=>{var Y=jD(),$=zS(),J=c8();function X(G){if(!(this instanceof X))return new X(G);this.hash=G.hash,this.predResist=!!G.predResist,this.outLen=this.hash.outSize,this.minEntropy=G.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var W=$.toArray(G.entropy,G.entropyEnc||"hex"),U=$.toArray(G.nonce,G.nonceEnc||"hex"),K=$.toArray(G.pers,G.persEnc||"hex");J(W.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(W,U,K)}Z.exports=X,X.prototype._init=function(G,W,U){var K=G.concat(W).concat(U);this.K=Array(this.outLen/8),this.V=Array(this.outLen/8);for(var O=0;O<this.V.length;O++)this.K[O]=0,this.V[O]=1;this._update(K),this._reseed=1,this.reseedInterval=281474976710656},X.prototype._hmac=function(){return new Y.hmac(this.hash,this.K)},X.prototype._update=function(G){var W=this._hmac().update(this.V).update([0]);if(G)W=W.update(G);if(this.K=W.digest(),this.V=this._hmac().update(this.V).digest(),!G)return;this.K=this._hmac().update(this.V).update([1]).update(G).digest(),this.V=this._hmac().update(this.V).digest()},X.prototype.reseed=function(G,W,U,K){if(typeof W!=="string")K=U,U=W,W=null;G=$.toArray(G,W),U=$.toArray(U,K),J(G.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(G.concat(U||[])),this._reseed=1},X.prototype.generate=function(G,W,U,K){if(this._reseed>this.reseedInterval)throw Error("Reseed is required");if(typeof W!=="string")K=U,U=W,W=null;if(U)U=$.toArray(U,K||"hex"),this._update(U);var O=[];while(O.length<G)this.V=this._hmac().update(this.V).digest(),O=O.concat(this.V);var I=O.slice(0,G);return this._update(U),this._reseed++,$.encode(I,W)}}),tt=v0((Q,Z)=>{var Y=m1(),$=DJ(),J=$.assert;function X(G,W){if(this.ec=G,this.priv=null,this.pub=null,W.priv)this._importPrivate(W.priv,W.privEnc);if(W.pub)this._importPublic(W.pub,W.pubEnc)}Z.exports=X,X.fromPublic=function(G,W,U){if(W instanceof X)return W;return new X(G,{pub:W,pubEnc:U})},X.fromPrivate=function(G,W,U){if(W instanceof X)return W;return new X(G,{priv:W,privEnc:U})},X.prototype.validate=function(){var G=this.getPublic();if(G.isInfinity())return{result:!1,reason:"Invalid public key"};if(!G.validate())return{result:!1,reason:"Public key is not a point"};if(!G.mul(this.ec.curve.n).isInfinity())return{result:!1,reason:"Public key * N != O"};return{result:!0,reason:null}},X.prototype.getPublic=function(G,W){if(typeof G==="string")W=G,G=null;if(!this.pub)this.pub=this.ec.g.mul(this.priv);if(!W)return this.pub;return this.pub.encode(W,G)},X.prototype.getPrivate=function(G){if(G==="hex")return this.priv.toString(16,2);else return this.priv},X.prototype._importPrivate=function(G,W){this.priv=new Y(G,W||16),this.priv=this.priv.umod(this.ec.curve.n)},X.prototype._importPublic=function(G,W){if(G.x||G.y){if(this.ec.curve.type==="mont")J(G.x,"Need x coordinate");else if(this.ec.curve.type==="short"||this.ec.curve.type==="edwards")J(G.x&&G.y,"Need both x and y coordinate");this.pub=this.ec.curve.point(G.x,G.y);return}this.pub=this.ec.curve.decodePoint(G,W)},X.prototype.derive=function(G){if(!G.validate())J(G.validate(),"public point not validated");return G.mul(this.priv).getX()},X.prototype.sign=function(G,W,U){return this.ec.sign(G,this,W,U)},X.prototype.verify=function(G,W,U){return this.ec.verify(G,W,this,void 0,U)},X.prototype.inspect=function(){return"<Key priv: "+(this.priv&&this.priv.toString(16,2))+" pub: "+(this.pub&&this.pub.inspect())+" >"}}),et=v0((Q,Z)=>{var Y=m1(),$=DJ(),J=$.assert;function X(O,I){if(O instanceof X)return O;if(this._importDER(O,I))return;if(J(O.r&&O.s,"Signature without r or s"),this.r=new Y(O.r,16),this.s=new Y(O.s,16),O.recoveryParam===void 0)this.recoveryParam=null;else this.recoveryParam=O.recoveryParam}Z.exports=X;function G(){this.place=0}function W(O,I){var L=O[I.place++];if(!(L&128))return L;var A=L&15;if(A===0||A>4)return!1;if(O[I.place]===0)return!1;var M=0;for(var k=0,B=I.place;k<A;k++,B++)M<<=8,M|=O[B],M>>>=0;if(M<=127)return!1;return I.place=B,M}function U(O){var I=0,L=O.length-1;while(!O[I]&&!(O[I+1]&128)&&I<L)I++;if(I===0)return O;return O.slice(I)}X.prototype._importDER=function(O,I){O=$.toArray(O,I);var L=new G;if(O[L.place++]!==48)return!1;var A=W(O,L);if(A===!1)return!1;if(A+L.place!==O.length)return!1;if(O[L.place++]!==2)return!1;var M=W(O,L);if(M===!1)return!1;if((O[L.place]&128)!==0)return!1;var k=O.slice(L.place,M+L.place);if(L.place+=M,O[L.place++]!==2)return!1;var B=W(O,L);if(B===!1)return!1;if(O.length!==B+L.place)return!1;if((O[L.place]&128)!==0)return!1;var C=O.slice(L.place,B+L.place);if(k[0]===0)if(k[1]&128)k=k.slice(1);else return!1;if(C[0]===0)if(C[1]&128)C=C.slice(1);else return!1;return this.r=new Y(k),this.s=new Y(C),this.recoveryParam=null,!0};function K(O,I){if(I<128){O.push(I);return}var L=1+(Math.log(I)/Math.LN2>>>3);O.push(L|128);while(--L)O.push(I>>>(L<<3)&255);O.push(I)}X.prototype.toDER=function(O){var I=this.r.toArray(),L=this.s.toArray();if(I[0]&128)I=[0].concat(I);if(L[0]&128)L=[0].concat(L);I=U(I),L=U(L);while(!L[0]&&!(L[1]&128))L=L.slice(1);var A=[2];K(A,I.length),A=A.concat(I),A.push(2),K(A,L.length);var M=A.concat(L),k=[48];return K(k,M.length),k=k.concat(M),$.encode(k,O)}}),Qe=v0((Q,Z)=>{var Y=m1(),$=rt(),J=DJ(),X=AD(),G=WS(),W=J.assert,U=tt(),K=et();function O(I){if(!(this instanceof O))return new O(I);if(typeof I==="string")W(Object.prototype.hasOwnProperty.call(X,I),"Unknown curve "+I),I=X[I];if(I instanceof X.PresetCurve)I={curve:I};this.curve=I.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=I.curve.g,this.g.precompute(I.curve.n.bitLength()+1),this.hash=I.hash||I.curve.hash}Z.exports=O,O.prototype.keyPair=function(I){return new U(this,I)},O.prototype.keyFromPrivate=function(I,L){return U.fromPrivate(this,I,L)},O.prototype.keyFromPublic=function(I,L){return U.fromPublic(this,I,L)},O.prototype.genKeyPair=function(I){if(!I)I={};var L=new $({hash:this.hash,pers:I.pers,persEnc:I.persEnc||"utf8",entropy:I.entropy||G(this.hash.hmacStrength),entropyEnc:I.entropy&&I.entropyEnc||"utf8",nonce:this.n.toArray()}),A=this.n.byteLength(),M=this.n.sub(new Y(2));for(;;){var k=new Y(L.generate(A));if(k.cmp(M)>0)continue;return k.iaddn(1),this.keyFromPrivate(k)}},O.prototype._truncateToN=function(I,L,A){var M;if(Y.isBN(I)||typeof I==="number")I=new Y(I,16),M=I.byteLength();else if(typeof I==="object")M=I.length,I=new Y(I,16);else{var k=I.toString();M=k.length+1>>>1,I=new Y(k,16)}if(typeof A!=="number")A=M*8;var B=A-this.n.bitLength();if(B>0)I=I.ushrn(B);if(!L&&I.cmp(this.n)>=0)return I.sub(this.n);else return I},O.prototype.sign=function(I,L,A,M){if(typeof A==="object")M=A,A=null;if(!M)M={};if(typeof I!=="string"&&typeof I!=="number"&&!Y.isBN(I)){W(typeof I==="object"&&I&&typeof I.length==="number","Expected message to be an array-like, a hex string, or a BN instance"),W(I.length>>>0===I.length);for(var k=0;k<I.length;k++)W((I[k]&255)===I[k])}L=this.keyFromPrivate(L,A),I=this._truncateToN(I,!1,M.msgBitLength),W(!I.isNeg(),"Can not sign a negative message");var B=this.n.byteLength(),C=L.getPrivate().toArray("be",B),S=I.toArray("be",B);W(new Y(S).eq(I),"Can not sign message");var _=new $({hash:this.hash,entropy:C,nonce:S,pers:M.pers,persEnc:M.persEnc||"utf8"}),x=this.n.sub(new Y(1));for(var f=0;;f++){var h=M.k?M.k(f):new Y(_.generate(this.n.byteLength()));if(h=this._truncateToN(h,!0),h.cmpn(1)<=0||h.cmp(x)>=0)continue;var i=this.g.mul(h);if(i.isInfinity())continue;var Z0=i.getX(),t=Z0.umod(this.n);if(t.cmpn(0)===0)continue;var c=h.invm(this.n).mul(t.mul(L.getPrivate()).iadd(I));if(c=c.umod(this.n),c.cmpn(0)===0)continue;var l=(i.getY().isOdd()?1:0)|(Z0.cmp(t)!==0?2:0);if(M.canonical&&c.cmp(this.nh)>0)c=this.n.sub(c),l^=1;return new K({r:t,s:c,recoveryParam:l})}},O.prototype.verify=function(I,L,A,M,k){if(!k)k={};I=this._truncateToN(I,!1,k.msgBitLength),A=this.keyFromPublic(A,M),L=new K(L,"hex");var{r:B,s:C}=L;if(B.cmpn(1)<0||B.cmp(this.n)>=0)return!1;if(C.cmpn(1)<0||C.cmp(this.n)>=0)return!1;var S=C.invm(this.n),_=S.mul(I).umod(this.n),x=S.mul(B).umod(this.n),f;if(!this.curve._maxwellTrick){if(f=this.g.mulAdd(_,A.getPublic(),x),f.isInfinity())return!1;return f.getX().umod(this.n).cmp(B)===0}if(f=this.g.jmulAdd(_,A.getPublic(),x),f.isInfinity())return!1;return f.eqXToP(B)},O.prototype.recoverPubKey=function(I,L,A,M){W((3&A)===A,"The recovery param is more than two bits"),L=new K(L,M);var k=this.n,B=new Y(I),C=L.r,S=L.s,_=A&1,x=A>>1;if(C.cmp(this.curve.p.umod(this.curve.n))>=0&&x)throw Error("Unable to find sencond key candinate");if(x)C=this.curve.pointFromX(C.add(this.curve.n),_);else C=this.curve.pointFromX(C,_);var f=L.r.invm(k),h=k.sub(B).mul(f).umod(k),i=S.mul(f).umod(k);return this.g.mulAdd(h,C,i)},O.prototype.getKeyRecoveryParam=function(I,L,A,M){if(L=new K(L,M),L.recoveryParam!==null)return L.recoveryParam;for(var k=0;k<4;k++){var B;try{B=this.recoverPubKey(I,L,k)}catch(C){continue}if(B.eq(A))return k}throw Error("Unable to find valid recovery factor")}}),Ze=v0((Q,Z)=>{var Y=DJ(),$=Y.assert,J=Y.parseBytes,X=Y.cachedProperty;function G(W,U){if(this.eddsa=W,this._secret=J(U.secret),W.isPoint(U.pub))this._pub=U.pub;else this._pubBytes=J(U.pub)}G.fromPublic=function(W,U){if(U instanceof G)return U;return new G(W,{pub:U})},G.fromSecret=function(W,U){if(U instanceof G)return U;return new G(W,{secret:U})},G.prototype.secret=function(){return this._secret},X(G,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())}),X(G,"pub",function(){if(this._pubBytes)return this.eddsa.decodePoint(this._pubBytes);return this.eddsa.g.mul(this.priv())}),X(G,"privBytes",function(){var W=this.eddsa,U=this.hash(),K=W.encodingLength-1,O=U.slice(0,W.encodingLength);return O[0]&=248,O[K]&=127,O[K]|=64,O}),X(G,"priv",function(){return this.eddsa.decodeInt(this.privBytes())}),X(G,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()}),X(G,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)}),G.prototype.sign=function(W){return $(this._secret,"KeyPair can only verify"),this.eddsa.sign(W,this)},G.prototype.verify=function(W,U){return this.eddsa.verify(W,U,this)},G.prototype.getSecret=function(W){return $(this._secret,"KeyPair is public only"),Y.encode(this.secret(),W)},G.prototype.getPublic=function(W){return Y.encode(this.pubBytes(),W)},Z.exports=G}),Ye=v0((Q,Z)=>{var Y=m1(),$=DJ(),J=$.assert,X=$.cachedProperty,G=$.parseBytes;function W(U,K){if(this.eddsa=U,typeof K!=="object")K=G(K);if(Array.isArray(K))J(K.length===U.encodingLength*2,"Signature has invalid size"),K={R:K.slice(0,U.encodingLength),S:K.slice(U.encodingLength)};if(J(K.R&&K.S,"Signature without R or S"),U.isPoint(K.R))this._R=K.R;if(K.S instanceof Y)this._S=K.S;this._Rencoded=Array.isArray(K.R)?K.R:K.Rencoded,this._Sencoded=Array.isArray(K.S)?K.S:K.Sencoded}X(W,"S",function(){return this.eddsa.decodeInt(this.Sencoded())}),X(W,"R",function(){return this.eddsa.decodePoint(this.Rencoded())}),X(W,"Rencoded",function(){return this.eddsa.encodePoint(this.R())}),X(W,"Sencoded",function(){return this.eddsa.encodeInt(this.S())}),W.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},W.prototype.toHex=function(){return $.encode(this.toBytes(),"hex").toUpperCase()},Z.exports=W}),$e=v0((Q,Z)=>{var Y=jD(),$=AD(),J=DJ(),X=J.assert,G=J.parseBytes,W=Ze(),U=Ye();function K(O){if(X(O==="ed25519","only tested with ed25519 so far"),!(this instanceof K))return new K(O);O=$[O].curve,this.curve=O,this.g=O.g,this.g.precompute(O.n.bitLength()+1),this.pointClass=O.point().constructor,this.encodingLength=Math.ceil(O.n.bitLength()/8),this.hash=Y.sha512}Z.exports=K,K.prototype.sign=function(O,I){O=G(O);var L=this.keyFromSecret(I),A=this.hashInt(L.messagePrefix(),O),M=this.g.mul(A),k=this.encodePoint(M),B=this.hashInt(k,L.pubBytes(),O).mul(L.priv()),C=A.add(B).umod(this.curve.n);return this.makeSignature({R:M,S:C,Rencoded:k})},K.prototype.verify=function(O,I,L){if(O=G(O),I=this.makeSignature(I),I.S().gte(I.eddsa.curve.n)||I.S().isNeg())return!1;var A=this.keyFromPublic(L),M=this.hashInt(I.Rencoded(),A.pubBytes(),O),k=this.g.mul(I.S()),B=I.R().add(A.pub().mul(M));return B.eq(k)},K.prototype.hashInt=function(){var O=this.hash();for(var I=0;I<arguments.length;I++)O.update(arguments[I]);return J.intFromLE(O.digest()).umod(this.curve.n)},K.prototype.keyFromPublic=function(O){return W.fromPublic(this,O)},K.prototype.keyFromSecret=function(O){return W.fromSecret(this,O)},K.prototype.makeSignature=function(O){if(O instanceof U)return O;return new U(this,O)},K.prototype.encodePoint=function(O){var I=O.getY().toArray("le",this.encodingLength);return I[this.encodingLength-1]|=O.getX().isOdd()?128:0,I},K.prototype.decodePoint=function(O){O=J.parseBytes(O);var I=O.length-1,L=O.slice(0,I).concat(O[I]&-129),A=(O[I]&128)!==0,M=J.intFromLE(L);return this.curve.pointFromY(M,A)},K.prototype.encodeInt=function(O){return O.toArray("le",this.encodingLength)},K.prototype.decodeInt=function(O){return J.intFromLE(O)},K.prototype.isPoint=function(O){return O instanceof this.pointClass}}),Je=v0((Q)=>{var Z=Q;Z.version=bt().version,Z.utils=DJ(),Z.rand=WS(),Z.curve=KS(),Z.curves=AD(),Z.ec=Qe(),Z.eddsa=$e()}),Ge=v0((Q,Z)=>{(function(Y,$){function J(V,z){if(!V)throw Error(z||"Assertion failed")}function X(V,z){V.super_=z;var H=function(){};H.prototype=z.prototype,V.prototype=new H,V.prototype.constructor=V}function G(V,z,H){if(G.isBN(V))return V;if(this.negative=0,this.words=null,this.length=0,this.red=null,V!==null){if(z==="le"||z==="be")H=z,z=10;this._init(V||0,z||10,H||"be")}}if(typeof Y==="object")Y.exports=G;else $.BN=G;G.BN=G,G.wordSize=26;var W;try{if(typeof window<"u"&&typeof window.Buffer<"u")W=window.Buffer;else W=(vY(),oQ(_Y)).Buffer}catch(V){}G.isBN=function(V){if(V instanceof G)return!0;return V!==null&&typeof V==="object"&&V.constructor.wordSize===G.wordSize&&Array.isArray(V.words)},G.max=function(V,z){if(V.cmp(z)>0)return V;return z},G.min=function(V,z){if(V.cmp(z)<0)return V;return z},G.prototype._init=function(V,z,H){if(typeof V==="number")return this._initNumber(V,z,H);if(typeof V==="object")return this._initArray(V,z,H);if(z==="hex")z=16;J(z===(z|0)&&z>=2&&z<=36),V=V.toString().replace(/\s+/g,"");var F=0;if(V[0]==="-")F++,this.negative=1;if(F<V.length){if(z===16)this._parseHex(V,F,H);else if(this._parseBase(V,z,F),H==="le")this._initArray(this.toArray(),z,H)}},G.prototype._initNumber=function(V,z,H){if(V<0)this.negative=1,V=-V;if(V<67108864)this.words=[V&67108863],this.length=1;else if(V<4503599627370496)this.words=[V&67108863,V/67108864&67108863],this.length=2;else J(V<9007199254740992),this.words=[V&67108863,V/67108864&67108863,1],this.length=3;if(H!=="le")return;this._initArray(this.toArray(),z,H)},G.prototype._initArray=function(V,z,H){if(J(typeof V.length==="number"),V.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(V.length/3),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D,P,j=0;if(H==="be"){for(F=V.length-1,D=0;F>=0;F-=3)if(P=V[F]|V[F-1]<<8|V[F-2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}else if(H==="le"){for(F=0,D=0;F<V.length;F+=3)if(P=V[F]|V[F+1]<<8|V[F+2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}return this.strip()};function U(V,z){var H=V.charCodeAt(z);if(H>=65&&H<=70)return H-55;else if(H>=97&&H<=102)return H-87;else return H-48&15}function K(V,z,H){var F=U(V,H);if(H-1>=z)F|=U(V,H-1)<<4;return F}G.prototype._parseHex=function(V,z,H){this.length=Math.ceil((V.length-z)/6),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D=0,P=0,j;if(H==="be")for(F=V.length-1;F>=z;F-=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8;else{var R=V.length-z;for(F=R%2===0?z+1:z;F<V.length;F+=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8}this.strip()};function O(V,z,H,F){var D=0,P=Math.min(V.length,H);for(var j=z;j<P;j++){var R=V.charCodeAt(j)-48;if(D*=F,R>=49)D+=R-49+10;else if(R>=17)D+=R-17+10;else D+=R}return D}G.prototype._parseBase=function(V,z,H){this.words=[0],this.length=1;for(var F=0,D=1;D<=67108863;D*=z)F++;F--,D=D/z|0;var P=V.length-H,j=P%F,R=Math.min(P,P-j)+H,q=0;for(var E=H;E<R;E+=F)if(q=O(V,E,E+F,z),this.imuln(D),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q);if(j!==0){var N=1;q=O(V,E,V.length,z);for(E=0;E<j;E++)N*=z;if(this.imuln(N),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q)}this.strip()},G.prototype.copy=function(V){V.words=Array(this.length);for(var z=0;z<this.length;z++)V.words[z]=this.words[z];V.length=this.length,V.negative=this.negative,V.red=this.red},G.prototype.clone=function(){var V=new G(null);return this.copy(V),V},G.prototype._expand=function(V){while(this.length<V)this.words[this.length++]=0;return this},G.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},G.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],L=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(G.prototype.toString=function(V,z){V=V||10,z=z|0||1;var H;if(V===16||V==="hex"){H="";var F=0,D=0;for(var P=0;P<this.length;P++){var j=this.words[P],R=((j<<F|D)&16777215).toString(16);if(D=j>>>24-F&16777215,F+=2,F>=26)F-=26,P--;if(D!==0||P!==this.length-1)H=I[6-R.length]+R+H;else H=R+H}if(D!==0)H=D.toString(16)+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}if(V===(V|0)&&V>=2&&V<=36){var q=L[V],E=A[V];H="";var N=this.clone();N.negative=0;while(!N.isZero()){var T=N.modn(E).toString(V);if(N=N.idivn(E),!N.isZero())H=I[q-T.length]+T+H;else H=T+H}if(this.isZero())H="0"+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}J(!1,"Base should be between 2 and 36")},G.prototype.toNumber=function(){var V=this.words[0];if(this.length===2)V+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)V+=4503599627370496+this.words[1]*67108864;else if(this.length>2)J(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-V:V},G.prototype.toJSON=function(){return this.toString(16)},G.prototype.toBuffer=function(V,z){return J(typeof W<"u"),this.toArrayLike(W,V,z)},G.prototype.toArray=function(V,z){return this.toArrayLike(Array,V,z)},G.prototype.toArrayLike=function(V,z,H){var F=this.byteLength(),D=H||Math.max(1,F);J(F<=D,"byte array longer than desired length"),J(D>0,"Requested array length <= 0"),this.strip();var P=z==="le",j=new V(D),R,q,E=this.clone();if(!P){for(q=0;q<D-F;q++)j[q]=0;for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[D-q-1]=R}else{for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[q]=R;for(;q<D;q++)j[q]=0}return j},Math.clz32)G.prototype._countBits=function(V){return 32-Math.clz32(V)};else G.prototype._countBits=function(V){var z=V,H=0;if(z>=4096)H+=13,z>>>=13;if(z>=64)H+=7,z>>>=7;if(z>=8)H+=4,z>>>=4;if(z>=2)H+=2,z>>>=2;return H+z};G.prototype._zeroBits=function(V){if(V===0)return 26;var z=V,H=0;if((z&8191)===0)H+=13,z>>>=13;if((z&127)===0)H+=7,z>>>=7;if((z&15)===0)H+=4,z>>>=4;if((z&3)===0)H+=2,z>>>=2;if((z&1)===0)H++;return H},G.prototype.bitLength=function(){var V=this.words[this.length-1],z=this._countBits(V);return(this.length-1)*26+z};function M(V){var z=Array(V.bitLength());for(var H=0;H<z.length;H++){var F=H/26|0,D=H%26;z[H]=(V.words[F]&1<<D)>>>D}return z}G.prototype.zeroBits=function(){if(this.isZero())return 0;var V=0;for(var z=0;z<this.length;z++){var H=this._zeroBits(this.words[z]);if(V+=H,H!==26)break}return V},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(V){if(this.negative!==0)return this.abs().inotn(V).iaddn(1);return this.clone()},G.prototype.fromTwos=function(V){if(this.testn(V-1))return this.notn(V).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(V){while(this.length<V.length)this.words[this.length++]=0;for(var z=0;z<V.length;z++)this.words[z]=this.words[z]|V.words[z];return this.strip()},G.prototype.ior=function(V){return J((this.negative|V.negative)===0),this.iuor(V)},G.prototype.or=function(V){if(this.length>V.length)return this.clone().ior(V);return V.clone().ior(this)},G.prototype.uor=function(V){if(this.length>V.length)return this.clone().iuor(V);return V.clone().iuor(this)},G.prototype.iuand=function(V){var z;if(this.length>V.length)z=V;else z=this;for(var H=0;H<z.length;H++)this.words[H]=this.words[H]&V.words[H];return this.length=z.length,this.strip()},G.prototype.iand=function(V){return J((this.negative|V.negative)===0),this.iuand(V)},G.prototype.and=function(V){if(this.length>V.length)return this.clone().iand(V);return V.clone().iand(this)},G.prototype.uand=function(V){if(this.length>V.length)return this.clone().iuand(V);return V.clone().iuand(this)},G.prototype.iuxor=function(V){var z,H;if(this.length>V.length)z=this,H=V;else z=V,H=this;for(var F=0;F<H.length;F++)this.words[F]=z.words[F]^H.words[F];if(this!==z)for(;F<z.length;F++)this.words[F]=z.words[F];return this.length=z.length,this.strip()},G.prototype.ixor=function(V){return J((this.negative|V.negative)===0),this.iuxor(V)},G.prototype.xor=function(V){if(this.length>V.length)return this.clone().ixor(V);return V.clone().ixor(this)},G.prototype.uxor=function(V){if(this.length>V.length)return this.clone().iuxor(V);return V.clone().iuxor(this)},G.prototype.inotn=function(V){J(typeof V==="number"&&V>=0);var z=Math.ceil(V/26)|0,H=V%26;if(this._expand(z),H>0)z--;for(var F=0;F<z;F++)this.words[F]=~this.words[F]&67108863;if(H>0)this.words[F]=~this.words[F]&67108863>>26-H;return this.strip()},G.prototype.notn=function(V){return this.clone().inotn(V)},G.prototype.setn=function(V,z){J(typeof V==="number"&&V>=0);var H=V/26|0,F=V%26;if(this._expand(H+1),z)this.words[H]=this.words[H]|1<<F;else this.words[H]=this.words[H]&~(1<<F);return this.strip()},G.prototype.iadd=function(V){var z;if(this.negative!==0&&V.negative===0)return this.negative=0,z=this.isub(V),this.negative^=1,this._normSign();else if(this.negative===0&&V.negative!==0)return V.negative=0,z=this.isub(V),V.negative=1,z._normSign();var H,F;if(this.length>V.length)H=this,F=V;else H=V,F=this;var D=0;for(var P=0;P<F.length;P++)z=(H.words[P]|0)+(F.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;for(;D!==0&&P<H.length;P++)z=(H.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;if(this.length=H.length,D!==0)this.words[this.length]=D,this.length++;else if(H!==this)for(;P<H.length;P++)this.words[P]=H.words[P];return this},G.prototype.add=function(V){var z;if(V.negative!==0&&this.negative===0)return V.negative=0,z=this.sub(V),V.negative^=1,z;else if(V.negative===0&&this.negative!==0)return this.negative=0,z=V.sub(this),this.negative=1,z;if(this.length>V.length)return this.clone().iadd(V);return V.clone().iadd(this)},G.prototype.isub=function(V){if(V.negative!==0){V.negative=0;var z=this.iadd(V);return V.negative=1,z._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(V),this.negative=1,this._normSign();var H=this.cmp(V);if(H===0)return this.negative=0,this.length=1,this.words[0]=0,this;var F,D;if(H>0)F=this,D=V;else F=V,D=this;var P=0;for(var j=0;j<D.length;j++)z=(F.words[j]|0)-(D.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;for(;P!==0&&j<F.length;j++)z=(F.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;if(P===0&&j<F.length&&F!==this)for(;j<F.length;j++)this.words[j]=F.words[j];if(this.length=Math.max(this.length,j),F!==this)this.negative=1;return this.strip()},G.prototype.sub=function(V){return this.clone().isub(V)};function k(V,z,H){H.negative=z.negative^V.negative;var F=V.length+z.length|0;H.length=F,F=F-1|0;var D=V.words[0]|0,P=z.words[0]|0,j=D*P,R=j&67108863,q=j/67108864|0;H.words[0]=R;for(var E=1;E<F;E++){var N=q>>>26,T=q&67108863,v=Math.min(E,z.length-1);for(var y=Math.max(0,E-V.length+1);y<=v;y++){var p=E-y|0;D=V.words[p]|0,P=z.words[y]|0,j=D*P+T,N+=j/67108864|0,T=j&67108863}H.words[E]=T|0,q=N|0}if(q!==0)H.words[E]=q|0;else H.length--;return H.strip()}var B=function(V,z,H){var F=V.words,D=z.words,P=H.words,j=0,R,q,E,N=F[0]|0,T=N&8191,v=N>>>13,y=F[1]|0,p=y&8191,J0=y>>>13,x0=F[2]|0,K0=x0&8191,Y0=x0>>>13,j0=F[3]|0,$0=j0&8191,D0=j0>>>13,$Q=F[4]|0,m=$Q&8191,n=$Q>>>13,B0=F[5]|0,F0=B0&8191,z0=B0>>>13,l0=F[6]|0,d=l0&8191,X0=l0>>>13,QQ=F[7]|0,V0=QQ&8191,P0=QQ>>>13,jQ=F[8]|0,c0=jQ&8191,u0=jQ>>>13,$Z=F[9]|0,y0=$Z&8191,s=$Z>>>13,M0=D[0]|0,G0=M0&8191,H0=M0>>>13,KQ=D[1]|0,f0=KQ&8191,h0=KQ>>>13,LQ=D[2]|0,E0=LQ&8191,A0=LQ>>>13,GQ=D[3]|0,T0=GQ&8191,S0=GQ>>>13,gQ=D[4]|0,g0=gQ&8191,d0=gQ>>>13,_Z=D[5]|0,o0=_Z&8191,b=_Z>>>13,Q0=D[6]|0,O0=Q0&8191,L0=Q0>>>13,qQ=D[7]|0,m0=qQ&8191,n0=qQ>>>13,lZ=D[8]|0,r0=lZ&8191,e0=lZ>>>13,bY=D[9]|0,t0=bY&8191,a0=bY>>>13;H.negative=V.negative^z.negative,H.length=19,R=Math.imul(T,G0),q=Math.imul(T,H0),q=q+Math.imul(v,G0)|0,E=Math.imul(v,H0);var mZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(mZ>>>26)|0,mZ&=67108863,R=Math.imul(p,G0),q=Math.imul(p,H0),q=q+Math.imul(J0,G0)|0,E=Math.imul(J0,H0),R=R+Math.imul(T,f0)|0,q=q+Math.imul(T,h0)|0,q=q+Math.imul(v,f0)|0,E=E+Math.imul(v,h0)|0;var lQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(lQ>>>26)|0,lQ&=67108863,R=Math.imul(K0,G0),q=Math.imul(K0,H0),q=q+Math.imul(Y0,G0)|0,E=Math.imul(Y0,H0),R=R+Math.imul(p,f0)|0,q=q+Math.imul(p,h0)|0,q=q+Math.imul(J0,f0)|0,E=E+Math.imul(J0,h0)|0,R=R+Math.imul(T,E0)|0,q=q+Math.imul(T,A0)|0,q=q+Math.imul(v,E0)|0,E=E+Math.imul(v,A0)|0;var pQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(pQ>>>26)|0,pQ&=67108863,R=Math.imul($0,G0),q=Math.imul($0,H0),q=q+Math.imul(D0,G0)|0,E=Math.imul(D0,H0),R=R+Math.imul(K0,f0)|0,q=q+Math.imul(K0,h0)|0,q=q+Math.imul(Y0,f0)|0,E=E+Math.imul(Y0,h0)|0,R=R+Math.imul(p,E0)|0,q=q+Math.imul(p,A0)|0,q=q+Math.imul(J0,E0)|0,E=E+Math.imul(J0,A0)|0,R=R+Math.imul(T,T0)|0,q=q+Math.imul(T,S0)|0,q=q+Math.imul(v,T0)|0,E=E+Math.imul(v,S0)|0;var IZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,R=Math.imul(m,G0),q=Math.imul(m,H0),q=q+Math.imul(n,G0)|0,E=Math.imul(n,H0),R=R+Math.imul($0,f0)|0,q=q+Math.imul($0,h0)|0,q=q+Math.imul(D0,f0)|0,E=E+Math.imul(D0,h0)|0,R=R+Math.imul(K0,E0)|0,q=q+Math.imul(K0,A0)|0,q=q+Math.imul(Y0,E0)|0,E=E+Math.imul(Y0,A0)|0,R=R+Math.imul(p,T0)|0,q=q+Math.imul(p,S0)|0,q=q+Math.imul(J0,T0)|0,E=E+Math.imul(J0,S0)|0,R=R+Math.imul(T,g0)|0,q=q+Math.imul(T,d0)|0,q=q+Math.imul(v,g0)|0,E=E+Math.imul(v,d0)|0;var zZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,R=Math.imul(F0,G0),q=Math.imul(F0,H0),q=q+Math.imul(z0,G0)|0,E=Math.imul(z0,H0),R=R+Math.imul(m,f0)|0,q=q+Math.imul(m,h0)|0,q=q+Math.imul(n,f0)|0,E=E+Math.imul(n,h0)|0,R=R+Math.imul($0,E0)|0,q=q+Math.imul($0,A0)|0,q=q+Math.imul(D0,E0)|0,E=E+Math.imul(D0,A0)|0,R=R+Math.imul(K0,T0)|0,q=q+Math.imul(K0,S0)|0,q=q+Math.imul(Y0,T0)|0,E=E+Math.imul(Y0,S0)|0,R=R+Math.imul(p,g0)|0,q=q+Math.imul(p,d0)|0,q=q+Math.imul(J0,g0)|0,E=E+Math.imul(J0,d0)|0,R=R+Math.imul(T,o0)|0,q=q+Math.imul(T,b)|0,q=q+Math.imul(v,o0)|0,E=E+Math.imul(v,b)|0;var $Y=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+($Y>>>26)|0,$Y&=67108863,R=Math.imul(d,G0),q=Math.imul(d,H0),q=q+Math.imul(X0,G0)|0,E=Math.imul(X0,H0),R=R+Math.imul(F0,f0)|0,q=q+Math.imul(F0,h0)|0,q=q+Math.imul(z0,f0)|0,E=E+Math.imul(z0,h0)|0,R=R+Math.imul(m,E0)|0,q=q+Math.imul(m,A0)|0,q=q+Math.imul(n,E0)|0,E=E+Math.imul(n,A0)|0,R=R+Math.imul($0,T0)|0,q=q+Math.imul($0,S0)|0,q=q+Math.imul(D0,T0)|0,E=E+Math.imul(D0,S0)|0,R=R+Math.imul(K0,g0)|0,q=q+Math.imul(K0,d0)|0,q=q+Math.imul(Y0,g0)|0,E=E+Math.imul(Y0,d0)|0,R=R+Math.imul(p,o0)|0,q=q+Math.imul(p,b)|0,q=q+Math.imul(J0,o0)|0,E=E+Math.imul(J0,b)|0,R=R+Math.imul(T,O0)|0,q=q+Math.imul(T,L0)|0,q=q+Math.imul(v,O0)|0,E=E+Math.imul(v,L0)|0;var JY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(JY>>>26)|0,JY&=67108863,R=Math.imul(V0,G0),q=Math.imul(V0,H0),q=q+Math.imul(P0,G0)|0,E=Math.imul(P0,H0),R=R+Math.imul(d,f0)|0,q=q+Math.imul(d,h0)|0,q=q+Math.imul(X0,f0)|0,E=E+Math.imul(X0,h0)|0,R=R+Math.imul(F0,E0)|0,q=q+Math.imul(F0,A0)|0,q=q+Math.imul(z0,E0)|0,E=E+Math.imul(z0,A0)|0,R=R+Math.imul(m,T0)|0,q=q+Math.imul(m,S0)|0,q=q+Math.imul(n,T0)|0,E=E+Math.imul(n,S0)|0,R=R+Math.imul($0,g0)|0,q=q+Math.imul($0,d0)|0,q=q+Math.imul(D0,g0)|0,E=E+Math.imul(D0,d0)|0,R=R+Math.imul(K0,o0)|0,q=q+Math.imul(K0,b)|0,q=q+Math.imul(Y0,o0)|0,E=E+Math.imul(Y0,b)|0,R=R+Math.imul(p,O0)|0,q=q+Math.imul(p,L0)|0,q=q+Math.imul(J0,O0)|0,E=E+Math.imul(J0,L0)|0,R=R+Math.imul(T,m0)|0,q=q+Math.imul(T,n0)|0,q=q+Math.imul(v,m0)|0,E=E+Math.imul(v,n0)|0;var GY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(GY>>>26)|0,GY&=67108863,R=Math.imul(c0,G0),q=Math.imul(c0,H0),q=q+Math.imul(u0,G0)|0,E=Math.imul(u0,H0),R=R+Math.imul(V0,f0)|0,q=q+Math.imul(V0,h0)|0,q=q+Math.imul(P0,f0)|0,E=E+Math.imul(P0,h0)|0,R=R+Math.imul(d,E0)|0,q=q+Math.imul(d,A0)|0,q=q+Math.imul(X0,E0)|0,E=E+Math.imul(X0,A0)|0,R=R+Math.imul(F0,T0)|0,q=q+Math.imul(F0,S0)|0,q=q+Math.imul(z0,T0)|0,E=E+Math.imul(z0,S0)|0,R=R+Math.imul(m,g0)|0,q=q+Math.imul(m,d0)|0,q=q+Math.imul(n,g0)|0,E=E+Math.imul(n,d0)|0,R=R+Math.imul($0,o0)|0,q=q+Math.imul($0,b)|0,q=q+Math.imul(D0,o0)|0,E=E+Math.imul(D0,b)|0,R=R+Math.imul(K0,O0)|0,q=q+Math.imul(K0,L0)|0,q=q+Math.imul(Y0,O0)|0,E=E+Math.imul(Y0,L0)|0,R=R+Math.imul(p,m0)|0,q=q+Math.imul(p,n0)|0,q=q+Math.imul(J0,m0)|0,E=E+Math.imul(J0,n0)|0,R=R+Math.imul(T,r0)|0,q=q+Math.imul(T,e0)|0,q=q+Math.imul(v,r0)|0,E=E+Math.imul(v,e0)|0;var XY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(XY>>>26)|0,XY&=67108863,R=Math.imul(y0,G0),q=Math.imul(y0,H0),q=q+Math.imul(s,G0)|0,E=Math.imul(s,H0),R=R+Math.imul(c0,f0)|0,q=q+Math.imul(c0,h0)|0,q=q+Math.imul(u0,f0)|0,E=E+Math.imul(u0,h0)|0,R=R+Math.imul(V0,E0)|0,q=q+Math.imul(V0,A0)|0,q=q+Math.imul(P0,E0)|0,E=E+Math.imul(P0,A0)|0,R=R+Math.imul(d,T0)|0,q=q+Math.imul(d,S0)|0,q=q+Math.imul(X0,T0)|0,E=E+Math.imul(X0,S0)|0,R=R+Math.imul(F0,g0)|0,q=q+Math.imul(F0,d0)|0,q=q+Math.imul(z0,g0)|0,E=E+Math.imul(z0,d0)|0,R=R+Math.imul(m,o0)|0,q=q+Math.imul(m,b)|0,q=q+Math.imul(n,o0)|0,E=E+Math.imul(n,b)|0,R=R+Math.imul($0,O0)|0,q=q+Math.imul($0,L0)|0,q=q+Math.imul(D0,O0)|0,E=E+Math.imul(D0,L0)|0,R=R+Math.imul(K0,m0)|0,q=q+Math.imul(K0,n0)|0,q=q+Math.imul(Y0,m0)|0,E=E+Math.imul(Y0,n0)|0,R=R+Math.imul(p,r0)|0,q=q+Math.imul(p,e0)|0,q=q+Math.imul(J0,r0)|0,E=E+Math.imul(J0,e0)|0,R=R+Math.imul(T,t0)|0,q=q+Math.imul(T,a0)|0,q=q+Math.imul(v,t0)|0,E=E+Math.imul(v,a0)|0;var VY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(VY>>>26)|0,VY&=67108863,R=Math.imul(y0,f0),q=Math.imul(y0,h0),q=q+Math.imul(s,f0)|0,E=Math.imul(s,h0),R=R+Math.imul(c0,E0)|0,q=q+Math.imul(c0,A0)|0,q=q+Math.imul(u0,E0)|0,E=E+Math.imul(u0,A0)|0,R=R+Math.imul(V0,T0)|0,q=q+Math.imul(V0,S0)|0,q=q+Math.imul(P0,T0)|0,E=E+Math.imul(P0,S0)|0,R=R+Math.imul(d,g0)|0,q=q+Math.imul(d,d0)|0,q=q+Math.imul(X0,g0)|0,E=E+Math.imul(X0,d0)|0,R=R+Math.imul(F0,o0)|0,q=q+Math.imul(F0,b)|0,q=q+Math.imul(z0,o0)|0,E=E+Math.imul(z0,b)|0,R=R+Math.imul(m,O0)|0,q=q+Math.imul(m,L0)|0,q=q+Math.imul(n,O0)|0,E=E+Math.imul(n,L0)|0,R=R+Math.imul($0,m0)|0,q=q+Math.imul($0,n0)|0,q=q+Math.imul(D0,m0)|0,E=E+Math.imul(D0,n0)|0,R=R+Math.imul(K0,r0)|0,q=q+Math.imul(K0,e0)|0,q=q+Math.imul(Y0,r0)|0,E=E+Math.imul(Y0,e0)|0,R=R+Math.imul(p,t0)|0,q=q+Math.imul(p,a0)|0,q=q+Math.imul(J0,t0)|0,E=E+Math.imul(J0,a0)|0;var qY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(qY>>>26)|0,qY&=67108863,R=Math.imul(y0,E0),q=Math.imul(y0,A0),q=q+Math.imul(s,E0)|0,E=Math.imul(s,A0),R=R+Math.imul(c0,T0)|0,q=q+Math.imul(c0,S0)|0,q=q+Math.imul(u0,T0)|0,E=E+Math.imul(u0,S0)|0,R=R+Math.imul(V0,g0)|0,q=q+Math.imul(V0,d0)|0,q=q+Math.imul(P0,g0)|0,E=E+Math.imul(P0,d0)|0,R=R+Math.imul(d,o0)|0,q=q+Math.imul(d,b)|0,q=q+Math.imul(X0,o0)|0,E=E+Math.imul(X0,b)|0,R=R+Math.imul(F0,O0)|0,q=q+Math.imul(F0,L0)|0,q=q+Math.imul(z0,O0)|0,E=E+Math.imul(z0,L0)|0,R=R+Math.imul(m,m0)|0,q=q+Math.imul(m,n0)|0,q=q+Math.imul(n,m0)|0,E=E+Math.imul(n,n0)|0,R=R+Math.imul($0,r0)|0,q=q+Math.imul($0,e0)|0,q=q+Math.imul(D0,r0)|0,E=E+Math.imul(D0,e0)|0,R=R+Math.imul(K0,t0)|0,q=q+Math.imul(K0,a0)|0,q=q+Math.imul(Y0,t0)|0,E=E+Math.imul(Y0,a0)|0;var FY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(FY>>>26)|0,FY&=67108863,R=Math.imul(y0,T0),q=Math.imul(y0,S0),q=q+Math.imul(s,T0)|0,E=Math.imul(s,S0),R=R+Math.imul(c0,g0)|0,q=q+Math.imul(c0,d0)|0,q=q+Math.imul(u0,g0)|0,E=E+Math.imul(u0,d0)|0,R=R+Math.imul(V0,o0)|0,q=q+Math.imul(V0,b)|0,q=q+Math.imul(P0,o0)|0,E=E+Math.imul(P0,b)|0,R=R+Math.imul(d,O0)|0,q=q+Math.imul(d,L0)|0,q=q+Math.imul(X0,O0)|0,E=E+Math.imul(X0,L0)|0,R=R+Math.imul(F0,m0)|0,q=q+Math.imul(F0,n0)|0,q=q+Math.imul(z0,m0)|0,E=E+Math.imul(z0,n0)|0,R=R+Math.imul(m,r0)|0,q=q+Math.imul(m,e0)|0,q=q+Math.imul(n,r0)|0,E=E+Math.imul(n,e0)|0,R=R+Math.imul($0,t0)|0,q=q+Math.imul($0,a0)|0,q=q+Math.imul(D0,t0)|0,E=E+Math.imul(D0,a0)|0;var zY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zY>>>26)|0,zY&=67108863,R=Math.imul(y0,g0),q=Math.imul(y0,d0),q=q+Math.imul(s,g0)|0,E=Math.imul(s,d0),R=R+Math.imul(c0,o0)|0,q=q+Math.imul(c0,b)|0,q=q+Math.imul(u0,o0)|0,E=E+Math.imul(u0,b)|0,R=R+Math.imul(V0,O0)|0,q=q+Math.imul(V0,L0)|0,q=q+Math.imul(P0,O0)|0,E=E+Math.imul(P0,L0)|0,R=R+Math.imul(d,m0)|0,q=q+Math.imul(d,n0)|0,q=q+Math.imul(X0,m0)|0,E=E+Math.imul(X0,n0)|0,R=R+Math.imul(F0,r0)|0,q=q+Math.imul(F0,e0)|0,q=q+Math.imul(z0,r0)|0,E=E+Math.imul(z0,e0)|0,R=R+Math.imul(m,t0)|0,q=q+Math.imul(m,a0)|0,q=q+Math.imul(n,t0)|0,E=E+Math.imul(n,a0)|0;var WY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(WY>>>26)|0,WY&=67108863,R=Math.imul(y0,o0),q=Math.imul(y0,b),q=q+Math.imul(s,o0)|0,E=Math.imul(s,b),R=R+Math.imul(c0,O0)|0,q=q+Math.imul(c0,L0)|0,q=q+Math.imul(u0,O0)|0,E=E+Math.imul(u0,L0)|0,R=R+Math.imul(V0,m0)|0,q=q+Math.imul(V0,n0)|0,q=q+Math.imul(P0,m0)|0,E=E+Math.imul(P0,n0)|0,R=R+Math.imul(d,r0)|0,q=q+Math.imul(d,e0)|0,q=q+Math.imul(X0,r0)|0,E=E+Math.imul(X0,e0)|0,R=R+Math.imul(F0,t0)|0,q=q+Math.imul(F0,a0)|0,q=q+Math.imul(z0,t0)|0,E=E+Math.imul(z0,a0)|0;var KY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(KY>>>26)|0,KY&=67108863,R=Math.imul(y0,O0),q=Math.imul(y0,L0),q=q+Math.imul(s,O0)|0,E=Math.imul(s,L0),R=R+Math.imul(c0,m0)|0,q=q+Math.imul(c0,n0)|0,q=q+Math.imul(u0,m0)|0,E=E+Math.imul(u0,n0)|0,R=R+Math.imul(V0,r0)|0,q=q+Math.imul(V0,e0)|0,q=q+Math.imul(P0,r0)|0,E=E+Math.imul(P0,e0)|0,R=R+Math.imul(d,t0)|0,q=q+Math.imul(d,a0)|0,q=q+Math.imul(X0,t0)|0,E=E+Math.imul(X0,a0)|0;var UY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(UY>>>26)|0,UY&=67108863,R=Math.imul(y0,m0),q=Math.imul(y0,n0),q=q+Math.imul(s,m0)|0,E=Math.imul(s,n0),R=R+Math.imul(c0,r0)|0,q=q+Math.imul(c0,e0)|0,q=q+Math.imul(u0,r0)|0,E=E+Math.imul(u0,e0)|0,R=R+Math.imul(V0,t0)|0,q=q+Math.imul(V0,a0)|0,q=q+Math.imul(P0,t0)|0,E=E+Math.imul(P0,a0)|0;var OY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(OY>>>26)|0,OY&=67108863,R=Math.imul(y0,r0),q=Math.imul(y0,e0),q=q+Math.imul(s,r0)|0,E=Math.imul(s,e0),R=R+Math.imul(c0,t0)|0,q=q+Math.imul(c0,a0)|0,q=q+Math.imul(u0,t0)|0,E=E+Math.imul(u0,a0)|0;var HY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(HY>>>26)|0,HY&=67108863,R=Math.imul(y0,t0),q=Math.imul(y0,a0),q=q+Math.imul(s,t0)|0,E=Math.imul(s,a0);var DY=(j+R|0)+((q&8191)<<13)|0;if(j=(E+(q>>>13)|0)+(DY>>>26)|0,DY&=67108863,P[0]=mZ,P[1]=lQ,P[2]=pQ,P[3]=IZ,P[4]=zZ,P[5]=$Y,P[6]=JY,P[7]=GY,P[8]=XY,P[9]=VY,P[10]=qY,P[11]=FY,P[12]=zY,P[13]=WY,P[14]=KY,P[15]=UY,P[16]=OY,P[17]=HY,P[18]=DY,j!==0)P[19]=j,H.length++;return H};if(!Math.imul)B=k;function C(V,z,H){H.negative=z.negative^V.negative,H.length=V.length+z.length;var F=0,D=0;for(var P=0;P<H.length-1;P++){var j=D;D=0;var R=F&67108863,q=Math.min(P,z.length-1);for(var E=Math.max(0,P-V.length+1);E<=q;E++){var N=P-E,T=V.words[N]|0,v=z.words[E]|0,y=T*v,p=y&67108863;j=j+(y/67108864|0)|0,p=p+R|0,R=p&67108863,j=j+(p>>>26)|0,D+=j>>>26,j&=67108863}H.words[P]=R,F=j,j=D}if(F!==0)H.words[P]=F;else H.length--;return H.strip()}function S(V,z,H){var F=new _;return F.mulp(V,z,H)}G.prototype.mulTo=function(V,z){var H,F=this.length+V.length;if(this.length===10&&V.length===10)H=B(this,V,z);else if(F<63)H=k(this,V,z);else if(F<1024)H=C(this,V,z);else H=S(this,V,z);return H};function _(V,z){this.x=V,this.y=z}_.prototype.makeRBT=function(V){var z=Array(V),H=G.prototype._countBits(V)-1;for(var F=0;F<V;F++)z[F]=this.revBin(F,H,V);return z},_.prototype.revBin=function(V,z,H){if(V===0||V===H-1)return V;var F=0;for(var D=0;D<z;D++)F|=(V&1)<<z-D-1,V>>=1;return F},_.prototype.permute=function(V,z,H,F,D,P){for(var j=0;j<P;j++)F[j]=z[V[j]],D[j]=H[V[j]]},_.prototype.transform=function(V,z,H,F,D,P){this.permute(P,V,z,H,F,D);for(var j=1;j<D;j<<=1){var R=j<<1,q=Math.cos(2*Math.PI/R),E=Math.sin(2*Math.PI/R);for(var N=0;N<D;N+=R){var T=q,v=E;for(var y=0;y<j;y++){var p=H[N+y],J0=F[N+y],x0=H[N+y+j],K0=F[N+y+j],Y0=T*x0-v*K0;if(K0=T*K0+v*x0,x0=Y0,H[N+y]=p+x0,F[N+y]=J0+K0,H[N+y+j]=p-x0,F[N+y+j]=J0-K0,y!==R)Y0=q*T-E*v,v=q*v+E*T,T=Y0}}}},_.prototype.guessLen13b=function(V,z){var H=Math.max(z,V)|1,F=H&1,D=0;for(H=H/2|0;H;H=H>>>1)D++;return 1<<D+1+F},_.prototype.conjugate=function(V,z,H){if(H<=1)return;for(var F=0;F<H/2;F++){var D=V[F];V[F]=V[H-F-1],V[H-F-1]=D,D=z[F],z[F]=-z[H-F-1],z[H-F-1]=-D}},_.prototype.normalize13b=function(V,z){var H=0;for(var F=0;F<z/2;F++){var D=Math.round(V[2*F+1]/z)*8192+Math.round(V[2*F]/z)+H;if(V[F]=D&67108863,D<67108864)H=0;else H=D/67108864|0}return V},_.prototype.convert13b=function(V,z,H,F){var D=0;for(var P=0;P<z;P++)D=D+(V[P]|0),H[2*P]=D&8191,D=D>>>13,H[2*P+1]=D&8191,D=D>>>13;for(P=2*z;P<F;++P)H[P]=0;J(D===0),J((D&-8192)===0)},_.prototype.stub=function(V){var z=Array(V);for(var H=0;H<V;H++)z[H]=0;return z},_.prototype.mulp=function(V,z,H){var F=2*this.guessLen13b(V.length,z.length),D=this.makeRBT(F),P=this.stub(F),j=Array(F),R=Array(F),q=Array(F),E=Array(F),N=Array(F),T=Array(F),v=H.words;v.length=F,this.convert13b(V.words,V.length,j,F),this.convert13b(z.words,z.length,E,F),this.transform(j,P,R,q,F,D),this.transform(E,P,N,T,F,D);for(var y=0;y<F;y++){var p=R[y]*N[y]-q[y]*T[y];q[y]=R[y]*T[y]+q[y]*N[y],R[y]=p}return this.conjugate(R,q,F),this.transform(R,q,v,P,F,D),this.conjugate(v,P,F),this.normalize13b(v,F),H.negative=V.negative^z.negative,H.length=V.length+z.length,H.strip()},G.prototype.mul=function(V){var z=new G(null);return z.words=Array(this.length+V.length),this.mulTo(V,z)},G.prototype.mulf=function(V){var z=new G(null);return z.words=Array(this.length+V.length),S(this,V,z)},G.prototype.imul=function(V){return this.clone().mulTo(V,this)},G.prototype.imuln=function(V){J(typeof V==="number"),J(V<67108864);var z=0;for(var H=0;H<this.length;H++){var F=(this.words[H]|0)*V,D=(F&67108863)+(z&67108863);z>>=26,z+=F/67108864|0,z+=D>>>26,this.words[H]=D&67108863}if(z!==0)this.words[H]=z,this.length++;return this.length=V===0?1:this.length,this},G.prototype.muln=function(V){return this.clone().imuln(V)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(V){var z=M(V);if(z.length===0)return new G(1);var H=this;for(var F=0;F<z.length;F++,H=H.sqr())if(z[F]!==0)break;if(++F<z.length)for(var D=H.sqr();F<z.length;F++,D=D.sqr()){if(z[F]===0)continue;H=H.mul(D)}return H},G.prototype.iushln=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=67108863>>>26-z<<26-z,D;if(z!==0){var P=0;for(D=0;D<this.length;D++){var j=this.words[D]&F,R=(this.words[D]|0)-j<<z;this.words[D]=R|P,P=j>>>26-z}if(P)this.words[D]=P,this.length++}if(H!==0){for(D=this.length-1;D>=0;D--)this.words[D+H]=this.words[D];for(D=0;D<H;D++)this.words[D]=0;this.length+=H}return this.strip()},G.prototype.ishln=function(V){return J(this.negative===0),this.iushln(V)},G.prototype.iushrn=function(V,z,H){J(typeof V==="number"&&V>=0);var F;if(z)F=(z-z%26)/26;else F=0;var D=V%26,P=Math.min((V-D)/26,this.length),j=67108863^67108863>>>D<<D,R=H;if(F-=P,F=Math.max(0,F),R){for(var q=0;q<P;q++)R.words[q]=this.words[q];R.length=P}if(P===0);else if(this.length>P){this.length-=P;for(q=0;q<this.length;q++)this.words[q]=this.words[q+P]}else this.words[0]=0,this.length=1;var E=0;for(q=this.length-1;q>=0&&(E!==0||q>=F);q--){var N=this.words[q]|0;this.words[q]=E<<26-D|N>>>D,E=N&j}if(R&&E!==0)R.words[R.length++]=E;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},G.prototype.ishrn=function(V,z,H){return J(this.negative===0),this.iushrn(V,z,H)},G.prototype.shln=function(V){return this.clone().ishln(V)},G.prototype.ushln=function(V){return this.clone().iushln(V)},G.prototype.shrn=function(V){return this.clone().ishrn(V)},G.prototype.ushrn=function(V){return this.clone().iushrn(V)},G.prototype.testn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return!1;var D=this.words[H];return!!(D&F)},G.prototype.imaskn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26;if(J(this.negative===0,"imaskn works only with positive numbers"),this.length<=H)return this;if(z!==0)H++;if(this.length=Math.min(H,this.length),z!==0){var F=67108863^67108863>>>z<<z;this.words[this.length-1]&=F}return this.strip()},G.prototype.maskn=function(V){return this.clone().imaskn(V)},G.prototype.iaddn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.isubn(-V);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<V)return this.words[0]=V-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(V),this.negative=1,this}return this._iaddn(V)},G.prototype._iaddn=function(V){this.words[0]+=V;for(var z=0;z<this.length&&this.words[z]>=67108864;z++)if(this.words[z]-=67108864,z===this.length-1)this.words[z+1]=1;else this.words[z+1]++;return this.length=Math.max(this.length,z+1),this},G.prototype.isubn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.iaddn(-V);if(this.negative!==0)return this.negative=0,this.iaddn(V),this.negative=1,this;if(this.words[0]-=V,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var z=0;z<this.length&&this.words[z]<0;z++)this.words[z]+=67108864,this.words[z+1]-=1;return this.strip()},G.prototype.addn=function(V){return this.clone().iaddn(V)},G.prototype.subn=function(V){return this.clone().isubn(V)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(V,z,H){var F=V.length+H,D;this._expand(F);var P,j=0;for(D=0;D<V.length;D++){P=(this.words[D+H]|0)+j;var R=(V.words[D]|0)*z;P-=R&67108863,j=(P>>26)-(R/67108864|0),this.words[D+H]=P&67108863}for(;D<this.length-H;D++)P=(this.words[D+H]|0)+j,j=P>>26,this.words[D+H]=P&67108863;if(j===0)return this.strip();J(j===-1),j=0;for(D=0;D<this.length;D++)P=-(this.words[D]|0)+j,j=P>>26,this.words[D]=P&67108863;return this.negative=1,this.strip()},G.prototype._wordDiv=function(V,z){var H=this.length-V.length,F=this.clone(),D=V,P=D.words[D.length-1]|0,j=this._countBits(P);if(H=26-j,H!==0)D=D.ushln(H),F.iushln(H),P=D.words[D.length-1]|0;var R=F.length-D.length,q;if(z!=="mod"){q=new G(null),q.length=R+1,q.words=Array(q.length);for(var E=0;E<q.length;E++)q.words[E]=0}var N=F.clone()._ishlnsubmul(D,1,R);if(N.negative===0){if(F=N,q)q.words[R]=1}for(var T=R-1;T>=0;T--){var v=(F.words[D.length+T]|0)*67108864+(F.words[D.length+T-1]|0);v=Math.min(v/P|0,67108863),F._ishlnsubmul(D,v,T);while(F.negative!==0)if(v--,F.negative=0,F._ishlnsubmul(D,1,T),!F.isZero())F.negative^=1;if(q)q.words[T]=v}if(q)q.strip();if(F.strip(),z!=="div"&&H!==0)F.iushrn(H);return{div:q||null,mod:F}},G.prototype.divmod=function(V,z,H){if(J(!V.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var F,D,P;if(this.negative!==0&&V.negative===0){if(P=this.neg().divmod(V,z),z!=="mod")F=P.div.neg();if(z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.iadd(V)}return{div:F,mod:D}}if(this.negative===0&&V.negative!==0){if(P=this.divmod(V.neg(),z),z!=="mod")F=P.div.neg();return{div:F,mod:P.mod}}if((this.negative&V.negative)!==0){if(P=this.neg().divmod(V.neg(),z),z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.isub(V)}return{div:P.div,mod:D}}if(V.length>this.length||this.cmp(V)<0)return{div:new G(0),mod:this};if(V.length===1){if(z==="div")return{div:this.divn(V.words[0]),mod:null};if(z==="mod")return{div:null,mod:new G(this.modn(V.words[0]))};return{div:this.divn(V.words[0]),mod:new G(this.modn(V.words[0]))}}return this._wordDiv(V,z)},G.prototype.div=function(V){return this.divmod(V,"div",!1).div},G.prototype.mod=function(V){return this.divmod(V,"mod",!1).mod},G.prototype.umod=function(V){return this.divmod(V,"mod",!0).mod},G.prototype.divRound=function(V){var z=this.divmod(V);if(z.mod.isZero())return z.div;var H=z.div.negative!==0?z.mod.isub(V):z.mod,F=V.ushrn(1),D=V.andln(1),P=H.cmp(F);if(P<0||D===1&&P===0)return z.div;return z.div.negative!==0?z.div.isubn(1):z.div.iaddn(1)},G.prototype.modn=function(V){J(V<=67108863);var z=67108864%V,H=0;for(var F=this.length-1;F>=0;F--)H=(z*H+(this.words[F]|0))%V;return H},G.prototype.idivn=function(V){J(V<=67108863);var z=0;for(var H=this.length-1;H>=0;H--){var F=(this.words[H]|0)+z*67108864;this.words[H]=F/V|0,z=F%V}return this.strip()},G.prototype.divn=function(V){return this.clone().idivn(V)},G.prototype.egcd=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=new G(0),j=new G(1),R=0;while(z.isEven()&&H.isEven())z.iushrn(1),H.iushrn(1),++R;var q=H.clone(),E=z.clone();while(!z.isZero()){for(var N=0,T=1;(z.words[0]&T)===0&&N<26;++N,T<<=1);if(N>0){z.iushrn(N);while(N-- >0){if(F.isOdd()||D.isOdd())F.iadd(q),D.isub(E);F.iushrn(1),D.iushrn(1)}}for(var v=0,y=1;(H.words[0]&y)===0&&v<26;++v,y<<=1);if(v>0){H.iushrn(v);while(v-- >0){if(P.isOdd()||j.isOdd())P.iadd(q),j.isub(E);P.iushrn(1),j.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(P),D.isub(j);else H.isub(z),P.isub(F),j.isub(D)}return{a:P,b:j,gcd:H.iushln(R)}},G.prototype._invmp=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=H.clone();while(z.cmpn(1)>0&&H.cmpn(1)>0){for(var j=0,R=1;(z.words[0]&R)===0&&j<26;++j,R<<=1);if(j>0){z.iushrn(j);while(j-- >0){if(F.isOdd())F.iadd(P);F.iushrn(1)}}for(var q=0,E=1;(H.words[0]&E)===0&&q<26;++q,E<<=1);if(q>0){H.iushrn(q);while(q-- >0){if(D.isOdd())D.iadd(P);D.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(D);else H.isub(z),D.isub(F)}var N;if(z.cmpn(1)===0)N=F;else N=D;if(N.cmpn(0)<0)N.iadd(V);return N},G.prototype.gcd=function(V){if(this.isZero())return V.abs();if(V.isZero())return this.abs();var z=this.clone(),H=V.clone();z.negative=0,H.negative=0;for(var F=0;z.isEven()&&H.isEven();F++)z.iushrn(1),H.iushrn(1);do{while(z.isEven())z.iushrn(1);while(H.isEven())H.iushrn(1);var D=z.cmp(H);if(D<0){var P=z;z=H,H=P}else if(D===0||H.cmpn(1)===0)break;z.isub(H)}while(!0);return H.iushln(F)},G.prototype.invm=function(V){return this.egcd(V).a.umod(V)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(V){return this.words[0]&V},G.prototype.bincn=function(V){J(typeof V==="number");var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return this._expand(H+1),this.words[H]|=F,this;var D=F;for(var P=H;D!==0&&P<this.length;P++){var j=this.words[P]|0;j+=D,D=j>>>26,j&=67108863,this.words[P]=j}if(D!==0)this.words[P]=D,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(V){var z=V<0;if(this.negative!==0&&!z)return-1;if(this.negative===0&&z)return 1;this.strip();var H;if(this.length>1)H=1;else{if(z)V=-V;J(V<=67108863,"Number is too big");var F=this.words[0]|0;H=F===V?0:F<V?-1:1}if(this.negative!==0)return-H|0;return H},G.prototype.cmp=function(V){if(this.negative!==0&&V.negative===0)return-1;if(this.negative===0&&V.negative!==0)return 1;var z=this.ucmp(V);if(this.negative!==0)return-z|0;return z},G.prototype.ucmp=function(V){if(this.length>V.length)return 1;if(this.length<V.length)return-1;var z=0;for(var H=this.length-1;H>=0;H--){var F=this.words[H]|0,D=V.words[H]|0;if(F===D)continue;if(F<D)z=-1;else if(F>D)z=1;break}return z},G.prototype.gtn=function(V){return this.cmpn(V)===1},G.prototype.gt=function(V){return this.cmp(V)===1},G.prototype.gten=function(V){return this.cmpn(V)>=0},G.prototype.gte=function(V){return this.cmp(V)>=0},G.prototype.ltn=function(V){return this.cmpn(V)===-1},G.prototype.lt=function(V){return this.cmp(V)===-1},G.prototype.lten=function(V){return this.cmpn(V)<=0},G.prototype.lte=function(V){return this.cmp(V)<=0},G.prototype.eqn=function(V){return this.cmpn(V)===0},G.prototype.eq=function(V){return this.cmp(V)===0},G.red=function(V){return new c(V)},G.prototype.toRed=function(V){return J(!this.red,"Already a number in reduction context"),J(this.negative===0,"red works only with positives"),V.convertTo(this)._forceRed(V)},G.prototype.fromRed=function(){return J(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(V){return this.red=V,this},G.prototype.forceRed=function(V){return J(!this.red,"Already a number in reduction context"),this._forceRed(V)},G.prototype.redAdd=function(V){return J(this.red,"redAdd works only with red numbers"),this.red.add(this,V)},G.prototype.redIAdd=function(V){return J(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,V)},G.prototype.redSub=function(V){return J(this.red,"redSub works only with red numbers"),this.red.sub(this,V)},G.prototype.redISub=function(V){return J(this.red,"redISub works only with red numbers"),this.red.isub(this,V)},G.prototype.redShl=function(V){return J(this.red,"redShl works only with red numbers"),this.red.shl(this,V)},G.prototype.redMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.mul(this,V)},G.prototype.redIMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.imul(this,V)},G.prototype.redSqr=function(){return J(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return J(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return J(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return J(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return J(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(V){return J(this.red&&!V.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,V)};var x={k256:null,p224:null,p192:null,p25519:null};function f(V,z){this.name=V,this.p=new G(z,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}f.prototype._tmp=function(){var V=new G(null);return V.words=Array(Math.ceil(this.n/13)),V},f.prototype.ireduce=function(V){var z=V,H;do this.split(z,this.tmp),z=this.imulK(z),z=z.iadd(this.tmp),H=z.bitLength();while(H>this.n);var F=H<this.n?-1:z.ucmp(this.p);if(F===0)z.words[0]=0,z.length=1;else if(F>0)z.isub(this.p);else if(z.strip!==void 0)z.strip();else z._strip();return z},f.prototype.split=function(V,z){V.iushrn(this.n,0,z)},f.prototype.imulK=function(V){return V.imul(this.k)};function h(){f.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,f),h.prototype.split=function(V,z){var H=4194303,F=Math.min(V.length,9);for(var D=0;D<F;D++)z.words[D]=V.words[D];if(z.length=F,V.length<=9){V.words[0]=0,V.length=1;return}var P=V.words[9];z.words[z.length++]=P&H;for(D=10;D<V.length;D++){var j=V.words[D]|0;V.words[D-10]=(j&H)<<4|P>>>22,P=j}if(P>>>=22,V.words[D-10]=P,P===0&&V.length>10)V.length-=10;else V.length-=9},h.prototype.imulK=function(V){V.words[V.length]=0,V.words[V.length+1]=0,V.length+=2;var z=0;for(var H=0;H<V.length;H++){var F=V.words[H]|0;z+=F*977,V.words[H]=z&67108863,z=F*64+(z/67108864|0)}if(V.words[V.length-1]===0){if(V.length--,V.words[V.length-1]===0)V.length--}return V};function i(){f.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(i,f);function Z0(){f.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(Z0,f);function t(){f.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(t,f),t.prototype.imulK=function(V){var z=0;for(var H=0;H<V.length;H++){var F=(V.words[H]|0)*19+z,D=F&67108863;F>>>=26,V.words[H]=D,z=F}if(z!==0)V.words[V.length++]=z;return V},G._prime=function(V){if(x[V])return x[V];var z;if(V==="k256")z=new h;else if(V==="p224")z=new i;else if(V==="p192")z=new Z0;else if(V==="p25519")z=new t;else throw Error("Unknown prime "+V);return x[V]=z,z};function c(V){if(typeof V==="string"){var z=G._prime(V);this.m=z.p,this.prime=z}else J(V.gtn(1),"modulus must be greater than 1"),this.m=V,this.prime=null}c.prototype._verify1=function(V){J(V.negative===0,"red works only with positives"),J(V.red,"red works only with red numbers")},c.prototype._verify2=function(V,z){J((V.negative|z.negative)===0,"red works only with positives"),J(V.red&&V.red===z.red,"red works only with red numbers")},c.prototype.imod=function(V){if(this.prime)return this.prime.ireduce(V)._forceRed(this);return V.umod(this.m)._forceRed(this)},c.prototype.neg=function(V){if(V.isZero())return V.clone();return this.m.sub(V)._forceRed(this)},c.prototype.add=function(V,z){this._verify2(V,z);var H=V.add(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H._forceRed(this)},c.prototype.iadd=function(V,z){this._verify2(V,z);var H=V.iadd(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H},c.prototype.sub=function(V,z){this._verify2(V,z);var H=V.sub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H._forceRed(this)},c.prototype.isub=function(V,z){this._verify2(V,z);var H=V.isub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H},c.prototype.shl=function(V,z){return this._verify1(V),this.imod(V.ushln(z))},c.prototype.imul=function(V,z){return this._verify2(V,z),this.imod(V.imul(z))},c.prototype.mul=function(V,z){return this._verify2(V,z),this.imod(V.mul(z))},c.prototype.isqr=function(V){return this.imul(V,V.clone())},c.prototype.sqr=function(V){return this.mul(V,V)},c.prototype.sqrt=function(V){if(V.isZero())return V.clone();var z=this.m.andln(3);if(J(z%2===1),z===3){var H=this.m.add(new G(1)).iushrn(2);return this.pow(V,H)}var F=this.m.subn(1),D=0;while(!F.isZero()&&F.andln(1)===0)D++,F.iushrn(1);J(!F.isZero());var P=new G(1).toRed(this),j=P.redNeg(),R=this.m.subn(1).iushrn(1),q=this.m.bitLength();q=new G(2*q*q).toRed(this);while(this.pow(q,R).cmp(j)!==0)q.redIAdd(j);var E=this.pow(q,F),N=this.pow(V,F.addn(1).iushrn(1)),T=this.pow(V,F),v=D;while(T.cmp(P)!==0){var y=T;for(var p=0;y.cmp(P)!==0;p++)y=y.redSqr();J(p<v);var J0=this.pow(E,new G(1).iushln(v-p-1));N=N.redMul(J0),E=J0.redSqr(),T=T.redMul(E),v=p}return N},c.prototype.invm=function(V){var z=V._invmp(this.m);if(z.negative!==0)return z.negative=0,this.imod(z).redNeg();else return this.imod(z)},c.prototype.pow=function(V,z){if(z.isZero())return new G(1).toRed(this);if(z.cmpn(1)===0)return V.clone();var H=4,F=Array(1<<H);F[0]=new G(1).toRed(this),F[1]=V;for(var D=2;D<F.length;D++)F[D]=this.mul(F[D-1],V);var P=F[0],j=0,R=0,q=z.bitLength()%26;if(q===0)q=26;for(D=z.length-1;D>=0;D--){var E=z.words[D];for(var N=q-1;N>=0;N--){var T=E>>N&1;if(P!==F[0])P=this.sqr(P);if(T===0&&j===0){R=0;continue}if(j<<=1,j|=T,R++,R!==H&&(D!==0||N!==0))continue;P=this.mul(P,F[j]),R=0,j=0}q=26}return P},c.prototype.convertTo=function(V){var z=V.umod(this.m);return z===V?z.clone():z},c.prototype.convertFrom=function(V){var z=V.clone();return z.red=null,z},G.mont=function(V){return new l(V)};function l(V){if(c.call(this,V),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(l,c),l.prototype.convertTo=function(V){return this.imod(V.ushln(this.shift))},l.prototype.convertFrom=function(V){var z=this.imod(V.mul(this.rinv));return z.red=null,z},l.prototype.imul=function(V,z){if(V.isZero()||z.isZero())return V.words[0]=0,V.length=1,V;var H=V.imul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.mul=function(V,z){if(V.isZero()||z.isZero())return new G(0)._forceRed(this);var H=V.mul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.invm=function(V){var z=this.imod(V._invmp(this.m).mul(this.r2));return z._forceRed(this)}})(typeof Z>"u"||Z,Q)}),Xe=v0((Q,Z)=>{var Y=Je(),$=Ge();Z.exports=function(W){return new X(W)};var J={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};J.p224=J.secp224r1,J.p256=J.secp256r1=J.prime256v1,J.p192=J.secp192r1=J.prime192v1,J.p384=J.secp384r1,J.p521=J.secp521r1;function X(W){if(this.curveType=J[W],!this.curveType)this.curveType={name:W};this.curve=new Y.ec(this.curveType.name),this.keys=void 0}X.prototype.generateKeys=function(W,U){return this.keys=this.curve.genKeyPair(),this.getPublicKey(W,U)},X.prototype.computeSecret=function(W,U,K){if(U=U||"utf8",!Buffer.isBuffer(W))W=new Buffer(W,U);var O=this.curve.keyFromPublic(W).getPublic(),I=O.mul(this.keys.getPrivate()).getX();return G(I,K,this.curveType.byteLength)},X.prototype.getPublicKey=function(W,U){var K=this.keys.getPublic(U==="compressed",!0);if(U==="hybrid")if(K[K.length-1]%2)K[0]=7;else K[0]=6;return G(K,W)},X.prototype.getPrivateKey=function(W){return G(this.keys.getPrivate(),W)},X.prototype.setPublicKey=function(W,U){if(U=U||"utf8",!Buffer.isBuffer(W))W=new Buffer(W,U);return this.keys._importPublic(W),this},X.prototype.setPrivateKey=function(W,U){if(U=U||"utf8",!Buffer.isBuffer(W))W=new Buffer(W,U);var K=new $(W);return K=K.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(K),this};function G(W,U,K){if(!Array.isArray(W))W=W.toArray();var O=new Buffer(W);if(K&&O.length<K){var I=new Buffer(K-O.length);I.fill(0),O=Buffer.concat([I,O])}if(!U)return O;else return O.toString(U)}}),Ve=v0((Q,Z)=>{var Y=(v$(),oQ(_$)).createECDH;Z.exports=Y||Xe()}),qe=v0((Q,Z)=>{(function(Y,$){function J(V,z){if(!V)throw Error(z||"Assertion failed")}function X(V,z){V.super_=z;var H=function(){};H.prototype=z.prototype,V.prototype=new H,V.prototype.constructor=V}function G(V,z,H){if(G.isBN(V))return V;if(this.negative=0,this.words=null,this.length=0,this.red=null,V!==null){if(z==="le"||z==="be")H=z,z=10;this._init(V||0,z||10,H||"be")}}if(typeof Y==="object")Y.exports=G;else $.BN=G;G.BN=G,G.wordSize=26;var W;try{if(typeof window<"u"&&typeof window.Buffer<"u")W=window.Buffer;else W=(vY(),oQ(_Y)).Buffer}catch(V){}G.isBN=function(V){if(V instanceof G)return!0;return V!==null&&typeof V==="object"&&V.constructor.wordSize===G.wordSize&&Array.isArray(V.words)},G.max=function(V,z){if(V.cmp(z)>0)return V;return z},G.min=function(V,z){if(V.cmp(z)<0)return V;return z},G.prototype._init=function(V,z,H){if(typeof V==="number")return this._initNumber(V,z,H);if(typeof V==="object")return this._initArray(V,z,H);if(z==="hex")z=16;J(z===(z|0)&&z>=2&&z<=36),V=V.toString().replace(/\s+/g,"");var F=0;if(V[0]==="-")F++,this.negative=1;if(F<V.length){if(z===16)this._parseHex(V,F,H);else if(this._parseBase(V,z,F),H==="le")this._initArray(this.toArray(),z,H)}},G.prototype._initNumber=function(V,z,H){if(V<0)this.negative=1,V=-V;if(V<67108864)this.words=[V&67108863],this.length=1;else if(V<4503599627370496)this.words=[V&67108863,V/67108864&67108863],this.length=2;else J(V<9007199254740992),this.words=[V&67108863,V/67108864&67108863,1],this.length=3;if(H!=="le")return;this._initArray(this.toArray(),z,H)},G.prototype._initArray=function(V,z,H){if(J(typeof V.length==="number"),V.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(V.length/3),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D,P,j=0;if(H==="be"){for(F=V.length-1,D=0;F>=0;F-=3)if(P=V[F]|V[F-1]<<8|V[F-2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}else if(H==="le"){for(F=0,D=0;F<V.length;F+=3)if(P=V[F]|V[F+1]<<8|V[F+2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}return this.strip()};function U(V,z){var H=V.charCodeAt(z);if(H>=65&&H<=70)return H-55;else if(H>=97&&H<=102)return H-87;else return H-48&15}function K(V,z,H){var F=U(V,H);if(H-1>=z)F|=U(V,H-1)<<4;return F}G.prototype._parseHex=function(V,z,H){this.length=Math.ceil((V.length-z)/6),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D=0,P=0,j;if(H==="be")for(F=V.length-1;F>=z;F-=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8;else{var R=V.length-z;for(F=R%2===0?z+1:z;F<V.length;F+=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8}this.strip()};function O(V,z,H,F){var D=0,P=Math.min(V.length,H);for(var j=z;j<P;j++){var R=V.charCodeAt(j)-48;if(D*=F,R>=49)D+=R-49+10;else if(R>=17)D+=R-17+10;else D+=R}return D}G.prototype._parseBase=function(V,z,H){this.words=[0],this.length=1;for(var F=0,D=1;D<=67108863;D*=z)F++;F--,D=D/z|0;var P=V.length-H,j=P%F,R=Math.min(P,P-j)+H,q=0;for(var E=H;E<R;E+=F)if(q=O(V,E,E+F,z),this.imuln(D),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q);if(j!==0){var N=1;q=O(V,E,V.length,z);for(E=0;E<j;E++)N*=z;if(this.imuln(N),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q)}this.strip()},G.prototype.copy=function(V){V.words=Array(this.length);for(var z=0;z<this.length;z++)V.words[z]=this.words[z];V.length=this.length,V.negative=this.negative,V.red=this.red},G.prototype.clone=function(){var V=new G(null);return this.copy(V),V},G.prototype._expand=function(V){while(this.length<V)this.words[this.length++]=0;return this},G.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},G.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],L=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(G.prototype.toString=function(V,z){V=V||10,z=z|0||1;var H;if(V===16||V==="hex"){H="";var F=0,D=0;for(var P=0;P<this.length;P++){var j=this.words[P],R=((j<<F|D)&16777215).toString(16);if(D=j>>>24-F&16777215,F+=2,F>=26)F-=26,P--;if(D!==0||P!==this.length-1)H=I[6-R.length]+R+H;else H=R+H}if(D!==0)H=D.toString(16)+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}if(V===(V|0)&&V>=2&&V<=36){var q=L[V],E=A[V];H="";var N=this.clone();N.negative=0;while(!N.isZero()){var T=N.modn(E).toString(V);if(N=N.idivn(E),!N.isZero())H=I[q-T.length]+T+H;else H=T+H}if(this.isZero())H="0"+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}J(!1,"Base should be between 2 and 36")},G.prototype.toNumber=function(){var V=this.words[0];if(this.length===2)V+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)V+=4503599627370496+this.words[1]*67108864;else if(this.length>2)J(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-V:V},G.prototype.toJSON=function(){return this.toString(16)},G.prototype.toBuffer=function(V,z){return J(typeof W<"u"),this.toArrayLike(W,V,z)},G.prototype.toArray=function(V,z){return this.toArrayLike(Array,V,z)},G.prototype.toArrayLike=function(V,z,H){var F=this.byteLength(),D=H||Math.max(1,F);J(F<=D,"byte array longer than desired length"),J(D>0,"Requested array length <= 0"),this.strip();var P=z==="le",j=new V(D),R,q,E=this.clone();if(!P){for(q=0;q<D-F;q++)j[q]=0;for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[D-q-1]=R}else{for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[q]=R;for(;q<D;q++)j[q]=0}return j},Math.clz32)G.prototype._countBits=function(V){return 32-Math.clz32(V)};else G.prototype._countBits=function(V){var z=V,H=0;if(z>=4096)H+=13,z>>>=13;if(z>=64)H+=7,z>>>=7;if(z>=8)H+=4,z>>>=4;if(z>=2)H+=2,z>>>=2;return H+z};G.prototype._zeroBits=function(V){if(V===0)return 26;var z=V,H=0;if((z&8191)===0)H+=13,z>>>=13;if((z&127)===0)H+=7,z>>>=7;if((z&15)===0)H+=4,z>>>=4;if((z&3)===0)H+=2,z>>>=2;if((z&1)===0)H++;return H},G.prototype.bitLength=function(){var V=this.words[this.length-1],z=this._countBits(V);return(this.length-1)*26+z};function M(V){var z=Array(V.bitLength());for(var H=0;H<z.length;H++){var F=H/26|0,D=H%26;z[H]=(V.words[F]&1<<D)>>>D}return z}G.prototype.zeroBits=function(){if(this.isZero())return 0;var V=0;for(var z=0;z<this.length;z++){var H=this._zeroBits(this.words[z]);if(V+=H,H!==26)break}return V},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(V){if(this.negative!==0)return this.abs().inotn(V).iaddn(1);return this.clone()},G.prototype.fromTwos=function(V){if(this.testn(V-1))return this.notn(V).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(V){while(this.length<V.length)this.words[this.length++]=0;for(var z=0;z<V.length;z++)this.words[z]=this.words[z]|V.words[z];return this.strip()},G.prototype.ior=function(V){return J((this.negative|V.negative)===0),this.iuor(V)},G.prototype.or=function(V){if(this.length>V.length)return this.clone().ior(V);return V.clone().ior(this)},G.prototype.uor=function(V){if(this.length>V.length)return this.clone().iuor(V);return V.clone().iuor(this)},G.prototype.iuand=function(V){var z;if(this.length>V.length)z=V;else z=this;for(var H=0;H<z.length;H++)this.words[H]=this.words[H]&V.words[H];return this.length=z.length,this.strip()},G.prototype.iand=function(V){return J((this.negative|V.negative)===0),this.iuand(V)},G.prototype.and=function(V){if(this.length>V.length)return this.clone().iand(V);return V.clone().iand(this)},G.prototype.uand=function(V){if(this.length>V.length)return this.clone().iuand(V);return V.clone().iuand(this)},G.prototype.iuxor=function(V){var z,H;if(this.length>V.length)z=this,H=V;else z=V,H=this;for(var F=0;F<H.length;F++)this.words[F]=z.words[F]^H.words[F];if(this!==z)for(;F<z.length;F++)this.words[F]=z.words[F];return this.length=z.length,this.strip()},G.prototype.ixor=function(V){return J((this.negative|V.negative)===0),this.iuxor(V)},G.prototype.xor=function(V){if(this.length>V.length)return this.clone().ixor(V);return V.clone().ixor(this)},G.prototype.uxor=function(V){if(this.length>V.length)return this.clone().iuxor(V);return V.clone().iuxor(this)},G.prototype.inotn=function(V){J(typeof V==="number"&&V>=0);var z=Math.ceil(V/26)|0,H=V%26;if(this._expand(z),H>0)z--;for(var F=0;F<z;F++)this.words[F]=~this.words[F]&67108863;if(H>0)this.words[F]=~this.words[F]&67108863>>26-H;return this.strip()},G.prototype.notn=function(V){return this.clone().inotn(V)},G.prototype.setn=function(V,z){J(typeof V==="number"&&V>=0);var H=V/26|0,F=V%26;if(this._expand(H+1),z)this.words[H]=this.words[H]|1<<F;else this.words[H]=this.words[H]&~(1<<F);return this.strip()},G.prototype.iadd=function(V){var z;if(this.negative!==0&&V.negative===0)return this.negative=0,z=this.isub(V),this.negative^=1,this._normSign();else if(this.negative===0&&V.negative!==0)return V.negative=0,z=this.isub(V),V.negative=1,z._normSign();var H,F;if(this.length>V.length)H=this,F=V;else H=V,F=this;var D=0;for(var P=0;P<F.length;P++)z=(H.words[P]|0)+(F.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;for(;D!==0&&P<H.length;P++)z=(H.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;if(this.length=H.length,D!==0)this.words[this.length]=D,this.length++;else if(H!==this)for(;P<H.length;P++)this.words[P]=H.words[P];return this},G.prototype.add=function(V){var z;if(V.negative!==0&&this.negative===0)return V.negative=0,z=this.sub(V),V.negative^=1,z;else if(V.negative===0&&this.negative!==0)return this.negative=0,z=V.sub(this),this.negative=1,z;if(this.length>V.length)return this.clone().iadd(V);return V.clone().iadd(this)},G.prototype.isub=function(V){if(V.negative!==0){V.negative=0;var z=this.iadd(V);return V.negative=1,z._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(V),this.negative=1,this._normSign();var H=this.cmp(V);if(H===0)return this.negative=0,this.length=1,this.words[0]=0,this;var F,D;if(H>0)F=this,D=V;else F=V,D=this;var P=0;for(var j=0;j<D.length;j++)z=(F.words[j]|0)-(D.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;for(;P!==0&&j<F.length;j++)z=(F.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;if(P===0&&j<F.length&&F!==this)for(;j<F.length;j++)this.words[j]=F.words[j];if(this.length=Math.max(this.length,j),F!==this)this.negative=1;return this.strip()},G.prototype.sub=function(V){return this.clone().isub(V)};function k(V,z,H){H.negative=z.negative^V.negative;var F=V.length+z.length|0;H.length=F,F=F-1|0;var D=V.words[0]|0,P=z.words[0]|0,j=D*P,R=j&67108863,q=j/67108864|0;H.words[0]=R;for(var E=1;E<F;E++){var N=q>>>26,T=q&67108863,v=Math.min(E,z.length-1);for(var y=Math.max(0,E-V.length+1);y<=v;y++){var p=E-y|0;D=V.words[p]|0,P=z.words[y]|0,j=D*P+T,N+=j/67108864|0,T=j&67108863}H.words[E]=T|0,q=N|0}if(q!==0)H.words[E]=q|0;else H.length--;return H.strip()}var B=function(V,z,H){var F=V.words,D=z.words,P=H.words,j=0,R,q,E,N=F[0]|0,T=N&8191,v=N>>>13,y=F[1]|0,p=y&8191,J0=y>>>13,x0=F[2]|0,K0=x0&8191,Y0=x0>>>13,j0=F[3]|0,$0=j0&8191,D0=j0>>>13,$Q=F[4]|0,m=$Q&8191,n=$Q>>>13,B0=F[5]|0,F0=B0&8191,z0=B0>>>13,l0=F[6]|0,d=l0&8191,X0=l0>>>13,QQ=F[7]|0,V0=QQ&8191,P0=QQ>>>13,jQ=F[8]|0,c0=jQ&8191,u0=jQ>>>13,$Z=F[9]|0,y0=$Z&8191,s=$Z>>>13,M0=D[0]|0,G0=M0&8191,H0=M0>>>13,KQ=D[1]|0,f0=KQ&8191,h0=KQ>>>13,LQ=D[2]|0,E0=LQ&8191,A0=LQ>>>13,GQ=D[3]|0,T0=GQ&8191,S0=GQ>>>13,gQ=D[4]|0,g0=gQ&8191,d0=gQ>>>13,_Z=D[5]|0,o0=_Z&8191,b=_Z>>>13,Q0=D[6]|0,O0=Q0&8191,L0=Q0>>>13,qQ=D[7]|0,m0=qQ&8191,n0=qQ>>>13,lZ=D[8]|0,r0=lZ&8191,e0=lZ>>>13,bY=D[9]|0,t0=bY&8191,a0=bY>>>13;H.negative=V.negative^z.negative,H.length=19,R=Math.imul(T,G0),q=Math.imul(T,H0),q=q+Math.imul(v,G0)|0,E=Math.imul(v,H0);var mZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(mZ>>>26)|0,mZ&=67108863,R=Math.imul(p,G0),q=Math.imul(p,H0),q=q+Math.imul(J0,G0)|0,E=Math.imul(J0,H0),R=R+Math.imul(T,f0)|0,q=q+Math.imul(T,h0)|0,q=q+Math.imul(v,f0)|0,E=E+Math.imul(v,h0)|0;var lQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(lQ>>>26)|0,lQ&=67108863,R=Math.imul(K0,G0),q=Math.imul(K0,H0),q=q+Math.imul(Y0,G0)|0,E=Math.imul(Y0,H0),R=R+Math.imul(p,f0)|0,q=q+Math.imul(p,h0)|0,q=q+Math.imul(J0,f0)|0,E=E+Math.imul(J0,h0)|0,R=R+Math.imul(T,E0)|0,q=q+Math.imul(T,A0)|0,q=q+Math.imul(v,E0)|0,E=E+Math.imul(v,A0)|0;var pQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(pQ>>>26)|0,pQ&=67108863,R=Math.imul($0,G0),q=Math.imul($0,H0),q=q+Math.imul(D0,G0)|0,E=Math.imul(D0,H0),R=R+Math.imul(K0,f0)|0,q=q+Math.imul(K0,h0)|0,q=q+Math.imul(Y0,f0)|0,E=E+Math.imul(Y0,h0)|0,R=R+Math.imul(p,E0)|0,q=q+Math.imul(p,A0)|0,q=q+Math.imul(J0,E0)|0,E=E+Math.imul(J0,A0)|0,R=R+Math.imul(T,T0)|0,q=q+Math.imul(T,S0)|0,q=q+Math.imul(v,T0)|0,E=E+Math.imul(v,S0)|0;var IZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,R=Math.imul(m,G0),q=Math.imul(m,H0),q=q+Math.imul(n,G0)|0,E=Math.imul(n,H0),R=R+Math.imul($0,f0)|0,q=q+Math.imul($0,h0)|0,q=q+Math.imul(D0,f0)|0,E=E+Math.imul(D0,h0)|0,R=R+Math.imul(K0,E0)|0,q=q+Math.imul(K0,A0)|0,q=q+Math.imul(Y0,E0)|0,E=E+Math.imul(Y0,A0)|0,R=R+Math.imul(p,T0)|0,q=q+Math.imul(p,S0)|0,q=q+Math.imul(J0,T0)|0,E=E+Math.imul(J0,S0)|0,R=R+Math.imul(T,g0)|0,q=q+Math.imul(T,d0)|0,q=q+Math.imul(v,g0)|0,E=E+Math.imul(v,d0)|0;var zZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,R=Math.imul(F0,G0),q=Math.imul(F0,H0),q=q+Math.imul(z0,G0)|0,E=Math.imul(z0,H0),R=R+Math.imul(m,f0)|0,q=q+Math.imul(m,h0)|0,q=q+Math.imul(n,f0)|0,E=E+Math.imul(n,h0)|0,R=R+Math.imul($0,E0)|0,q=q+Math.imul($0,A0)|0,q=q+Math.imul(D0,E0)|0,E=E+Math.imul(D0,A0)|0,R=R+Math.imul(K0,T0)|0,q=q+Math.imul(K0,S0)|0,q=q+Math.imul(Y0,T0)|0,E=E+Math.imul(Y0,S0)|0,R=R+Math.imul(p,g0)|0,q=q+Math.imul(p,d0)|0,q=q+Math.imul(J0,g0)|0,E=E+Math.imul(J0,d0)|0,R=R+Math.imul(T,o0)|0,q=q+Math.imul(T,b)|0,q=q+Math.imul(v,o0)|0,E=E+Math.imul(v,b)|0;var $Y=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+($Y>>>26)|0,$Y&=67108863,R=Math.imul(d,G0),q=Math.imul(d,H0),q=q+Math.imul(X0,G0)|0,E=Math.imul(X0,H0),R=R+Math.imul(F0,f0)|0,q=q+Math.imul(F0,h0)|0,q=q+Math.imul(z0,f0)|0,E=E+Math.imul(z0,h0)|0,R=R+Math.imul(m,E0)|0,q=q+Math.imul(m,A0)|0,q=q+Math.imul(n,E0)|0,E=E+Math.imul(n,A0)|0,R=R+Math.imul($0,T0)|0,q=q+Math.imul($0,S0)|0,q=q+Math.imul(D0,T0)|0,E=E+Math.imul(D0,S0)|0,R=R+Math.imul(K0,g0)|0,q=q+Math.imul(K0,d0)|0,q=q+Math.imul(Y0,g0)|0,E=E+Math.imul(Y0,d0)|0,R=R+Math.imul(p,o0)|0,q=q+Math.imul(p,b)|0,q=q+Math.imul(J0,o0)|0,E=E+Math.imul(J0,b)|0,R=R+Math.imul(T,O0)|0,q=q+Math.imul(T,L0)|0,q=q+Math.imul(v,O0)|0,E=E+Math.imul(v,L0)|0;var JY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(JY>>>26)|0,JY&=67108863,R=Math.imul(V0,G0),q=Math.imul(V0,H0),q=q+Math.imul(P0,G0)|0,E=Math.imul(P0,H0),R=R+Math.imul(d,f0)|0,q=q+Math.imul(d,h0)|0,q=q+Math.imul(X0,f0)|0,E=E+Math.imul(X0,h0)|0,R=R+Math.imul(F0,E0)|0,q=q+Math.imul(F0,A0)|0,q=q+Math.imul(z0,E0)|0,E=E+Math.imul(z0,A0)|0,R=R+Math.imul(m,T0)|0,q=q+Math.imul(m,S0)|0,q=q+Math.imul(n,T0)|0,E=E+Math.imul(n,S0)|0,R=R+Math.imul($0,g0)|0,q=q+Math.imul($0,d0)|0,q=q+Math.imul(D0,g0)|0,E=E+Math.imul(D0,d0)|0,R=R+Math.imul(K0,o0)|0,q=q+Math.imul(K0,b)|0,q=q+Math.imul(Y0,o0)|0,E=E+Math.imul(Y0,b)|0,R=R+Math.imul(p,O0)|0,q=q+Math.imul(p,L0)|0,q=q+Math.imul(J0,O0)|0,E=E+Math.imul(J0,L0)|0,R=R+Math.imul(T,m0)|0,q=q+Math.imul(T,n0)|0,q=q+Math.imul(v,m0)|0,E=E+Math.imul(v,n0)|0;var GY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(GY>>>26)|0,GY&=67108863,R=Math.imul(c0,G0),q=Math.imul(c0,H0),q=q+Math.imul(u0,G0)|0,E=Math.imul(u0,H0),R=R+Math.imul(V0,f0)|0,q=q+Math.imul(V0,h0)|0,q=q+Math.imul(P0,f0)|0,E=E+Math.imul(P0,h0)|0,R=R+Math.imul(d,E0)|0,q=q+Math.imul(d,A0)|0,q=q+Math.imul(X0,E0)|0,E=E+Math.imul(X0,A0)|0,R=R+Math.imul(F0,T0)|0,q=q+Math.imul(F0,S0)|0,q=q+Math.imul(z0,T0)|0,E=E+Math.imul(z0,S0)|0,R=R+Math.imul(m,g0)|0,q=q+Math.imul(m,d0)|0,q=q+Math.imul(n,g0)|0,E=E+Math.imul(n,d0)|0,R=R+Math.imul($0,o0)|0,q=q+Math.imul($0,b)|0,q=q+Math.imul(D0,o0)|0,E=E+Math.imul(D0,b)|0,R=R+Math.imul(K0,O0)|0,q=q+Math.imul(K0,L0)|0,q=q+Math.imul(Y0,O0)|0,E=E+Math.imul(Y0,L0)|0,R=R+Math.imul(p,m0)|0,q=q+Math.imul(p,n0)|0,q=q+Math.imul(J0,m0)|0,E=E+Math.imul(J0,n0)|0,R=R+Math.imul(T,r0)|0,q=q+Math.imul(T,e0)|0,q=q+Math.imul(v,r0)|0,E=E+Math.imul(v,e0)|0;var XY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(XY>>>26)|0,XY&=67108863,R=Math.imul(y0,G0),q=Math.imul(y0,H0),q=q+Math.imul(s,G0)|0,E=Math.imul(s,H0),R=R+Math.imul(c0,f0)|0,q=q+Math.imul(c0,h0)|0,q=q+Math.imul(u0,f0)|0,E=E+Math.imul(u0,h0)|0,R=R+Math.imul(V0,E0)|0,q=q+Math.imul(V0,A0)|0,q=q+Math.imul(P0,E0)|0,E=E+Math.imul(P0,A0)|0,R=R+Math.imul(d,T0)|0,q=q+Math.imul(d,S0)|0,q=q+Math.imul(X0,T0)|0,E=E+Math.imul(X0,S0)|0,R=R+Math.imul(F0,g0)|0,q=q+Math.imul(F0,d0)|0,q=q+Math.imul(z0,g0)|0,E=E+Math.imul(z0,d0)|0,R=R+Math.imul(m,o0)|0,q=q+Math.imul(m,b)|0,q=q+Math.imul(n,o0)|0,E=E+Math.imul(n,b)|0,R=R+Math.imul($0,O0)|0,q=q+Math.imul($0,L0)|0,q=q+Math.imul(D0,O0)|0,E=E+Math.imul(D0,L0)|0,R=R+Math.imul(K0,m0)|0,q=q+Math.imul(K0,n0)|0,q=q+Math.imul(Y0,m0)|0,E=E+Math.imul(Y0,n0)|0,R=R+Math.imul(p,r0)|0,q=q+Math.imul(p,e0)|0,q=q+Math.imul(J0,r0)|0,E=E+Math.imul(J0,e0)|0,R=R+Math.imul(T,t0)|0,q=q+Math.imul(T,a0)|0,q=q+Math.imul(v,t0)|0,E=E+Math.imul(v,a0)|0;var VY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(VY>>>26)|0,VY&=67108863,R=Math.imul(y0,f0),q=Math.imul(y0,h0),q=q+Math.imul(s,f0)|0,E=Math.imul(s,h0),R=R+Math.imul(c0,E0)|0,q=q+Math.imul(c0,A0)|0,q=q+Math.imul(u0,E0)|0,E=E+Math.imul(u0,A0)|0,R=R+Math.imul(V0,T0)|0,q=q+Math.imul(V0,S0)|0,q=q+Math.imul(P0,T0)|0,E=E+Math.imul(P0,S0)|0,R=R+Math.imul(d,g0)|0,q=q+Math.imul(d,d0)|0,q=q+Math.imul(X0,g0)|0,E=E+Math.imul(X0,d0)|0,R=R+Math.imul(F0,o0)|0,q=q+Math.imul(F0,b)|0,q=q+Math.imul(z0,o0)|0,E=E+Math.imul(z0,b)|0,R=R+Math.imul(m,O0)|0,q=q+Math.imul(m,L0)|0,q=q+Math.imul(n,O0)|0,E=E+Math.imul(n,L0)|0,R=R+Math.imul($0,m0)|0,q=q+Math.imul($0,n0)|0,q=q+Math.imul(D0,m0)|0,E=E+Math.imul(D0,n0)|0,R=R+Math.imul(K0,r0)|0,q=q+Math.imul(K0,e0)|0,q=q+Math.imul(Y0,r0)|0,E=E+Math.imul(Y0,e0)|0,R=R+Math.imul(p,t0)|0,q=q+Math.imul(p,a0)|0,q=q+Math.imul(J0,t0)|0,E=E+Math.imul(J0,a0)|0;var qY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(qY>>>26)|0,qY&=67108863,R=Math.imul(y0,E0),q=Math.imul(y0,A0),q=q+Math.imul(s,E0)|0,E=Math.imul(s,A0),R=R+Math.imul(c0,T0)|0,q=q+Math.imul(c0,S0)|0,q=q+Math.imul(u0,T0)|0,E=E+Math.imul(u0,S0)|0,R=R+Math.imul(V0,g0)|0,q=q+Math.imul(V0,d0)|0,q=q+Math.imul(P0,g0)|0,E=E+Math.imul(P0,d0)|0,R=R+Math.imul(d,o0)|0,q=q+Math.imul(d,b)|0,q=q+Math.imul(X0,o0)|0,E=E+Math.imul(X0,b)|0,R=R+Math.imul(F0,O0)|0,q=q+Math.imul(F0,L0)|0,q=q+Math.imul(z0,O0)|0,E=E+Math.imul(z0,L0)|0,R=R+Math.imul(m,m0)|0,q=q+Math.imul(m,n0)|0,q=q+Math.imul(n,m0)|0,E=E+Math.imul(n,n0)|0,R=R+Math.imul($0,r0)|0,q=q+Math.imul($0,e0)|0,q=q+Math.imul(D0,r0)|0,E=E+Math.imul(D0,e0)|0,R=R+Math.imul(K0,t0)|0,q=q+Math.imul(K0,a0)|0,q=q+Math.imul(Y0,t0)|0,E=E+Math.imul(Y0,a0)|0;var FY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(FY>>>26)|0,FY&=67108863,R=Math.imul(y0,T0),q=Math.imul(y0,S0),q=q+Math.imul(s,T0)|0,E=Math.imul(s,S0),R=R+Math.imul(c0,g0)|0,q=q+Math.imul(c0,d0)|0,q=q+Math.imul(u0,g0)|0,E=E+Math.imul(u0,d0)|0,R=R+Math.imul(V0,o0)|0,q=q+Math.imul(V0,b)|0,q=q+Math.imul(P0,o0)|0,E=E+Math.imul(P0,b)|0,R=R+Math.imul(d,O0)|0,q=q+Math.imul(d,L0)|0,q=q+Math.imul(X0,O0)|0,E=E+Math.imul(X0,L0)|0,R=R+Math.imul(F0,m0)|0,q=q+Math.imul(F0,n0)|0,q=q+Math.imul(z0,m0)|0,E=E+Math.imul(z0,n0)|0,R=R+Math.imul(m,r0)|0,q=q+Math.imul(m,e0)|0,q=q+Math.imul(n,r0)|0,E=E+Math.imul(n,e0)|0,R=R+Math.imul($0,t0)|0,q=q+Math.imul($0,a0)|0,q=q+Math.imul(D0,t0)|0,E=E+Math.imul(D0,a0)|0;var zY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zY>>>26)|0,zY&=67108863,R=Math.imul(y0,g0),q=Math.imul(y0,d0),q=q+Math.imul(s,g0)|0,E=Math.imul(s,d0),R=R+Math.imul(c0,o0)|0,q=q+Math.imul(c0,b)|0,q=q+Math.imul(u0,o0)|0,E=E+Math.imul(u0,b)|0,R=R+Math.imul(V0,O0)|0,q=q+Math.imul(V0,L0)|0,q=q+Math.imul(P0,O0)|0,E=E+Math.imul(P0,L0)|0,R=R+Math.imul(d,m0)|0,q=q+Math.imul(d,n0)|0,q=q+Math.imul(X0,m0)|0,E=E+Math.imul(X0,n0)|0,R=R+Math.imul(F0,r0)|0,q=q+Math.imul(F0,e0)|0,q=q+Math.imul(z0,r0)|0,E=E+Math.imul(z0,e0)|0,R=R+Math.imul(m,t0)|0,q=q+Math.imul(m,a0)|0,q=q+Math.imul(n,t0)|0,E=E+Math.imul(n,a0)|0;var WY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(WY>>>26)|0,WY&=67108863,R=Math.imul(y0,o0),q=Math.imul(y0,b),q=q+Math.imul(s,o0)|0,E=Math.imul(s,b),R=R+Math.imul(c0,O0)|0,q=q+Math.imul(c0,L0)|0,q=q+Math.imul(u0,O0)|0,E=E+Math.imul(u0,L0)|0,R=R+Math.imul(V0,m0)|0,q=q+Math.imul(V0,n0)|0,q=q+Math.imul(P0,m0)|0,E=E+Math.imul(P0,n0)|0,R=R+Math.imul(d,r0)|0,q=q+Math.imul(d,e0)|0,q=q+Math.imul(X0,r0)|0,E=E+Math.imul(X0,e0)|0,R=R+Math.imul(F0,t0)|0,q=q+Math.imul(F0,a0)|0,q=q+Math.imul(z0,t0)|0,E=E+Math.imul(z0,a0)|0;var KY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(KY>>>26)|0,KY&=67108863,R=Math.imul(y0,O0),q=Math.imul(y0,L0),q=q+Math.imul(s,O0)|0,E=Math.imul(s,L0),R=R+Math.imul(c0,m0)|0,q=q+Math.imul(c0,n0)|0,q=q+Math.imul(u0,m0)|0,E=E+Math.imul(u0,n0)|0,R=R+Math.imul(V0,r0)|0,q=q+Math.imul(V0,e0)|0,q=q+Math.imul(P0,r0)|0,E=E+Math.imul(P0,e0)|0,R=R+Math.imul(d,t0)|0,q=q+Math.imul(d,a0)|0,q=q+Math.imul(X0,t0)|0,E=E+Math.imul(X0,a0)|0;var UY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(UY>>>26)|0,UY&=67108863,R=Math.imul(y0,m0),q=Math.imul(y0,n0),q=q+Math.imul(s,m0)|0,E=Math.imul(s,n0),R=R+Math.imul(c0,r0)|0,q=q+Math.imul(c0,e0)|0,q=q+Math.imul(u0,r0)|0,E=E+Math.imul(u0,e0)|0,R=R+Math.imul(V0,t0)|0,q=q+Math.imul(V0,a0)|0,q=q+Math.imul(P0,t0)|0,E=E+Math.imul(P0,a0)|0;var OY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(OY>>>26)|0,OY&=67108863,R=Math.imul(y0,r0),q=Math.imul(y0,e0),q=q+Math.imul(s,r0)|0,E=Math.imul(s,e0),R=R+Math.imul(c0,t0)|0,q=q+Math.imul(c0,a0)|0,q=q+Math.imul(u0,t0)|0,E=E+Math.imul(u0,a0)|0;var HY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(HY>>>26)|0,HY&=67108863,R=Math.imul(y0,t0),q=Math.imul(y0,a0),q=q+Math.imul(s,t0)|0,E=Math.imul(s,a0);var DY=(j+R|0)+((q&8191)<<13)|0;if(j=(E+(q>>>13)|0)+(DY>>>26)|0,DY&=67108863,P[0]=mZ,P[1]=lQ,P[2]=pQ,P[3]=IZ,P[4]=zZ,P[5]=$Y,P[6]=JY,P[7]=GY,P[8]=XY,P[9]=VY,P[10]=qY,P[11]=FY,P[12]=zY,P[13]=WY,P[14]=KY,P[15]=UY,P[16]=OY,P[17]=HY,P[18]=DY,j!==0)P[19]=j,H.length++;return H};if(!Math.imul)B=k;function C(V,z,H){H.negative=z.negative^V.negative,H.length=V.length+z.length;var F=0,D=0;for(var P=0;P<H.length-1;P++){var j=D;D=0;var R=F&67108863,q=Math.min(P,z.length-1);for(var E=Math.max(0,P-V.length+1);E<=q;E++){var N=P-E,T=V.words[N]|0,v=z.words[E]|0,y=T*v,p=y&67108863;j=j+(y/67108864|0)|0,p=p+R|0,R=p&67108863,j=j+(p>>>26)|0,D+=j>>>26,j&=67108863}H.words[P]=R,F=j,j=D}if(F!==0)H.words[P]=F;else H.length--;return H.strip()}function S(V,z,H){var F=new _;return F.mulp(V,z,H)}G.prototype.mulTo=function(V,z){var H,F=this.length+V.length;if(this.length===10&&V.length===10)H=B(this,V,z);else if(F<63)H=k(this,V,z);else if(F<1024)H=C(this,V,z);else H=S(this,V,z);return H};function _(V,z){this.x=V,this.y=z}_.prototype.makeRBT=function(V){var z=Array(V),H=G.prototype._countBits(V)-1;for(var F=0;F<V;F++)z[F]=this.revBin(F,H,V);return z},_.prototype.revBin=function(V,z,H){if(V===0||V===H-1)return V;var F=0;for(var D=0;D<z;D++)F|=(V&1)<<z-D-1,V>>=1;return F},_.prototype.permute=function(V,z,H,F,D,P){for(var j=0;j<P;j++)F[j]=z[V[j]],D[j]=H[V[j]]},_.prototype.transform=function(V,z,H,F,D,P){this.permute(P,V,z,H,F,D);for(var j=1;j<D;j<<=1){var R=j<<1,q=Math.cos(2*Math.PI/R),E=Math.sin(2*Math.PI/R);for(var N=0;N<D;N+=R){var T=q,v=E;for(var y=0;y<j;y++){var p=H[N+y],J0=F[N+y],x0=H[N+y+j],K0=F[N+y+j],Y0=T*x0-v*K0;if(K0=T*K0+v*x0,x0=Y0,H[N+y]=p+x0,F[N+y]=J0+K0,H[N+y+j]=p-x0,F[N+y+j]=J0-K0,y!==R)Y0=q*T-E*v,v=q*v+E*T,T=Y0}}}},_.prototype.guessLen13b=function(V,z){var H=Math.max(z,V)|1,F=H&1,D=0;for(H=H/2|0;H;H=H>>>1)D++;return 1<<D+1+F},_.prototype.conjugate=function(V,z,H){if(H<=1)return;for(var F=0;F<H/2;F++){var D=V[F];V[F]=V[H-F-1],V[H-F-1]=D,D=z[F],z[F]=-z[H-F-1],z[H-F-1]=-D}},_.prototype.normalize13b=function(V,z){var H=0;for(var F=0;F<z/2;F++){var D=Math.round(V[2*F+1]/z)*8192+Math.round(V[2*F]/z)+H;if(V[F]=D&67108863,D<67108864)H=0;else H=D/67108864|0}return V},_.prototype.convert13b=function(V,z,H,F){var D=0;for(var P=0;P<z;P++)D=D+(V[P]|0),H[2*P]=D&8191,D=D>>>13,H[2*P+1]=D&8191,D=D>>>13;for(P=2*z;P<F;++P)H[P]=0;J(D===0),J((D&-8192)===0)},_.prototype.stub=function(V){var z=Array(V);for(var H=0;H<V;H++)z[H]=0;return z},_.prototype.mulp=function(V,z,H){var F=2*this.guessLen13b(V.length,z.length),D=this.makeRBT(F),P=this.stub(F),j=Array(F),R=Array(F),q=Array(F),E=Array(F),N=Array(F),T=Array(F),v=H.words;v.length=F,this.convert13b(V.words,V.length,j,F),this.convert13b(z.words,z.length,E,F),this.transform(j,P,R,q,F,D),this.transform(E,P,N,T,F,D);for(var y=0;y<F;y++){var p=R[y]*N[y]-q[y]*T[y];q[y]=R[y]*T[y]+q[y]*N[y],R[y]=p}return this.conjugate(R,q,F),this.transform(R,q,v,P,F,D),this.conjugate(v,P,F),this.normalize13b(v,F),H.negative=V.negative^z.negative,H.length=V.length+z.length,H.strip()},G.prototype.mul=function(V){var z=new G(null);return z.words=Array(this.length+V.length),this.mulTo(V,z)},G.prototype.mulf=function(V){var z=new G(null);return z.words=Array(this.length+V.length),S(this,V,z)},G.prototype.imul=function(V){return this.clone().mulTo(V,this)},G.prototype.imuln=function(V){J(typeof V==="number"),J(V<67108864);var z=0;for(var H=0;H<this.length;H++){var F=(this.words[H]|0)*V,D=(F&67108863)+(z&67108863);z>>=26,z+=F/67108864|0,z+=D>>>26,this.words[H]=D&67108863}if(z!==0)this.words[H]=z,this.length++;return this.length=V===0?1:this.length,this},G.prototype.muln=function(V){return this.clone().imuln(V)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(V){var z=M(V);if(z.length===0)return new G(1);var H=this;for(var F=0;F<z.length;F++,H=H.sqr())if(z[F]!==0)break;if(++F<z.length)for(var D=H.sqr();F<z.length;F++,D=D.sqr()){if(z[F]===0)continue;H=H.mul(D)}return H},G.prototype.iushln=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=67108863>>>26-z<<26-z,D;if(z!==0){var P=0;for(D=0;D<this.length;D++){var j=this.words[D]&F,R=(this.words[D]|0)-j<<z;this.words[D]=R|P,P=j>>>26-z}if(P)this.words[D]=P,this.length++}if(H!==0){for(D=this.length-1;D>=0;D--)this.words[D+H]=this.words[D];for(D=0;D<H;D++)this.words[D]=0;this.length+=H}return this.strip()},G.prototype.ishln=function(V){return J(this.negative===0),this.iushln(V)},G.prototype.iushrn=function(V,z,H){J(typeof V==="number"&&V>=0);var F;if(z)F=(z-z%26)/26;else F=0;var D=V%26,P=Math.min((V-D)/26,this.length),j=67108863^67108863>>>D<<D,R=H;if(F-=P,F=Math.max(0,F),R){for(var q=0;q<P;q++)R.words[q]=this.words[q];R.length=P}if(P===0);else if(this.length>P){this.length-=P;for(q=0;q<this.length;q++)this.words[q]=this.words[q+P]}else this.words[0]=0,this.length=1;var E=0;for(q=this.length-1;q>=0&&(E!==0||q>=F);q--){var N=this.words[q]|0;this.words[q]=E<<26-D|N>>>D,E=N&j}if(R&&E!==0)R.words[R.length++]=E;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},G.prototype.ishrn=function(V,z,H){return J(this.negative===0),this.iushrn(V,z,H)},G.prototype.shln=function(V){return this.clone().ishln(V)},G.prototype.ushln=function(V){return this.clone().iushln(V)},G.prototype.shrn=function(V){return this.clone().ishrn(V)},G.prototype.ushrn=function(V){return this.clone().iushrn(V)},G.prototype.testn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return!1;var D=this.words[H];return!!(D&F)},G.prototype.imaskn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26;if(J(this.negative===0,"imaskn works only with positive numbers"),this.length<=H)return this;if(z!==0)H++;if(this.length=Math.min(H,this.length),z!==0){var F=67108863^67108863>>>z<<z;this.words[this.length-1]&=F}return this.strip()},G.prototype.maskn=function(V){return this.clone().imaskn(V)},G.prototype.iaddn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.isubn(-V);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<V)return this.words[0]=V-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(V),this.negative=1,this}return this._iaddn(V)},G.prototype._iaddn=function(V){this.words[0]+=V;for(var z=0;z<this.length&&this.words[z]>=67108864;z++)if(this.words[z]-=67108864,z===this.length-1)this.words[z+1]=1;else this.words[z+1]++;return this.length=Math.max(this.length,z+1),this},G.prototype.isubn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.iaddn(-V);if(this.negative!==0)return this.negative=0,this.iaddn(V),this.negative=1,this;if(this.words[0]-=V,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var z=0;z<this.length&&this.words[z]<0;z++)this.words[z]+=67108864,this.words[z+1]-=1;return this.strip()},G.prototype.addn=function(V){return this.clone().iaddn(V)},G.prototype.subn=function(V){return this.clone().isubn(V)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(V,z,H){var F=V.length+H,D;this._expand(F);var P,j=0;for(D=0;D<V.length;D++){P=(this.words[D+H]|0)+j;var R=(V.words[D]|0)*z;P-=R&67108863,j=(P>>26)-(R/67108864|0),this.words[D+H]=P&67108863}for(;D<this.length-H;D++)P=(this.words[D+H]|0)+j,j=P>>26,this.words[D+H]=P&67108863;if(j===0)return this.strip();J(j===-1),j=0;for(D=0;D<this.length;D++)P=-(this.words[D]|0)+j,j=P>>26,this.words[D]=P&67108863;return this.negative=1,this.strip()},G.prototype._wordDiv=function(V,z){var H=this.length-V.length,F=this.clone(),D=V,P=D.words[D.length-1]|0,j=this._countBits(P);if(H=26-j,H!==0)D=D.ushln(H),F.iushln(H),P=D.words[D.length-1]|0;var R=F.length-D.length,q;if(z!=="mod"){q=new G(null),q.length=R+1,q.words=Array(q.length);for(var E=0;E<q.length;E++)q.words[E]=0}var N=F.clone()._ishlnsubmul(D,1,R);if(N.negative===0){if(F=N,q)q.words[R]=1}for(var T=R-1;T>=0;T--){var v=(F.words[D.length+T]|0)*67108864+(F.words[D.length+T-1]|0);v=Math.min(v/P|0,67108863),F._ishlnsubmul(D,v,T);while(F.negative!==0)if(v--,F.negative=0,F._ishlnsubmul(D,1,T),!F.isZero())F.negative^=1;if(q)q.words[T]=v}if(q)q.strip();if(F.strip(),z!=="div"&&H!==0)F.iushrn(H);return{div:q||null,mod:F}},G.prototype.divmod=function(V,z,H){if(J(!V.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var F,D,P;if(this.negative!==0&&V.negative===0){if(P=this.neg().divmod(V,z),z!=="mod")F=P.div.neg();if(z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.iadd(V)}return{div:F,mod:D}}if(this.negative===0&&V.negative!==0){if(P=this.divmod(V.neg(),z),z!=="mod")F=P.div.neg();return{div:F,mod:P.mod}}if((this.negative&V.negative)!==0){if(P=this.neg().divmod(V.neg(),z),z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.isub(V)}return{div:P.div,mod:D}}if(V.length>this.length||this.cmp(V)<0)return{div:new G(0),mod:this};if(V.length===1){if(z==="div")return{div:this.divn(V.words[0]),mod:null};if(z==="mod")return{div:null,mod:new G(this.modn(V.words[0]))};return{div:this.divn(V.words[0]),mod:new G(this.modn(V.words[0]))}}return this._wordDiv(V,z)},G.prototype.div=function(V){return this.divmod(V,"div",!1).div},G.prototype.mod=function(V){return this.divmod(V,"mod",!1).mod},G.prototype.umod=function(V){return this.divmod(V,"mod",!0).mod},G.prototype.divRound=function(V){var z=this.divmod(V);if(z.mod.isZero())return z.div;var H=z.div.negative!==0?z.mod.isub(V):z.mod,F=V.ushrn(1),D=V.andln(1),P=H.cmp(F);if(P<0||D===1&&P===0)return z.div;return z.div.negative!==0?z.div.isubn(1):z.div.iaddn(1)},G.prototype.modn=function(V){J(V<=67108863);var z=67108864%V,H=0;for(var F=this.length-1;F>=0;F--)H=(z*H+(this.words[F]|0))%V;return H},G.prototype.idivn=function(V){J(V<=67108863);var z=0;for(var H=this.length-1;H>=0;H--){var F=(this.words[H]|0)+z*67108864;this.words[H]=F/V|0,z=F%V}return this.strip()},G.prototype.divn=function(V){return this.clone().idivn(V)},G.prototype.egcd=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=new G(0),j=new G(1),R=0;while(z.isEven()&&H.isEven())z.iushrn(1),H.iushrn(1),++R;var q=H.clone(),E=z.clone();while(!z.isZero()){for(var N=0,T=1;(z.words[0]&T)===0&&N<26;++N,T<<=1);if(N>0){z.iushrn(N);while(N-- >0){if(F.isOdd()||D.isOdd())F.iadd(q),D.isub(E);F.iushrn(1),D.iushrn(1)}}for(var v=0,y=1;(H.words[0]&y)===0&&v<26;++v,y<<=1);if(v>0){H.iushrn(v);while(v-- >0){if(P.isOdd()||j.isOdd())P.iadd(q),j.isub(E);P.iushrn(1),j.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(P),D.isub(j);else H.isub(z),P.isub(F),j.isub(D)}return{a:P,b:j,gcd:H.iushln(R)}},G.prototype._invmp=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=H.clone();while(z.cmpn(1)>0&&H.cmpn(1)>0){for(var j=0,R=1;(z.words[0]&R)===0&&j<26;++j,R<<=1);if(j>0){z.iushrn(j);while(j-- >0){if(F.isOdd())F.iadd(P);F.iushrn(1)}}for(var q=0,E=1;(H.words[0]&E)===0&&q<26;++q,E<<=1);if(q>0){H.iushrn(q);while(q-- >0){if(D.isOdd())D.iadd(P);D.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(D);else H.isub(z),D.isub(F)}var N;if(z.cmpn(1)===0)N=F;else N=D;if(N.cmpn(0)<0)N.iadd(V);return N},G.prototype.gcd=function(V){if(this.isZero())return V.abs();if(V.isZero())return this.abs();var z=this.clone(),H=V.clone();z.negative=0,H.negative=0;for(var F=0;z.isEven()&&H.isEven();F++)z.iushrn(1),H.iushrn(1);do{while(z.isEven())z.iushrn(1);while(H.isEven())H.iushrn(1);var D=z.cmp(H);if(D<0){var P=z;z=H,H=P}else if(D===0||H.cmpn(1)===0)break;z.isub(H)}while(!0);return H.iushln(F)},G.prototype.invm=function(V){return this.egcd(V).a.umod(V)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(V){return this.words[0]&V},G.prototype.bincn=function(V){J(typeof V==="number");var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return this._expand(H+1),this.words[H]|=F,this;var D=F;for(var P=H;D!==0&&P<this.length;P++){var j=this.words[P]|0;j+=D,D=j>>>26,j&=67108863,this.words[P]=j}if(D!==0)this.words[P]=D,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(V){var z=V<0;if(this.negative!==0&&!z)return-1;if(this.negative===0&&z)return 1;this.strip();var H;if(this.length>1)H=1;else{if(z)V=-V;J(V<=67108863,"Number is too big");var F=this.words[0]|0;H=F===V?0:F<V?-1:1}if(this.negative!==0)return-H|0;return H},G.prototype.cmp=function(V){if(this.negative!==0&&V.negative===0)return-1;if(this.negative===0&&V.negative!==0)return 1;var z=this.ucmp(V);if(this.negative!==0)return-z|0;return z},G.prototype.ucmp=function(V){if(this.length>V.length)return 1;if(this.length<V.length)return-1;var z=0;for(var H=this.length-1;H>=0;H--){var F=this.words[H]|0,D=V.words[H]|0;if(F===D)continue;if(F<D)z=-1;else if(F>D)z=1;break}return z},G.prototype.gtn=function(V){return this.cmpn(V)===1},G.prototype.gt=function(V){return this.cmp(V)===1},G.prototype.gten=function(V){return this.cmpn(V)>=0},G.prototype.gte=function(V){return this.cmp(V)>=0},G.prototype.ltn=function(V){return this.cmpn(V)===-1},G.prototype.lt=function(V){return this.cmp(V)===-1},G.prototype.lten=function(V){return this.cmpn(V)<=0},G.prototype.lte=function(V){return this.cmp(V)<=0},G.prototype.eqn=function(V){return this.cmpn(V)===0},G.prototype.eq=function(V){return this.cmp(V)===0},G.red=function(V){return new c(V)},G.prototype.toRed=function(V){return J(!this.red,"Already a number in reduction context"),J(this.negative===0,"red works only with positives"),V.convertTo(this)._forceRed(V)},G.prototype.fromRed=function(){return J(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(V){return this.red=V,this},G.prototype.forceRed=function(V){return J(!this.red,"Already a number in reduction context"),this._forceRed(V)},G.prototype.redAdd=function(V){return J(this.red,"redAdd works only with red numbers"),this.red.add(this,V)},G.prototype.redIAdd=function(V){return J(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,V)},G.prototype.redSub=function(V){return J(this.red,"redSub works only with red numbers"),this.red.sub(this,V)},G.prototype.redISub=function(V){return J(this.red,"redISub works only with red numbers"),this.red.isub(this,V)},G.prototype.redShl=function(V){return J(this.red,"redShl works only with red numbers"),this.red.shl(this,V)},G.prototype.redMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.mul(this,V)},G.prototype.redIMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.imul(this,V)},G.prototype.redSqr=function(){return J(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return J(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return J(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return J(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return J(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(V){return J(this.red&&!V.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,V)};var x={k256:null,p224:null,p192:null,p25519:null};function f(V,z){this.name=V,this.p=new G(z,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}f.prototype._tmp=function(){var V=new G(null);return V.words=Array(Math.ceil(this.n/13)),V},f.prototype.ireduce=function(V){var z=V,H;do this.split(z,this.tmp),z=this.imulK(z),z=z.iadd(this.tmp),H=z.bitLength();while(H>this.n);var F=H<this.n?-1:z.ucmp(this.p);if(F===0)z.words[0]=0,z.length=1;else if(F>0)z.isub(this.p);else if(z.strip!==void 0)z.strip();else z._strip();return z},f.prototype.split=function(V,z){V.iushrn(this.n,0,z)},f.prototype.imulK=function(V){return V.imul(this.k)};function h(){f.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,f),h.prototype.split=function(V,z){var H=4194303,F=Math.min(V.length,9);for(var D=0;D<F;D++)z.words[D]=V.words[D];if(z.length=F,V.length<=9){V.words[0]=0,V.length=1;return}var P=V.words[9];z.words[z.length++]=P&H;for(D=10;D<V.length;D++){var j=V.words[D]|0;V.words[D-10]=(j&H)<<4|P>>>22,P=j}if(P>>>=22,V.words[D-10]=P,P===0&&V.length>10)V.length-=10;else V.length-=9},h.prototype.imulK=function(V){V.words[V.length]=0,V.words[V.length+1]=0,V.length+=2;var z=0;for(var H=0;H<V.length;H++){var F=V.words[H]|0;z+=F*977,V.words[H]=z&67108863,z=F*64+(z/67108864|0)}if(V.words[V.length-1]===0){if(V.length--,V.words[V.length-1]===0)V.length--}return V};function i(){f.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(i,f);function Z0(){f.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(Z0,f);function t(){f.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(t,f),t.prototype.imulK=function(V){var z=0;for(var H=0;H<V.length;H++){var F=(V.words[H]|0)*19+z,D=F&67108863;F>>>=26,V.words[H]=D,z=F}if(z!==0)V.words[V.length++]=z;return V},G._prime=function(V){if(x[V])return x[V];var z;if(V==="k256")z=new h;else if(V==="p224")z=new i;else if(V==="p192")z=new Z0;else if(V==="p25519")z=new t;else throw Error("Unknown prime "+V);return x[V]=z,z};function c(V){if(typeof V==="string"){var z=G._prime(V);this.m=z.p,this.prime=z}else J(V.gtn(1),"modulus must be greater than 1"),this.m=V,this.prime=null}c.prototype._verify1=function(V){J(V.negative===0,"red works only with positives"),J(V.red,"red works only with red numbers")},c.prototype._verify2=function(V,z){J((V.negative|z.negative)===0,"red works only with positives"),J(V.red&&V.red===z.red,"red works only with red numbers")},c.prototype.imod=function(V){if(this.prime)return this.prime.ireduce(V)._forceRed(this);return V.umod(this.m)._forceRed(this)},c.prototype.neg=function(V){if(V.isZero())return V.clone();return this.m.sub(V)._forceRed(this)},c.prototype.add=function(V,z){this._verify2(V,z);var H=V.add(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H._forceRed(this)},c.prototype.iadd=function(V,z){this._verify2(V,z);var H=V.iadd(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H},c.prototype.sub=function(V,z){this._verify2(V,z);var H=V.sub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H._forceRed(this)},c.prototype.isub=function(V,z){this._verify2(V,z);var H=V.isub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H},c.prototype.shl=function(V,z){return this._verify1(V),this.imod(V.ushln(z))},c.prototype.imul=function(V,z){return this._verify2(V,z),this.imod(V.imul(z))},c.prototype.mul=function(V,z){return this._verify2(V,z),this.imod(V.mul(z))},c.prototype.isqr=function(V){return this.imul(V,V.clone())},c.prototype.sqr=function(V){return this.mul(V,V)},c.prototype.sqrt=function(V){if(V.isZero())return V.clone();var z=this.m.andln(3);if(J(z%2===1),z===3){var H=this.m.add(new G(1)).iushrn(2);return this.pow(V,H)}var F=this.m.subn(1),D=0;while(!F.isZero()&&F.andln(1)===0)D++,F.iushrn(1);J(!F.isZero());var P=new G(1).toRed(this),j=P.redNeg(),R=this.m.subn(1).iushrn(1),q=this.m.bitLength();q=new G(2*q*q).toRed(this);while(this.pow(q,R).cmp(j)!==0)q.redIAdd(j);var E=this.pow(q,F),N=this.pow(V,F.addn(1).iushrn(1)),T=this.pow(V,F),v=D;while(T.cmp(P)!==0){var y=T;for(var p=0;y.cmp(P)!==0;p++)y=y.redSqr();J(p<v);var J0=this.pow(E,new G(1).iushln(v-p-1));N=N.redMul(J0),E=J0.redSqr(),T=T.redMul(E),v=p}return N},c.prototype.invm=function(V){var z=V._invmp(this.m);if(z.negative!==0)return z.negative=0,this.imod(z).redNeg();else return this.imod(z)},c.prototype.pow=function(V,z){if(z.isZero())return new G(1).toRed(this);if(z.cmpn(1)===0)return V.clone();var H=4,F=Array(1<<H);F[0]=new G(1).toRed(this),F[1]=V;for(var D=2;D<F.length;D++)F[D]=this.mul(F[D-1],V);var P=F[0],j=0,R=0,q=z.bitLength()%26;if(q===0)q=26;for(D=z.length-1;D>=0;D--){var E=z.words[D];for(var N=q-1;N>=0;N--){var T=E>>N&1;if(P!==F[0])P=this.sqr(P);if(T===0&&j===0){R=0;continue}if(j<<=1,j|=T,R++,R!==H&&(D!==0||N!==0))continue;P=this.mul(P,F[j]),R=0,j=0}q=26}return P},c.prototype.convertTo=function(V){var z=V.umod(this.m);return z===V?z.clone():z},c.prototype.convertFrom=function(V){var z=V.clone();return z.red=null,z},G.mont=function(V){return new l(V)};function l(V){if(c.call(this,V),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(l,c),l.prototype.convertTo=function(V){return this.imod(V.ushln(this.shift))},l.prototype.convertFrom=function(V){var z=this.imod(V.mul(this.rinv));return z.red=null,z},l.prototype.imul=function(V,z){if(V.isZero()||z.isZero())return V.words[0]=0,V.length=1,V;var H=V.imul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.mul=function(V,z){if(V.isZero()||z.isZero())return new G(0)._forceRed(this);var H=V.mul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.invm=function(V){var z=this.imod(V._invmp(this.m).mul(this.r2));return z._forceRed(this)}})(typeof Z>"u"||Z,Q)}),Fe=v0((Q)=>{var Z=i6(),Y=YJ(),$=Q;$.define=function(X,G){return new J(X,G)};function J(X,G){this.name=X,this.body=G,this.decoders={},this.encoders={}}J.prototype._createNamed=function(X){var G;try{G=(()=>{throw new Error("Cannot require module "+"vm");})().runInThisContext("(function "+this.name+`(entity) {
|
|
85
|
+
this._initNamed(entity);
|
|
86
|
+
})`)}catch(W){G=function(U){this._initNamed(U)}}return Y(G,X),G.prototype._initNamed=function(W){X.call(this,W)},new G(this)},J.prototype._getDecoder=function(X){if(X=X||"der",!this.decoders.hasOwnProperty(X))this.decoders[X]=this._createNamed(Z.decoders[X]);return this.decoders[X]},J.prototype.decode=function(X,G,W){return this._getDecoder(G).decode(X,W)},J.prototype._getEncoder=function(X){if(X=X||"der",!this.encoders.hasOwnProperty(X))this.encoders[X]=this._createNamed(Z.encoders[X]);return this.encoders[X]},J.prototype.encode=function(X,G,W){return this._getEncoder(G).encode(X,W)}}),ze=v0((Q)=>{var Z=YJ();function Y(J){this._reporterState={obj:null,path:[],options:J||{},errors:[]}}Q.Reporter=Y,Y.prototype.isError=function(J){return J instanceof $},Y.prototype.save=function(){var J=this._reporterState;return{obj:J.obj,pathLen:J.path.length}},Y.prototype.restore=function(J){var X=this._reporterState;X.obj=J.obj,X.path=X.path.slice(0,J.pathLen)},Y.prototype.enterKey=function(J){return this._reporterState.path.push(J)},Y.prototype.exitKey=function(J){var X=this._reporterState;X.path=X.path.slice(0,J-1)},Y.prototype.leaveKey=function(J,X,G){var W=this._reporterState;if(this.exitKey(J),W.obj!==null)W.obj[X]=G},Y.prototype.path=function(){return this._reporterState.path.join("/")},Y.prototype.enterObject=function(){var J=this._reporterState,X=J.obj;return J.obj={},X},Y.prototype.leaveObject=function(J){var X=this._reporterState,G=X.obj;return X.obj=J,G},Y.prototype.error=function(J){var X,G=this._reporterState,W=J instanceof $;if(W)X=J;else X=new $(G.path.map(function(U){return"["+JSON.stringify(U)+"]"}).join(""),J.message||J,J.stack);if(!G.options.partial)throw X;if(!W)G.errors.push(X);return X},Y.prototype.wrapResult=function(J){var X=this._reporterState;if(!X.options.partial)return J;return{result:this.isError(J)?null:J,errors:X.errors}};function $(J,X){this.path=J,this.rethrow(X)}Z($,Error),$.prototype.rethrow=function(J){if(this.message=J+" at: "+(this.path||"(shallow)"),Error.captureStackTrace)Error.captureStackTrace(this,$);if(!this.stack)try{throw Error(this.message)}catch(X){this.stack=X.stack}return this}}),rC=v0((Q)=>{var Z=YJ(),Y=m6().Reporter,$=(vY(),oQ(_Y)).Buffer;function J(G,W){if(Y.call(this,W),!$.isBuffer(G)){this.error("Input not Buffer");return}this.base=G,this.offset=0,this.length=G.length}Z(J,Y),Q.DecoderBuffer=J,J.prototype.save=function(){return{offset:this.offset,reporter:Y.prototype.save.call(this)}},J.prototype.restore=function(G){var W=new J(this.base);return W.offset=G.offset,W.length=this.offset,this.offset=G.offset,Y.prototype.restore.call(this,G.reporter),W},J.prototype.isEmpty=function(){return this.offset===this.length},J.prototype.readUInt8=function(G){if(this.offset+1<=this.length)return this.base.readUInt8(this.offset++,!0);else return this.error(G||"DecoderBuffer overrun")},J.prototype.skip=function(G,W){if(!(this.offset+G<=this.length))return this.error(W||"DecoderBuffer overrun");var U=new J(this.base);return U._reporterState=this._reporterState,U.offset=this.offset,U.length=this.offset+G,this.offset+=G,U},J.prototype.raw=function(G){return this.base.slice(G?G.offset:this.offset,this.length)};function X(G,W){if(Array.isArray(G))this.length=0,this.value=G.map(function(U){if(!(U instanceof X))U=new X(U,W);return this.length+=U.length,U},this);else if(typeof G==="number"){if(!(0<=G&&G<=255))return W.error("non-byte EncoderBuffer value");this.value=G,this.length=1}else if(typeof G==="string")this.value=G,this.length=$.byteLength(G);else if($.isBuffer(G))this.value=G,this.length=G.length;else return W.error("Unsupported type: "+typeof G)}Q.EncoderBuffer=X,X.prototype.join=function(G,W){if(!G)G=new $(this.length);if(!W)W=0;if(this.length===0)return G;if(Array.isArray(this.value))this.value.forEach(function(U){U.join(G,W),W+=U.length});else{if(typeof this.value==="number")G[W]=this.value;else if(typeof this.value==="string")G.write(this.value,W);else if($.isBuffer(this.value))this.value.copy(G,W);W+=this.length}return G}}),We=v0((Q,Z)=>{var Y=m6().Reporter,$=m6().EncoderBuffer,J=m6().DecoderBuffer,X=c8(),G=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],W=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(G),U=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function K(I,L){var A={};if(this._baseState=A,A.enc=I,A.parent=L||null,A.children=null,A.tag=null,A.args=null,A.reverseArgs=null,A.choice=null,A.optional=!1,A.any=!1,A.obj=!1,A.use=null,A.useDecoder=null,A.key=null,A.default=null,A.explicit=null,A.implicit=null,A.contains=null,!A.parent)A.children=[],this._wrap()}Z.exports=K;var O=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];K.prototype.clone=function(){var I=this._baseState,L={};O.forEach(function(M){L[M]=I[M]});var A=new this.constructor(L.parent);return A._baseState=L,A},K.prototype._wrap=function(){var I=this._baseState;W.forEach(function(L){this[L]=function(){var A=new this.constructor(this);return I.children.push(A),A[L].apply(A,arguments)}},this)},K.prototype._init=function(I){var L=this._baseState;X(L.parent===null),I.call(this),L.children=L.children.filter(function(A){return A._baseState.parent===this},this),X.equal(L.children.length,1,"Root node can have only one child")},K.prototype._useArgs=function(I){var L=this._baseState,A=I.filter(function(M){return M instanceof this.constructor},this);if(I=I.filter(function(M){return!(M instanceof this.constructor)},this),A.length!==0)X(L.children===null),L.children=A,A.forEach(function(M){M._baseState.parent=this},this);if(I.length!==0)X(L.args===null),L.args=I,L.reverseArgs=I.map(function(M){if(typeof M!=="object"||M.constructor!==Object)return M;var k={};return Object.keys(M).forEach(function(B){if(B==(B|0))B|=0;var C=M[B];k[C]=B}),k})},U.forEach(function(I){K.prototype[I]=function(){var L=this._baseState;throw Error(I+" not implemented for encoding: "+L.enc)}}),G.forEach(function(I){K.prototype[I]=function(){var L=this._baseState,A=Array.prototype.slice.call(arguments);return X(L.tag===null),L.tag=I,this._useArgs(A),this}}),K.prototype.use=function(I){X(I);var L=this._baseState;return X(L.use===null),L.use=I,this},K.prototype.optional=function(){var I=this._baseState;return I.optional=!0,this},K.prototype.def=function(I){var L=this._baseState;return X(L.default===null),L.default=I,L.optional=!0,this},K.prototype.explicit=function(I){var L=this._baseState;return X(L.explicit===null&&L.implicit===null),L.explicit=I,this},K.prototype.implicit=function(I){var L=this._baseState;return X(L.explicit===null&&L.implicit===null),L.implicit=I,this},K.prototype.obj=function(){var I=this._baseState,L=Array.prototype.slice.call(arguments);if(I.obj=!0,L.length!==0)this._useArgs(L);return this},K.prototype.key=function(I){var L=this._baseState;return X(L.key===null),L.key=I,this},K.prototype.any=function(){var I=this._baseState;return I.any=!0,this},K.prototype.choice=function(I){var L=this._baseState;return X(L.choice===null),L.choice=I,this._useArgs(Object.keys(I).map(function(A){return I[A]})),this},K.prototype.contains=function(I){var L=this._baseState;return X(L.use===null),L.contains=I,this},K.prototype._decode=function(I,L){var A=this._baseState;if(A.parent===null)return I.wrapResult(A.children[0]._decode(I,L));var M=A.default,k=!0,B=null;if(A.key!==null)B=I.enterKey(A.key);if(A.optional){var C=null;if(A.explicit!==null)C=A.explicit;else if(A.implicit!==null)C=A.implicit;else if(A.tag!==null)C=A.tag;if(C===null&&!A.any){var S=I.save();try{if(A.choice===null)this._decodeGeneric(A.tag,I,L);else this._decodeChoice(I,L);k=!0}catch(Z0){k=!1}I.restore(S)}else if(k=this._peekTag(I,C,A.any),I.isError(k))return k}var _;if(A.obj&&k)_=I.enterObject();if(k){if(A.explicit!==null){var x=this._decodeTag(I,A.explicit);if(I.isError(x))return x;I=x}var f=I.offset;if(A.use===null&&A.choice===null){if(A.any)var S=I.save();var h=this._decodeTag(I,A.implicit!==null?A.implicit:A.tag,A.any);if(I.isError(h))return h;if(A.any)M=I.raw(S);else I=h}if(L&&L.track&&A.tag!==null)L.track(I.path(),f,I.length,"tagged");if(L&&L.track&&A.tag!==null)L.track(I.path(),I.offset,I.length,"content");if(A.any)M=M;else if(A.choice===null)M=this._decodeGeneric(A.tag,I,L);else M=this._decodeChoice(I,L);if(I.isError(M))return M;if(!A.any&&A.choice===null&&A.children!==null)A.children.forEach(function(Z0){Z0._decode(I,L)});if(A.contains&&(A.tag==="octstr"||A.tag==="bitstr")){var i=new J(M);M=this._getUse(A.contains,I._reporterState.obj)._decode(i,L)}}if(A.obj&&k)M=I.leaveObject(_);if(A.key!==null&&(M!==null||k===!0))I.leaveKey(B,A.key,M);else if(B!==null)I.exitKey(B);return M},K.prototype._decodeGeneric=function(I,L,A){var M=this._baseState;if(I==="seq"||I==="set")return null;if(I==="seqof"||I==="setof")return this._decodeList(L,I,M.args[0],A);else if(/str$/.test(I))return this._decodeStr(L,I,A);else if(I==="objid"&&M.args)return this._decodeObjid(L,M.args[0],M.args[1],A);else if(I==="objid")return this._decodeObjid(L,null,null,A);else if(I==="gentime"||I==="utctime")return this._decodeTime(L,I,A);else if(I==="null_")return this._decodeNull(L,A);else if(I==="bool")return this._decodeBool(L,A);else if(I==="objDesc")return this._decodeStr(L,I,A);else if(I==="int"||I==="enum")return this._decodeInt(L,M.args&&M.args[0],A);if(M.use!==null)return this._getUse(M.use,L._reporterState.obj)._decode(L,A);else return L.error("unknown tag: "+I)},K.prototype._getUse=function(I,L){var A=this._baseState;if(A.useDecoder=this._use(I,L),X(A.useDecoder._baseState.parent===null),A.useDecoder=A.useDecoder._baseState.children[0],A.implicit!==A.useDecoder._baseState.implicit)A.useDecoder=A.useDecoder.clone(),A.useDecoder._baseState.implicit=A.implicit;return A.useDecoder},K.prototype._decodeChoice=function(I,L){var A=this._baseState,M=null,k=!1;if(Object.keys(A.choice).some(function(B){var C=I.save(),S=A.choice[B];try{var _=S._decode(I,L);if(I.isError(_))return!1;M={type:B,value:_},k=!0}catch(x){return I.restore(C),!1}return!0},this),!k)return I.error("Choice not matched");return M},K.prototype._createEncoderBuffer=function(I){return new $(I,this.reporter)},K.prototype._encode=function(I,L,A){var M=this._baseState;if(M.default!==null&&M.default===I)return;var k=this._encodeValue(I,L,A);if(k===void 0)return;if(this._skipDefault(k,L,A))return;return k},K.prototype._encodeValue=function(I,L,A){var M=this._baseState;if(M.parent===null)return M.children[0]._encode(I,L||new Y);var S=null;if(this.reporter=L,M.optional&&I===void 0)if(M.default!==null)I=M.default;else return;var k=null,B=!1;if(M.any)S=this._createEncoderBuffer(I);else if(M.choice)S=this._encodeChoice(I,L);else if(M.contains)k=this._getUse(M.contains,A)._encode(I,L),B=!0;else if(M.children)k=M.children.map(function(f){if(f._baseState.tag==="null_")return f._encode(null,L,I);if(f._baseState.key===null)return L.error("Child should have a key");var h=L.enterKey(f._baseState.key);if(typeof I!=="object")return L.error("Child expected, but input is not object");var i=f._encode(I[f._baseState.key],L,I);return L.leaveKey(h),i},this).filter(function(f){return f}),k=this._createEncoderBuffer(k);else if(M.tag==="seqof"||M.tag==="setof"){if(!(M.args&&M.args.length===1))return L.error("Too many args for : "+M.tag);if(!Array.isArray(I))return L.error("seqof/setof, but data is not Array");var C=this.clone();C._baseState.implicit=null,k=this._createEncoderBuffer(I.map(function(f){var h=this._baseState;return this._getUse(h.args[0],I)._encode(f,L)},C))}else if(M.use!==null)S=this._getUse(M.use,A)._encode(I,L);else k=this._encodePrimitive(M.tag,I),B=!0;var S;if(!M.any&&M.choice===null){var _=M.implicit!==null?M.implicit:M.tag,x=M.implicit===null?"universal":"context";if(_===null){if(M.use===null)L.error("Tag could be omitted only for .use()")}else if(M.use===null)S=this._encodeComposite(_,B,x,k)}if(M.explicit!==null)S=this._encodeComposite(M.explicit,!1,"context",S);return S},K.prototype._encodeChoice=function(I,L){var A=this._baseState,M=A.choice[I.type];if(!M)X(!1,I.type+" not found in "+JSON.stringify(Object.keys(A.choice)));return M._encode(I.value,L)},K.prototype._encodePrimitive=function(I,L){var A=this._baseState;if(/str$/.test(I))return this._encodeStr(L,I);else if(I==="objid"&&A.args)return this._encodeObjid(L,A.reverseArgs[0],A.args[1]);else if(I==="objid")return this._encodeObjid(L,null,null);else if(I==="gentime"||I==="utctime")return this._encodeTime(L,I);else if(I==="null_")return this._encodeNull();else if(I==="int"||I==="enum")return this._encodeInt(L,A.args&&A.reverseArgs[0]);else if(I==="bool")return this._encodeBool(L);else if(I==="objDesc")return this._encodeStr(L,I);else throw Error("Unsupported tag: "+I)},K.prototype._isNumstr=function(I){return/^[0-9 ]*$/.test(I)},K.prototype._isPrintstr=function(I){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(I)}}),m6=v0((Q)=>{var Z=Q;Z.Reporter=ze().Reporter,Z.DecoderBuffer=rC().DecoderBuffer,Z.EncoderBuffer=rC().EncoderBuffer,Z.Node=We()}),Ke=v0((Q)=>{var Z=DS();Q.tagClass={0:"universal",1:"application",2:"context",3:"private"},Q.tagClassByName=Z._reverse(Q.tagClass),Q.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},Q.tagByName=Z._reverse(Q.tag)}),DS=v0((Q)=>{var Z=Q;Z._reverse=function(Y){var $={};return Object.keys(Y).forEach(function(J){if((J|0)==J)J=J|0;var X=Y[J];$[X]=J}),$},Z.der=Ke()}),IS=v0((Q,Z)=>{var Y=YJ(),$=i6(),J=$.base,X=$.bignum,G=$.constants.der;function W(I){this.enc="der",this.name=I.name,this.entity=I,this.tree=new U,this.tree._init(I.body)}Z.exports=W,W.prototype.decode=function(I,L){if(!(I instanceof J.DecoderBuffer))I=new J.DecoderBuffer(I,L);return this.tree._decode(I,L)};function U(I){J.Node.call(this,"der",I)}Y(U,J.Node),U.prototype._peekTag=function(I,L,A){if(I.isEmpty())return!1;var M=I.save(),k=K(I,'Failed to peek tag: "'+L+'"');if(I.isError(k))return k;return I.restore(M),k.tag===L||k.tagStr===L||k.tagStr+"of"===L||A},U.prototype._decodeTag=function(I,L,A){var M=K(I,'Failed to decode tag of "'+L+'"');if(I.isError(M))return M;var k=O(I,M.primitive,'Failed to get length of "'+L+'"');if(I.isError(k))return k;if(!A&&M.tag!==L&&M.tagStr!==L&&M.tagStr+"of"!==L)return I.error('Failed to match tag: "'+L+'"');if(M.primitive||k!==null)return I.skip(k,'Failed to match body of: "'+L+'"');var B=I.save(),C=this._skipUntilEnd(I,'Failed to skip indefinite length body: "'+this.tag+'"');if(I.isError(C))return C;return k=I.offset-B.offset,I.restore(B),I.skip(k,'Failed to match body of: "'+L+'"')},U.prototype._skipUntilEnd=function(I,L){while(!0){var A=K(I,L);if(I.isError(A))return A;var M=O(I,A.primitive,L);if(I.isError(M))return M;var k;if(A.primitive||M!==null)k=I.skip(M);else k=this._skipUntilEnd(I,L);if(I.isError(k))return k;if(A.tagStr==="end")break}},U.prototype._decodeList=function(I,L,A,M){var k=[];while(!I.isEmpty()){var B=this._peekTag(I,"end");if(I.isError(B))return B;var C=A.decode(I,"der",M);if(I.isError(C)&&B)break;k.push(C)}return k},U.prototype._decodeStr=function(I,L){if(L==="bitstr"){var A=I.readUInt8();if(I.isError(A))return A;return{unused:A,data:I.raw()}}else if(L==="bmpstr"){var M=I.raw();if(M.length%2===1)return I.error("Decoding of string type: bmpstr length mismatch");var k="";for(var B=0;B<M.length/2;B++)k+=String.fromCharCode(M.readUInt16BE(B*2));return k}else if(L==="numstr"){var C=I.raw().toString("ascii");if(!this._isNumstr(C))return I.error("Decoding of string type: numstr unsupported characters");return C}else if(L==="octstr")return I.raw();else if(L==="objDesc")return I.raw();else if(L==="printstr"){var S=I.raw().toString("ascii");if(!this._isPrintstr(S))return I.error("Decoding of string type: printstr unsupported characters");return S}else if(/str$/.test(L))return I.raw().toString();else return I.error("Decoding of string type: "+L+" unsupported")},U.prototype._decodeObjid=function(I,L,A){var M,k=[],B=0;while(!I.isEmpty()){var C=I.readUInt8();if(B<<=7,B|=C&127,(C&128)===0)k.push(B),B=0}if(C&128)k.push(B);var S=k[0]/40|0,_=k[0]%40;if(A)M=k;else M=[S,_].concat(k.slice(1));if(L){var x=L[M.join(" ")];if(x===void 0)x=L[M.join(".")];if(x!==void 0)M=x}return M},U.prototype._decodeTime=function(I,L){var A=I.raw().toString();if(L==="gentime")var M=A.slice(0,4)|0,k=A.slice(4,6)|0,B=A.slice(6,8)|0,C=A.slice(8,10)|0,S=A.slice(10,12)|0,_=A.slice(12,14)|0;else if(L==="utctime"){var M=A.slice(0,2)|0,k=A.slice(2,4)|0,B=A.slice(4,6)|0,C=A.slice(6,8)|0,S=A.slice(8,10)|0,_=A.slice(10,12)|0;if(M<70)M=2000+M;else M=1900+M}else return I.error("Decoding "+L+" time is not supported yet");return Date.UTC(M,k-1,B,C,S,_,0)},U.prototype._decodeNull=function(I){return null},U.prototype._decodeBool=function(I){var L=I.readUInt8();if(I.isError(L))return L;else return L!==0},U.prototype._decodeInt=function(I,L){var A=I.raw(),M=new X(A);if(L)M=L[M.toString(10)]||M;return M},U.prototype._use=function(I,L){if(typeof I==="function")I=I(L);return I._getDecoder("der").tree};function K(I,L){var A=I.readUInt8(L);if(I.isError(A))return A;var M=G.tagClass[A>>6],k=(A&32)===0;if((A&31)===31){var B=A;A=0;while((B&128)===128){if(B=I.readUInt8(L),I.isError(B))return B;A<<=7,A|=B&127}}else A&=31;var C=G.tag[A];return{cls:M,primitive:k,tag:A,tagStr:C}}function O(I,L,A){var M=I.readUInt8(A);if(I.isError(M))return M;if(!L&&M===128)return null;if((M&128)===0)return M;var k=M&127;if(k>4)return I.error("length octect is too long");M=0;for(var B=0;B<k;B++){M<<=8;var C=I.readUInt8(A);if(I.isError(C))return C;M|=C}return M}}),Ue=v0((Q,Z)=>{var Y=YJ(),$=(vY(),oQ(_Y)).Buffer,J=IS();function X(G){J.call(this,G),this.enc="pem"}Y(X,J),Z.exports=X,X.prototype.decode=function(G,W){var U=G.toString().split(/[\r\n]+/g),K=W.label.toUpperCase(),O=/^-----(BEGIN|END) ([^-]+)-----$/,I=-1,L=-1;for(var A=0;A<U.length;A++){var M=U[A].match(O);if(M===null)continue;if(M[2]!==K)continue;if(I===-1){if(M[1]!=="BEGIN")break;I=A}else{if(M[1]!=="END")break;L=A;break}}if(I===-1||L===-1)throw Error("PEM section not found for: "+K);var k=U.slice(I+1,L).join("");k.replace(/[^a-z0-9\+\/=]+/gi,"");var B=new $(k,"base64");return J.prototype.decode.call(this,B,W)}}),Oe=v0((Q)=>{var Z=Q;Z.der=IS(),Z.pem=Ue()}),RS=v0((Q,Z)=>{var Y=YJ(),$=(vY(),oQ(_Y)).Buffer,J=i6(),X=J.base,G=J.constants.der;function W(I){this.enc="der",this.name=I.name,this.entity=I,this.tree=new U,this.tree._init(I.body)}Z.exports=W,W.prototype.encode=function(I,L){return this.tree._encode(I,L).join()};function U(I){X.Node.call(this,"der",I)}Y(U,X.Node),U.prototype._encodeComposite=function(I,L,A,M){var k=O(I,L,A,this.reporter);if(M.length<128){var S=new $(2);return S[0]=k,S[1]=M.length,this._createEncoderBuffer([S,M])}var B=1;for(var C=M.length;C>=256;C>>=8)B++;var S=new $(2+B);S[0]=k,S[1]=128|B;for(var C=1+B,_=M.length;_>0;C--,_>>=8)S[C]=_&255;return this._createEncoderBuffer([S,M])},U.prototype._encodeStr=function(I,L){if(L==="bitstr")return this._createEncoderBuffer([I.unused|0,I.data]);else if(L==="bmpstr"){var A=new $(I.length*2);for(var M=0;M<I.length;M++)A.writeUInt16BE(I.charCodeAt(M),M*2);return this._createEncoderBuffer(A)}else if(L==="numstr"){if(!this._isNumstr(I))return this.reporter.error("Encoding of string type: numstr supports only digits and space");return this._createEncoderBuffer(I)}else if(L==="printstr"){if(!this._isPrintstr(I))return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");return this._createEncoderBuffer(I)}else if(/str$/.test(L))return this._createEncoderBuffer(I);else if(L==="objDesc")return this._createEncoderBuffer(I);else return this.reporter.error("Encoding of string type: "+L+" unsupported")},U.prototype._encodeObjid=function(I,L,A){if(typeof I==="string"){if(!L)return this.reporter.error("string objid given, but no values map found");if(!L.hasOwnProperty(I))return this.reporter.error("objid not found in values map");I=L[I].split(/[\s\.]+/g);for(var M=0;M<I.length;M++)I[M]|=0}else if(Array.isArray(I)){I=I.slice();for(var M=0;M<I.length;M++)I[M]|=0}if(!Array.isArray(I))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(I));if(!A){if(I[1]>=40)return this.reporter.error("Second objid identifier OOB");I.splice(0,2,I[0]*40+I[1])}var k=0;for(var M=0;M<I.length;M++){var B=I[M];for(k++;B>=128;B>>=7)k++}var C=new $(k),S=C.length-1;for(var M=I.length-1;M>=0;M--){var B=I[M];C[S--]=B&127;while((B>>=7)>0)C[S--]=128|B&127}return this._createEncoderBuffer(C)};function K(I){if(I<10)return"0"+I;else return I}U.prototype._encodeTime=function(I,L){var A,M=new Date(I);if(L==="gentime")A=[K(M.getFullYear()),K(M.getUTCMonth()+1),K(M.getUTCDate()),K(M.getUTCHours()),K(M.getUTCMinutes()),K(M.getUTCSeconds()),"Z"].join("");else if(L==="utctime")A=[K(M.getFullYear()%100),K(M.getUTCMonth()+1),K(M.getUTCDate()),K(M.getUTCHours()),K(M.getUTCMinutes()),K(M.getUTCSeconds()),"Z"].join("");else this.reporter.error("Encoding "+L+" time is not supported yet");return this._encodeStr(A,"octstr")},U.prototype._encodeNull=function(){return this._createEncoderBuffer("")},U.prototype._encodeInt=function(I,L){if(typeof I==="string"){if(!L)return this.reporter.error("String int or enum given, but no values map");if(!L.hasOwnProperty(I))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(I));I=L[I]}if(typeof I!=="number"&&!$.isBuffer(I)){var A=I.toArray();if(!I.sign&&A[0]&128)A.unshift(0);I=new $(A)}if($.isBuffer(I)){var M=I.length;if(I.length===0)M++;var B=new $(M);if(I.copy(B),I.length===0)B[0]=0;return this._createEncoderBuffer(B)}if(I<128)return this._createEncoderBuffer(I);if(I<256)return this._createEncoderBuffer([0,I]);var M=1;for(var k=I;k>=256;k>>=8)M++;var B=Array(M);for(var k=B.length-1;k>=0;k--)B[k]=I&255,I>>=8;if(B[0]&128)B.unshift(0);return this._createEncoderBuffer(new $(B))},U.prototype._encodeBool=function(I){return this._createEncoderBuffer(I?255:0)},U.prototype._use=function(I,L){if(typeof I==="function")I=I(L);return I._getEncoder("der").tree},U.prototype._skipDefault=function(I,L,A){var M=this._baseState,k;if(M.default===null)return!1;var B=I.join();if(M.defaultBuffer===void 0)M.defaultBuffer=this._encodeValue(M.default,L,A).join();if(B.length!==M.defaultBuffer.length)return!1;for(k=0;k<B.length;k++)if(B[k]!==M.defaultBuffer[k])return!1;return!0};function O(I,L,A,M){var k;if(I==="seqof")I="seq";else if(I==="setof")I="set";if(G.tagByName.hasOwnProperty(I))k=G.tagByName[I];else if(typeof I==="number"&&(I|0)===I)k=I;else return M.error("Unknown tag: "+I);if(k>=31)return M.error("Multi-octet tag encoding unsupported");if(!L)k|=32;return k|=G.tagClassByName[A||"universal"]<<6,k}}),He=v0((Q,Z)=>{var Y=YJ(),$=RS();function J(X){$.call(this,X),this.enc="pem"}Y(J,$),Z.exports=J,J.prototype.encode=function(X,G){var W=$.prototype.encode.call(this,X),U=W.toString("base64"),K=["-----BEGIN "+G.label+"-----"];for(var O=0;O<U.length;O+=64)K.push(U.slice(O,O+64));return K.push("-----END "+G.label+"-----"),K.join(`
|
|
87
|
+
`)}}),De=v0((Q)=>{var Z=Q;Z.der=RS(),Z.pem=He()}),i6=v0((Q)=>{var Z=Q;Z.bignum=qe(),Z.define=Fe().define,Z.base=m6(),Z.constants=DS(),Z.decoders=Oe(),Z.encoders=De()}),Ie=v0((Q,Z)=>{var Y=i6(),$=Y.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),J=Y.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),X=Y.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())}),G=Y.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(X),this.key("subjectPublicKey").bitstr())}),W=Y.define("RelativeDistinguishedName",function(){this.setof(J)}),U=Y.define("RDNSequence",function(){this.seqof(W)}),K=Y.define("Name",function(){this.choice({rdnSequence:this.use(U)})}),O=Y.define("Validity",function(){this.seq().obj(this.key("notBefore").use($),this.key("notAfter").use($))}),I=Y.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),L=Y.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(X),this.key("issuer").use(K),this.key("validity").use(O),this.key("subject").use(K),this.key("subjectPublicKeyInfo").use(G),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(I).optional())}),A=Y.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(L),this.key("signatureAlgorithm").use(X),this.key("signatureValue").bitstr())});Z.exports=A}),Re=v0((Q)=>{var Z=i6();Q.certificate=Ie();var Y=Z.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});Q.RSAPrivateKey=Y;var $=Z.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});Q.RSAPublicKey=$;var J=Z.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),X=Z.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(J),this.key("subjectPublicKey").bitstr())});Q.PublicKey=X;var G=Z.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(J),this.key("subjectPrivateKey").octstr())});Q.PrivateKey=G;var W=Z.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});Q.EncryptedPrivateKey=W;var U=Z.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});Q.DSAPrivateKey=U,Q.DSAparam=Z.define("DSAparam",function(){this.int()});var K=Z.define("ECParameters",function(){this.choice({namedCurve:this.objid()})}),O=Z.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(K),this.key("publicKey").optional().explicit(1).bitstr())});Q.ECPrivateKey=O,Q.signature=Z.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})}),Le=v0((Q,Z)=>{Z.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}}),Ee=v0((Q,Z)=>{var Y=I$().Buffer,$=OD().Transform,J=YJ();function X(K){$.call(this),this._block=Y.allocUnsafe(K),this._blockSize=K,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}J(X,$),X.prototype._transform=function(K,O,I){var L=null;try{this.update(K,O)}catch(A){L=A}I(L)},X.prototype._flush=function(K){var O=null;try{this.push(this.digest())}catch(I){O=I}K(O)};var G=typeof Uint8Array<"u",W=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&ArrayBuffer.isView&&(Y.prototype instanceof Uint8Array||Y.TYPED_ARRAY_SUPPORT);function U(K,O){if(K instanceof Y)return K;if(typeof K==="string")return Y.from(K,O);if(W&&ArrayBuffer.isView(K)){if(K.byteLength===0)return Y.alloc(0);var I=Y.from(K.buffer,K.byteOffset,K.byteLength);if(I.byteLength===K.byteLength)return I}if(G&&K instanceof Uint8Array)return Y.from(K);if(Y.isBuffer(K)&&K.constructor&&typeof K.constructor.isBuffer==="function"&&K.constructor.isBuffer(K))return Y.from(K);throw TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}X.prototype.update=function(K,O){if(this._finalized)throw Error("Digest already called");K=U(K,O);var I=this._block,L=0;while(this._blockOffset+K.length-L>=this._blockSize){for(var A=this._blockOffset;A<this._blockSize;)I[A++]=K[L++];this._update(),this._blockOffset=0}while(L<K.length)I[this._blockOffset++]=K[L++];for(var M=0,k=K.length*8;k>0;++M)if(this._length[M]+=k,k=this._length[M]/4294967296|0,k>0)this._length[M]-=4294967296*k;return this},X.prototype._update=function(){throw Error("_update is not implemented")},X.prototype.digest=function(K){if(this._finalized)throw Error("Digest already called");this._finalized=!0;var O=this._digest();if(K!==void 0)O=O.toString(K);this._block.fill(0),this._blockOffset=0;for(var I=0;I<4;++I)this._length[I]=0;return O},X.prototype._digest=function(){throw Error("_digest is not implemented")},Z.exports=X}),Pe=v0((Q,Z)=>{var Y=YJ(),$=Ee(),J=I$().Buffer,X=Array(16);function G(){$.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}Y(G,$),G.prototype._update=function(){var L=X;for(var A=0;A<16;++A)L[A]=this._block.readInt32LE(A*4);var M=this._a,k=this._b,B=this._c,C=this._d;M=U(M,k,B,C,L[0],3614090360,7),C=U(C,M,k,B,L[1],3905402710,12),B=U(B,C,M,k,L[2],606105819,17),k=U(k,B,C,M,L[3],3250441966,22),M=U(M,k,B,C,L[4],4118548399,7),C=U(C,M,k,B,L[5],1200080426,12),B=U(B,C,M,k,L[6],2821735955,17),k=U(k,B,C,M,L[7],4249261313,22),M=U(M,k,B,C,L[8],1770035416,7),C=U(C,M,k,B,L[9],2336552879,12),B=U(B,C,M,k,L[10],4294925233,17),k=U(k,B,C,M,L[11],2304563134,22),M=U(M,k,B,C,L[12],1804603682,7),C=U(C,M,k,B,L[13],4254626195,12),B=U(B,C,M,k,L[14],2792965006,17),k=U(k,B,C,M,L[15],1236535329,22),M=K(M,k,B,C,L[1],4129170786,5),C=K(C,M,k,B,L[6],3225465664,9),B=K(B,C,M,k,L[11],643717713,14),k=K(k,B,C,M,L[0],3921069994,20),M=K(M,k,B,C,L[5],3593408605,5),C=K(C,M,k,B,L[10],38016083,9),B=K(B,C,M,k,L[15],3634488961,14),k=K(k,B,C,M,L[4],3889429448,20),M=K(M,k,B,C,L[9],568446438,5),C=K(C,M,k,B,L[14],3275163606,9),B=K(B,C,M,k,L[3],4107603335,14),k=K(k,B,C,M,L[8],1163531501,20),M=K(M,k,B,C,L[13],2850285829,5),C=K(C,M,k,B,L[2],4243563512,9),B=K(B,C,M,k,L[7],1735328473,14),k=K(k,B,C,M,L[12],2368359562,20),M=O(M,k,B,C,L[5],4294588738,4),C=O(C,M,k,B,L[8],2272392833,11),B=O(B,C,M,k,L[11],1839030562,16),k=O(k,B,C,M,L[14],4259657740,23),M=O(M,k,B,C,L[1],2763975236,4),C=O(C,M,k,B,L[4],1272893353,11),B=O(B,C,M,k,L[7],4139469664,16),k=O(k,B,C,M,L[10],3200236656,23),M=O(M,k,B,C,L[13],681279174,4),C=O(C,M,k,B,L[0],3936430074,11),B=O(B,C,M,k,L[3],3572445317,16),k=O(k,B,C,M,L[6],76029189,23),M=O(M,k,B,C,L[9],3654602809,4),C=O(C,M,k,B,L[12],3873151461,11),B=O(B,C,M,k,L[15],530742520,16),k=O(k,B,C,M,L[2],3299628645,23),M=I(M,k,B,C,L[0],4096336452,6),C=I(C,M,k,B,L[7],1126891415,10),B=I(B,C,M,k,L[14],2878612391,15),k=I(k,B,C,M,L[5],4237533241,21),M=I(M,k,B,C,L[12],1700485571,6),C=I(C,M,k,B,L[3],2399980690,10),B=I(B,C,M,k,L[10],4293915773,15),k=I(k,B,C,M,L[1],2240044497,21),M=I(M,k,B,C,L[8],1873313359,6),C=I(C,M,k,B,L[15],4264355552,10),B=I(B,C,M,k,L[6],2734768916,15),k=I(k,B,C,M,L[13],1309151649,21),M=I(M,k,B,C,L[4],4149444226,6),C=I(C,M,k,B,L[11],3174756917,10),B=I(B,C,M,k,L[2],718787259,15),k=I(k,B,C,M,L[9],3951481745,21),this._a=this._a+M|0,this._b=this._b+k|0,this._c=this._c+B|0,this._d=this._d+C|0},G.prototype._digest=function(){if(this._block[this._blockOffset++]=128,this._blockOffset>56)this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0;this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var L=J.allocUnsafe(16);return L.writeInt32LE(this._a,0),L.writeInt32LE(this._b,4),L.writeInt32LE(this._c,8),L.writeInt32LE(this._d,12),L};function W(L,A){return L<<A|L>>>32-A}function U(L,A,M,k,B,C,S){return W(L+(A&M|~A&k)+B+C|0,S)+A|0}function K(L,A,M,k,B,C,S){return W(L+(A&k|M&~k)+B+C|0,S)+A|0}function O(L,A,M,k,B,C,S){return W(L+(A^M^k)+B+C|0,S)+A|0}function I(L,A,M,k,B,C,S){return W(L+(M^(A|~k))+B+C|0,S)+A|0}Z.exports=G}),je=v0((Q,Z)=>{var Y=I$().Buffer,$=Pe();function J(X,G,W,U){if(!Y.isBuffer(X))X=Y.from(X,"binary");if(G){if(!Y.isBuffer(G))G=Y.from(G,"binary");if(G.length!==8)throw RangeError("salt should be Buffer with 8 byte length")}var K=W/8,O=Y.alloc(K),I=Y.alloc(U||0),L=Y.alloc(0);while(K>0||U>0){var A=new $;if(A.update(L),A.update(X),G)A.update(G);L=A.digest();var M=0;if(K>0){var k=O.length-K;M=Math.min(K,L.length),L.copy(O,k,0,M),K-=M}if(M<L.length&&U>0){var B=I.length-U,C=Math.min(U,L.length-M);L.copy(I,B,M,M+C),U-=C}}return L.fill(0),{key:O,iv:I}}Z.exports=J}),LS=v0((Q)=>{var Z=(v$(),oQ(_$));Q.createCipher=Q.Cipher=Z.createCipher,Q.createCipheriv=Q.Cipheriv=Z.createCipheriv,Q.createDecipher=Q.Decipher=Z.createDecipher,Q.createDecipheriv=Q.Decipheriv=Z.createDecipheriv,Q.listCiphers=Q.getCiphers=Z.getCiphers}),Ae=v0((Q,Z)=>{var Y=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,$=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,J=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,X=je(),G=LS(),W=I$().Buffer;Z.exports=function(U,K){var O=U.toString(),I=O.match(Y),L;if(!I){var A=O.match(J);L=W.from(A[2].replace(/[\r\n]/g,""),"base64")}else{var M="aes"+I[1],k=W.from(I[2],"hex"),B=W.from(I[3].replace(/[\r\n]/g,""),"base64"),C=X(K,k.slice(0,8),parseInt(I[1],10)).key,S=[],_=G.createDecipheriv(M,C,k);S.push(_.update(B)),S.push(_.final()),L=W.concat(S)}var x=O.match($)[1];return{tag:x,data:L}}}),ES=v0((Q,Z)=>{var Y=Re(),$=Le(),J=Ae(),X=LS(),G=FS().pbkdf2Sync,W=I$().Buffer;function U(O,I){var L=O.algorithm.decrypt.kde.kdeparams.salt,A=parseInt(O.algorithm.decrypt.kde.kdeparams.iters.toString(),10),M=$[O.algorithm.decrypt.cipher.algo.join(".")],k=O.algorithm.decrypt.cipher.iv,B=O.subjectPrivateKey,C=parseInt(M.split("-")[1],10)/8,S=G(I,L,A,C,"sha1"),_=X.createDecipheriv(M,S,k),x=[];return x.push(_.update(B)),x.push(_.final()),W.concat(x)}function K(O){var I;if(typeof O==="object"&&!W.isBuffer(O))I=O.passphrase,O=O.key;if(typeof O==="string")O=W.from(O);var L=J(O,I),A=L.tag,M=L.data,k,B;switch(A){case"CERTIFICATE":B=Y.certificate.decode(M,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":if(!B)B=Y.PublicKey.decode(M,"der");switch(k=B.algorithm.algorithm.join("."),k){case"1.2.840.113549.1.1.1":return Y.RSAPublicKey.decode(B.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return B.subjectPrivateKey=B.subjectPublicKey,{type:"ec",data:B};case"1.2.840.10040.4.1":return B.algorithm.params.pub_key=Y.DSAparam.decode(B.subjectPublicKey.data,"der"),{type:"dsa",data:B.algorithm.params};default:throw Error("unknown key id "+k)}case"ENCRYPTED PRIVATE KEY":M=Y.EncryptedPrivateKey.decode(M,"der"),M=U(M,I);case"PRIVATE KEY":switch(B=Y.PrivateKey.decode(M,"der"),k=B.algorithm.algorithm.join("."),k){case"1.2.840.113549.1.1.1":return Y.RSAPrivateKey.decode(B.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:B.algorithm.curve,privateKey:Y.ECPrivateKey.decode(B.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return B.algorithm.params.priv_key=Y.DSAparam.decode(B.subjectPrivateKey,"der"),{type:"dsa",params:B.algorithm.params};default:throw Error("unknown key id "+k)}case"RSA PUBLIC KEY":return Y.RSAPublicKey.decode(M,"der");case"RSA PRIVATE KEY":return Y.RSAPrivateKey.decode(M,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:Y.DSAPrivateKey.decode(M,"der")};case"EC PRIVATE KEY":return M=Y.ECPrivateKey.decode(M,"der"),{curve:M.parameters.value,privateKey:M.privateKey};default:throw Error("unknown key type "+A)}}K.signature=Y.signature,Z.exports=K}),PS=v0((Q,Z)=>{var Y=yW(),$=I$().Buffer;Z.exports=function(X,G){var W=$.alloc(0),U=0,K;while(W.length<G)K=J(U++),W=$.concat([W,Y("sha1").update(X).update(K).digest()]);return W.slice(0,G)};function J(X){var G=$.allocUnsafe(4);return G.writeUInt32BE(X,0),G}}),jS=v0((Q,Z)=>{Z.exports=function(Y,$){var J=Y.length,X=-1;while(++X<J)Y[X]^=$[X];return Y}}),MD=v0((Q,Z)=>{(function(Y,$){function J(V,z){if(!V)throw Error(z||"Assertion failed")}function X(V,z){V.super_=z;var H=function(){};H.prototype=z.prototype,V.prototype=new H,V.prototype.constructor=V}function G(V,z,H){if(G.isBN(V))return V;if(this.negative=0,this.words=null,this.length=0,this.red=null,V!==null){if(z==="le"||z==="be")H=z,z=10;this._init(V||0,z||10,H||"be")}}if(typeof Y==="object")Y.exports=G;else $.BN=G;G.BN=G,G.wordSize=26;var W;try{if(typeof window<"u"&&typeof window.Buffer<"u")W=window.Buffer;else W=(vY(),oQ(_Y)).Buffer}catch(V){}G.isBN=function(V){if(V instanceof G)return!0;return V!==null&&typeof V==="object"&&V.constructor.wordSize===G.wordSize&&Array.isArray(V.words)},G.max=function(V,z){if(V.cmp(z)>0)return V;return z},G.min=function(V,z){if(V.cmp(z)<0)return V;return z},G.prototype._init=function(V,z,H){if(typeof V==="number")return this._initNumber(V,z,H);if(typeof V==="object")return this._initArray(V,z,H);if(z==="hex")z=16;J(z===(z|0)&&z>=2&&z<=36),V=V.toString().replace(/\s+/g,"");var F=0;if(V[0]==="-")F++,this.negative=1;if(F<V.length){if(z===16)this._parseHex(V,F,H);else if(this._parseBase(V,z,F),H==="le")this._initArray(this.toArray(),z,H)}},G.prototype._initNumber=function(V,z,H){if(V<0)this.negative=1,V=-V;if(V<67108864)this.words=[V&67108863],this.length=1;else if(V<4503599627370496)this.words=[V&67108863,V/67108864&67108863],this.length=2;else J(V<9007199254740992),this.words=[V&67108863,V/67108864&67108863,1],this.length=3;if(H!=="le")return;this._initArray(this.toArray(),z,H)},G.prototype._initArray=function(V,z,H){if(J(typeof V.length==="number"),V.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(V.length/3),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D,P,j=0;if(H==="be"){for(F=V.length-1,D=0;F>=0;F-=3)if(P=V[F]|V[F-1]<<8|V[F-2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}else if(H==="le"){for(F=0,D=0;F<V.length;F+=3)if(P=V[F]|V[F+1]<<8|V[F+2]<<16,this.words[D]|=P<<j&67108863,this.words[D+1]=P>>>26-j&67108863,j+=24,j>=26)j-=26,D++}return this.strip()};function U(V,z){var H=V.charCodeAt(z);if(H>=65&&H<=70)return H-55;else if(H>=97&&H<=102)return H-87;else return H-48&15}function K(V,z,H){var F=U(V,H);if(H-1>=z)F|=U(V,H-1)<<4;return F}G.prototype._parseHex=function(V,z,H){this.length=Math.ceil((V.length-z)/6),this.words=Array(this.length);for(var F=0;F<this.length;F++)this.words[F]=0;var D=0,P=0,j;if(H==="be")for(F=V.length-1;F>=z;F-=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8;else{var R=V.length-z;for(F=R%2===0?z+1:z;F<V.length;F+=2)if(j=K(V,z,F)<<D,this.words[P]|=j&67108863,D>=18)D-=18,P+=1,this.words[P]|=j>>>26;else D+=8}this.strip()};function O(V,z,H,F){var D=0,P=Math.min(V.length,H);for(var j=z;j<P;j++){var R=V.charCodeAt(j)-48;if(D*=F,R>=49)D+=R-49+10;else if(R>=17)D+=R-17+10;else D+=R}return D}G.prototype._parseBase=function(V,z,H){this.words=[0],this.length=1;for(var F=0,D=1;D<=67108863;D*=z)F++;F--,D=D/z|0;var P=V.length-H,j=P%F,R=Math.min(P,P-j)+H,q=0;for(var E=H;E<R;E+=F)if(q=O(V,E,E+F,z),this.imuln(D),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q);if(j!==0){var N=1;q=O(V,E,V.length,z);for(E=0;E<j;E++)N*=z;if(this.imuln(N),this.words[0]+q<67108864)this.words[0]+=q;else this._iaddn(q)}this.strip()},G.prototype.copy=function(V){V.words=Array(this.length);for(var z=0;z<this.length;z++)V.words[z]=this.words[z];V.length=this.length,V.negative=this.negative,V.red=this.red},G.prototype.clone=function(){var V=new G(null);return this.copy(V),V},G.prototype._expand=function(V){while(this.length<V)this.words[this.length++]=0;return this},G.prototype.strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},G.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var I=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],L=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],A=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(G.prototype.toString=function(V,z){V=V||10,z=z|0||1;var H;if(V===16||V==="hex"){H="";var F=0,D=0;for(var P=0;P<this.length;P++){var j=this.words[P],R=((j<<F|D)&16777215).toString(16);if(D=j>>>24-F&16777215,F+=2,F>=26)F-=26,P--;if(D!==0||P!==this.length-1)H=I[6-R.length]+R+H;else H=R+H}if(D!==0)H=D.toString(16)+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}if(V===(V|0)&&V>=2&&V<=36){var q=L[V],E=A[V];H="";var N=this.clone();N.negative=0;while(!N.isZero()){var T=N.modn(E).toString(V);if(N=N.idivn(E),!N.isZero())H=I[q-T.length]+T+H;else H=T+H}if(this.isZero())H="0"+H;while(H.length%z!==0)H="0"+H;if(this.negative!==0)H="-"+H;return H}J(!1,"Base should be between 2 and 36")},G.prototype.toNumber=function(){var V=this.words[0];if(this.length===2)V+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)V+=4503599627370496+this.words[1]*67108864;else if(this.length>2)J(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-V:V},G.prototype.toJSON=function(){return this.toString(16)},G.prototype.toBuffer=function(V,z){return J(typeof W<"u"),this.toArrayLike(W,V,z)},G.prototype.toArray=function(V,z){return this.toArrayLike(Array,V,z)},G.prototype.toArrayLike=function(V,z,H){var F=this.byteLength(),D=H||Math.max(1,F);J(F<=D,"byte array longer than desired length"),J(D>0,"Requested array length <= 0"),this.strip();var P=z==="le",j=new V(D),R,q,E=this.clone();if(!P){for(q=0;q<D-F;q++)j[q]=0;for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[D-q-1]=R}else{for(q=0;!E.isZero();q++)R=E.andln(255),E.iushrn(8),j[q]=R;for(;q<D;q++)j[q]=0}return j},Math.clz32)G.prototype._countBits=function(V){return 32-Math.clz32(V)};else G.prototype._countBits=function(V){var z=V,H=0;if(z>=4096)H+=13,z>>>=13;if(z>=64)H+=7,z>>>=7;if(z>=8)H+=4,z>>>=4;if(z>=2)H+=2,z>>>=2;return H+z};G.prototype._zeroBits=function(V){if(V===0)return 26;var z=V,H=0;if((z&8191)===0)H+=13,z>>>=13;if((z&127)===0)H+=7,z>>>=7;if((z&15)===0)H+=4,z>>>=4;if((z&3)===0)H+=2,z>>>=2;if((z&1)===0)H++;return H},G.prototype.bitLength=function(){var V=this.words[this.length-1],z=this._countBits(V);return(this.length-1)*26+z};function M(V){var z=Array(V.bitLength());for(var H=0;H<z.length;H++){var F=H/26|0,D=H%26;z[H]=(V.words[F]&1<<D)>>>D}return z}G.prototype.zeroBits=function(){if(this.isZero())return 0;var V=0;for(var z=0;z<this.length;z++){var H=this._zeroBits(this.words[z]);if(V+=H,H!==26)break}return V},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(V){if(this.negative!==0)return this.abs().inotn(V).iaddn(1);return this.clone()},G.prototype.fromTwos=function(V){if(this.testn(V-1))return this.notn(V).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(V){while(this.length<V.length)this.words[this.length++]=0;for(var z=0;z<V.length;z++)this.words[z]=this.words[z]|V.words[z];return this.strip()},G.prototype.ior=function(V){return J((this.negative|V.negative)===0),this.iuor(V)},G.prototype.or=function(V){if(this.length>V.length)return this.clone().ior(V);return V.clone().ior(this)},G.prototype.uor=function(V){if(this.length>V.length)return this.clone().iuor(V);return V.clone().iuor(this)},G.prototype.iuand=function(V){var z;if(this.length>V.length)z=V;else z=this;for(var H=0;H<z.length;H++)this.words[H]=this.words[H]&V.words[H];return this.length=z.length,this.strip()},G.prototype.iand=function(V){return J((this.negative|V.negative)===0),this.iuand(V)},G.prototype.and=function(V){if(this.length>V.length)return this.clone().iand(V);return V.clone().iand(this)},G.prototype.uand=function(V){if(this.length>V.length)return this.clone().iuand(V);return V.clone().iuand(this)},G.prototype.iuxor=function(V){var z,H;if(this.length>V.length)z=this,H=V;else z=V,H=this;for(var F=0;F<H.length;F++)this.words[F]=z.words[F]^H.words[F];if(this!==z)for(;F<z.length;F++)this.words[F]=z.words[F];return this.length=z.length,this.strip()},G.prototype.ixor=function(V){return J((this.negative|V.negative)===0),this.iuxor(V)},G.prototype.xor=function(V){if(this.length>V.length)return this.clone().ixor(V);return V.clone().ixor(this)},G.prototype.uxor=function(V){if(this.length>V.length)return this.clone().iuxor(V);return V.clone().iuxor(this)},G.prototype.inotn=function(V){J(typeof V==="number"&&V>=0);var z=Math.ceil(V/26)|0,H=V%26;if(this._expand(z),H>0)z--;for(var F=0;F<z;F++)this.words[F]=~this.words[F]&67108863;if(H>0)this.words[F]=~this.words[F]&67108863>>26-H;return this.strip()},G.prototype.notn=function(V){return this.clone().inotn(V)},G.prototype.setn=function(V,z){J(typeof V==="number"&&V>=0);var H=V/26|0,F=V%26;if(this._expand(H+1),z)this.words[H]=this.words[H]|1<<F;else this.words[H]=this.words[H]&~(1<<F);return this.strip()},G.prototype.iadd=function(V){var z;if(this.negative!==0&&V.negative===0)return this.negative=0,z=this.isub(V),this.negative^=1,this._normSign();else if(this.negative===0&&V.negative!==0)return V.negative=0,z=this.isub(V),V.negative=1,z._normSign();var H,F;if(this.length>V.length)H=this,F=V;else H=V,F=this;var D=0;for(var P=0;P<F.length;P++)z=(H.words[P]|0)+(F.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;for(;D!==0&&P<H.length;P++)z=(H.words[P]|0)+D,this.words[P]=z&67108863,D=z>>>26;if(this.length=H.length,D!==0)this.words[this.length]=D,this.length++;else if(H!==this)for(;P<H.length;P++)this.words[P]=H.words[P];return this},G.prototype.add=function(V){var z;if(V.negative!==0&&this.negative===0)return V.negative=0,z=this.sub(V),V.negative^=1,z;else if(V.negative===0&&this.negative!==0)return this.negative=0,z=V.sub(this),this.negative=1,z;if(this.length>V.length)return this.clone().iadd(V);return V.clone().iadd(this)},G.prototype.isub=function(V){if(V.negative!==0){V.negative=0;var z=this.iadd(V);return V.negative=1,z._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(V),this.negative=1,this._normSign();var H=this.cmp(V);if(H===0)return this.negative=0,this.length=1,this.words[0]=0,this;var F,D;if(H>0)F=this,D=V;else F=V,D=this;var P=0;for(var j=0;j<D.length;j++)z=(F.words[j]|0)-(D.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;for(;P!==0&&j<F.length;j++)z=(F.words[j]|0)+P,P=z>>26,this.words[j]=z&67108863;if(P===0&&j<F.length&&F!==this)for(;j<F.length;j++)this.words[j]=F.words[j];if(this.length=Math.max(this.length,j),F!==this)this.negative=1;return this.strip()},G.prototype.sub=function(V){return this.clone().isub(V)};function k(V,z,H){H.negative=z.negative^V.negative;var F=V.length+z.length|0;H.length=F,F=F-1|0;var D=V.words[0]|0,P=z.words[0]|0,j=D*P,R=j&67108863,q=j/67108864|0;H.words[0]=R;for(var E=1;E<F;E++){var N=q>>>26,T=q&67108863,v=Math.min(E,z.length-1);for(var y=Math.max(0,E-V.length+1);y<=v;y++){var p=E-y|0;D=V.words[p]|0,P=z.words[y]|0,j=D*P+T,N+=j/67108864|0,T=j&67108863}H.words[E]=T|0,q=N|0}if(q!==0)H.words[E]=q|0;else H.length--;return H.strip()}var B=function(V,z,H){var F=V.words,D=z.words,P=H.words,j=0,R,q,E,N=F[0]|0,T=N&8191,v=N>>>13,y=F[1]|0,p=y&8191,J0=y>>>13,x0=F[2]|0,K0=x0&8191,Y0=x0>>>13,j0=F[3]|0,$0=j0&8191,D0=j0>>>13,$Q=F[4]|0,m=$Q&8191,n=$Q>>>13,B0=F[5]|0,F0=B0&8191,z0=B0>>>13,l0=F[6]|0,d=l0&8191,X0=l0>>>13,QQ=F[7]|0,V0=QQ&8191,P0=QQ>>>13,jQ=F[8]|0,c0=jQ&8191,u0=jQ>>>13,$Z=F[9]|0,y0=$Z&8191,s=$Z>>>13,M0=D[0]|0,G0=M0&8191,H0=M0>>>13,KQ=D[1]|0,f0=KQ&8191,h0=KQ>>>13,LQ=D[2]|0,E0=LQ&8191,A0=LQ>>>13,GQ=D[3]|0,T0=GQ&8191,S0=GQ>>>13,gQ=D[4]|0,g0=gQ&8191,d0=gQ>>>13,_Z=D[5]|0,o0=_Z&8191,b=_Z>>>13,Q0=D[6]|0,O0=Q0&8191,L0=Q0>>>13,qQ=D[7]|0,m0=qQ&8191,n0=qQ>>>13,lZ=D[8]|0,r0=lZ&8191,e0=lZ>>>13,bY=D[9]|0,t0=bY&8191,a0=bY>>>13;H.negative=V.negative^z.negative,H.length=19,R=Math.imul(T,G0),q=Math.imul(T,H0),q=q+Math.imul(v,G0)|0,E=Math.imul(v,H0);var mZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(mZ>>>26)|0,mZ&=67108863,R=Math.imul(p,G0),q=Math.imul(p,H0),q=q+Math.imul(J0,G0)|0,E=Math.imul(J0,H0),R=R+Math.imul(T,f0)|0,q=q+Math.imul(T,h0)|0,q=q+Math.imul(v,f0)|0,E=E+Math.imul(v,h0)|0;var lQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(lQ>>>26)|0,lQ&=67108863,R=Math.imul(K0,G0),q=Math.imul(K0,H0),q=q+Math.imul(Y0,G0)|0,E=Math.imul(Y0,H0),R=R+Math.imul(p,f0)|0,q=q+Math.imul(p,h0)|0,q=q+Math.imul(J0,f0)|0,E=E+Math.imul(J0,h0)|0,R=R+Math.imul(T,E0)|0,q=q+Math.imul(T,A0)|0,q=q+Math.imul(v,E0)|0,E=E+Math.imul(v,A0)|0;var pQ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(pQ>>>26)|0,pQ&=67108863,R=Math.imul($0,G0),q=Math.imul($0,H0),q=q+Math.imul(D0,G0)|0,E=Math.imul(D0,H0),R=R+Math.imul(K0,f0)|0,q=q+Math.imul(K0,h0)|0,q=q+Math.imul(Y0,f0)|0,E=E+Math.imul(Y0,h0)|0,R=R+Math.imul(p,E0)|0,q=q+Math.imul(p,A0)|0,q=q+Math.imul(J0,E0)|0,E=E+Math.imul(J0,A0)|0,R=R+Math.imul(T,T0)|0,q=q+Math.imul(T,S0)|0,q=q+Math.imul(v,T0)|0,E=E+Math.imul(v,S0)|0;var IZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,R=Math.imul(m,G0),q=Math.imul(m,H0),q=q+Math.imul(n,G0)|0,E=Math.imul(n,H0),R=R+Math.imul($0,f0)|0,q=q+Math.imul($0,h0)|0,q=q+Math.imul(D0,f0)|0,E=E+Math.imul(D0,h0)|0,R=R+Math.imul(K0,E0)|0,q=q+Math.imul(K0,A0)|0,q=q+Math.imul(Y0,E0)|0,E=E+Math.imul(Y0,A0)|0,R=R+Math.imul(p,T0)|0,q=q+Math.imul(p,S0)|0,q=q+Math.imul(J0,T0)|0,E=E+Math.imul(J0,S0)|0,R=R+Math.imul(T,g0)|0,q=q+Math.imul(T,d0)|0,q=q+Math.imul(v,g0)|0,E=E+Math.imul(v,d0)|0;var zZ=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,R=Math.imul(F0,G0),q=Math.imul(F0,H0),q=q+Math.imul(z0,G0)|0,E=Math.imul(z0,H0),R=R+Math.imul(m,f0)|0,q=q+Math.imul(m,h0)|0,q=q+Math.imul(n,f0)|0,E=E+Math.imul(n,h0)|0,R=R+Math.imul($0,E0)|0,q=q+Math.imul($0,A0)|0,q=q+Math.imul(D0,E0)|0,E=E+Math.imul(D0,A0)|0,R=R+Math.imul(K0,T0)|0,q=q+Math.imul(K0,S0)|0,q=q+Math.imul(Y0,T0)|0,E=E+Math.imul(Y0,S0)|0,R=R+Math.imul(p,g0)|0,q=q+Math.imul(p,d0)|0,q=q+Math.imul(J0,g0)|0,E=E+Math.imul(J0,d0)|0,R=R+Math.imul(T,o0)|0,q=q+Math.imul(T,b)|0,q=q+Math.imul(v,o0)|0,E=E+Math.imul(v,b)|0;var $Y=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+($Y>>>26)|0,$Y&=67108863,R=Math.imul(d,G0),q=Math.imul(d,H0),q=q+Math.imul(X0,G0)|0,E=Math.imul(X0,H0),R=R+Math.imul(F0,f0)|0,q=q+Math.imul(F0,h0)|0,q=q+Math.imul(z0,f0)|0,E=E+Math.imul(z0,h0)|0,R=R+Math.imul(m,E0)|0,q=q+Math.imul(m,A0)|0,q=q+Math.imul(n,E0)|0,E=E+Math.imul(n,A0)|0,R=R+Math.imul($0,T0)|0,q=q+Math.imul($0,S0)|0,q=q+Math.imul(D0,T0)|0,E=E+Math.imul(D0,S0)|0,R=R+Math.imul(K0,g0)|0,q=q+Math.imul(K0,d0)|0,q=q+Math.imul(Y0,g0)|0,E=E+Math.imul(Y0,d0)|0,R=R+Math.imul(p,o0)|0,q=q+Math.imul(p,b)|0,q=q+Math.imul(J0,o0)|0,E=E+Math.imul(J0,b)|0,R=R+Math.imul(T,O0)|0,q=q+Math.imul(T,L0)|0,q=q+Math.imul(v,O0)|0,E=E+Math.imul(v,L0)|0;var JY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(JY>>>26)|0,JY&=67108863,R=Math.imul(V0,G0),q=Math.imul(V0,H0),q=q+Math.imul(P0,G0)|0,E=Math.imul(P0,H0),R=R+Math.imul(d,f0)|0,q=q+Math.imul(d,h0)|0,q=q+Math.imul(X0,f0)|0,E=E+Math.imul(X0,h0)|0,R=R+Math.imul(F0,E0)|0,q=q+Math.imul(F0,A0)|0,q=q+Math.imul(z0,E0)|0,E=E+Math.imul(z0,A0)|0,R=R+Math.imul(m,T0)|0,q=q+Math.imul(m,S0)|0,q=q+Math.imul(n,T0)|0,E=E+Math.imul(n,S0)|0,R=R+Math.imul($0,g0)|0,q=q+Math.imul($0,d0)|0,q=q+Math.imul(D0,g0)|0,E=E+Math.imul(D0,d0)|0,R=R+Math.imul(K0,o0)|0,q=q+Math.imul(K0,b)|0,q=q+Math.imul(Y0,o0)|0,E=E+Math.imul(Y0,b)|0,R=R+Math.imul(p,O0)|0,q=q+Math.imul(p,L0)|0,q=q+Math.imul(J0,O0)|0,E=E+Math.imul(J0,L0)|0,R=R+Math.imul(T,m0)|0,q=q+Math.imul(T,n0)|0,q=q+Math.imul(v,m0)|0,E=E+Math.imul(v,n0)|0;var GY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(GY>>>26)|0,GY&=67108863,R=Math.imul(c0,G0),q=Math.imul(c0,H0),q=q+Math.imul(u0,G0)|0,E=Math.imul(u0,H0),R=R+Math.imul(V0,f0)|0,q=q+Math.imul(V0,h0)|0,q=q+Math.imul(P0,f0)|0,E=E+Math.imul(P0,h0)|0,R=R+Math.imul(d,E0)|0,q=q+Math.imul(d,A0)|0,q=q+Math.imul(X0,E0)|0,E=E+Math.imul(X0,A0)|0,R=R+Math.imul(F0,T0)|0,q=q+Math.imul(F0,S0)|0,q=q+Math.imul(z0,T0)|0,E=E+Math.imul(z0,S0)|0,R=R+Math.imul(m,g0)|0,q=q+Math.imul(m,d0)|0,q=q+Math.imul(n,g0)|0,E=E+Math.imul(n,d0)|0,R=R+Math.imul($0,o0)|0,q=q+Math.imul($0,b)|0,q=q+Math.imul(D0,o0)|0,E=E+Math.imul(D0,b)|0,R=R+Math.imul(K0,O0)|0,q=q+Math.imul(K0,L0)|0,q=q+Math.imul(Y0,O0)|0,E=E+Math.imul(Y0,L0)|0,R=R+Math.imul(p,m0)|0,q=q+Math.imul(p,n0)|0,q=q+Math.imul(J0,m0)|0,E=E+Math.imul(J0,n0)|0,R=R+Math.imul(T,r0)|0,q=q+Math.imul(T,e0)|0,q=q+Math.imul(v,r0)|0,E=E+Math.imul(v,e0)|0;var XY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(XY>>>26)|0,XY&=67108863,R=Math.imul(y0,G0),q=Math.imul(y0,H0),q=q+Math.imul(s,G0)|0,E=Math.imul(s,H0),R=R+Math.imul(c0,f0)|0,q=q+Math.imul(c0,h0)|0,q=q+Math.imul(u0,f0)|0,E=E+Math.imul(u0,h0)|0,R=R+Math.imul(V0,E0)|0,q=q+Math.imul(V0,A0)|0,q=q+Math.imul(P0,E0)|0,E=E+Math.imul(P0,A0)|0,R=R+Math.imul(d,T0)|0,q=q+Math.imul(d,S0)|0,q=q+Math.imul(X0,T0)|0,E=E+Math.imul(X0,S0)|0,R=R+Math.imul(F0,g0)|0,q=q+Math.imul(F0,d0)|0,q=q+Math.imul(z0,g0)|0,E=E+Math.imul(z0,d0)|0,R=R+Math.imul(m,o0)|0,q=q+Math.imul(m,b)|0,q=q+Math.imul(n,o0)|0,E=E+Math.imul(n,b)|0,R=R+Math.imul($0,O0)|0,q=q+Math.imul($0,L0)|0,q=q+Math.imul(D0,O0)|0,E=E+Math.imul(D0,L0)|0,R=R+Math.imul(K0,m0)|0,q=q+Math.imul(K0,n0)|0,q=q+Math.imul(Y0,m0)|0,E=E+Math.imul(Y0,n0)|0,R=R+Math.imul(p,r0)|0,q=q+Math.imul(p,e0)|0,q=q+Math.imul(J0,r0)|0,E=E+Math.imul(J0,e0)|0,R=R+Math.imul(T,t0)|0,q=q+Math.imul(T,a0)|0,q=q+Math.imul(v,t0)|0,E=E+Math.imul(v,a0)|0;var VY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(VY>>>26)|0,VY&=67108863,R=Math.imul(y0,f0),q=Math.imul(y0,h0),q=q+Math.imul(s,f0)|0,E=Math.imul(s,h0),R=R+Math.imul(c0,E0)|0,q=q+Math.imul(c0,A0)|0,q=q+Math.imul(u0,E0)|0,E=E+Math.imul(u0,A0)|0,R=R+Math.imul(V0,T0)|0,q=q+Math.imul(V0,S0)|0,q=q+Math.imul(P0,T0)|0,E=E+Math.imul(P0,S0)|0,R=R+Math.imul(d,g0)|0,q=q+Math.imul(d,d0)|0,q=q+Math.imul(X0,g0)|0,E=E+Math.imul(X0,d0)|0,R=R+Math.imul(F0,o0)|0,q=q+Math.imul(F0,b)|0,q=q+Math.imul(z0,o0)|0,E=E+Math.imul(z0,b)|0,R=R+Math.imul(m,O0)|0,q=q+Math.imul(m,L0)|0,q=q+Math.imul(n,O0)|0,E=E+Math.imul(n,L0)|0,R=R+Math.imul($0,m0)|0,q=q+Math.imul($0,n0)|0,q=q+Math.imul(D0,m0)|0,E=E+Math.imul(D0,n0)|0,R=R+Math.imul(K0,r0)|0,q=q+Math.imul(K0,e0)|0,q=q+Math.imul(Y0,r0)|0,E=E+Math.imul(Y0,e0)|0,R=R+Math.imul(p,t0)|0,q=q+Math.imul(p,a0)|0,q=q+Math.imul(J0,t0)|0,E=E+Math.imul(J0,a0)|0;var qY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(qY>>>26)|0,qY&=67108863,R=Math.imul(y0,E0),q=Math.imul(y0,A0),q=q+Math.imul(s,E0)|0,E=Math.imul(s,A0),R=R+Math.imul(c0,T0)|0,q=q+Math.imul(c0,S0)|0,q=q+Math.imul(u0,T0)|0,E=E+Math.imul(u0,S0)|0,R=R+Math.imul(V0,g0)|0,q=q+Math.imul(V0,d0)|0,q=q+Math.imul(P0,g0)|0,E=E+Math.imul(P0,d0)|0,R=R+Math.imul(d,o0)|0,q=q+Math.imul(d,b)|0,q=q+Math.imul(X0,o0)|0,E=E+Math.imul(X0,b)|0,R=R+Math.imul(F0,O0)|0,q=q+Math.imul(F0,L0)|0,q=q+Math.imul(z0,O0)|0,E=E+Math.imul(z0,L0)|0,R=R+Math.imul(m,m0)|0,q=q+Math.imul(m,n0)|0,q=q+Math.imul(n,m0)|0,E=E+Math.imul(n,n0)|0,R=R+Math.imul($0,r0)|0,q=q+Math.imul($0,e0)|0,q=q+Math.imul(D0,r0)|0,E=E+Math.imul(D0,e0)|0,R=R+Math.imul(K0,t0)|0,q=q+Math.imul(K0,a0)|0,q=q+Math.imul(Y0,t0)|0,E=E+Math.imul(Y0,a0)|0;var FY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(FY>>>26)|0,FY&=67108863,R=Math.imul(y0,T0),q=Math.imul(y0,S0),q=q+Math.imul(s,T0)|0,E=Math.imul(s,S0),R=R+Math.imul(c0,g0)|0,q=q+Math.imul(c0,d0)|0,q=q+Math.imul(u0,g0)|0,E=E+Math.imul(u0,d0)|0,R=R+Math.imul(V0,o0)|0,q=q+Math.imul(V0,b)|0,q=q+Math.imul(P0,o0)|0,E=E+Math.imul(P0,b)|0,R=R+Math.imul(d,O0)|0,q=q+Math.imul(d,L0)|0,q=q+Math.imul(X0,O0)|0,E=E+Math.imul(X0,L0)|0,R=R+Math.imul(F0,m0)|0,q=q+Math.imul(F0,n0)|0,q=q+Math.imul(z0,m0)|0,E=E+Math.imul(z0,n0)|0,R=R+Math.imul(m,r0)|0,q=q+Math.imul(m,e0)|0,q=q+Math.imul(n,r0)|0,E=E+Math.imul(n,e0)|0,R=R+Math.imul($0,t0)|0,q=q+Math.imul($0,a0)|0,q=q+Math.imul(D0,t0)|0,E=E+Math.imul(D0,a0)|0;var zY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(zY>>>26)|0,zY&=67108863,R=Math.imul(y0,g0),q=Math.imul(y0,d0),q=q+Math.imul(s,g0)|0,E=Math.imul(s,d0),R=R+Math.imul(c0,o0)|0,q=q+Math.imul(c0,b)|0,q=q+Math.imul(u0,o0)|0,E=E+Math.imul(u0,b)|0,R=R+Math.imul(V0,O0)|0,q=q+Math.imul(V0,L0)|0,q=q+Math.imul(P0,O0)|0,E=E+Math.imul(P0,L0)|0,R=R+Math.imul(d,m0)|0,q=q+Math.imul(d,n0)|0,q=q+Math.imul(X0,m0)|0,E=E+Math.imul(X0,n0)|0,R=R+Math.imul(F0,r0)|0,q=q+Math.imul(F0,e0)|0,q=q+Math.imul(z0,r0)|0,E=E+Math.imul(z0,e0)|0,R=R+Math.imul(m,t0)|0,q=q+Math.imul(m,a0)|0,q=q+Math.imul(n,t0)|0,E=E+Math.imul(n,a0)|0;var WY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(WY>>>26)|0,WY&=67108863,R=Math.imul(y0,o0),q=Math.imul(y0,b),q=q+Math.imul(s,o0)|0,E=Math.imul(s,b),R=R+Math.imul(c0,O0)|0,q=q+Math.imul(c0,L0)|0,q=q+Math.imul(u0,O0)|0,E=E+Math.imul(u0,L0)|0,R=R+Math.imul(V0,m0)|0,q=q+Math.imul(V0,n0)|0,q=q+Math.imul(P0,m0)|0,E=E+Math.imul(P0,n0)|0,R=R+Math.imul(d,r0)|0,q=q+Math.imul(d,e0)|0,q=q+Math.imul(X0,r0)|0,E=E+Math.imul(X0,e0)|0,R=R+Math.imul(F0,t0)|0,q=q+Math.imul(F0,a0)|0,q=q+Math.imul(z0,t0)|0,E=E+Math.imul(z0,a0)|0;var KY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(KY>>>26)|0,KY&=67108863,R=Math.imul(y0,O0),q=Math.imul(y0,L0),q=q+Math.imul(s,O0)|0,E=Math.imul(s,L0),R=R+Math.imul(c0,m0)|0,q=q+Math.imul(c0,n0)|0,q=q+Math.imul(u0,m0)|0,E=E+Math.imul(u0,n0)|0,R=R+Math.imul(V0,r0)|0,q=q+Math.imul(V0,e0)|0,q=q+Math.imul(P0,r0)|0,E=E+Math.imul(P0,e0)|0,R=R+Math.imul(d,t0)|0,q=q+Math.imul(d,a0)|0,q=q+Math.imul(X0,t0)|0,E=E+Math.imul(X0,a0)|0;var UY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(UY>>>26)|0,UY&=67108863,R=Math.imul(y0,m0),q=Math.imul(y0,n0),q=q+Math.imul(s,m0)|0,E=Math.imul(s,n0),R=R+Math.imul(c0,r0)|0,q=q+Math.imul(c0,e0)|0,q=q+Math.imul(u0,r0)|0,E=E+Math.imul(u0,e0)|0,R=R+Math.imul(V0,t0)|0,q=q+Math.imul(V0,a0)|0,q=q+Math.imul(P0,t0)|0,E=E+Math.imul(P0,a0)|0;var OY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(OY>>>26)|0,OY&=67108863,R=Math.imul(y0,r0),q=Math.imul(y0,e0),q=q+Math.imul(s,r0)|0,E=Math.imul(s,e0),R=R+Math.imul(c0,t0)|0,q=q+Math.imul(c0,a0)|0,q=q+Math.imul(u0,t0)|0,E=E+Math.imul(u0,a0)|0;var HY=(j+R|0)+((q&8191)<<13)|0;j=(E+(q>>>13)|0)+(HY>>>26)|0,HY&=67108863,R=Math.imul(y0,t0),q=Math.imul(y0,a0),q=q+Math.imul(s,t0)|0,E=Math.imul(s,a0);var DY=(j+R|0)+((q&8191)<<13)|0;if(j=(E+(q>>>13)|0)+(DY>>>26)|0,DY&=67108863,P[0]=mZ,P[1]=lQ,P[2]=pQ,P[3]=IZ,P[4]=zZ,P[5]=$Y,P[6]=JY,P[7]=GY,P[8]=XY,P[9]=VY,P[10]=qY,P[11]=FY,P[12]=zY,P[13]=WY,P[14]=KY,P[15]=UY,P[16]=OY,P[17]=HY,P[18]=DY,j!==0)P[19]=j,H.length++;return H};if(!Math.imul)B=k;function C(V,z,H){H.negative=z.negative^V.negative,H.length=V.length+z.length;var F=0,D=0;for(var P=0;P<H.length-1;P++){var j=D;D=0;var R=F&67108863,q=Math.min(P,z.length-1);for(var E=Math.max(0,P-V.length+1);E<=q;E++){var N=P-E,T=V.words[N]|0,v=z.words[E]|0,y=T*v,p=y&67108863;j=j+(y/67108864|0)|0,p=p+R|0,R=p&67108863,j=j+(p>>>26)|0,D+=j>>>26,j&=67108863}H.words[P]=R,F=j,j=D}if(F!==0)H.words[P]=F;else H.length--;return H.strip()}function S(V,z,H){var F=new _;return F.mulp(V,z,H)}G.prototype.mulTo=function(V,z){var H,F=this.length+V.length;if(this.length===10&&V.length===10)H=B(this,V,z);else if(F<63)H=k(this,V,z);else if(F<1024)H=C(this,V,z);else H=S(this,V,z);return H};function _(V,z){this.x=V,this.y=z}_.prototype.makeRBT=function(V){var z=Array(V),H=G.prototype._countBits(V)-1;for(var F=0;F<V;F++)z[F]=this.revBin(F,H,V);return z},_.prototype.revBin=function(V,z,H){if(V===0||V===H-1)return V;var F=0;for(var D=0;D<z;D++)F|=(V&1)<<z-D-1,V>>=1;return F},_.prototype.permute=function(V,z,H,F,D,P){for(var j=0;j<P;j++)F[j]=z[V[j]],D[j]=H[V[j]]},_.prototype.transform=function(V,z,H,F,D,P){this.permute(P,V,z,H,F,D);for(var j=1;j<D;j<<=1){var R=j<<1,q=Math.cos(2*Math.PI/R),E=Math.sin(2*Math.PI/R);for(var N=0;N<D;N+=R){var T=q,v=E;for(var y=0;y<j;y++){var p=H[N+y],J0=F[N+y],x0=H[N+y+j],K0=F[N+y+j],Y0=T*x0-v*K0;if(K0=T*K0+v*x0,x0=Y0,H[N+y]=p+x0,F[N+y]=J0+K0,H[N+y+j]=p-x0,F[N+y+j]=J0-K0,y!==R)Y0=q*T-E*v,v=q*v+E*T,T=Y0}}}},_.prototype.guessLen13b=function(V,z){var H=Math.max(z,V)|1,F=H&1,D=0;for(H=H/2|0;H;H=H>>>1)D++;return 1<<D+1+F},_.prototype.conjugate=function(V,z,H){if(H<=1)return;for(var F=0;F<H/2;F++){var D=V[F];V[F]=V[H-F-1],V[H-F-1]=D,D=z[F],z[F]=-z[H-F-1],z[H-F-1]=-D}},_.prototype.normalize13b=function(V,z){var H=0;for(var F=0;F<z/2;F++){var D=Math.round(V[2*F+1]/z)*8192+Math.round(V[2*F]/z)+H;if(V[F]=D&67108863,D<67108864)H=0;else H=D/67108864|0}return V},_.prototype.convert13b=function(V,z,H,F){var D=0;for(var P=0;P<z;P++)D=D+(V[P]|0),H[2*P]=D&8191,D=D>>>13,H[2*P+1]=D&8191,D=D>>>13;for(P=2*z;P<F;++P)H[P]=0;J(D===0),J((D&-8192)===0)},_.prototype.stub=function(V){var z=Array(V);for(var H=0;H<V;H++)z[H]=0;return z},_.prototype.mulp=function(V,z,H){var F=2*this.guessLen13b(V.length,z.length),D=this.makeRBT(F),P=this.stub(F),j=Array(F),R=Array(F),q=Array(F),E=Array(F),N=Array(F),T=Array(F),v=H.words;v.length=F,this.convert13b(V.words,V.length,j,F),this.convert13b(z.words,z.length,E,F),this.transform(j,P,R,q,F,D),this.transform(E,P,N,T,F,D);for(var y=0;y<F;y++){var p=R[y]*N[y]-q[y]*T[y];q[y]=R[y]*T[y]+q[y]*N[y],R[y]=p}return this.conjugate(R,q,F),this.transform(R,q,v,P,F,D),this.conjugate(v,P,F),this.normalize13b(v,F),H.negative=V.negative^z.negative,H.length=V.length+z.length,H.strip()},G.prototype.mul=function(V){var z=new G(null);return z.words=Array(this.length+V.length),this.mulTo(V,z)},G.prototype.mulf=function(V){var z=new G(null);return z.words=Array(this.length+V.length),S(this,V,z)},G.prototype.imul=function(V){return this.clone().mulTo(V,this)},G.prototype.imuln=function(V){J(typeof V==="number"),J(V<67108864);var z=0;for(var H=0;H<this.length;H++){var F=(this.words[H]|0)*V,D=(F&67108863)+(z&67108863);z>>=26,z+=F/67108864|0,z+=D>>>26,this.words[H]=D&67108863}if(z!==0)this.words[H]=z,this.length++;return this.length=V===0?1:this.length,this},G.prototype.muln=function(V){return this.clone().imuln(V)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(V){var z=M(V);if(z.length===0)return new G(1);var H=this;for(var F=0;F<z.length;F++,H=H.sqr())if(z[F]!==0)break;if(++F<z.length)for(var D=H.sqr();F<z.length;F++,D=D.sqr()){if(z[F]===0)continue;H=H.mul(D)}return H},G.prototype.iushln=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=67108863>>>26-z<<26-z,D;if(z!==0){var P=0;for(D=0;D<this.length;D++){var j=this.words[D]&F,R=(this.words[D]|0)-j<<z;this.words[D]=R|P,P=j>>>26-z}if(P)this.words[D]=P,this.length++}if(H!==0){for(D=this.length-1;D>=0;D--)this.words[D+H]=this.words[D];for(D=0;D<H;D++)this.words[D]=0;this.length+=H}return this.strip()},G.prototype.ishln=function(V){return J(this.negative===0),this.iushln(V)},G.prototype.iushrn=function(V,z,H){J(typeof V==="number"&&V>=0);var F;if(z)F=(z-z%26)/26;else F=0;var D=V%26,P=Math.min((V-D)/26,this.length),j=67108863^67108863>>>D<<D,R=H;if(F-=P,F=Math.max(0,F),R){for(var q=0;q<P;q++)R.words[q]=this.words[q];R.length=P}if(P===0);else if(this.length>P){this.length-=P;for(q=0;q<this.length;q++)this.words[q]=this.words[q+P]}else this.words[0]=0,this.length=1;var E=0;for(q=this.length-1;q>=0&&(E!==0||q>=F);q--){var N=this.words[q]|0;this.words[q]=E<<26-D|N>>>D,E=N&j}if(R&&E!==0)R.words[R.length++]=E;if(this.length===0)this.words[0]=0,this.length=1;return this.strip()},G.prototype.ishrn=function(V,z,H){return J(this.negative===0),this.iushrn(V,z,H)},G.prototype.shln=function(V){return this.clone().ishln(V)},G.prototype.ushln=function(V){return this.clone().iushln(V)},G.prototype.shrn=function(V){return this.clone().ishrn(V)},G.prototype.ushrn=function(V){return this.clone().iushrn(V)},G.prototype.testn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return!1;var D=this.words[H];return!!(D&F)},G.prototype.imaskn=function(V){J(typeof V==="number"&&V>=0);var z=V%26,H=(V-z)/26;if(J(this.negative===0,"imaskn works only with positive numbers"),this.length<=H)return this;if(z!==0)H++;if(this.length=Math.min(H,this.length),z!==0){var F=67108863^67108863>>>z<<z;this.words[this.length-1]&=F}return this.strip()},G.prototype.maskn=function(V){return this.clone().imaskn(V)},G.prototype.iaddn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.isubn(-V);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<V)return this.words[0]=V-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(V),this.negative=1,this}return this._iaddn(V)},G.prototype._iaddn=function(V){this.words[0]+=V;for(var z=0;z<this.length&&this.words[z]>=67108864;z++)if(this.words[z]-=67108864,z===this.length-1)this.words[z+1]=1;else this.words[z+1]++;return this.length=Math.max(this.length,z+1),this},G.prototype.isubn=function(V){if(J(typeof V==="number"),J(V<67108864),V<0)return this.iaddn(-V);if(this.negative!==0)return this.negative=0,this.iaddn(V),this.negative=1,this;if(this.words[0]-=V,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var z=0;z<this.length&&this.words[z]<0;z++)this.words[z]+=67108864,this.words[z+1]-=1;return this.strip()},G.prototype.addn=function(V){return this.clone().iaddn(V)},G.prototype.subn=function(V){return this.clone().isubn(V)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(V,z,H){var F=V.length+H,D;this._expand(F);var P,j=0;for(D=0;D<V.length;D++){P=(this.words[D+H]|0)+j;var R=(V.words[D]|0)*z;P-=R&67108863,j=(P>>26)-(R/67108864|0),this.words[D+H]=P&67108863}for(;D<this.length-H;D++)P=(this.words[D+H]|0)+j,j=P>>26,this.words[D+H]=P&67108863;if(j===0)return this.strip();J(j===-1),j=0;for(D=0;D<this.length;D++)P=-(this.words[D]|0)+j,j=P>>26,this.words[D]=P&67108863;return this.negative=1,this.strip()},G.prototype._wordDiv=function(V,z){var H=this.length-V.length,F=this.clone(),D=V,P=D.words[D.length-1]|0,j=this._countBits(P);if(H=26-j,H!==0)D=D.ushln(H),F.iushln(H),P=D.words[D.length-1]|0;var R=F.length-D.length,q;if(z!=="mod"){q=new G(null),q.length=R+1,q.words=Array(q.length);for(var E=0;E<q.length;E++)q.words[E]=0}var N=F.clone()._ishlnsubmul(D,1,R);if(N.negative===0){if(F=N,q)q.words[R]=1}for(var T=R-1;T>=0;T--){var v=(F.words[D.length+T]|0)*67108864+(F.words[D.length+T-1]|0);v=Math.min(v/P|0,67108863),F._ishlnsubmul(D,v,T);while(F.negative!==0)if(v--,F.negative=0,F._ishlnsubmul(D,1,T),!F.isZero())F.negative^=1;if(q)q.words[T]=v}if(q)q.strip();if(F.strip(),z!=="div"&&H!==0)F.iushrn(H);return{div:q||null,mod:F}},G.prototype.divmod=function(V,z,H){if(J(!V.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var F,D,P;if(this.negative!==0&&V.negative===0){if(P=this.neg().divmod(V,z),z!=="mod")F=P.div.neg();if(z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.iadd(V)}return{div:F,mod:D}}if(this.negative===0&&V.negative!==0){if(P=this.divmod(V.neg(),z),z!=="mod")F=P.div.neg();return{div:F,mod:P.mod}}if((this.negative&V.negative)!==0){if(P=this.neg().divmod(V.neg(),z),z!=="div"){if(D=P.mod.neg(),H&&D.negative!==0)D.isub(V)}return{div:P.div,mod:D}}if(V.length>this.length||this.cmp(V)<0)return{div:new G(0),mod:this};if(V.length===1){if(z==="div")return{div:this.divn(V.words[0]),mod:null};if(z==="mod")return{div:null,mod:new G(this.modn(V.words[0]))};return{div:this.divn(V.words[0]),mod:new G(this.modn(V.words[0]))}}return this._wordDiv(V,z)},G.prototype.div=function(V){return this.divmod(V,"div",!1).div},G.prototype.mod=function(V){return this.divmod(V,"mod",!1).mod},G.prototype.umod=function(V){return this.divmod(V,"mod",!0).mod},G.prototype.divRound=function(V){var z=this.divmod(V);if(z.mod.isZero())return z.div;var H=z.div.negative!==0?z.mod.isub(V):z.mod,F=V.ushrn(1),D=V.andln(1),P=H.cmp(F);if(P<0||D===1&&P===0)return z.div;return z.div.negative!==0?z.div.isubn(1):z.div.iaddn(1)},G.prototype.modn=function(V){J(V<=67108863);var z=67108864%V,H=0;for(var F=this.length-1;F>=0;F--)H=(z*H+(this.words[F]|0))%V;return H},G.prototype.idivn=function(V){J(V<=67108863);var z=0;for(var H=this.length-1;H>=0;H--){var F=(this.words[H]|0)+z*67108864;this.words[H]=F/V|0,z=F%V}return this.strip()},G.prototype.divn=function(V){return this.clone().idivn(V)},G.prototype.egcd=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=new G(0),j=new G(1),R=0;while(z.isEven()&&H.isEven())z.iushrn(1),H.iushrn(1),++R;var q=H.clone(),E=z.clone();while(!z.isZero()){for(var N=0,T=1;(z.words[0]&T)===0&&N<26;++N,T<<=1);if(N>0){z.iushrn(N);while(N-- >0){if(F.isOdd()||D.isOdd())F.iadd(q),D.isub(E);F.iushrn(1),D.iushrn(1)}}for(var v=0,y=1;(H.words[0]&y)===0&&v<26;++v,y<<=1);if(v>0){H.iushrn(v);while(v-- >0){if(P.isOdd()||j.isOdd())P.iadd(q),j.isub(E);P.iushrn(1),j.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(P),D.isub(j);else H.isub(z),P.isub(F),j.isub(D)}return{a:P,b:j,gcd:H.iushln(R)}},G.prototype._invmp=function(V){J(V.negative===0),J(!V.isZero());var z=this,H=V.clone();if(z.negative!==0)z=z.umod(V);else z=z.clone();var F=new G(1),D=new G(0),P=H.clone();while(z.cmpn(1)>0&&H.cmpn(1)>0){for(var j=0,R=1;(z.words[0]&R)===0&&j<26;++j,R<<=1);if(j>0){z.iushrn(j);while(j-- >0){if(F.isOdd())F.iadd(P);F.iushrn(1)}}for(var q=0,E=1;(H.words[0]&E)===0&&q<26;++q,E<<=1);if(q>0){H.iushrn(q);while(q-- >0){if(D.isOdd())D.iadd(P);D.iushrn(1)}}if(z.cmp(H)>=0)z.isub(H),F.isub(D);else H.isub(z),D.isub(F)}var N;if(z.cmpn(1)===0)N=F;else N=D;if(N.cmpn(0)<0)N.iadd(V);return N},G.prototype.gcd=function(V){if(this.isZero())return V.abs();if(V.isZero())return this.abs();var z=this.clone(),H=V.clone();z.negative=0,H.negative=0;for(var F=0;z.isEven()&&H.isEven();F++)z.iushrn(1),H.iushrn(1);do{while(z.isEven())z.iushrn(1);while(H.isEven())H.iushrn(1);var D=z.cmp(H);if(D<0){var P=z;z=H,H=P}else if(D===0||H.cmpn(1)===0)break;z.isub(H)}while(!0);return H.iushln(F)},G.prototype.invm=function(V){return this.egcd(V).a.umod(V)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(V){return this.words[0]&V},G.prototype.bincn=function(V){J(typeof V==="number");var z=V%26,H=(V-z)/26,F=1<<z;if(this.length<=H)return this._expand(H+1),this.words[H]|=F,this;var D=F;for(var P=H;D!==0&&P<this.length;P++){var j=this.words[P]|0;j+=D,D=j>>>26,j&=67108863,this.words[P]=j}if(D!==0)this.words[P]=D,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(V){var z=V<0;if(this.negative!==0&&!z)return-1;if(this.negative===0&&z)return 1;this.strip();var H;if(this.length>1)H=1;else{if(z)V=-V;J(V<=67108863,"Number is too big");var F=this.words[0]|0;H=F===V?0:F<V?-1:1}if(this.negative!==0)return-H|0;return H},G.prototype.cmp=function(V){if(this.negative!==0&&V.negative===0)return-1;if(this.negative===0&&V.negative!==0)return 1;var z=this.ucmp(V);if(this.negative!==0)return-z|0;return z},G.prototype.ucmp=function(V){if(this.length>V.length)return 1;if(this.length<V.length)return-1;var z=0;for(var H=this.length-1;H>=0;H--){var F=this.words[H]|0,D=V.words[H]|0;if(F===D)continue;if(F<D)z=-1;else if(F>D)z=1;break}return z},G.prototype.gtn=function(V){return this.cmpn(V)===1},G.prototype.gt=function(V){return this.cmp(V)===1},G.prototype.gten=function(V){return this.cmpn(V)>=0},G.prototype.gte=function(V){return this.cmp(V)>=0},G.prototype.ltn=function(V){return this.cmpn(V)===-1},G.prototype.lt=function(V){return this.cmp(V)===-1},G.prototype.lten=function(V){return this.cmpn(V)<=0},G.prototype.lte=function(V){return this.cmp(V)<=0},G.prototype.eqn=function(V){return this.cmpn(V)===0},G.prototype.eq=function(V){return this.cmp(V)===0},G.red=function(V){return new c(V)},G.prototype.toRed=function(V){return J(!this.red,"Already a number in reduction context"),J(this.negative===0,"red works only with positives"),V.convertTo(this)._forceRed(V)},G.prototype.fromRed=function(){return J(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(V){return this.red=V,this},G.prototype.forceRed=function(V){return J(!this.red,"Already a number in reduction context"),this._forceRed(V)},G.prototype.redAdd=function(V){return J(this.red,"redAdd works only with red numbers"),this.red.add(this,V)},G.prototype.redIAdd=function(V){return J(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,V)},G.prototype.redSub=function(V){return J(this.red,"redSub works only with red numbers"),this.red.sub(this,V)},G.prototype.redISub=function(V){return J(this.red,"redISub works only with red numbers"),this.red.isub(this,V)},G.prototype.redShl=function(V){return J(this.red,"redShl works only with red numbers"),this.red.shl(this,V)},G.prototype.redMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.mul(this,V)},G.prototype.redIMul=function(V){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,V),this.red.imul(this,V)},G.prototype.redSqr=function(){return J(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return J(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return J(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return J(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return J(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(V){return J(this.red&&!V.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,V)};var x={k256:null,p224:null,p192:null,p25519:null};function f(V,z){this.name=V,this.p=new G(z,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}f.prototype._tmp=function(){var V=new G(null);return V.words=Array(Math.ceil(this.n/13)),V},f.prototype.ireduce=function(V){var z=V,H;do this.split(z,this.tmp),z=this.imulK(z),z=z.iadd(this.tmp),H=z.bitLength();while(H>this.n);var F=H<this.n?-1:z.ucmp(this.p);if(F===0)z.words[0]=0,z.length=1;else if(F>0)z.isub(this.p);else if(z.strip!==void 0)z.strip();else z._strip();return z},f.prototype.split=function(V,z){V.iushrn(this.n,0,z)},f.prototype.imulK=function(V){return V.imul(this.k)};function h(){f.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(h,f),h.prototype.split=function(V,z){var H=4194303,F=Math.min(V.length,9);for(var D=0;D<F;D++)z.words[D]=V.words[D];if(z.length=F,V.length<=9){V.words[0]=0,V.length=1;return}var P=V.words[9];z.words[z.length++]=P&H;for(D=10;D<V.length;D++){var j=V.words[D]|0;V.words[D-10]=(j&H)<<4|P>>>22,P=j}if(P>>>=22,V.words[D-10]=P,P===0&&V.length>10)V.length-=10;else V.length-=9},h.prototype.imulK=function(V){V.words[V.length]=0,V.words[V.length+1]=0,V.length+=2;var z=0;for(var H=0;H<V.length;H++){var F=V.words[H]|0;z+=F*977,V.words[H]=z&67108863,z=F*64+(z/67108864|0)}if(V.words[V.length-1]===0){if(V.length--,V.words[V.length-1]===0)V.length--}return V};function i(){f.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(i,f);function Z0(){f.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(Z0,f);function t(){f.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(t,f),t.prototype.imulK=function(V){var z=0;for(var H=0;H<V.length;H++){var F=(V.words[H]|0)*19+z,D=F&67108863;F>>>=26,V.words[H]=D,z=F}if(z!==0)V.words[V.length++]=z;return V},G._prime=function(V){if(x[V])return x[V];var z;if(V==="k256")z=new h;else if(V==="p224")z=new i;else if(V==="p192")z=new Z0;else if(V==="p25519")z=new t;else throw Error("Unknown prime "+V);return x[V]=z,z};function c(V){if(typeof V==="string"){var z=G._prime(V);this.m=z.p,this.prime=z}else J(V.gtn(1),"modulus must be greater than 1"),this.m=V,this.prime=null}c.prototype._verify1=function(V){J(V.negative===0,"red works only with positives"),J(V.red,"red works only with red numbers")},c.prototype._verify2=function(V,z){J((V.negative|z.negative)===0,"red works only with positives"),J(V.red&&V.red===z.red,"red works only with red numbers")},c.prototype.imod=function(V){if(this.prime)return this.prime.ireduce(V)._forceRed(this);return V.umod(this.m)._forceRed(this)},c.prototype.neg=function(V){if(V.isZero())return V.clone();return this.m.sub(V)._forceRed(this)},c.prototype.add=function(V,z){this._verify2(V,z);var H=V.add(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H._forceRed(this)},c.prototype.iadd=function(V,z){this._verify2(V,z);var H=V.iadd(z);if(H.cmp(this.m)>=0)H.isub(this.m);return H},c.prototype.sub=function(V,z){this._verify2(V,z);var H=V.sub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H._forceRed(this)},c.prototype.isub=function(V,z){this._verify2(V,z);var H=V.isub(z);if(H.cmpn(0)<0)H.iadd(this.m);return H},c.prototype.shl=function(V,z){return this._verify1(V),this.imod(V.ushln(z))},c.prototype.imul=function(V,z){return this._verify2(V,z),this.imod(V.imul(z))},c.prototype.mul=function(V,z){return this._verify2(V,z),this.imod(V.mul(z))},c.prototype.isqr=function(V){return this.imul(V,V.clone())},c.prototype.sqr=function(V){return this.mul(V,V)},c.prototype.sqrt=function(V){if(V.isZero())return V.clone();var z=this.m.andln(3);if(J(z%2===1),z===3){var H=this.m.add(new G(1)).iushrn(2);return this.pow(V,H)}var F=this.m.subn(1),D=0;while(!F.isZero()&&F.andln(1)===0)D++,F.iushrn(1);J(!F.isZero());var P=new G(1).toRed(this),j=P.redNeg(),R=this.m.subn(1).iushrn(1),q=this.m.bitLength();q=new G(2*q*q).toRed(this);while(this.pow(q,R).cmp(j)!==0)q.redIAdd(j);var E=this.pow(q,F),N=this.pow(V,F.addn(1).iushrn(1)),T=this.pow(V,F),v=D;while(T.cmp(P)!==0){var y=T;for(var p=0;y.cmp(P)!==0;p++)y=y.redSqr();J(p<v);var J0=this.pow(E,new G(1).iushln(v-p-1));N=N.redMul(J0),E=J0.redSqr(),T=T.redMul(E),v=p}return N},c.prototype.invm=function(V){var z=V._invmp(this.m);if(z.negative!==0)return z.negative=0,this.imod(z).redNeg();else return this.imod(z)},c.prototype.pow=function(V,z){if(z.isZero())return new G(1).toRed(this);if(z.cmpn(1)===0)return V.clone();var H=4,F=Array(1<<H);F[0]=new G(1).toRed(this),F[1]=V;for(var D=2;D<F.length;D++)F[D]=this.mul(F[D-1],V);var P=F[0],j=0,R=0,q=z.bitLength()%26;if(q===0)q=26;for(D=z.length-1;D>=0;D--){var E=z.words[D];for(var N=q-1;N>=0;N--){var T=E>>N&1;if(P!==F[0])P=this.sqr(P);if(T===0&&j===0){R=0;continue}if(j<<=1,j|=T,R++,R!==H&&(D!==0||N!==0))continue;P=this.mul(P,F[j]),R=0,j=0}q=26}return P},c.prototype.convertTo=function(V){var z=V.umod(this.m);return z===V?z.clone():z},c.prototype.convertFrom=function(V){var z=V.clone();return z.red=null,z},G.mont=function(V){return new l(V)};function l(V){if(c.call(this,V),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(l,c),l.prototype.convertTo=function(V){return this.imod(V.ushln(this.shift))},l.prototype.convertFrom=function(V){var z=this.imod(V.mul(this.rinv));return z.red=null,z},l.prototype.imul=function(V,z){if(V.isZero()||z.isZero())return V.words[0]=0,V.length=1,V;var H=V.imul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.mul=function(V,z){if(V.isZero()||z.isZero())return new G(0)._forceRed(this);var H=V.mul(z),F=H.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),D=H.isub(F).iushrn(this.shift),P=D;if(D.cmp(this.m)>=0)P=D.isub(this.m);else if(D.cmpn(0)<0)P=D.iadd(this.m);return P._forceRed(this)},l.prototype.invm=function(V){var z=this.imod(V._invmp(this.m).mul(this.r2));return z._forceRed(this)}})(typeof Z>"u"||Z,Q)}),AS=v0((Q,Z)=>{var Y=MD(),$=I$().Buffer;function J(X,G){return $.from(X.toRed(Y.mont(G.modulus)).redPow(new Y(G.publicExponent)).fromRed().toArray())}Z.exports=J}),Me=v0((Q,Z)=>{(function(Y,$){function J(F,D){if(!F)throw Error(D||"Assertion failed")}function X(F,D){F.super_=D;var P=function(){};P.prototype=D.prototype,F.prototype=new P,F.prototype.constructor=F}function G(F,D,P){if(G.isBN(F))return F;if(this.negative=0,this.words=null,this.length=0,this.red=null,F!==null){if(D==="le"||D==="be")P=D,D=10;this._init(F||0,D||10,P||"be")}}if(typeof Y==="object")Y.exports=G;else $.BN=G;G.BN=G,G.wordSize=26;var W;try{if(typeof window<"u"&&typeof window.Buffer<"u")W=window.Buffer;else W=(vY(),oQ(_Y)).Buffer}catch(F){}G.isBN=function(F){if(F instanceof G)return!0;return F!==null&&typeof F==="object"&&F.constructor.wordSize===G.wordSize&&Array.isArray(F.words)},G.max=function(F,D){if(F.cmp(D)>0)return F;return D},G.min=function(F,D){if(F.cmp(D)<0)return F;return D},G.prototype._init=function(F,D,P){if(typeof F==="number")return this._initNumber(F,D,P);if(typeof F==="object")return this._initArray(F,D,P);if(D==="hex")D=16;J(D===(D|0)&&D>=2&&D<=36),F=F.toString().replace(/\s+/g,"");var j=0;if(F[0]==="-")j++,this.negative=1;if(j<F.length){if(D===16)this._parseHex(F,j,P);else if(this._parseBase(F,D,j),P==="le")this._initArray(this.toArray(),D,P)}},G.prototype._initNumber=function(F,D,P){if(F<0)this.negative=1,F=-F;if(F<67108864)this.words=[F&67108863],this.length=1;else if(F<4503599627370496)this.words=[F&67108863,F/67108864&67108863],this.length=2;else J(F<9007199254740992),this.words=[F&67108863,F/67108864&67108863,1],this.length=3;if(P!=="le")return;this._initArray(this.toArray(),D,P)},G.prototype._initArray=function(F,D,P){if(J(typeof F.length==="number"),F.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(F.length/3),this.words=Array(this.length);for(var j=0;j<this.length;j++)this.words[j]=0;var R,q,E=0;if(P==="be"){for(j=F.length-1,R=0;j>=0;j-=3)if(q=F[j]|F[j-1]<<8|F[j-2]<<16,this.words[R]|=q<<E&67108863,this.words[R+1]=q>>>26-E&67108863,E+=24,E>=26)E-=26,R++}else if(P==="le"){for(j=0,R=0;j<F.length;j+=3)if(q=F[j]|F[j+1]<<8|F[j+2]<<16,this.words[R]|=q<<E&67108863,this.words[R+1]=q>>>26-E&67108863,E+=24,E>=26)E-=26,R++}return this._strip()};function U(F,D){var P=F.charCodeAt(D);if(P>=48&&P<=57)return P-48;else if(P>=65&&P<=70)return P-55;else if(P>=97&&P<=102)return P-87;else J(!1,"Invalid character in "+F)}function K(F,D,P){var j=U(F,P);if(P-1>=D)j|=U(F,P-1)<<4;return j}G.prototype._parseHex=function(F,D,P){this.length=Math.ceil((F.length-D)/6),this.words=Array(this.length);for(var j=0;j<this.length;j++)this.words[j]=0;var R=0,q=0,E;if(P==="be")for(j=F.length-1;j>=D;j-=2)if(E=K(F,D,j)<<R,this.words[q]|=E&67108863,R>=18)R-=18,q+=1,this.words[q]|=E>>>26;else R+=8;else{var N=F.length-D;for(j=N%2===0?D+1:D;j<F.length;j+=2)if(E=K(F,D,j)<<R,this.words[q]|=E&67108863,R>=18)R-=18,q+=1,this.words[q]|=E>>>26;else R+=8}this._strip()};function O(F,D,P,j){var R=0,q=0,E=Math.min(F.length,P);for(var N=D;N<E;N++){var T=F.charCodeAt(N)-48;if(R*=j,T>=49)q=T-49+10;else if(T>=17)q=T-17+10;else q=T;J(T>=0&&q<j,"Invalid character"),R+=q}return R}G.prototype._parseBase=function(F,D,P){this.words=[0],this.length=1;for(var j=0,R=1;R<=67108863;R*=D)j++;j--,R=R/D|0;var q=F.length-P,E=q%j,N=Math.min(q,q-E)+P,T=0;for(var v=P;v<N;v+=j)if(T=O(F,v,v+j,D),this.imuln(R),this.words[0]+T<67108864)this.words[0]+=T;else this._iaddn(T);if(E!==0){var y=1;T=O(F,v,F.length,D);for(v=0;v<E;v++)y*=D;if(this.imuln(y),this.words[0]+T<67108864)this.words[0]+=T;else this._iaddn(T)}this._strip()},G.prototype.copy=function(F){F.words=Array(this.length);for(var D=0;D<this.length;D++)F.words[D]=this.words[D];F.length=this.length,F.negative=this.negative,F.red=this.red};function I(F,D){F.words=D.words,F.length=D.length,F.negative=D.negative,F.red=D.red}if(G.prototype._move=function(F){I(F,this)},G.prototype.clone=function(){var F=new G(null);return this.copy(F),F},G.prototype._expand=function(F){while(this.length<F)this.words[this.length++]=0;return this},G.prototype._strip=function(){while(this.length>1&&this.words[this.length-1]===0)this.length--;return this._normSign()},G.prototype._normSign=function(){if(this.length===1&&this.words[0]===0)this.negative=0;return this},typeof Symbol<"u"&&typeof Symbol.for==="function")try{G.prototype[Symbol.for("nodejs.util.inspect.custom")]=L}catch(F){G.prototype.inspect=L}else G.prototype.inspect=L;function L(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var A=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],M=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],k=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];if(G.prototype.toString=function(F,D){F=F||10,D=D|0||1;var P;if(F===16||F==="hex"){P="";var j=0,R=0;for(var q=0;q<this.length;q++){var E=this.words[q],N=((E<<j|R)&16777215).toString(16);if(R=E>>>24-j&16777215,j+=2,j>=26)j-=26,q--;if(R!==0||q!==this.length-1)P=A[6-N.length]+N+P;else P=N+P}if(R!==0)P=R.toString(16)+P;while(P.length%D!==0)P="0"+P;if(this.negative!==0)P="-"+P;return P}if(F===(F|0)&&F>=2&&F<=36){var T=M[F],v=k[F];P="";var y=this.clone();y.negative=0;while(!y.isZero()){var p=y.modrn(v).toString(F);if(y=y.idivn(v),!y.isZero())P=A[T-p.length]+p+P;else P=p+P}if(this.isZero())P="0"+P;while(P.length%D!==0)P="0"+P;if(this.negative!==0)P="-"+P;return P}J(!1,"Base should be between 2 and 36")},G.prototype.toNumber=function(){var F=this.words[0];if(this.length===2)F+=this.words[1]*67108864;else if(this.length===3&&this.words[2]===1)F+=4503599627370496+this.words[1]*67108864;else if(this.length>2)J(!1,"Number can only safely store up to 53 bits");return this.negative!==0?-F:F},G.prototype.toJSON=function(){return this.toString(16,2)},W)G.prototype.toBuffer=function(F,D){return this.toArrayLike(W,F,D)};G.prototype.toArray=function(F,D){return this.toArrayLike(Array,F,D)};var B=function(F,D){if(F.allocUnsafe)return F.allocUnsafe(D);return new F(D)};if(G.prototype.toArrayLike=function(F,D,P){this._strip();var j=this.byteLength(),R=P||Math.max(1,j);J(j<=R,"byte array longer than desired length"),J(R>0,"Requested array length <= 0");var q=B(F,R),E=D==="le"?"LE":"BE";return this["_toArrayLike"+E](q,j),q},G.prototype._toArrayLikeLE=function(F,D){var P=0,j=0;for(var R=0,q=0;R<this.length;R++){var E=this.words[R]<<q|j;if(F[P++]=E&255,P<F.length)F[P++]=E>>8&255;if(P<F.length)F[P++]=E>>16&255;if(q===6){if(P<F.length)F[P++]=E>>24&255;j=0,q=0}else j=E>>>24,q+=2}if(P<F.length){F[P++]=j;while(P<F.length)F[P++]=0}},G.prototype._toArrayLikeBE=function(F,D){var P=F.length-1,j=0;for(var R=0,q=0;R<this.length;R++){var E=this.words[R]<<q|j;if(F[P--]=E&255,P>=0)F[P--]=E>>8&255;if(P>=0)F[P--]=E>>16&255;if(q===6){if(P>=0)F[P--]=E>>24&255;j=0,q=0}else j=E>>>24,q+=2}if(P>=0){F[P--]=j;while(P>=0)F[P--]=0}},Math.clz32)G.prototype._countBits=function(F){return 32-Math.clz32(F)};else G.prototype._countBits=function(F){var D=F,P=0;if(D>=4096)P+=13,D>>>=13;if(D>=64)P+=7,D>>>=7;if(D>=8)P+=4,D>>>=4;if(D>=2)P+=2,D>>>=2;return P+D};G.prototype._zeroBits=function(F){if(F===0)return 26;var D=F,P=0;if((D&8191)===0)P+=13,D>>>=13;if((D&127)===0)P+=7,D>>>=7;if((D&15)===0)P+=4,D>>>=4;if((D&3)===0)P+=2,D>>>=2;if((D&1)===0)P++;return P},G.prototype.bitLength=function(){var F=this.words[this.length-1],D=this._countBits(F);return(this.length-1)*26+D};function C(F){var D=Array(F.bitLength());for(var P=0;P<D.length;P++){var j=P/26|0,R=P%26;D[P]=F.words[j]>>>R&1}return D}G.prototype.zeroBits=function(){if(this.isZero())return 0;var F=0;for(var D=0;D<this.length;D++){var P=this._zeroBits(this.words[D]);if(F+=P,P!==26)break}return F},G.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},G.prototype.toTwos=function(F){if(this.negative!==0)return this.abs().inotn(F).iaddn(1);return this.clone()},G.prototype.fromTwos=function(F){if(this.testn(F-1))return this.notn(F).iaddn(1).ineg();return this.clone()},G.prototype.isNeg=function(){return this.negative!==0},G.prototype.neg=function(){return this.clone().ineg()},G.prototype.ineg=function(){if(!this.isZero())this.negative^=1;return this},G.prototype.iuor=function(F){while(this.length<F.length)this.words[this.length++]=0;for(var D=0;D<F.length;D++)this.words[D]=this.words[D]|F.words[D];return this._strip()},G.prototype.ior=function(F){return J((this.negative|F.negative)===0),this.iuor(F)},G.prototype.or=function(F){if(this.length>F.length)return this.clone().ior(F);return F.clone().ior(this)},G.prototype.uor=function(F){if(this.length>F.length)return this.clone().iuor(F);return F.clone().iuor(this)},G.prototype.iuand=function(F){var D;if(this.length>F.length)D=F;else D=this;for(var P=0;P<D.length;P++)this.words[P]=this.words[P]&F.words[P];return this.length=D.length,this._strip()},G.prototype.iand=function(F){return J((this.negative|F.negative)===0),this.iuand(F)},G.prototype.and=function(F){if(this.length>F.length)return this.clone().iand(F);return F.clone().iand(this)},G.prototype.uand=function(F){if(this.length>F.length)return this.clone().iuand(F);return F.clone().iuand(this)},G.prototype.iuxor=function(F){var D,P;if(this.length>F.length)D=this,P=F;else D=F,P=this;for(var j=0;j<P.length;j++)this.words[j]=D.words[j]^P.words[j];if(this!==D)for(;j<D.length;j++)this.words[j]=D.words[j];return this.length=D.length,this._strip()},G.prototype.ixor=function(F){return J((this.negative|F.negative)===0),this.iuxor(F)},G.prototype.xor=function(F){if(this.length>F.length)return this.clone().ixor(F);return F.clone().ixor(this)},G.prototype.uxor=function(F){if(this.length>F.length)return this.clone().iuxor(F);return F.clone().iuxor(this)},G.prototype.inotn=function(F){J(typeof F==="number"&&F>=0);var D=Math.ceil(F/26)|0,P=F%26;if(this._expand(D),P>0)D--;for(var j=0;j<D;j++)this.words[j]=~this.words[j]&67108863;if(P>0)this.words[j]=~this.words[j]&67108863>>26-P;return this._strip()},G.prototype.notn=function(F){return this.clone().inotn(F)},G.prototype.setn=function(F,D){J(typeof F==="number"&&F>=0);var P=F/26|0,j=F%26;if(this._expand(P+1),D)this.words[P]=this.words[P]|1<<j;else this.words[P]=this.words[P]&~(1<<j);return this._strip()},G.prototype.iadd=function(F){var D;if(this.negative!==0&&F.negative===0)return this.negative=0,D=this.isub(F),this.negative^=1,this._normSign();else if(this.negative===0&&F.negative!==0)return F.negative=0,D=this.isub(F),F.negative=1,D._normSign();var P,j;if(this.length>F.length)P=this,j=F;else P=F,j=this;var R=0;for(var q=0;q<j.length;q++)D=(P.words[q]|0)+(j.words[q]|0)+R,this.words[q]=D&67108863,R=D>>>26;for(;R!==0&&q<P.length;q++)D=(P.words[q]|0)+R,this.words[q]=D&67108863,R=D>>>26;if(this.length=P.length,R!==0)this.words[this.length]=R,this.length++;else if(P!==this)for(;q<P.length;q++)this.words[q]=P.words[q];return this},G.prototype.add=function(F){var D;if(F.negative!==0&&this.negative===0)return F.negative=0,D=this.sub(F),F.negative^=1,D;else if(F.negative===0&&this.negative!==0)return this.negative=0,D=F.sub(this),this.negative=1,D;if(this.length>F.length)return this.clone().iadd(F);return F.clone().iadd(this)},G.prototype.isub=function(F){if(F.negative!==0){F.negative=0;var D=this.iadd(F);return F.negative=1,D._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(F),this.negative=1,this._normSign();var P=this.cmp(F);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var j,R;if(P>0)j=this,R=F;else j=F,R=this;var q=0;for(var E=0;E<R.length;E++)D=(j.words[E]|0)-(R.words[E]|0)+q,q=D>>26,this.words[E]=D&67108863;for(;q!==0&&E<j.length;E++)D=(j.words[E]|0)+q,q=D>>26,this.words[E]=D&67108863;if(q===0&&E<j.length&&j!==this)for(;E<j.length;E++)this.words[E]=j.words[E];if(this.length=Math.max(this.length,E),j!==this)this.negative=1;return this._strip()},G.prototype.sub=function(F){return this.clone().isub(F)};function S(F,D,P){P.negative=D.negative^F.negative;var j=F.length+D.length|0;P.length=j,j=j-1|0;var R=F.words[0]|0,q=D.words[0]|0,E=R*q,N=E&67108863,T=E/67108864|0;P.words[0]=N;for(var v=1;v<j;v++){var y=T>>>26,p=T&67108863,J0=Math.min(v,D.length-1);for(var x0=Math.max(0,v-F.length+1);x0<=J0;x0++){var K0=v-x0|0;R=F.words[K0]|0,q=D.words[x0]|0,E=R*q+p,y+=E/67108864|0,p=E&67108863}P.words[v]=p|0,T=y|0}if(T!==0)P.words[v]=T|0;else P.length--;return P._strip()}var _=function(F,D,P){var j=F.words,R=D.words,q=P.words,E=0,N,T,v,y=j[0]|0,p=y&8191,J0=y>>>13,x0=j[1]|0,K0=x0&8191,Y0=x0>>>13,j0=j[2]|0,$0=j0&8191,D0=j0>>>13,$Q=j[3]|0,m=$Q&8191,n=$Q>>>13,B0=j[4]|0,F0=B0&8191,z0=B0>>>13,l0=j[5]|0,d=l0&8191,X0=l0>>>13,QQ=j[6]|0,V0=QQ&8191,P0=QQ>>>13,jQ=j[7]|0,c0=jQ&8191,u0=jQ>>>13,$Z=j[8]|0,y0=$Z&8191,s=$Z>>>13,M0=j[9]|0,G0=M0&8191,H0=M0>>>13,KQ=R[0]|0,f0=KQ&8191,h0=KQ>>>13,LQ=R[1]|0,E0=LQ&8191,A0=LQ>>>13,GQ=R[2]|0,T0=GQ&8191,S0=GQ>>>13,gQ=R[3]|0,g0=gQ&8191,d0=gQ>>>13,_Z=R[4]|0,o0=_Z&8191,b=_Z>>>13,Q0=R[5]|0,O0=Q0&8191,L0=Q0>>>13,qQ=R[6]|0,m0=qQ&8191,n0=qQ>>>13,lZ=R[7]|0,r0=lZ&8191,e0=lZ>>>13,bY=R[8]|0,t0=bY&8191,a0=bY>>>13,mZ=R[9]|0,lQ=mZ&8191,pQ=mZ>>>13;P.negative=F.negative^D.negative,P.length=19,N=Math.imul(p,f0),T=Math.imul(p,h0),T=T+Math.imul(J0,f0)|0,v=Math.imul(J0,h0);var IZ=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(IZ>>>26)|0,IZ&=67108863,N=Math.imul(K0,f0),T=Math.imul(K0,h0),T=T+Math.imul(Y0,f0)|0,v=Math.imul(Y0,h0),N=N+Math.imul(p,E0)|0,T=T+Math.imul(p,A0)|0,T=T+Math.imul(J0,E0)|0,v=v+Math.imul(J0,A0)|0;var zZ=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(zZ>>>26)|0,zZ&=67108863,N=Math.imul($0,f0),T=Math.imul($0,h0),T=T+Math.imul(D0,f0)|0,v=Math.imul(D0,h0),N=N+Math.imul(K0,E0)|0,T=T+Math.imul(K0,A0)|0,T=T+Math.imul(Y0,E0)|0,v=v+Math.imul(Y0,A0)|0,N=N+Math.imul(p,T0)|0,T=T+Math.imul(p,S0)|0,T=T+Math.imul(J0,T0)|0,v=v+Math.imul(J0,S0)|0;var $Y=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+($Y>>>26)|0,$Y&=67108863,N=Math.imul(m,f0),T=Math.imul(m,h0),T=T+Math.imul(n,f0)|0,v=Math.imul(n,h0),N=N+Math.imul($0,E0)|0,T=T+Math.imul($0,A0)|0,T=T+Math.imul(D0,E0)|0,v=v+Math.imul(D0,A0)|0,N=N+Math.imul(K0,T0)|0,T=T+Math.imul(K0,S0)|0,T=T+Math.imul(Y0,T0)|0,v=v+Math.imul(Y0,S0)|0,N=N+Math.imul(p,g0)|0,T=T+Math.imul(p,d0)|0,T=T+Math.imul(J0,g0)|0,v=v+Math.imul(J0,d0)|0;var JY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(JY>>>26)|0,JY&=67108863,N=Math.imul(F0,f0),T=Math.imul(F0,h0),T=T+Math.imul(z0,f0)|0,v=Math.imul(z0,h0),N=N+Math.imul(m,E0)|0,T=T+Math.imul(m,A0)|0,T=T+Math.imul(n,E0)|0,v=v+Math.imul(n,A0)|0,N=N+Math.imul($0,T0)|0,T=T+Math.imul($0,S0)|0,T=T+Math.imul(D0,T0)|0,v=v+Math.imul(D0,S0)|0,N=N+Math.imul(K0,g0)|0,T=T+Math.imul(K0,d0)|0,T=T+Math.imul(Y0,g0)|0,v=v+Math.imul(Y0,d0)|0,N=N+Math.imul(p,o0)|0,T=T+Math.imul(p,b)|0,T=T+Math.imul(J0,o0)|0,v=v+Math.imul(J0,b)|0;var GY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(GY>>>26)|0,GY&=67108863,N=Math.imul(d,f0),T=Math.imul(d,h0),T=T+Math.imul(X0,f0)|0,v=Math.imul(X0,h0),N=N+Math.imul(F0,E0)|0,T=T+Math.imul(F0,A0)|0,T=T+Math.imul(z0,E0)|0,v=v+Math.imul(z0,A0)|0,N=N+Math.imul(m,T0)|0,T=T+Math.imul(m,S0)|0,T=T+Math.imul(n,T0)|0,v=v+Math.imul(n,S0)|0,N=N+Math.imul($0,g0)|0,T=T+Math.imul($0,d0)|0,T=T+Math.imul(D0,g0)|0,v=v+Math.imul(D0,d0)|0,N=N+Math.imul(K0,o0)|0,T=T+Math.imul(K0,b)|0,T=T+Math.imul(Y0,o0)|0,v=v+Math.imul(Y0,b)|0,N=N+Math.imul(p,O0)|0,T=T+Math.imul(p,L0)|0,T=T+Math.imul(J0,O0)|0,v=v+Math.imul(J0,L0)|0;var XY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(XY>>>26)|0,XY&=67108863,N=Math.imul(V0,f0),T=Math.imul(V0,h0),T=T+Math.imul(P0,f0)|0,v=Math.imul(P0,h0),N=N+Math.imul(d,E0)|0,T=T+Math.imul(d,A0)|0,T=T+Math.imul(X0,E0)|0,v=v+Math.imul(X0,A0)|0,N=N+Math.imul(F0,T0)|0,T=T+Math.imul(F0,S0)|0,T=T+Math.imul(z0,T0)|0,v=v+Math.imul(z0,S0)|0,N=N+Math.imul(m,g0)|0,T=T+Math.imul(m,d0)|0,T=T+Math.imul(n,g0)|0,v=v+Math.imul(n,d0)|0,N=N+Math.imul($0,o0)|0,T=T+Math.imul($0,b)|0,T=T+Math.imul(D0,o0)|0,v=v+Math.imul(D0,b)|0,N=N+Math.imul(K0,O0)|0,T=T+Math.imul(K0,L0)|0,T=T+Math.imul(Y0,O0)|0,v=v+Math.imul(Y0,L0)|0,N=N+Math.imul(p,m0)|0,T=T+Math.imul(p,n0)|0,T=T+Math.imul(J0,m0)|0,v=v+Math.imul(J0,n0)|0;var VY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(VY>>>26)|0,VY&=67108863,N=Math.imul(c0,f0),T=Math.imul(c0,h0),T=T+Math.imul(u0,f0)|0,v=Math.imul(u0,h0),N=N+Math.imul(V0,E0)|0,T=T+Math.imul(V0,A0)|0,T=T+Math.imul(P0,E0)|0,v=v+Math.imul(P0,A0)|0,N=N+Math.imul(d,T0)|0,T=T+Math.imul(d,S0)|0,T=T+Math.imul(X0,T0)|0,v=v+Math.imul(X0,S0)|0,N=N+Math.imul(F0,g0)|0,T=T+Math.imul(F0,d0)|0,T=T+Math.imul(z0,g0)|0,v=v+Math.imul(z0,d0)|0,N=N+Math.imul(m,o0)|0,T=T+Math.imul(m,b)|0,T=T+Math.imul(n,o0)|0,v=v+Math.imul(n,b)|0,N=N+Math.imul($0,O0)|0,T=T+Math.imul($0,L0)|0,T=T+Math.imul(D0,O0)|0,v=v+Math.imul(D0,L0)|0,N=N+Math.imul(K0,m0)|0,T=T+Math.imul(K0,n0)|0,T=T+Math.imul(Y0,m0)|0,v=v+Math.imul(Y0,n0)|0,N=N+Math.imul(p,r0)|0,T=T+Math.imul(p,e0)|0,T=T+Math.imul(J0,r0)|0,v=v+Math.imul(J0,e0)|0;var qY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(qY>>>26)|0,qY&=67108863,N=Math.imul(y0,f0),T=Math.imul(y0,h0),T=T+Math.imul(s,f0)|0,v=Math.imul(s,h0),N=N+Math.imul(c0,E0)|0,T=T+Math.imul(c0,A0)|0,T=T+Math.imul(u0,E0)|0,v=v+Math.imul(u0,A0)|0,N=N+Math.imul(V0,T0)|0,T=T+Math.imul(V0,S0)|0,T=T+Math.imul(P0,T0)|0,v=v+Math.imul(P0,S0)|0,N=N+Math.imul(d,g0)|0,T=T+Math.imul(d,d0)|0,T=T+Math.imul(X0,g0)|0,v=v+Math.imul(X0,d0)|0,N=N+Math.imul(F0,o0)|0,T=T+Math.imul(F0,b)|0,T=T+Math.imul(z0,o0)|0,v=v+Math.imul(z0,b)|0,N=N+Math.imul(m,O0)|0,T=T+Math.imul(m,L0)|0,T=T+Math.imul(n,O0)|0,v=v+Math.imul(n,L0)|0,N=N+Math.imul($0,m0)|0,T=T+Math.imul($0,n0)|0,T=T+Math.imul(D0,m0)|0,v=v+Math.imul(D0,n0)|0,N=N+Math.imul(K0,r0)|0,T=T+Math.imul(K0,e0)|0,T=T+Math.imul(Y0,r0)|0,v=v+Math.imul(Y0,e0)|0,N=N+Math.imul(p,t0)|0,T=T+Math.imul(p,a0)|0,T=T+Math.imul(J0,t0)|0,v=v+Math.imul(J0,a0)|0;var FY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(FY>>>26)|0,FY&=67108863,N=Math.imul(G0,f0),T=Math.imul(G0,h0),T=T+Math.imul(H0,f0)|0,v=Math.imul(H0,h0),N=N+Math.imul(y0,E0)|0,T=T+Math.imul(y0,A0)|0,T=T+Math.imul(s,E0)|0,v=v+Math.imul(s,A0)|0,N=N+Math.imul(c0,T0)|0,T=T+Math.imul(c0,S0)|0,T=T+Math.imul(u0,T0)|0,v=v+Math.imul(u0,S0)|0,N=N+Math.imul(V0,g0)|0,T=T+Math.imul(V0,d0)|0,T=T+Math.imul(P0,g0)|0,v=v+Math.imul(P0,d0)|0,N=N+Math.imul(d,o0)|0,T=T+Math.imul(d,b)|0,T=T+Math.imul(X0,o0)|0,v=v+Math.imul(X0,b)|0,N=N+Math.imul(F0,O0)|0,T=T+Math.imul(F0,L0)|0,T=T+Math.imul(z0,O0)|0,v=v+Math.imul(z0,L0)|0,N=N+Math.imul(m,m0)|0,T=T+Math.imul(m,n0)|0,T=T+Math.imul(n,m0)|0,v=v+Math.imul(n,n0)|0,N=N+Math.imul($0,r0)|0,T=T+Math.imul($0,e0)|0,T=T+Math.imul(D0,r0)|0,v=v+Math.imul(D0,e0)|0,N=N+Math.imul(K0,t0)|0,T=T+Math.imul(K0,a0)|0,T=T+Math.imul(Y0,t0)|0,v=v+Math.imul(Y0,a0)|0,N=N+Math.imul(p,lQ)|0,T=T+Math.imul(p,pQ)|0,T=T+Math.imul(J0,lQ)|0,v=v+Math.imul(J0,pQ)|0;var zY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(zY>>>26)|0,zY&=67108863,N=Math.imul(G0,E0),T=Math.imul(G0,A0),T=T+Math.imul(H0,E0)|0,v=Math.imul(H0,A0),N=N+Math.imul(y0,T0)|0,T=T+Math.imul(y0,S0)|0,T=T+Math.imul(s,T0)|0,v=v+Math.imul(s,S0)|0,N=N+Math.imul(c0,g0)|0,T=T+Math.imul(c0,d0)|0,T=T+Math.imul(u0,g0)|0,v=v+Math.imul(u0,d0)|0,N=N+Math.imul(V0,o0)|0,T=T+Math.imul(V0,b)|0,T=T+Math.imul(P0,o0)|0,v=v+Math.imul(P0,b)|0,N=N+Math.imul(d,O0)|0,T=T+Math.imul(d,L0)|0,T=T+Math.imul(X0,O0)|0,v=v+Math.imul(X0,L0)|0,N=N+Math.imul(F0,m0)|0,T=T+Math.imul(F0,n0)|0,T=T+Math.imul(z0,m0)|0,v=v+Math.imul(z0,n0)|0,N=N+Math.imul(m,r0)|0,T=T+Math.imul(m,e0)|0,T=T+Math.imul(n,r0)|0,v=v+Math.imul(n,e0)|0,N=N+Math.imul($0,t0)|0,T=T+Math.imul($0,a0)|0,T=T+Math.imul(D0,t0)|0,v=v+Math.imul(D0,a0)|0,N=N+Math.imul(K0,lQ)|0,T=T+Math.imul(K0,pQ)|0,T=T+Math.imul(Y0,lQ)|0,v=v+Math.imul(Y0,pQ)|0;var WY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(WY>>>26)|0,WY&=67108863,N=Math.imul(G0,T0),T=Math.imul(G0,S0),T=T+Math.imul(H0,T0)|0,v=Math.imul(H0,S0),N=N+Math.imul(y0,g0)|0,T=T+Math.imul(y0,d0)|0,T=T+Math.imul(s,g0)|0,v=v+Math.imul(s,d0)|0,N=N+Math.imul(c0,o0)|0,T=T+Math.imul(c0,b)|0,T=T+Math.imul(u0,o0)|0,v=v+Math.imul(u0,b)|0,N=N+Math.imul(V0,O0)|0,T=T+Math.imul(V0,L0)|0,T=T+Math.imul(P0,O0)|0,v=v+Math.imul(P0,L0)|0,N=N+Math.imul(d,m0)|0,T=T+Math.imul(d,n0)|0,T=T+Math.imul(X0,m0)|0,v=v+Math.imul(X0,n0)|0,N=N+Math.imul(F0,r0)|0,T=T+Math.imul(F0,e0)|0,T=T+Math.imul(z0,r0)|0,v=v+Math.imul(z0,e0)|0,N=N+Math.imul(m,t0)|0,T=T+Math.imul(m,a0)|0,T=T+Math.imul(n,t0)|0,v=v+Math.imul(n,a0)|0,N=N+Math.imul($0,lQ)|0,T=T+Math.imul($0,pQ)|0,T=T+Math.imul(D0,lQ)|0,v=v+Math.imul(D0,pQ)|0;var KY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(KY>>>26)|0,KY&=67108863,N=Math.imul(G0,g0),T=Math.imul(G0,d0),T=T+Math.imul(H0,g0)|0,v=Math.imul(H0,d0),N=N+Math.imul(y0,o0)|0,T=T+Math.imul(y0,b)|0,T=T+Math.imul(s,o0)|0,v=v+Math.imul(s,b)|0,N=N+Math.imul(c0,O0)|0,T=T+Math.imul(c0,L0)|0,T=T+Math.imul(u0,O0)|0,v=v+Math.imul(u0,L0)|0,N=N+Math.imul(V0,m0)|0,T=T+Math.imul(V0,n0)|0,T=T+Math.imul(P0,m0)|0,v=v+Math.imul(P0,n0)|0,N=N+Math.imul(d,r0)|0,T=T+Math.imul(d,e0)|0,T=T+Math.imul(X0,r0)|0,v=v+Math.imul(X0,e0)|0,N=N+Math.imul(F0,t0)|0,T=T+Math.imul(F0,a0)|0,T=T+Math.imul(z0,t0)|0,v=v+Math.imul(z0,a0)|0,N=N+Math.imul(m,lQ)|0,T=T+Math.imul(m,pQ)|0,T=T+Math.imul(n,lQ)|0,v=v+Math.imul(n,pQ)|0;var UY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(UY>>>26)|0,UY&=67108863,N=Math.imul(G0,o0),T=Math.imul(G0,b),T=T+Math.imul(H0,o0)|0,v=Math.imul(H0,b),N=N+Math.imul(y0,O0)|0,T=T+Math.imul(y0,L0)|0,T=T+Math.imul(s,O0)|0,v=v+Math.imul(s,L0)|0,N=N+Math.imul(c0,m0)|0,T=T+Math.imul(c0,n0)|0,T=T+Math.imul(u0,m0)|0,v=v+Math.imul(u0,n0)|0,N=N+Math.imul(V0,r0)|0,T=T+Math.imul(V0,e0)|0,T=T+Math.imul(P0,r0)|0,v=v+Math.imul(P0,e0)|0,N=N+Math.imul(d,t0)|0,T=T+Math.imul(d,a0)|0,T=T+Math.imul(X0,t0)|0,v=v+Math.imul(X0,a0)|0,N=N+Math.imul(F0,lQ)|0,T=T+Math.imul(F0,pQ)|0,T=T+Math.imul(z0,lQ)|0,v=v+Math.imul(z0,pQ)|0;var OY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(OY>>>26)|0,OY&=67108863,N=Math.imul(G0,O0),T=Math.imul(G0,L0),T=T+Math.imul(H0,O0)|0,v=Math.imul(H0,L0),N=N+Math.imul(y0,m0)|0,T=T+Math.imul(y0,n0)|0,T=T+Math.imul(s,m0)|0,v=v+Math.imul(s,n0)|0,N=N+Math.imul(c0,r0)|0,T=T+Math.imul(c0,e0)|0,T=T+Math.imul(u0,r0)|0,v=v+Math.imul(u0,e0)|0,N=N+Math.imul(V0,t0)|0,T=T+Math.imul(V0,a0)|0,T=T+Math.imul(P0,t0)|0,v=v+Math.imul(P0,a0)|0,N=N+Math.imul(d,lQ)|0,T=T+Math.imul(d,pQ)|0,T=T+Math.imul(X0,lQ)|0,v=v+Math.imul(X0,pQ)|0;var HY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(HY>>>26)|0,HY&=67108863,N=Math.imul(G0,m0),T=Math.imul(G0,n0),T=T+Math.imul(H0,m0)|0,v=Math.imul(H0,n0),N=N+Math.imul(y0,r0)|0,T=T+Math.imul(y0,e0)|0,T=T+Math.imul(s,r0)|0,v=v+Math.imul(s,e0)|0,N=N+Math.imul(c0,t0)|0,T=T+Math.imul(c0,a0)|0,T=T+Math.imul(u0,t0)|0,v=v+Math.imul(u0,a0)|0,N=N+Math.imul(V0,lQ)|0,T=T+Math.imul(V0,pQ)|0,T=T+Math.imul(P0,lQ)|0,v=v+Math.imul(P0,pQ)|0;var DY=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(DY>>>26)|0,DY&=67108863,N=Math.imul(G0,r0),T=Math.imul(G0,e0),T=T+Math.imul(H0,r0)|0,v=Math.imul(H0,e0),N=N+Math.imul(y0,t0)|0,T=T+Math.imul(y0,a0)|0,T=T+Math.imul(s,t0)|0,v=v+Math.imul(s,a0)|0,N=N+Math.imul(c0,lQ)|0,T=T+Math.imul(c0,pQ)|0,T=T+Math.imul(u0,lQ)|0,v=v+Math.imul(u0,pQ)|0;var OO=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(OO>>>26)|0,OO&=67108863,N=Math.imul(G0,t0),T=Math.imul(G0,a0),T=T+Math.imul(H0,t0)|0,v=Math.imul(H0,a0),N=N+Math.imul(y0,lQ)|0,T=T+Math.imul(y0,pQ)|0,T=T+Math.imul(s,lQ)|0,v=v+Math.imul(s,pQ)|0;var HO=(E+N|0)+((T&8191)<<13)|0;E=(v+(T>>>13)|0)+(HO>>>26)|0,HO&=67108863,N=Math.imul(G0,lQ),T=Math.imul(G0,pQ),T=T+Math.imul(H0,lQ)|0,v=Math.imul(H0,pQ);var DO=(E+N|0)+((T&8191)<<13)|0;if(E=(v+(T>>>13)|0)+(DO>>>26)|0,DO&=67108863,q[0]=IZ,q[1]=zZ,q[2]=$Y,q[3]=JY,q[4]=GY,q[5]=XY,q[6]=VY,q[7]=qY,q[8]=FY,q[9]=zY,q[10]=WY,q[11]=KY,q[12]=UY,q[13]=OY,q[14]=HY,q[15]=DY,q[16]=OO,q[17]=HO,q[18]=DO,E!==0)q[19]=E,P.length++;return P};if(!Math.imul)_=S;function x(F,D,P){P.negative=D.negative^F.negative,P.length=F.length+D.length;var j=0,R=0;for(var q=0;q<P.length-1;q++){var E=R;R=0;var N=j&67108863,T=Math.min(q,D.length-1);for(var v=Math.max(0,q-F.length+1);v<=T;v++){var y=q-v,p=F.words[y]|0,J0=D.words[v]|0,x0=p*J0,K0=x0&67108863;E=E+(x0/67108864|0)|0,K0=K0+N|0,N=K0&67108863,E=E+(K0>>>26)|0,R+=E>>>26,E&=67108863}P.words[q]=N,j=E,E=R}if(j!==0)P.words[q]=j;else P.length--;return P._strip()}function f(F,D,P){return x(F,D,P)}G.prototype.mulTo=function(F,D){var P,j=this.length+F.length;if(this.length===10&&F.length===10)P=_(this,F,D);else if(j<63)P=S(this,F,D);else if(j<1024)P=x(this,F,D);else P=f(this,F,D);return P};function h(F,D){this.x=F,this.y=D}h.prototype.makeRBT=function(F){var D=Array(F),P=G.prototype._countBits(F)-1;for(var j=0;j<F;j++)D[j]=this.revBin(j,P,F);return D},h.prototype.revBin=function(F,D,P){if(F===0||F===P-1)return F;var j=0;for(var R=0;R<D;R++)j|=(F&1)<<D-R-1,F>>=1;return j},h.prototype.permute=function(F,D,P,j,R,q){for(var E=0;E<q;E++)j[E]=D[F[E]],R[E]=P[F[E]]},h.prototype.transform=function(F,D,P,j,R,q){this.permute(q,F,D,P,j,R);for(var E=1;E<R;E<<=1){var N=E<<1,T=Math.cos(2*Math.PI/N),v=Math.sin(2*Math.PI/N);for(var y=0;y<R;y+=N){var p=T,J0=v;for(var x0=0;x0<E;x0++){var K0=P[y+x0],Y0=j[y+x0],j0=P[y+x0+E],$0=j[y+x0+E],D0=p*j0-J0*$0;if($0=p*$0+J0*j0,j0=D0,P[y+x0]=K0+j0,j[y+x0]=Y0+$0,P[y+x0+E]=K0-j0,j[y+x0+E]=Y0-$0,x0!==N)D0=T*p-v*J0,J0=T*J0+v*p,p=D0}}}},h.prototype.guessLen13b=function(F,D){var P=Math.max(D,F)|1,j=P&1,R=0;for(P=P/2|0;P;P=P>>>1)R++;return 1<<R+1+j},h.prototype.conjugate=function(F,D,P){if(P<=1)return;for(var j=0;j<P/2;j++){var R=F[j];F[j]=F[P-j-1],F[P-j-1]=R,R=D[j],D[j]=-D[P-j-1],D[P-j-1]=-R}},h.prototype.normalize13b=function(F,D){var P=0;for(var j=0;j<D/2;j++){var R=Math.round(F[2*j+1]/D)*8192+Math.round(F[2*j]/D)+P;if(F[j]=R&67108863,R<67108864)P=0;else P=R/67108864|0}return F},h.prototype.convert13b=function(F,D,P,j){var R=0;for(var q=0;q<D;q++)R=R+(F[q]|0),P[2*q]=R&8191,R=R>>>13,P[2*q+1]=R&8191,R=R>>>13;for(q=2*D;q<j;++q)P[q]=0;J(R===0),J((R&-8192)===0)},h.prototype.stub=function(F){var D=Array(F);for(var P=0;P<F;P++)D[P]=0;return D},h.prototype.mulp=function(F,D,P){var j=2*this.guessLen13b(F.length,D.length),R=this.makeRBT(j),q=this.stub(j),E=Array(j),N=Array(j),T=Array(j),v=Array(j),y=Array(j),p=Array(j),J0=P.words;J0.length=j,this.convert13b(F.words,F.length,E,j),this.convert13b(D.words,D.length,v,j),this.transform(E,q,N,T,j,R),this.transform(v,q,y,p,j,R);for(var x0=0;x0<j;x0++){var K0=N[x0]*y[x0]-T[x0]*p[x0];T[x0]=N[x0]*p[x0]+T[x0]*y[x0],N[x0]=K0}return this.conjugate(N,T,j),this.transform(N,T,J0,q,j,R),this.conjugate(J0,q,j),this.normalize13b(J0,j),P.negative=F.negative^D.negative,P.length=F.length+D.length,P._strip()},G.prototype.mul=function(F){var D=new G(null);return D.words=Array(this.length+F.length),this.mulTo(F,D)},G.prototype.mulf=function(F){var D=new G(null);return D.words=Array(this.length+F.length),f(this,F,D)},G.prototype.imul=function(F){return this.clone().mulTo(F,this)},G.prototype.imuln=function(F){var D=F<0;if(D)F=-F;J(typeof F==="number"),J(F<67108864);var P=0;for(var j=0;j<this.length;j++){var R=(this.words[j]|0)*F,q=(R&67108863)+(P&67108863);P>>=26,P+=R/67108864|0,P+=q>>>26,this.words[j]=q&67108863}if(P!==0)this.words[j]=P,this.length++;return this.length=F===0?1:this.length,D?this.ineg():this},G.prototype.muln=function(F){return this.clone().imuln(F)},G.prototype.sqr=function(){return this.mul(this)},G.prototype.isqr=function(){return this.imul(this.clone())},G.prototype.pow=function(F){var D=C(F);if(D.length===0)return new G(1);var P=this;for(var j=0;j<D.length;j++,P=P.sqr())if(D[j]!==0)break;if(++j<D.length)for(var R=P.sqr();j<D.length;j++,R=R.sqr()){if(D[j]===0)continue;P=P.mul(R)}return P},G.prototype.iushln=function(F){J(typeof F==="number"&&F>=0);var D=F%26,P=(F-D)/26,j=67108863>>>26-D<<26-D,R;if(D!==0){var q=0;for(R=0;R<this.length;R++){var E=this.words[R]&j,N=(this.words[R]|0)-E<<D;this.words[R]=N|q,q=E>>>26-D}if(q)this.words[R]=q,this.length++}if(P!==0){for(R=this.length-1;R>=0;R--)this.words[R+P]=this.words[R];for(R=0;R<P;R++)this.words[R]=0;this.length+=P}return this._strip()},G.prototype.ishln=function(F){return J(this.negative===0),this.iushln(F)},G.prototype.iushrn=function(F,D,P){J(typeof F==="number"&&F>=0);var j;if(D)j=(D-D%26)/26;else j=0;var R=F%26,q=Math.min((F-R)/26,this.length),E=67108863^67108863>>>R<<R,N=P;if(j-=q,j=Math.max(0,j),N){for(var T=0;T<q;T++)N.words[T]=this.words[T];N.length=q}if(q===0);else if(this.length>q){this.length-=q;for(T=0;T<this.length;T++)this.words[T]=this.words[T+q]}else this.words[0]=0,this.length=1;var v=0;for(T=this.length-1;T>=0&&(v!==0||T>=j);T--){var y=this.words[T]|0;this.words[T]=v<<26-R|y>>>R,v=y&E}if(N&&v!==0)N.words[N.length++]=v;if(this.length===0)this.words[0]=0,this.length=1;return this._strip()},G.prototype.ishrn=function(F,D,P){return J(this.negative===0),this.iushrn(F,D,P)},G.prototype.shln=function(F){return this.clone().ishln(F)},G.prototype.ushln=function(F){return this.clone().iushln(F)},G.prototype.shrn=function(F){return this.clone().ishrn(F)},G.prototype.ushrn=function(F){return this.clone().iushrn(F)},G.prototype.testn=function(F){J(typeof F==="number"&&F>=0);var D=F%26,P=(F-D)/26,j=1<<D;if(this.length<=P)return!1;var R=this.words[P];return!!(R&j)},G.prototype.imaskn=function(F){J(typeof F==="number"&&F>=0);var D=F%26,P=(F-D)/26;if(J(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(D!==0)P++;if(this.length=Math.min(P,this.length),D!==0){var j=67108863^67108863>>>D<<D;this.words[this.length-1]&=j}return this._strip()},G.prototype.maskn=function(F){return this.clone().imaskn(F)},G.prototype.iaddn=function(F){if(J(typeof F==="number"),J(F<67108864),F<0)return this.isubn(-F);if(this.negative!==0){if(this.length===1&&(this.words[0]|0)<=F)return this.words[0]=F-(this.words[0]|0),this.negative=0,this;return this.negative=0,this.isubn(F),this.negative=1,this}return this._iaddn(F)},G.prototype._iaddn=function(F){this.words[0]+=F;for(var D=0;D<this.length&&this.words[D]>=67108864;D++)if(this.words[D]-=67108864,D===this.length-1)this.words[D+1]=1;else this.words[D+1]++;return this.length=Math.max(this.length,D+1),this},G.prototype.isubn=function(F){if(J(typeof F==="number"),J(F<67108864),F<0)return this.iaddn(-F);if(this.negative!==0)return this.negative=0,this.iaddn(F),this.negative=1,this;if(this.words[0]-=F,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var D=0;D<this.length&&this.words[D]<0;D++)this.words[D]+=67108864,this.words[D+1]-=1;return this._strip()},G.prototype.addn=function(F){return this.clone().iaddn(F)},G.prototype.subn=function(F){return this.clone().isubn(F)},G.prototype.iabs=function(){return this.negative=0,this},G.prototype.abs=function(){return this.clone().iabs()},G.prototype._ishlnsubmul=function(F,D,P){var j=F.length+P,R;this._expand(j);var q,E=0;for(R=0;R<F.length;R++){q=(this.words[R+P]|0)+E;var N=(F.words[R]|0)*D;q-=N&67108863,E=(q>>26)-(N/67108864|0),this.words[R+P]=q&67108863}for(;R<this.length-P;R++)q=(this.words[R+P]|0)+E,E=q>>26,this.words[R+P]=q&67108863;if(E===0)return this._strip();J(E===-1),E=0;for(R=0;R<this.length;R++)q=-(this.words[R]|0)+E,E=q>>26,this.words[R]=q&67108863;return this.negative=1,this._strip()},G.prototype._wordDiv=function(F,D){var P=this.length-F.length,j=this.clone(),R=F,q=R.words[R.length-1]|0,E=this._countBits(q);if(P=26-E,P!==0)R=R.ushln(P),j.iushln(P),q=R.words[R.length-1]|0;var N=j.length-R.length,T;if(D!=="mod"){T=new G(null),T.length=N+1,T.words=Array(T.length);for(var v=0;v<T.length;v++)T.words[v]=0}var y=j.clone()._ishlnsubmul(R,1,N);if(y.negative===0){if(j=y,T)T.words[N]=1}for(var p=N-1;p>=0;p--){var J0=(j.words[R.length+p]|0)*67108864+(j.words[R.length+p-1]|0);J0=Math.min(J0/q|0,67108863),j._ishlnsubmul(R,J0,p);while(j.negative!==0)if(J0--,j.negative=0,j._ishlnsubmul(R,1,p),!j.isZero())j.negative^=1;if(T)T.words[p]=J0}if(T)T._strip();if(j._strip(),D!=="div"&&P!==0)j.iushrn(P);return{div:T||null,mod:j}},G.prototype.divmod=function(F,D,P){if(J(!F.isZero()),this.isZero())return{div:new G(0),mod:new G(0)};var j,R,q;if(this.negative!==0&&F.negative===0){if(q=this.neg().divmod(F,D),D!=="mod")j=q.div.neg();if(D!=="div"){if(R=q.mod.neg(),P&&R.negative!==0)R.iadd(F)}return{div:j,mod:R}}if(this.negative===0&&F.negative!==0){if(q=this.divmod(F.neg(),D),D!=="mod")j=q.div.neg();return{div:j,mod:q.mod}}if((this.negative&F.negative)!==0){if(q=this.neg().divmod(F.neg(),D),D!=="div"){if(R=q.mod.neg(),P&&R.negative!==0)R.isub(F)}return{div:q.div,mod:R}}if(F.length>this.length||this.cmp(F)<0)return{div:new G(0),mod:this};if(F.length===1){if(D==="div")return{div:this.divn(F.words[0]),mod:null};if(D==="mod")return{div:null,mod:new G(this.modrn(F.words[0]))};return{div:this.divn(F.words[0]),mod:new G(this.modrn(F.words[0]))}}return this._wordDiv(F,D)},G.prototype.div=function(F){return this.divmod(F,"div",!1).div},G.prototype.mod=function(F){return this.divmod(F,"mod",!1).mod},G.prototype.umod=function(F){return this.divmod(F,"mod",!0).mod},G.prototype.divRound=function(F){var D=this.divmod(F);if(D.mod.isZero())return D.div;var P=D.div.negative!==0?D.mod.isub(F):D.mod,j=F.ushrn(1),R=F.andln(1),q=P.cmp(j);if(q<0||R===1&&q===0)return D.div;return D.div.negative!==0?D.div.isubn(1):D.div.iaddn(1)},G.prototype.modrn=function(F){var D=F<0;if(D)F=-F;J(F<=67108863);var P=67108864%F,j=0;for(var R=this.length-1;R>=0;R--)j=(P*j+(this.words[R]|0))%F;return D?-j:j},G.prototype.modn=function(F){return this.modrn(F)},G.prototype.idivn=function(F){var D=F<0;if(D)F=-F;J(F<=67108863);var P=0;for(var j=this.length-1;j>=0;j--){var R=(this.words[j]|0)+P*67108864;this.words[j]=R/F|0,P=R%F}return this._strip(),D?this.ineg():this},G.prototype.divn=function(F){return this.clone().idivn(F)},G.prototype.egcd=function(F){J(F.negative===0),J(!F.isZero());var D=this,P=F.clone();if(D.negative!==0)D=D.umod(F);else D=D.clone();var j=new G(1),R=new G(0),q=new G(0),E=new G(1),N=0;while(D.isEven()&&P.isEven())D.iushrn(1),P.iushrn(1),++N;var T=P.clone(),v=D.clone();while(!D.isZero()){for(var y=0,p=1;(D.words[0]&p)===0&&y<26;++y,p<<=1);if(y>0){D.iushrn(y);while(y-- >0){if(j.isOdd()||R.isOdd())j.iadd(T),R.isub(v);j.iushrn(1),R.iushrn(1)}}for(var J0=0,x0=1;(P.words[0]&x0)===0&&J0<26;++J0,x0<<=1);if(J0>0){P.iushrn(J0);while(J0-- >0){if(q.isOdd()||E.isOdd())q.iadd(T),E.isub(v);q.iushrn(1),E.iushrn(1)}}if(D.cmp(P)>=0)D.isub(P),j.isub(q),R.isub(E);else P.isub(D),q.isub(j),E.isub(R)}return{a:q,b:E,gcd:P.iushln(N)}},G.prototype._invmp=function(F){J(F.negative===0),J(!F.isZero());var D=this,P=F.clone();if(D.negative!==0)D=D.umod(F);else D=D.clone();var j=new G(1),R=new G(0),q=P.clone();while(D.cmpn(1)>0&&P.cmpn(1)>0){for(var E=0,N=1;(D.words[0]&N)===0&&E<26;++E,N<<=1);if(E>0){D.iushrn(E);while(E-- >0){if(j.isOdd())j.iadd(q);j.iushrn(1)}}for(var T=0,v=1;(P.words[0]&v)===0&&T<26;++T,v<<=1);if(T>0){P.iushrn(T);while(T-- >0){if(R.isOdd())R.iadd(q);R.iushrn(1)}}if(D.cmp(P)>=0)D.isub(P),j.isub(R);else P.isub(D),R.isub(j)}var y;if(D.cmpn(1)===0)y=j;else y=R;if(y.cmpn(0)<0)y.iadd(F);return y},G.prototype.gcd=function(F){if(this.isZero())return F.abs();if(F.isZero())return this.abs();var D=this.clone(),P=F.clone();D.negative=0,P.negative=0;for(var j=0;D.isEven()&&P.isEven();j++)D.iushrn(1),P.iushrn(1);do{while(D.isEven())D.iushrn(1);while(P.isEven())P.iushrn(1);var R=D.cmp(P);if(R<0){var q=D;D=P,P=q}else if(R===0||P.cmpn(1)===0)break;D.isub(P)}while(!0);return P.iushln(j)},G.prototype.invm=function(F){return this.egcd(F).a.umod(F)},G.prototype.isEven=function(){return(this.words[0]&1)===0},G.prototype.isOdd=function(){return(this.words[0]&1)===1},G.prototype.andln=function(F){return this.words[0]&F},G.prototype.bincn=function(F){J(typeof F==="number");var D=F%26,P=(F-D)/26,j=1<<D;if(this.length<=P)return this._expand(P+1),this.words[P]|=j,this;var R=j;for(var q=P;R!==0&&q<this.length;q++){var E=this.words[q]|0;E+=R,R=E>>>26,E&=67108863,this.words[q]=E}if(R!==0)this.words[q]=R,this.length++;return this},G.prototype.isZero=function(){return this.length===1&&this.words[0]===0},G.prototype.cmpn=function(F){var D=F<0;if(this.negative!==0&&!D)return-1;if(this.negative===0&&D)return 1;this._strip();var P;if(this.length>1)P=1;else{if(D)F=-F;J(F<=67108863,"Number is too big");var j=this.words[0]|0;P=j===F?0:j<F?-1:1}if(this.negative!==0)return-P|0;return P},G.prototype.cmp=function(F){if(this.negative!==0&&F.negative===0)return-1;if(this.negative===0&&F.negative!==0)return 1;var D=this.ucmp(F);if(this.negative!==0)return-D|0;return D},G.prototype.ucmp=function(F){if(this.length>F.length)return 1;if(this.length<F.length)return-1;var D=0;for(var P=this.length-1;P>=0;P--){var j=this.words[P]|0,R=F.words[P]|0;if(j===R)continue;if(j<R)D=-1;else if(j>R)D=1;break}return D},G.prototype.gtn=function(F){return this.cmpn(F)===1},G.prototype.gt=function(F){return this.cmp(F)===1},G.prototype.gten=function(F){return this.cmpn(F)>=0},G.prototype.gte=function(F){return this.cmp(F)>=0},G.prototype.ltn=function(F){return this.cmpn(F)===-1},G.prototype.lt=function(F){return this.cmp(F)===-1},G.prototype.lten=function(F){return this.cmpn(F)<=0},G.prototype.lte=function(F){return this.cmp(F)<=0},G.prototype.eqn=function(F){return this.cmpn(F)===0},G.prototype.eq=function(F){return this.cmp(F)===0},G.red=function(F){return new z(F)},G.prototype.toRed=function(F){return J(!this.red,"Already a number in reduction context"),J(this.negative===0,"red works only with positives"),F.convertTo(this)._forceRed(F)},G.prototype.fromRed=function(){return J(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},G.prototype._forceRed=function(F){return this.red=F,this},G.prototype.forceRed=function(F){return J(!this.red,"Already a number in reduction context"),this._forceRed(F)},G.prototype.redAdd=function(F){return J(this.red,"redAdd works only with red numbers"),this.red.add(this,F)},G.prototype.redIAdd=function(F){return J(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,F)},G.prototype.redSub=function(F){return J(this.red,"redSub works only with red numbers"),this.red.sub(this,F)},G.prototype.redISub=function(F){return J(this.red,"redISub works only with red numbers"),this.red.isub(this,F)},G.prototype.redShl=function(F){return J(this.red,"redShl works only with red numbers"),this.red.shl(this,F)},G.prototype.redMul=function(F){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,F),this.red.mul(this,F)},G.prototype.redIMul=function(F){return J(this.red,"redMul works only with red numbers"),this.red._verify2(this,F),this.red.imul(this,F)},G.prototype.redSqr=function(){return J(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},G.prototype.redISqr=function(){return J(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},G.prototype.redSqrt=function(){return J(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},G.prototype.redInvm=function(){return J(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},G.prototype.redNeg=function(){return J(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},G.prototype.redPow=function(F){return J(this.red&&!F.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,F)};var i={k256:null,p224:null,p192:null,p25519:null};function Z0(F,D){this.name=F,this.p=new G(D,16),this.n=this.p.bitLength(),this.k=new G(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}Z0.prototype._tmp=function(){var F=new G(null);return F.words=Array(Math.ceil(this.n/13)),F},Z0.prototype.ireduce=function(F){var D=F,P;do this.split(D,this.tmp),D=this.imulK(D),D=D.iadd(this.tmp),P=D.bitLength();while(P>this.n);var j=P<this.n?-1:D.ucmp(this.p);if(j===0)D.words[0]=0,D.length=1;else if(j>0)D.isub(this.p);else if(D.strip!==void 0)D.strip();else D._strip();return D},Z0.prototype.split=function(F,D){F.iushrn(this.n,0,D)},Z0.prototype.imulK=function(F){return F.imul(this.k)};function t(){Z0.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}X(t,Z0),t.prototype.split=function(F,D){var P=4194303,j=Math.min(F.length,9);for(var R=0;R<j;R++)D.words[R]=F.words[R];if(D.length=j,F.length<=9){F.words[0]=0,F.length=1;return}var q=F.words[9];D.words[D.length++]=q&P;for(R=10;R<F.length;R++){var E=F.words[R]|0;F.words[R-10]=(E&P)<<4|q>>>22,q=E}if(q>>>=22,F.words[R-10]=q,q===0&&F.length>10)F.length-=10;else F.length-=9},t.prototype.imulK=function(F){F.words[F.length]=0,F.words[F.length+1]=0,F.length+=2;var D=0;for(var P=0;P<F.length;P++){var j=F.words[P]|0;D+=j*977,F.words[P]=D&67108863,D=j*64+(D/67108864|0)}if(F.words[F.length-1]===0){if(F.length--,F.words[F.length-1]===0)F.length--}return F};function c(){Z0.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}X(c,Z0);function l(){Z0.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}X(l,Z0);function V(){Z0.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}X(V,Z0),V.prototype.imulK=function(F){var D=0;for(var P=0;P<F.length;P++){var j=(F.words[P]|0)*19+D,R=j&67108863;j>>>=26,F.words[P]=R,D=j}if(D!==0)F.words[F.length++]=D;return F},G._prime=function(F){if(i[F])return i[F];var D;if(F==="k256")D=new t;else if(F==="p224")D=new c;else if(F==="p192")D=new l;else if(F==="p25519")D=new V;else throw Error("Unknown prime "+F);return i[F]=D,D};function z(F){if(typeof F==="string"){var D=G._prime(F);this.m=D.p,this.prime=D}else J(F.gtn(1),"modulus must be greater than 1"),this.m=F,this.prime=null}z.prototype._verify1=function(F){J(F.negative===0,"red works only with positives"),J(F.red,"red works only with red numbers")},z.prototype._verify2=function(F,D){J((F.negative|D.negative)===0,"red works only with positives"),J(F.red&&F.red===D.red,"red works only with red numbers")},z.prototype.imod=function(F){if(this.prime)return this.prime.ireduce(F)._forceRed(this);return I(F,F.umod(this.m)._forceRed(this)),F},z.prototype.neg=function(F){if(F.isZero())return F.clone();return this.m.sub(F)._forceRed(this)},z.prototype.add=function(F,D){this._verify2(F,D);var P=F.add(D);if(P.cmp(this.m)>=0)P.isub(this.m);return P._forceRed(this)},z.prototype.iadd=function(F,D){this._verify2(F,D);var P=F.iadd(D);if(P.cmp(this.m)>=0)P.isub(this.m);return P},z.prototype.sub=function(F,D){this._verify2(F,D);var P=F.sub(D);if(P.cmpn(0)<0)P.iadd(this.m);return P._forceRed(this)},z.prototype.isub=function(F,D){this._verify2(F,D);var P=F.isub(D);if(P.cmpn(0)<0)P.iadd(this.m);return P},z.prototype.shl=function(F,D){return this._verify1(F),this.imod(F.ushln(D))},z.prototype.imul=function(F,D){return this._verify2(F,D),this.imod(F.imul(D))},z.prototype.mul=function(F,D){return this._verify2(F,D),this.imod(F.mul(D))},z.prototype.isqr=function(F){return this.imul(F,F.clone())},z.prototype.sqr=function(F){return this.mul(F,F)},z.prototype.sqrt=function(F){if(F.isZero())return F.clone();var D=this.m.andln(3);if(J(D%2===1),D===3){var P=this.m.add(new G(1)).iushrn(2);return this.pow(F,P)}var j=this.m.subn(1),R=0;while(!j.isZero()&&j.andln(1)===0)R++,j.iushrn(1);J(!j.isZero());var q=new G(1).toRed(this),E=q.redNeg(),N=this.m.subn(1).iushrn(1),T=this.m.bitLength();T=new G(2*T*T).toRed(this);while(this.pow(T,N).cmp(E)!==0)T.redIAdd(E);var v=this.pow(T,j),y=this.pow(F,j.addn(1).iushrn(1)),p=this.pow(F,j),J0=R;while(p.cmp(q)!==0){var x0=p;for(var K0=0;x0.cmp(q)!==0;K0++)x0=x0.redSqr();J(K0<J0);var Y0=this.pow(v,new G(1).iushln(J0-K0-1));y=y.redMul(Y0),v=Y0.redSqr(),p=p.redMul(v),J0=K0}return y},z.prototype.invm=function(F){var D=F._invmp(this.m);if(D.negative!==0)return D.negative=0,this.imod(D).redNeg();else return this.imod(D)},z.prototype.pow=function(F,D){if(D.isZero())return new G(1).toRed(this);if(D.cmpn(1)===0)return F.clone();var P=4,j=Array(1<<P);j[0]=new G(1).toRed(this),j[1]=F;for(var R=2;R<j.length;R++)j[R]=this.mul(j[R-1],F);var q=j[0],E=0,N=0,T=D.bitLength()%26;if(T===0)T=26;for(R=D.length-1;R>=0;R--){var v=D.words[R];for(var y=T-1;y>=0;y--){var p=v>>y&1;if(q!==j[0])q=this.sqr(q);if(p===0&&E===0){N=0;continue}if(E<<=1,E|=p,N++,N!==P&&(R!==0||y!==0))continue;q=this.mul(q,j[E]),N=0,E=0}T=26}return q},z.prototype.convertTo=function(F){var D=F.umod(this.m);return D===F?D.clone():D},z.prototype.convertFrom=function(F){var D=F.clone();return D.red=null,D},G.mont=function(F){return new H(F)};function H(F){if(z.call(this,F),this.shift=this.m.bitLength(),this.shift%26!==0)this.shift+=26-this.shift%26;this.r=new G(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}X(H,z),H.prototype.convertTo=function(F){return this.imod(F.ushln(this.shift))},H.prototype.convertFrom=function(F){var D=this.imod(F.mul(this.rinv));return D.red=null,D},H.prototype.imul=function(F,D){if(F.isZero()||D.isZero())return F.words[0]=0,F.length=1,F;var P=F.imul(D),j=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=P.isub(j).iushrn(this.shift),q=R;if(R.cmp(this.m)>=0)q=R.isub(this.m);else if(R.cmpn(0)<0)q=R.iadd(this.m);return q._forceRed(this)},H.prototype.mul=function(F,D){if(F.isZero()||D.isZero())return new G(0)._forceRed(this);var P=F.mul(D),j=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),R=P.isub(j).iushrn(this.shift),q=R;if(R.cmp(this.m)>=0)q=R.isub(this.m);else if(R.cmpn(0)<0)q=R.iadd(this.m);return q._forceRed(this)},H.prototype.invm=function(F){var D=this.imod(F._invmp(this.m).mul(this.r2));return D._forceRed(this)}})(typeof Z>"u"||Z,Q)}),MS=v0((Q,Z)=>{var Y=Me(),$=fW(),J=I$().Buffer;function X(U){var K=U.modulus.byteLength(),O;do O=new Y($(K));while(O.cmp(U.modulus)>=0||!O.umod(U.prime1)||!O.umod(U.prime2));return O}function G(U){var K=X(U),O=K.toRed(Y.mont(U.modulus)).redPow(new Y(U.publicExponent)).fromRed();return{blinder:O,unblinder:K.invm(U.modulus)}}function W(U,K){var O=G(K),I=K.modulus.byteLength(),L=new Y(U).mul(O.blinder).umod(K.modulus),A=L.toRed(Y.mont(K.prime1)),M=L.toRed(Y.mont(K.prime2)),k=K.coefficient,B=K.prime1,C=K.prime2,S=A.redPow(K.exponent1).fromRed(),_=M.redPow(K.exponent2).fromRed(),x=S.isub(_).imul(k).umod(B).imul(C);return _.iadd(x).imul(O.unblinder).umod(K.modulus).toArrayLike(J,"be",I)}W.getr=X,Z.exports=W}),Te=v0((Q,Z)=>{var Y=ES(),$=fW(),J=yW(),X=PS(),G=jS(),W=MD(),U=AS(),K=MS(),O=I$().Buffer;Z.exports=function(M,k,B){var C;if(M.padding)C=M.padding;else if(B)C=1;else C=4;var S=Y(M),_;if(C===4)_=I(S,k);else if(C===1)_=L(S,k,B);else if(C===3){if(_=new W(k),_.cmp(S.modulus)>=0)throw Error("data too long for modulus")}else throw Error("unknown padding");if(B)return K(_,S);else return U(_,S)};function I(M,k){var B=M.modulus.byteLength(),C=k.length,S=J("sha1").update(O.alloc(0)).digest(),_=S.length,x=2*_;if(C>B-x-2)throw Error("message too long");var f=O.alloc(B-C-x-2),h=B-_-1,i=$(_),Z0=G(O.concat([S,f,O.alloc(1,1),k],h),X(i,h)),t=G(i,X(Z0,_));return new W(O.concat([O.alloc(1),t,Z0],B))}function L(M,k,B){var C=k.length,S=M.modulus.byteLength();if(C>S-11)throw Error("message too long");var _;if(B)_=O.alloc(S-C-3,255);else _=A(S-C-3);return new W(O.concat([O.from([0,B?1:2]),_,O.alloc(1),k],S))}function A(M){var k=O.allocUnsafe(M),B=0,C=$(M*2),S=0,_;while(B<M){if(S===C.length)C=$(M*2),S=0;if(_=C[S++],_)k[B++]=_}return k}}),Ne=v0((Q,Z)=>{var Y=ES(),$=PS(),J=jS(),X=MD(),G=MS(),W=yW(),U=AS(),K=I$().Buffer;Z.exports=function(A,M,k){var B;if(A.padding)B=A.padding;else if(k)B=1;else B=4;var C=Y(A),S=C.modulus.byteLength();if(M.length>S||new X(M).cmp(C.modulus)>=0)throw Error("decryption error");var _;if(k)_=U(new X(M),C);else _=G(M,C);var x=K.alloc(S-_.length);if(_=K.concat([x,_],S),B===4)return O(C,_);else if(B===1)return I(C,_,k);else if(B===3)return _;else throw Error("unknown padding")};function O(A,M){var k=A.modulus.byteLength(),B=W("sha1").update(K.alloc(0)).digest(),C=B.length;if(M[0]!==0)throw Error("decryption error");var S=M.slice(1,C+1),_=M.slice(C+1),x=J(S,$(_,C)),f=J(_,$(x,k-C-1));if(L(B,f.slice(0,C)))throw Error("decryption error");var h=C;while(f[h]===0)h++;if(f[h++]!==1)throw Error("decryption error");return f.slice(h)}function I(A,M,k){var B=M.slice(0,2),C=2,S=0;while(M[C++]!==0)if(C>=M.length){S++;break}var _=M.slice(2,C-1);if(B.toString("hex")!=="0002"&&!k||B.toString("hex")!=="0001"&&k)S++;if(_.length<8)S++;if(S)throw Error("decryption error");return M.slice(C)}function L(A,M){A=K.from(A),M=K.from(M);var k=0,B=A.length;if(A.length!==M.length)k++,B=Math.min(A.length,M.length);var C=-1;while(++C<B)k+=A[C]^M[C];return k}}),HD=v0((Q)=>{Q.publicEncrypt=Te(),Q.privateDecrypt=Ne(),Q.privateEncrypt=function(Z,Y){return Q.publicEncrypt(Z,Y,!0)},Q.publicDecrypt=function(Z,Y){return Q.privateDecrypt(Z,Y,!0)}}),Be=v0((Q)=>{var Z=(v$(),oQ(_$));if(typeof Z.publicEncrypt!=="function")Z=HD();if(Q.publicEncrypt=Z.publicEncrypt,Q.privateDecrypt=Z.privateDecrypt,typeof Z.privateEncrypt!=="function")Q.privateEncrypt=HD().privateEncrypt;else Q.privateEncrypt=Z.privateEncrypt;if(typeof Z.publicDecrypt!=="function")Q.publicDecrypt=HD().publicDecrypt;else Q.publicDecrypt=Z.publicDecrypt}),ke=v0((Q)=>{var Z=I$(),Y=fW(),$=Z.Buffer,J=Z.kMaxLength,X=globalThis.crypto||globalThis.msCrypto,G=Math.pow(2,32)-1;function W(L,A){if(typeof L!=="number"||L!==L)throw TypeError("offset must be a number");if(L>G||L<0)throw TypeError("offset must be a uint32");if(L>J||L>A)throw RangeError("offset out of range")}function U(L,A,M){if(typeof L!=="number"||L!==L)throw TypeError("size must be a number");if(L>G||L<0)throw TypeError("size must be a uint32");if(L+A>M||L>J)throw RangeError("buffer too small")}X&&X.getRandomValues,Q.randomFill=K,Q.randomFillSync=I;function K(L,A,M,k){if(!$.isBuffer(L)&&!(L instanceof globalThis.Uint8Array))throw TypeError('"buf" argument must be a Buffer or Uint8Array');if(typeof A==="function")k=A,A=0,M=L.length;else if(typeof M==="function")k=M,M=L.length-A;else if(typeof k!=="function")throw TypeError('"cb" argument must be a function');return W(A,L.length),U(M,A,L.length),O(L,A,M,k)}function O(L,A,M,k){if(!1)var B,C;if(k){Y(M,function(_,x){if(_)return k(_);x.copy(L,A),k(null,L)});return}var S=Y(M);return S.copy(L,A),L}function I(L,A,M){if(typeof A>"u")A=0;if(!$.isBuffer(L)&&!(L instanceof globalThis.Uint8Array))throw TypeError('"buf" argument must be a Buffer or Uint8Array');if(W(A,L.length),M===void 0)M=L.length-A;return U(M,A,L.length),O(L,A,M)}}),Ce=v0((Q,Z)=>{var Y=(v$(),oQ(_$));if(typeof Y.randomFill==="function"&&typeof Y.randomFillSync==="function")Q.randomFill=Y.randomFill,Q.randomFillSync=Y.randomFillSync;else Z.exports=ke()}),Se=v0((Q)=>{Q.randomBytes=Q.rng=Q.pseudoRandomBytes=Q.prng=fW(),Q.createHash=Q.Hash=yW(),Q.createHmac=Q.Hmac=tC();var Z=Qt(),Y=Object.keys(Z),$=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(Y);Q.getHashes=function(){return $};var J=FS();Q.pbkdf2=J.pbkdf2,Q.pbkdf2Sync=J.pbkdf2Sync;var X=yt();Q.Cipher=X.Cipher,Q.createCipher=X.createCipher,Q.Cipheriv=X.Cipheriv,Q.createCipheriv=X.createCipheriv,Q.Decipher=X.Decipher,Q.createDecipher=X.createDecipher,Q.Decipheriv=X.Decipheriv,Q.createDecipheriv=X.createDecipheriv,Q.getCiphers=X.getCiphers,Q.listCiphers=X.listCiphers;var G=gt();Q.DiffieHellmanGroup=G.DiffieHellmanGroup,Q.createDiffieHellmanGroup=G.createDiffieHellmanGroup,Q.getDiffieHellman=G.getDiffieHellman,Q.createDiffieHellman=G.createDiffieHellman,Q.DiffieHellman=G.DiffieHellman;var W=ht();Q.createSign=W.createSign,Q.Sign=W.Sign,Q.createVerify=W.createVerify,Q.Verify=W.Verify,Q.createECDH=Ve();var U=Be();Q.publicEncrypt=U.publicEncrypt,Q.privateEncrypt=U.privateEncrypt,Q.publicDecrypt=U.publicDecrypt,Q.privateDecrypt=U.privateDecrypt;var K=Ce();Q.randomFill=K.randomFill,Q.randomFillSync=K.randomFillSync,Q.createCredentials=function(){throw Error(`sorry, createCredentials is not implemented yet
|
|
88
|
+
we accept pull requests
|
|
89
|
+
https://github.com/browserify/crypto-browserify`)},Q.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}}),nQ=er(Se(),1),we=nQ.prng,_e=nQ.pseudoRandomBytes,ve=nQ.rng,xe=nQ.randomBytes,fe=nQ.Hash,ye=nQ.createHash,ge=nQ.Hmac,he=nQ.createHmac,be=nQ.getHashes,ce=nQ.pbkdf2,ue=nQ.pbkdf2Sync,pe=nQ.Cipher,le=nQ.createCipher,me=nQ.Cipheriv,de=nQ.createCipheriv,ne=nQ.Decipher,oe=nQ.createDecipher,se=nQ.Decipheriv,ie=nQ.createDecipheriv,ae=nQ.getCiphers,re=nQ.listCiphers,te=nQ.DiffieHellmanGroup,ee=nQ.createDiffieHellmanGroup,Q00=nQ.getDiffieHellman,Z00=nQ.createDiffieHellman,Y00=nQ.DiffieHellman,$00=nQ.createSign,J00=nQ.Sign,G00=nQ.createVerify,X00=nQ.Verify,V00=nQ.createECDH,q00=nQ.publicEncrypt,F00=nQ.privateEncrypt,z00=nQ.publicDecrypt,W00=nQ.privateDecrypt,K00=nQ.randomFill,U00=nQ.randomFillSync,O00=nQ.createCredentials,H00=nQ.constants,L00=["p192","p224","p256","p384","p521","curve25519","ed25519","secp256k1","secp224r1","prime256v1","prime192v1","ed25519","secp384r1","secp521r1"];P00=crypto,j00=crypto});var sQ=XQ((bW,TS)=>{(function(Q,Z){if(typeof bW==="object")TS.exports=bW=Z();else if(typeof define==="function"&&define.amd)define([],Z);else Q.CryptoJS=Z()})(bW,function(){var Q=Q||function(Z,Y){var $;if(typeof window<"u"&&window.crypto)$=window.crypto;if(typeof self<"u"&&self.crypto)$=self.crypto;if(typeof globalThis<"u"&&globalThis.crypto)$=globalThis.crypto;if(!$&&typeof window<"u"&&window.msCrypto)$=window.msCrypto;if(!$&&typeof global<"u"&&global.crypto)$=global.crypto;if(!$)try{$=(v$(),oQ(_$))}catch(C){}var J=function(){if($){if(typeof $.getRandomValues==="function")try{return $.getRandomValues(new Uint32Array(1))[0]}catch(C){}if(typeof $.randomBytes==="function")try{return $.randomBytes(4).readInt32LE()}catch(C){}}throw Error("Native crypto module could not be used to get secure random number.")},X=Object.create||function(){function C(){}return function(S){var _;return C.prototype=S,_=new C,C.prototype=null,_}}(),G={},W=G.lib={},U=W.Base=function(){return{extend:function(C){var S=X(this);if(C)S.mixIn(C);if(!S.hasOwnProperty("init")||this.init===S.init)S.init=function(){S.$super.init.apply(this,arguments)};return S.init.prototype=S,S.$super=this,S},create:function(){var C=this.extend();return C.init.apply(C,arguments),C},init:function(){},mixIn:function(C){for(var S in C)if(C.hasOwnProperty(S))this[S]=C[S];if(C.hasOwnProperty("toString"))this.toString=C.toString},clone:function(){return this.init.prototype.extend(this)}}}(),K=W.WordArray=U.extend({init:function(C,S){if(C=this.words=C||[],S!=Y)this.sigBytes=S;else this.sigBytes=C.length*4},toString:function(C){return(C||I).stringify(this)},concat:function(C){var S=this.words,_=C.words,x=this.sigBytes,f=C.sigBytes;if(this.clamp(),x%4)for(var h=0;h<f;h++){var i=_[h>>>2]>>>24-h%4*8&255;S[x+h>>>2]|=i<<24-(x+h)%4*8}else for(var Z0=0;Z0<f;Z0+=4)S[x+Z0>>>2]=_[Z0>>>2];return this.sigBytes+=f,this},clamp:function(){var C=this.words,S=this.sigBytes;C[S>>>2]&=4294967295<<32-S%4*8,C.length=Z.ceil(S/4)},clone:function(){var C=U.clone.call(this);return C.words=this.words.slice(0),C},random:function(C){var S=[];for(var _=0;_<C;_+=4)S.push(J());return new K.init(S,C)}}),O=G.enc={},I=O.Hex={stringify:function(C){var{words:S,sigBytes:_}=C,x=[];for(var f=0;f<_;f++){var h=S[f>>>2]>>>24-f%4*8&255;x.push((h>>>4).toString(16)),x.push((h&15).toString(16))}return x.join("")},parse:function(C){var S=C.length,_=[];for(var x=0;x<S;x+=2)_[x>>>3]|=parseInt(C.substr(x,2),16)<<24-x%8*4;return new K.init(_,S/2)}},L=O.Latin1={stringify:function(C){var{words:S,sigBytes:_}=C,x=[];for(var f=0;f<_;f++){var h=S[f>>>2]>>>24-f%4*8&255;x.push(String.fromCharCode(h))}return x.join("")},parse:function(C){var S=C.length,_=[];for(var x=0;x<S;x++)_[x>>>2]|=(C.charCodeAt(x)&255)<<24-x%4*8;return new K.init(_,S)}},A=O.Utf8={stringify:function(C){try{return decodeURIComponent(escape(L.stringify(C)))}catch(S){throw Error("Malformed UTF-8 data")}},parse:function(C){return L.parse(unescape(encodeURIComponent(C)))}},M=W.BufferedBlockAlgorithm=U.extend({reset:function(){this._data=new K.init,this._nDataBytes=0},_append:function(C){if(typeof C=="string")C=A.parse(C);this._data.concat(C),this._nDataBytes+=C.sigBytes},_process:function(C){var S,_=this._data,x=_.words,f=_.sigBytes,h=this.blockSize,i=h*4,Z0=f/i;if(C)Z0=Z.ceil(Z0);else Z0=Z.max((Z0|0)-this._minBufferSize,0);var t=Z0*h,c=Z.min(t*4,f);if(t){for(var l=0;l<t;l+=h)this._doProcessBlock(x,l);S=x.splice(0,t),_.sigBytes-=c}return new K.init(S,c)},clone:function(){var C=U.clone.call(this);return C._data=this._data.clone(),C},_minBufferSize:0}),k=W.Hasher=M.extend({cfg:U.extend(),init:function(C){this.cfg=this.cfg.extend(C),this.reset()},reset:function(){M.reset.call(this),this._doReset()},update:function(C){return this._append(C),this._process(),this},finalize:function(C){if(C)this._append(C);var S=this._doFinalize();return S},blockSize:16,_createHelper:function(C){return function(S,_){return new C.init(_).finalize(S)}},_createHmacHelper:function(C){return function(S,_){return new B.HMAC.init(C,_).finalize(S)}}}),B=G.algo={};return G}(Math);return Q})});var a6=XQ((cW,NS)=>{(function(Q,Z){if(typeof cW==="object")NS.exports=cW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(cW,function(Q){return function(Z){var Y=Q,$=Y.lib,J=$.Base,X=$.WordArray,G=Y.x64={},W=G.Word=J.extend({init:function(K,O){this.high=K,this.low=O}}),U=G.WordArray=J.extend({init:function(K,O){if(K=this.words=K||[],O!=Z)this.sigBytes=O;else this.sigBytes=K.length*8},toX32:function(){var K=this.words,O=K.length,I=[];for(var L=0;L<O;L++){var A=K[L];I.push(A.high),I.push(A.low)}return X.create(I,this.sigBytes)},clone:function(){var K=J.clone.call(this),O=K.words=this.words.slice(0),I=O.length;for(var L=0;L<I;L++)O[L]=O[L].clone();return K}})}(),Q})});var kS=XQ((uW,BS)=>{(function(Q,Z){if(typeof uW==="object")BS.exports=uW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(uW,function(Q){return function(){if(typeof ArrayBuffer!="function")return;var Z=Q,Y=Z.lib,$=Y.WordArray,J=$.init,X=$.init=function(G){if(G instanceof ArrayBuffer)G=new Uint8Array(G);if(G instanceof Int8Array||typeof Uint8ClampedArray<"u"&&G instanceof Uint8ClampedArray||G instanceof Int16Array||G instanceof Uint16Array||G instanceof Int32Array||G instanceof Uint32Array||G instanceof Float32Array||G instanceof Float64Array)G=new Uint8Array(G.buffer,G.byteOffset,G.byteLength);if(G instanceof Uint8Array){var W=G.byteLength,U=[];for(var K=0;K<W;K++)U[K>>>2]|=G[K]<<24-K%4*8;J.call(this,U,W)}else J.apply(this,arguments)};X.prototype=$}(),Q.lib.WordArray})});var SS=XQ((pW,CS)=>{(function(Q,Z){if(typeof pW==="object")CS.exports=pW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(pW,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.WordArray,J=Z.enc,X=J.Utf16=J.Utf16BE={stringify:function(W){var{words:U,sigBytes:K}=W,O=[];for(var I=0;I<K;I+=2){var L=U[I>>>2]>>>16-I%4*8&65535;O.push(String.fromCharCode(L))}return O.join("")},parse:function(W){var U=W.length,K=[];for(var O=0;O<U;O++)K[O>>>1]|=W.charCodeAt(O)<<16-O%2*16;return $.create(K,U*2)}};J.Utf16LE={stringify:function(W){var{words:U,sigBytes:K}=W,O=[];for(var I=0;I<K;I+=2){var L=G(U[I>>>2]>>>16-I%4*8&65535);O.push(String.fromCharCode(L))}return O.join("")},parse:function(W){var U=W.length,K=[];for(var O=0;O<U;O++)K[O>>>1]|=G(W.charCodeAt(O)<<16-O%2*16);return $.create(K,U*2)}};function G(W){return W<<8&4278255360|W>>>8&16711935}}(),Q.enc.Utf16})});var u8=XQ((lW,wS)=>{(function(Q,Z){if(typeof lW==="object")wS.exports=lW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(lW,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.WordArray,J=Z.enc,X=J.Base64={stringify:function(W){var{words:U,sigBytes:K}=W,O=this._map;W.clamp();var I=[];for(var L=0;L<K;L+=3){var A=U[L>>>2]>>>24-L%4*8&255,M=U[L+1>>>2]>>>24-(L+1)%4*8&255,k=U[L+2>>>2]>>>24-(L+2)%4*8&255,B=A<<16|M<<8|k;for(var C=0;C<4&&L+C*0.75<K;C++)I.push(O.charAt(B>>>6*(3-C)&63))}var S=O.charAt(64);if(S)while(I.length%4)I.push(S);return I.join("")},parse:function(W){var U=W.length,K=this._map,O=this._reverseMap;if(!O){O=this._reverseMap=[];for(var I=0;I<K.length;I++)O[K.charCodeAt(I)]=I}var L=K.charAt(64);if(L){var A=W.indexOf(L);if(A!==-1)U=A}return G(W,U,O)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};function G(W,U,K){var O=[],I=0;for(var L=0;L<U;L++)if(L%4){var A=K[W.charCodeAt(L-1)]<<L%4*2,M=K[W.charCodeAt(L)]>>>6-L%4*2,k=A|M;O[I>>>2]|=k<<24-I%4*8,I++}return $.create(O,I)}}(),Q.enc.Base64})});var vS=XQ((mW,_S)=>{(function(Q,Z){if(typeof mW==="object")_S.exports=mW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(mW,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.WordArray,J=Z.enc,X=J.Base64url={stringify:function(W,U){if(U===void 0)U=!0;var{words:K,sigBytes:O}=W,I=U?this._safe_map:this._map;W.clamp();var L=[];for(var A=0;A<O;A+=3){var M=K[A>>>2]>>>24-A%4*8&255,k=K[A+1>>>2]>>>24-(A+1)%4*8&255,B=K[A+2>>>2]>>>24-(A+2)%4*8&255,C=M<<16|k<<8|B;for(var S=0;S<4&&A+S*0.75<O;S++)L.push(I.charAt(C>>>6*(3-S)&63))}var _=I.charAt(64);if(_)while(L.length%4)L.push(_);return L.join("")},parse:function(W,U){if(U===void 0)U=!0;var K=W.length,O=U?this._safe_map:this._map,I=this._reverseMap;if(!I){I=this._reverseMap=[];for(var L=0;L<O.length;L++)I[O.charCodeAt(L)]=L}var A=O.charAt(64);if(A){var M=W.indexOf(A);if(M!==-1)K=M}return G(W,K,I)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function G(W,U,K){var O=[],I=0;for(var L=0;L<U;L++)if(L%4){var A=K[W.charCodeAt(L-1)]<<L%4*2,M=K[W.charCodeAt(L)]>>>6-L%4*2,k=A|M;O[I>>>2]|=k<<24-I%4*8,I++}return $.create(O,I)}}(),Q.enc.Base64url})});var p8=XQ((dW,xS)=>{(function(Q,Z){if(typeof dW==="object")xS.exports=dW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(dW,function(Q){return function(Z){var Y=Q,$=Y.lib,J=$.WordArray,X=$.Hasher,G=Y.algo,W=[];(function(){for(var A=0;A<64;A++)W[A]=Z.abs(Z.sin(A+1))*4294967296|0})();var U=G.MD5=X.extend({_doReset:function(){this._hash=new J.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(A,M){for(var k=0;k<16;k++){var B=M+k,C=A[B];A[B]=(C<<8|C>>>24)&16711935|(C<<24|C>>>8)&4278255360}var S=this._hash.words,_=A[M+0],x=A[M+1],f=A[M+2],h=A[M+3],i=A[M+4],Z0=A[M+5],t=A[M+6],c=A[M+7],l=A[M+8],V=A[M+9],z=A[M+10],H=A[M+11],F=A[M+12],D=A[M+13],P=A[M+14],j=A[M+15],R=S[0],q=S[1],E=S[2],N=S[3];R=K(R,q,E,N,_,7,W[0]),N=K(N,R,q,E,x,12,W[1]),E=K(E,N,R,q,f,17,W[2]),q=K(q,E,N,R,h,22,W[3]),R=K(R,q,E,N,i,7,W[4]),N=K(N,R,q,E,Z0,12,W[5]),E=K(E,N,R,q,t,17,W[6]),q=K(q,E,N,R,c,22,W[7]),R=K(R,q,E,N,l,7,W[8]),N=K(N,R,q,E,V,12,W[9]),E=K(E,N,R,q,z,17,W[10]),q=K(q,E,N,R,H,22,W[11]),R=K(R,q,E,N,F,7,W[12]),N=K(N,R,q,E,D,12,W[13]),E=K(E,N,R,q,P,17,W[14]),q=K(q,E,N,R,j,22,W[15]),R=O(R,q,E,N,x,5,W[16]),N=O(N,R,q,E,t,9,W[17]),E=O(E,N,R,q,H,14,W[18]),q=O(q,E,N,R,_,20,W[19]),R=O(R,q,E,N,Z0,5,W[20]),N=O(N,R,q,E,z,9,W[21]),E=O(E,N,R,q,j,14,W[22]),q=O(q,E,N,R,i,20,W[23]),R=O(R,q,E,N,V,5,W[24]),N=O(N,R,q,E,P,9,W[25]),E=O(E,N,R,q,h,14,W[26]),q=O(q,E,N,R,l,20,W[27]),R=O(R,q,E,N,D,5,W[28]),N=O(N,R,q,E,f,9,W[29]),E=O(E,N,R,q,c,14,W[30]),q=O(q,E,N,R,F,20,W[31]),R=I(R,q,E,N,Z0,4,W[32]),N=I(N,R,q,E,l,11,W[33]),E=I(E,N,R,q,H,16,W[34]),q=I(q,E,N,R,P,23,W[35]),R=I(R,q,E,N,x,4,W[36]),N=I(N,R,q,E,i,11,W[37]),E=I(E,N,R,q,c,16,W[38]),q=I(q,E,N,R,z,23,W[39]),R=I(R,q,E,N,D,4,W[40]),N=I(N,R,q,E,_,11,W[41]),E=I(E,N,R,q,h,16,W[42]),q=I(q,E,N,R,t,23,W[43]),R=I(R,q,E,N,V,4,W[44]),N=I(N,R,q,E,F,11,W[45]),E=I(E,N,R,q,j,16,W[46]),q=I(q,E,N,R,f,23,W[47]),R=L(R,q,E,N,_,6,W[48]),N=L(N,R,q,E,c,10,W[49]),E=L(E,N,R,q,P,15,W[50]),q=L(q,E,N,R,Z0,21,W[51]),R=L(R,q,E,N,F,6,W[52]),N=L(N,R,q,E,h,10,W[53]),E=L(E,N,R,q,z,15,W[54]),q=L(q,E,N,R,x,21,W[55]),R=L(R,q,E,N,l,6,W[56]),N=L(N,R,q,E,j,10,W[57]),E=L(E,N,R,q,t,15,W[58]),q=L(q,E,N,R,D,21,W[59]),R=L(R,q,E,N,i,6,W[60]),N=L(N,R,q,E,H,10,W[61]),E=L(E,N,R,q,f,15,W[62]),q=L(q,E,N,R,V,21,W[63]),S[0]=S[0]+R|0,S[1]=S[1]+q|0,S[2]=S[2]+E|0,S[3]=S[3]+N|0},_doFinalize:function(){var A=this._data,M=A.words,k=this._nDataBytes*8,B=A.sigBytes*8;M[B>>>5]|=128<<24-B%32;var C=Z.floor(k/4294967296),S=k;M[(B+64>>>9<<4)+15]=(C<<8|C>>>24)&16711935|(C<<24|C>>>8)&4278255360,M[(B+64>>>9<<4)+14]=(S<<8|S>>>24)&16711935|(S<<24|S>>>8)&4278255360,A.sigBytes=(M.length+1)*4,this._process();var _=this._hash,x=_.words;for(var f=0;f<4;f++){var h=x[f];x[f]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360}return _},clone:function(){var A=X.clone.call(this);return A._hash=this._hash.clone(),A}});function K(A,M,k,B,C,S,_){var x=A+(M&k|~M&B)+C+_;return(x<<S|x>>>32-S)+M}function O(A,M,k,B,C,S,_){var x=A+(M&B|k&~B)+C+_;return(x<<S|x>>>32-S)+M}function I(A,M,k,B,C,S,_){var x=A+(M^k^B)+C+_;return(x<<S|x>>>32-S)+M}function L(A,M,k,B,C,S,_){var x=A+(k^(M|~B))+C+_;return(x<<S|x>>>32-S)+M}Y.MD5=X._createHelper(U),Y.HmacMD5=X._createHmacHelper(U)}(Math),Q.MD5})});var TD=XQ((nW,fS)=>{(function(Q,Z){if(typeof nW==="object")fS.exports=nW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(nW,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.WordArray,J=Y.Hasher,X=Z.algo,G=[],W=X.SHA1=J.extend({_doReset:function(){this._hash=new $.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(U,K){var O=this._hash.words,I=O[0],L=O[1],A=O[2],M=O[3],k=O[4];for(var B=0;B<80;B++){if(B<16)G[B]=U[K+B]|0;else{var C=G[B-3]^G[B-8]^G[B-14]^G[B-16];G[B]=C<<1|C>>>31}var S=(I<<5|I>>>27)+k+G[B];if(B<20)S+=(L&A|~L&M)+1518500249;else if(B<40)S+=(L^A^M)+1859775393;else if(B<60)S+=(L&A|L&M|A&M)-1894007588;else S+=(L^A^M)-899497514;k=M,M=A,A=L<<30|L>>>2,L=I,I=S}O[0]=O[0]+I|0,O[1]=O[1]+L|0,O[2]=O[2]+A|0,O[3]=O[3]+M|0,O[4]=O[4]+k|0},_doFinalize:function(){var U=this._data,K=U.words,O=this._nDataBytes*8,I=U.sigBytes*8;return K[I>>>5]|=128<<24-I%32,K[(I+64>>>9<<4)+14]=Math.floor(O/4294967296),K[(I+64>>>9<<4)+15]=O,U.sigBytes=K.length*4,this._process(),this._hash},clone:function(){var U=J.clone.call(this);return U._hash=this._hash.clone(),U}});Z.SHA1=J._createHelper(W),Z.HmacSHA1=J._createHmacHelper(W)}(),Q.SHA1})});var sW=XQ((oW,yS)=>{(function(Q,Z){if(typeof oW==="object")yS.exports=oW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(oW,function(Q){return function(Z){var Y=Q,$=Y.lib,J=$.WordArray,X=$.Hasher,G=Y.algo,W=[],U=[];(function(){function I(k){var B=Z.sqrt(k);for(var C=2;C<=B;C++)if(!(k%C))return!1;return!0}function L(k){return(k-(k|0))*4294967296|0}var A=2,M=0;while(M<64){if(I(A)){if(M<8)W[M]=L(Z.pow(A,0.5));U[M]=L(Z.pow(A,0.3333333333333333)),M++}A++}})();var K=[],O=G.SHA256=X.extend({_doReset:function(){this._hash=new J.init(W.slice(0))},_doProcessBlock:function(I,L){var A=this._hash.words,M=A[0],k=A[1],B=A[2],C=A[3],S=A[4],_=A[5],x=A[6],f=A[7];for(var h=0;h<64;h++){if(h<16)K[h]=I[L+h]|0;else{var i=K[h-15],Z0=(i<<25|i>>>7)^(i<<14|i>>>18)^i>>>3,t=K[h-2],c=(t<<15|t>>>17)^(t<<13|t>>>19)^t>>>10;K[h]=Z0+K[h-7]+c+K[h-16]}var l=S&_^~S&x,V=M&k^M&B^k&B,z=(M<<30|M>>>2)^(M<<19|M>>>13)^(M<<10|M>>>22),H=(S<<26|S>>>6)^(S<<21|S>>>11)^(S<<7|S>>>25),F=f+H+l+U[h]+K[h],D=z+V;f=x,x=_,_=S,S=C+F|0,C=B,B=k,k=M,M=F+D|0}A[0]=A[0]+M|0,A[1]=A[1]+k|0,A[2]=A[2]+B|0,A[3]=A[3]+C|0,A[4]=A[4]+S|0,A[5]=A[5]+_|0,A[6]=A[6]+x|0,A[7]=A[7]+f|0},_doFinalize:function(){var I=this._data,L=I.words,A=this._nDataBytes*8,M=I.sigBytes*8;return L[M>>>5]|=128<<24-M%32,L[(M+64>>>9<<4)+14]=Z.floor(A/4294967296),L[(M+64>>>9<<4)+15]=A,I.sigBytes=L.length*4,this._process(),this._hash},clone:function(){var I=X.clone.call(this);return I._hash=this._hash.clone(),I}});Y.SHA256=X._createHelper(O),Y.HmacSHA256=X._createHmacHelper(O)}(Math),Q.SHA256})});var ND=XQ((iW,gS)=>{(function(Q,Z,Y){if(typeof iW==="object")gS.exports=iW=Z(sQ(),sW());else if(typeof define==="function"&&define.amd)define(["./core","./sha256"],Z);else Z(Q.CryptoJS)})(iW,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.WordArray,J=Z.algo,X=J.SHA256,G=J.SHA224=X.extend({_doReset:function(){this._hash=new $.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var W=X._doFinalize.call(this);return W.sigBytes-=4,W}});Z.SHA224=X._createHelper(G),Z.HmacSHA224=X._createHmacHelper(G)}(),Q.SHA224})});var BD=XQ((aW,hS)=>{(function(Q,Z,Y){if(typeof aW==="object")hS.exports=aW=Z(sQ(),a6());else if(typeof define==="function"&&define.amd)define(["./core","./x64-core"],Z);else Z(Q.CryptoJS)})(aW,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.Hasher,J=Z.x64,X=J.Word,G=J.WordArray,W=Z.algo;function U(){return X.create.apply(X,arguments)}var K=[U(1116352408,3609767458),U(1899447441,602891725),U(3049323471,3964484399),U(3921009573,2173295548),U(961987163,4081628472),U(1508970993,3053834265),U(2453635748,2937671579),U(2870763221,3664609560),U(3624381080,2734883394),U(310598401,1164996542),U(607225278,1323610764),U(1426881987,3590304994),U(1925078388,4068182383),U(2162078206,991336113),U(2614888103,633803317),U(3248222580,3479774868),U(3835390401,2666613458),U(4022224774,944711139),U(264347078,2341262773),U(604807628,2007800933),U(770255983,1495990901),U(1249150122,1856431235),U(1555081692,3175218132),U(1996064986,2198950837),U(2554220882,3999719339),U(2821834349,766784016),U(2952996808,2566594879),U(3210313671,3203337956),U(3336571891,1034457026),U(3584528711,2466948901),U(113926993,3758326383),U(338241895,168717936),U(666307205,1188179964),U(773529912,1546045734),U(1294757372,1522805485),U(1396182291,2643833823),U(1695183700,2343527390),U(1986661051,1014477480),U(2177026350,1206759142),U(2456956037,344077627),U(2730485921,1290863460),U(2820302411,3158454273),U(3259730800,3505952657),U(3345764771,106217008),U(3516065817,3606008344),U(3600352804,1432725776),U(4094571909,1467031594),U(275423344,851169720),U(430227734,3100823752),U(506948616,1363258195),U(659060556,3750685593),U(883997877,3785050280),U(958139571,3318307427),U(1322822218,3812723403),U(1537002063,2003034995),U(1747873779,3602036899),U(1955562222,1575990012),U(2024104815,1125592928),U(2227730452,2716904306),U(2361852424,442776044),U(2428436474,593698344),U(2756734187,3733110249),U(3204031479,2999351573),U(3329325298,3815920427),U(3391569614,3928383900),U(3515267271,566280711),U(3940187606,3454069534),U(4118630271,4000239992),U(116418474,1914138554),U(174292421,2731055270),U(289380356,3203993006),U(460393269,320620315),U(685471733,587496836),U(852142971,1086792851),U(1017036298,365543100),U(1126000580,2618297676),U(1288033470,3409855158),U(1501505948,4234509866),U(1607167915,987167468),U(1816402316,1246189591)],O=[];(function(){for(var L=0;L<80;L++)O[L]=U()})();var I=W.SHA512=$.extend({_doReset:function(){this._hash=new G.init([new X.init(1779033703,4089235720),new X.init(3144134277,2227873595),new X.init(1013904242,4271175723),new X.init(2773480762,1595750129),new X.init(1359893119,2917565137),new X.init(2600822924,725511199),new X.init(528734635,4215389547),new X.init(1541459225,327033209)])},_doProcessBlock:function(L,A){var M=this._hash.words,k=M[0],B=M[1],C=M[2],S=M[3],_=M[4],x=M[5],f=M[6],h=M[7],i=k.high,Z0=k.low,t=B.high,c=B.low,l=C.high,V=C.low,z=S.high,H=S.low,F=_.high,D=_.low,P=x.high,j=x.low,R=f.high,q=f.low,E=h.high,N=h.low,T=i,v=Z0,y=t,p=c,J0=l,x0=V,K0=z,Y0=H,j0=F,$0=D,D0=P,$Q=j,m=R,n=q,B0=E,F0=N;for(var z0=0;z0<80;z0++){var l0,d,X0=O[z0];if(z0<16)d=X0.high=L[A+z0*2]|0,l0=X0.low=L[A+z0*2+1]|0;else{var QQ=O[z0-15],V0=QQ.high,P0=QQ.low,jQ=(V0>>>1|P0<<31)^(V0>>>8|P0<<24)^V0>>>7,c0=(P0>>>1|V0<<31)^(P0>>>8|V0<<24)^(P0>>>7|V0<<25),u0=O[z0-2],$Z=u0.high,y0=u0.low,s=($Z>>>19|y0<<13)^($Z<<3|y0>>>29)^$Z>>>6,M0=(y0>>>19|$Z<<13)^(y0<<3|$Z>>>29)^(y0>>>6|$Z<<26),G0=O[z0-7],H0=G0.high,KQ=G0.low,f0=O[z0-16],h0=f0.high,LQ=f0.low;l0=c0+KQ,d=jQ+H0+(l0>>>0<c0>>>0?1:0),l0=l0+M0,d=d+s+(l0>>>0<M0>>>0?1:0),l0=l0+LQ,d=d+h0+(l0>>>0<LQ>>>0?1:0),X0.high=d,X0.low=l0}var E0=j0&D0^~j0&m,A0=$0&$Q^~$0&n,GQ=T&y^T&J0^y&J0,T0=v&p^v&x0^p&x0,S0=(T>>>28|v<<4)^(T<<30|v>>>2)^(T<<25|v>>>7),gQ=(v>>>28|T<<4)^(v<<30|T>>>2)^(v<<25|T>>>7),g0=(j0>>>14|$0<<18)^(j0>>>18|$0<<14)^(j0<<23|$0>>>9),d0=($0>>>14|j0<<18)^($0>>>18|j0<<14)^($0<<23|j0>>>9),_Z=K[z0],o0=_Z.high,b=_Z.low,Q0=F0+d0,O0=B0+g0+(Q0>>>0<F0>>>0?1:0),Q0=Q0+A0,O0=O0+E0+(Q0>>>0<A0>>>0?1:0),Q0=Q0+b,O0=O0+o0+(Q0>>>0<b>>>0?1:0),Q0=Q0+l0,O0=O0+d+(Q0>>>0<l0>>>0?1:0),L0=gQ+T0,qQ=S0+GQ+(L0>>>0<gQ>>>0?1:0);B0=m,F0=n,m=D0,n=$Q,D0=j0,$Q=$0,$0=Y0+Q0|0,j0=K0+O0+($0>>>0<Y0>>>0?1:0)|0,K0=J0,Y0=x0,J0=y,x0=p,y=T,p=v,v=Q0+L0|0,T=O0+qQ+(v>>>0<Q0>>>0?1:0)|0}Z0=k.low=Z0+v,k.high=i+T+(Z0>>>0<v>>>0?1:0),c=B.low=c+p,B.high=t+y+(c>>>0<p>>>0?1:0),V=C.low=V+x0,C.high=l+J0+(V>>>0<x0>>>0?1:0),H=S.low=H+Y0,S.high=z+K0+(H>>>0<Y0>>>0?1:0),D=_.low=D+$0,_.high=F+j0+(D>>>0<$0>>>0?1:0),j=x.low=j+$Q,x.high=P+D0+(j>>>0<$Q>>>0?1:0),q=f.low=q+n,f.high=R+m+(q>>>0<n>>>0?1:0),N=h.low=N+F0,h.high=E+B0+(N>>>0<F0>>>0?1:0)},_doFinalize:function(){var L=this._data,A=L.words,M=this._nDataBytes*8,k=L.sigBytes*8;A[k>>>5]|=128<<24-k%32,A[(k+128>>>10<<5)+30]=Math.floor(M/4294967296),A[(k+128>>>10<<5)+31]=M,L.sigBytes=A.length*4,this._process();var B=this._hash.toX32();return B},clone:function(){var L=$.clone.call(this);return L._hash=this._hash.clone(),L},blockSize:32});Z.SHA512=$._createHelper(I),Z.HmacSHA512=$._createHmacHelper(I)}(),Q.SHA512})});var cS=XQ((rW,bS)=>{(function(Q,Z,Y){if(typeof rW==="object")bS.exports=rW=Z(sQ(),a6(),BD());else if(typeof define==="function"&&define.amd)define(["./core","./x64-core","./sha512"],Z);else Z(Q.CryptoJS)})(rW,function(Q){return function(){var Z=Q,Y=Z.x64,$=Y.Word,J=Y.WordArray,X=Z.algo,G=X.SHA512,W=X.SHA384=G.extend({_doReset:function(){this._hash=new J.init([new $.init(3418070365,3238371032),new $.init(1654270250,914150663),new $.init(2438529370,812702999),new $.init(355462360,4144912697),new $.init(1731405415,4290775857),new $.init(2394180231,1750603025),new $.init(3675008525,1694076839),new $.init(1203062813,3204075428)])},_doFinalize:function(){var U=G._doFinalize.call(this);return U.sigBytes-=16,U}});Z.SHA384=G._createHelper(W),Z.HmacSHA384=G._createHmacHelper(W)}(),Q.SHA384})});var pS=XQ((tW,uS)=>{(function(Q,Z,Y){if(typeof tW==="object")uS.exports=tW=Z(sQ(),a6());else if(typeof define==="function"&&define.amd)define(["./core","./x64-core"],Z);else Z(Q.CryptoJS)})(tW,function(Q){return function(Z){var Y=Q,$=Y.lib,J=$.WordArray,X=$.Hasher,G=Y.x64,W=G.Word,U=Y.algo,K=[],O=[],I=[];(function(){var M=1,k=0;for(var B=0;B<24;B++){K[M+5*k]=(B+1)*(B+2)/2%64;var C=k%5,S=(2*M+3*k)%5;M=C,k=S}for(var M=0;M<5;M++)for(var k=0;k<5;k++)O[M+5*k]=k+(2*M+3*k)%5*5;var _=1;for(var x=0;x<24;x++){var f=0,h=0;for(var i=0;i<7;i++){if(_&1){var Z0=(1<<i)-1;if(Z0<32)h^=1<<Z0;else f^=1<<Z0-32}if(_&128)_=_<<1^113;else _<<=1}I[x]=W.create(f,h)}})();var L=[];(function(){for(var M=0;M<25;M++)L[M]=W.create()})();var A=U.SHA3=X.extend({cfg:X.cfg.extend({outputLength:512}),_doReset:function(){var M=this._state=[];for(var k=0;k<25;k++)M[k]=new W.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(M,k){var B=this._state,C=this.blockSize/2;for(var S=0;S<C;S++){var _=M[k+2*S],x=M[k+2*S+1];_=(_<<8|_>>>24)&16711935|(_<<24|_>>>8)&4278255360,x=(x<<8|x>>>24)&16711935|(x<<24|x>>>8)&4278255360;var f=B[S];f.high^=x,f.low^=_}for(var h=0;h<24;h++){for(var i=0;i<5;i++){var Z0=0,t=0;for(var c=0;c<5;c++){var f=B[i+5*c];Z0^=f.high,t^=f.low}var l=L[i];l.high=Z0,l.low=t}for(var i=0;i<5;i++){var V=L[(i+4)%5],z=L[(i+1)%5],H=z.high,F=z.low,Z0=V.high^(H<<1|F>>>31),t=V.low^(F<<1|H>>>31);for(var c=0;c<5;c++){var f=B[i+5*c];f.high^=Z0,f.low^=t}}for(var D=1;D<25;D++){var Z0,t,f=B[D],P=f.high,j=f.low,R=K[D];if(R<32)Z0=P<<R|j>>>32-R,t=j<<R|P>>>32-R;else Z0=j<<R-32|P>>>64-R,t=P<<R-32|j>>>64-R;var q=L[O[D]];q.high=Z0,q.low=t}var E=L[0],N=B[0];E.high=N.high,E.low=N.low;for(var i=0;i<5;i++)for(var c=0;c<5;c++){var D=i+5*c,f=B[D],T=L[D],v=L[(i+1)%5+5*c],y=L[(i+2)%5+5*c];f.high=T.high^~v.high&y.high,f.low=T.low^~v.low&y.low}var f=B[0],p=I[h];f.high^=p.high,f.low^=p.low}},_doFinalize:function(){var M=this._data,k=M.words,B=this._nDataBytes*8,C=M.sigBytes*8,S=this.blockSize*32;k[C>>>5]|=1<<24-C%32,k[(Z.ceil((C+1)/S)*S>>>5)-1]|=128,M.sigBytes=k.length*4,this._process();var _=this._state,x=this.cfg.outputLength/8,f=x/8,h=[];for(var i=0;i<f;i++){var Z0=_[i],t=Z0.high,c=Z0.low;t=(t<<8|t>>>24)&16711935|(t<<24|t>>>8)&4278255360,c=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360,h.push(c),h.push(t)}return new J.init(h,x)},clone:function(){var M=X.clone.call(this),k=M._state=this._state.slice(0);for(var B=0;B<25;B++)k[B]=k[B].clone();return M}});Y.SHA3=X._createHelper(A),Y.HmacSHA3=X._createHmacHelper(A)}(Math),Q.SHA3})});var mS=XQ((eW,lS)=>{(function(Q,Z){if(typeof eW==="object")lS.exports=eW=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(eW,function(Q){return function(Z){var Y=Q,$=Y.lib,J=$.WordArray,X=$.Hasher,G=Y.algo,W=J.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),U=J.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),K=J.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),O=J.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),I=J.create([0,1518500249,1859775393,2400959708,2840853838]),L=J.create([1352829926,1548603684,1836072691,2053994217,0]),A=G.RIPEMD160=X.extend({_doReset:function(){this._hash=J.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(x,f){for(var h=0;h<16;h++){var i=f+h,Z0=x[i];x[i]=(Z0<<8|Z0>>>24)&16711935|(Z0<<24|Z0>>>8)&4278255360}var t=this._hash.words,c=I.words,l=L.words,V=W.words,z=U.words,H=K.words,F=O.words,D,P,j,R,q,E,N,T,v,y;E=D=t[0],N=P=t[1],T=j=t[2],v=R=t[3],y=q=t[4];var p;for(var h=0;h<80;h+=1){if(p=D+x[f+V[h]]|0,h<16)p+=M(P,j,R)+c[0];else if(h<32)p+=k(P,j,R)+c[1];else if(h<48)p+=B(P,j,R)+c[2];else if(h<64)p+=C(P,j,R)+c[3];else p+=S(P,j,R)+c[4];if(p=p|0,p=_(p,H[h]),p=p+q|0,D=q,q=R,R=_(j,10),j=P,P=p,p=E+x[f+z[h]]|0,h<16)p+=S(N,T,v)+l[0];else if(h<32)p+=C(N,T,v)+l[1];else if(h<48)p+=B(N,T,v)+l[2];else if(h<64)p+=k(N,T,v)+l[3];else p+=M(N,T,v)+l[4];p=p|0,p=_(p,F[h]),p=p+y|0,E=y,y=v,v=_(T,10),T=N,N=p}p=t[1]+j+v|0,t[1]=t[2]+R+y|0,t[2]=t[3]+q+E|0,t[3]=t[4]+D+N|0,t[4]=t[0]+P+T|0,t[0]=p},_doFinalize:function(){var x=this._data,f=x.words,h=this._nDataBytes*8,i=x.sigBytes*8;f[i>>>5]|=128<<24-i%32,f[(i+64>>>9<<4)+14]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360,x.sigBytes=(f.length+1)*4,this._process();var Z0=this._hash,t=Z0.words;for(var c=0;c<5;c++){var l=t[c];t[c]=(l<<8|l>>>24)&16711935|(l<<24|l>>>8)&4278255360}return Z0},clone:function(){var x=X.clone.call(this);return x._hash=this._hash.clone(),x}});function M(x,f,h){return x^f^h}function k(x,f,h){return x&f|~x&h}function B(x,f,h){return(x|~f)^h}function C(x,f,h){return x&h|f&~h}function S(x,f,h){return x^(f|~h)}function _(x,f){return x<<f|x>>>32-f}Y.RIPEMD160=X._createHelper(A),Y.HmacRIPEMD160=X._createHmacHelper(A)}(Math),Q.RIPEMD160})});var ZK=XQ((QK,dS)=>{(function(Q,Z){if(typeof QK==="object")dS.exports=QK=Z(sQ());else if(typeof define==="function"&&define.amd)define(["./core"],Z);else Z(Q.CryptoJS)})(QK,function(Q){(function(){var Z=Q,Y=Z.lib,$=Y.Base,J=Z.enc,X=J.Utf8,G=Z.algo,W=G.HMAC=$.extend({init:function(U,K){if(U=this._hasher=new U.init,typeof K=="string")K=X.parse(K);var O=U.blockSize,I=O*4;if(K.sigBytes>I)K=U.finalize(K);K.clamp();var L=this._oKey=K.clone(),A=this._iKey=K.clone(),M=L.words,k=A.words;for(var B=0;B<O;B++)M[B]^=1549556828,k[B]^=909522486;L.sigBytes=A.sigBytes=I,this.reset()},reset:function(){var U=this._hasher;U.reset(),U.update(this._iKey)},update:function(U){return this._hasher.update(U),this},finalize:function(U){var K=this._hasher,O=K.finalize(U);K.reset();var I=K.finalize(this._oKey.clone().concat(O));return I}})})()})});var oS=XQ((YK,nS)=>{(function(Q,Z,Y){if(typeof YK==="object")nS.exports=YK=Z(sQ(),sW(),ZK());else if(typeof define==="function"&&define.amd)define(["./core","./sha256","./hmac"],Z);else Z(Q.CryptoJS)})(YK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.Base,J=Y.WordArray,X=Z.algo,G=X.SHA256,W=X.HMAC,U=X.PBKDF2=$.extend({cfg:$.extend({keySize:4,hasher:G,iterations:250000}),init:function(K){this.cfg=this.cfg.extend(K)},compute:function(K,O){var I=this.cfg,L=W.create(I.hasher,K),A=J.create(),M=J.create([1]),k=A.words,B=M.words,C=I.keySize,S=I.iterations;while(k.length<C){var _=L.update(O).finalize(M);L.reset();var x=_.words,f=x.length,h=_;for(var i=1;i<S;i++){h=L.finalize(h),L.reset();var Z0=h.words;for(var t=0;t<f;t++)x[t]^=Z0[t]}A.concat(_),B[0]++}return A.sigBytes=C*4,A}});Z.PBKDF2=function(K,O,I){return U.create(I).compute(K,O)}}(),Q.PBKDF2})});var d1=XQ(($K,sS)=>{(function(Q,Z,Y){if(typeof $K==="object")sS.exports=$K=Z(sQ(),TD(),ZK());else if(typeof define==="function"&&define.amd)define(["./core","./sha1","./hmac"],Z);else Z(Q.CryptoJS)})($K,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.Base,J=Y.WordArray,X=Z.algo,G=X.MD5,W=X.EvpKDF=$.extend({cfg:$.extend({keySize:4,hasher:G,iterations:1}),init:function(U){this.cfg=this.cfg.extend(U)},compute:function(U,K){var O,I=this.cfg,L=I.hasher.create(),A=J.create(),M=A.words,k=I.keySize,B=I.iterations;while(M.length<k){if(O)L.update(O);O=L.update(U).finalize(K),L.reset();for(var C=1;C<B;C++)O=L.finalize(O),L.reset();A.concat(O)}return A.sigBytes=k*4,A}});Z.EvpKDF=function(U,K,O){return W.create(O).compute(U,K)}}(),Q.EvpKDF})});var EY=XQ((JK,iS)=>{(function(Q,Z,Y){if(typeof JK==="object")iS.exports=JK=Z(sQ(),d1());else if(typeof define==="function"&&define.amd)define(["./core","./evpkdf"],Z);else Z(Q.CryptoJS)})(JK,function(Q){Q.lib.Cipher||function(Z){var Y=Q,$=Y.lib,J=$.Base,X=$.WordArray,G=$.BufferedBlockAlgorithm,W=Y.enc,U=W.Utf8,K=W.Base64,O=Y.algo,I=O.EvpKDF,L=$.Cipher=G.extend({cfg:J.extend(),createEncryptor:function(l,V){return this.create(this._ENC_XFORM_MODE,l,V)},createDecryptor:function(l,V){return this.create(this._DEC_XFORM_MODE,l,V)},init:function(l,V,z){this.cfg=this.cfg.extend(z),this._xformMode=l,this._key=V,this.reset()},reset:function(){G.reset.call(this),this._doReset()},process:function(l){return this._append(l),this._process()},finalize:function(l){if(l)this._append(l);var V=this._doFinalize();return V},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function l(V){if(typeof V=="string")return c;else return i}return function(V){return{encrypt:function(z,H,F){return l(H).encrypt(V,z,H,F)},decrypt:function(z,H,F){return l(H).decrypt(V,z,H,F)}}}}()}),A=$.StreamCipher=L.extend({_doFinalize:function(){var l=this._process(!0);return l},blockSize:1}),M=Y.mode={},k=$.BlockCipherMode=J.extend({createEncryptor:function(l,V){return this.Encryptor.create(l,V)},createDecryptor:function(l,V){return this.Decryptor.create(l,V)},init:function(l,V){this._cipher=l,this._iv=V}}),B=M.CBC=function(){var l=k.extend();l.Encryptor=l.extend({processBlock:function(z,H){var F=this._cipher,D=F.blockSize;V.call(this,z,H,D),F.encryptBlock(z,H),this._prevBlock=z.slice(H,H+D)}}),l.Decryptor=l.extend({processBlock:function(z,H){var F=this._cipher,D=F.blockSize,P=z.slice(H,H+D);F.decryptBlock(z,H),V.call(this,z,H,D),this._prevBlock=P}});function V(z,H,F){var D,P=this._iv;if(P)D=P,this._iv=Z;else D=this._prevBlock;for(var j=0;j<F;j++)z[H+j]^=D[j]}return l}(),C=Y.pad={},S=C.Pkcs7={pad:function(l,V){var z=V*4,H=z-l.sigBytes%z,F=H<<24|H<<16|H<<8|H,D=[];for(var P=0;P<H;P+=4)D.push(F);var j=X.create(D,H);l.concat(j)},unpad:function(l){var V=l.words[l.sigBytes-1>>>2]&255;l.sigBytes-=V}},_=$.BlockCipher=L.extend({cfg:L.cfg.extend({mode:B,padding:S}),reset:function(){var l;L.reset.call(this);var V=this.cfg,z=V.iv,H=V.mode;if(this._xformMode==this._ENC_XFORM_MODE)l=H.createEncryptor;else l=H.createDecryptor,this._minBufferSize=1;if(this._mode&&this._mode.__creator==l)this._mode.init(this,z&&z.words);else this._mode=l.call(H,this,z&&z.words),this._mode.__creator=l},_doProcessBlock:function(l,V){this._mode.processBlock(l,V)},_doFinalize:function(){var l,V=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE)V.pad(this._data,this.blockSize),l=this._process(!0);else l=this._process(!0),V.unpad(l);return l},blockSize:4}),x=$.CipherParams=J.extend({init:function(l){this.mixIn(l)},toString:function(l){return(l||this.formatter).stringify(this)}}),f=Y.format={},h=f.OpenSSL={stringify:function(l){var V,z=l.ciphertext,H=l.salt;if(H)V=X.create([1398893684,1701076831]).concat(H).concat(z);else V=z;return V.toString(K)},parse:function(l){var V,z=K.parse(l),H=z.words;if(H[0]==1398893684&&H[1]==1701076831)V=X.create(H.slice(2,4)),H.splice(0,4),z.sigBytes-=16;return x.create({ciphertext:z,salt:V})}},i=$.SerializableCipher=J.extend({cfg:J.extend({format:h}),encrypt:function(l,V,z,H){H=this.cfg.extend(H);var F=l.createEncryptor(z,H),D=F.finalize(V),P=F.cfg;return x.create({ciphertext:D,key:z,iv:P.iv,algorithm:l,mode:P.mode,padding:P.padding,blockSize:l.blockSize,formatter:H.format})},decrypt:function(l,V,z,H){H=this.cfg.extend(H),V=this._parse(V,H.format);var F=l.createDecryptor(z,H).finalize(V.ciphertext);return F},_parse:function(l,V){if(typeof l=="string")return V.parse(l,this);else return l}}),Z0=Y.kdf={},t=Z0.OpenSSL={execute:function(l,V,z,H,F){if(!H)H=X.random(8);if(!F)var D=I.create({keySize:V+z}).compute(l,H);else var D=I.create({keySize:V+z,hasher:F}).compute(l,H);var P=X.create(D.words.slice(V),z*4);return D.sigBytes=V*4,x.create({key:D,iv:P,salt:H})}},c=$.PasswordBasedCipher=i.extend({cfg:i.cfg.extend({kdf:t}),encrypt:function(l,V,z,H){H=this.cfg.extend(H);var F=H.kdf.execute(z,l.keySize,l.ivSize,H.salt,H.hasher);H.iv=F.iv;var D=i.encrypt.call(this,l,V,F.key,H);return D.mixIn(F),D},decrypt:function(l,V,z,H){H=this.cfg.extend(H),V=this._parse(V,H.format);var F=H.kdf.execute(z,l.keySize,l.ivSize,V.salt,H.hasher);H.iv=F.iv;var D=i.decrypt.call(this,l,V,F.key,H);return D}})}()})});var rS=XQ((GK,aS)=>{(function(Q,Z,Y){if(typeof GK==="object")aS.exports=GK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(GK,function(Q){return Q.mode.CFB=function(){var Z=Q.lib.BlockCipherMode.extend();Z.Encryptor=Z.extend({processBlock:function($,J){var X=this._cipher,G=X.blockSize;Y.call(this,$,J,G,X),this._prevBlock=$.slice(J,J+G)}}),Z.Decryptor=Z.extend({processBlock:function($,J){var X=this._cipher,G=X.blockSize,W=$.slice(J,J+G);Y.call(this,$,J,G,X),this._prevBlock=W}});function Y($,J,X,G){var W,U=this._iv;if(U)W=U.slice(0),this._iv=void 0;else W=this._prevBlock;G.encryptBlock(W,0);for(var K=0;K<X;K++)$[J+K]^=W[K]}return Z}(),Q.mode.CFB})});var eS=XQ((XK,tS)=>{(function(Q,Z,Y){if(typeof XK==="object")tS.exports=XK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(XK,function(Q){return Q.mode.CTR=function(){var Z=Q.lib.BlockCipherMode.extend(),Y=Z.Encryptor=Z.extend({processBlock:function($,J){var X=this._cipher,G=X.blockSize,W=this._iv,U=this._counter;if(W)U=this._counter=W.slice(0),this._iv=void 0;var K=U.slice(0);X.encryptBlock(K,0),U[G-1]=U[G-1]+1|0;for(var O=0;O<G;O++)$[J+O]^=K[O]}});return Z.Decryptor=Y,Z}(),Q.mode.CTR})});var Zw=XQ((VK,Qw)=>{(function(Q,Z,Y){if(typeof VK==="object")Qw.exports=VK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(VK,function(Q){return Q.mode.CTRGladman=function(){var Z=Q.lib.BlockCipherMode.extend();function Y(X){if((X>>24&255)===255){var G=X>>16&255,W=X>>8&255,U=X&255;if(G===255)if(G=0,W===255)if(W=0,U===255)U=0;else++U;else++W;else++G;X=0,X+=G<<16,X+=W<<8,X+=U}else X+=16777216;return X}function $(X){if((X[0]=Y(X[0]))===0)X[1]=Y(X[1]);return X}var J=Z.Encryptor=Z.extend({processBlock:function(X,G){var W=this._cipher,U=W.blockSize,K=this._iv,O=this._counter;if(K)O=this._counter=K.slice(0),this._iv=void 0;$(O);var I=O.slice(0);W.encryptBlock(I,0);for(var L=0;L<U;L++)X[G+L]^=I[L]}});return Z.Decryptor=J,Z}(),Q.mode.CTRGladman})});var $w=XQ((qK,Yw)=>{(function(Q,Z,Y){if(typeof qK==="object")Yw.exports=qK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(qK,function(Q){return Q.mode.OFB=function(){var Z=Q.lib.BlockCipherMode.extend(),Y=Z.Encryptor=Z.extend({processBlock:function($,J){var X=this._cipher,G=X.blockSize,W=this._iv,U=this._keystream;if(W)U=this._keystream=W.slice(0),this._iv=void 0;X.encryptBlock(U,0);for(var K=0;K<G;K++)$[J+K]^=U[K]}});return Z.Decryptor=Y,Z}(),Q.mode.OFB})});var Gw=XQ((FK,Jw)=>{(function(Q,Z,Y){if(typeof FK==="object")Jw.exports=FK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(FK,function(Q){return Q.mode.ECB=function(){var Z=Q.lib.BlockCipherMode.extend();return Z.Encryptor=Z.extend({processBlock:function(Y,$){this._cipher.encryptBlock(Y,$)}}),Z.Decryptor=Z.extend({processBlock:function(Y,$){this._cipher.decryptBlock(Y,$)}}),Z}(),Q.mode.ECB})});var Vw=XQ((zK,Xw)=>{(function(Q,Z,Y){if(typeof zK==="object")Xw.exports=zK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(zK,function(Q){return Q.pad.AnsiX923={pad:function(Z,Y){var $=Z.sigBytes,J=Y*4,X=J-$%J,G=$+X-1;Z.clamp(),Z.words[G>>>2]|=X<<24-G%4*8,Z.sigBytes+=X},unpad:function(Z){var Y=Z.words[Z.sigBytes-1>>>2]&255;Z.sigBytes-=Y}},Q.pad.Ansix923})});var Fw=XQ((WK,qw)=>{(function(Q,Z,Y){if(typeof WK==="object")qw.exports=WK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(WK,function(Q){return Q.pad.Iso10126={pad:function(Z,Y){var $=Y*4,J=$-Z.sigBytes%$;Z.concat(Q.lib.WordArray.random(J-1)).concat(Q.lib.WordArray.create([J<<24],1))},unpad:function(Z){var Y=Z.words[Z.sigBytes-1>>>2]&255;Z.sigBytes-=Y}},Q.pad.Iso10126})});var Ww=XQ((KK,zw)=>{(function(Q,Z,Y){if(typeof KK==="object")zw.exports=KK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(KK,function(Q){return Q.pad.Iso97971={pad:function(Z,Y){Z.concat(Q.lib.WordArray.create([2147483648],1)),Q.pad.ZeroPadding.pad(Z,Y)},unpad:function(Z){Q.pad.ZeroPadding.unpad(Z),Z.sigBytes--}},Q.pad.Iso97971})});var Uw=XQ((UK,Kw)=>{(function(Q,Z,Y){if(typeof UK==="object")Kw.exports=UK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(UK,function(Q){return Q.pad.ZeroPadding={pad:function(Z,Y){var $=Y*4;Z.clamp(),Z.sigBytes+=$-(Z.sigBytes%$||$)},unpad:function(Z){var Y=Z.words,$=Z.sigBytes-1;for(var $=Z.sigBytes-1;$>=0;$--)if(Y[$>>>2]>>>24-$%4*8&255){Z.sigBytes=$+1;break}}},Q.pad.ZeroPadding})});var Hw=XQ((OK,Ow)=>{(function(Q,Z,Y){if(typeof OK==="object")Ow.exports=OK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(OK,function(Q){return Q.pad.NoPadding={pad:function(){},unpad:function(){}},Q.pad.NoPadding})});var Iw=XQ((HK,Dw)=>{(function(Q,Z,Y){if(typeof HK==="object")Dw.exports=HK=Z(sQ(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./cipher-core"],Z);else Z(Q.CryptoJS)})(HK,function(Q){return function(Z){var Y=Q,$=Y.lib,J=$.CipherParams,X=Y.enc,G=X.Hex,W=Y.format,U=W.Hex={stringify:function(K){return K.ciphertext.toString(G)},parse:function(K){var O=G.parse(K);return J.create({ciphertext:O})}}}(),Q.format.Hex})});var Lw=XQ((DK,Rw)=>{(function(Q,Z,Y){if(typeof DK==="object")Rw.exports=DK=Z(sQ(),u8(),p8(),d1(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],Z);else Z(Q.CryptoJS)})(DK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.BlockCipher,J=Z.algo,X=[],G=[],W=[],U=[],K=[],O=[],I=[],L=[],A=[],M=[];(function(){var C=[];for(var S=0;S<256;S++)if(S<128)C[S]=S<<1;else C[S]=S<<1^283;var _=0,x=0;for(var S=0;S<256;S++){var f=x^x<<1^x<<2^x<<3^x<<4;f=f>>>8^f&255^99,X[_]=f,G[f]=_;var h=C[_],i=C[h],Z0=C[i],t=C[f]*257^f*16843008;W[_]=t<<24|t>>>8,U[_]=t<<16|t>>>16,K[_]=t<<8|t>>>24,O[_]=t;var t=Z0*16843009^i*65537^h*257^_*16843008;if(I[f]=t<<24|t>>>8,L[f]=t<<16|t>>>16,A[f]=t<<8|t>>>24,M[f]=t,!_)_=x=1;else _=h^C[C[C[Z0^h]]],x^=C[C[x]]}})();var k=[0,1,2,4,8,16,32,64,128,27,54],B=J.AES=$.extend({_doReset:function(){var C;if(this._nRounds&&this._keyPriorReset===this._key)return;var S=this._keyPriorReset=this._key,_=S.words,x=S.sigBytes/4,f=this._nRounds=x+6,h=(f+1)*4,i=this._keySchedule=[];for(var Z0=0;Z0<h;Z0++)if(Z0<x)i[Z0]=_[Z0];else{if(C=i[Z0-1],!(Z0%x))C=C<<8|C>>>24,C=X[C>>>24]<<24|X[C>>>16&255]<<16|X[C>>>8&255]<<8|X[C&255],C^=k[Z0/x|0]<<24;else if(x>6&&Z0%x==4)C=X[C>>>24]<<24|X[C>>>16&255]<<16|X[C>>>8&255]<<8|X[C&255];i[Z0]=i[Z0-x]^C}var t=this._invKeySchedule=[];for(var c=0;c<h;c++){var Z0=h-c;if(c%4)var C=i[Z0];else var C=i[Z0-4];if(c<4||Z0<=4)t[c]=C;else t[c]=I[X[C>>>24]]^L[X[C>>>16&255]]^A[X[C>>>8&255]]^M[X[C&255]]}},encryptBlock:function(C,S){this._doCryptBlock(C,S,this._keySchedule,W,U,K,O,X)},decryptBlock:function(C,S){var _=C[S+1];C[S+1]=C[S+3],C[S+3]=_,this._doCryptBlock(C,S,this._invKeySchedule,I,L,A,M,G);var _=C[S+1];C[S+1]=C[S+3],C[S+3]=_},_doCryptBlock:function(C,S,_,x,f,h,i,Z0){var t=this._nRounds,c=C[S]^_[0],l=C[S+1]^_[1],V=C[S+2]^_[2],z=C[S+3]^_[3],H=4;for(var F=1;F<t;F++){var D=x[c>>>24]^f[l>>>16&255]^h[V>>>8&255]^i[z&255]^_[H++],P=x[l>>>24]^f[V>>>16&255]^h[z>>>8&255]^i[c&255]^_[H++],j=x[V>>>24]^f[z>>>16&255]^h[c>>>8&255]^i[l&255]^_[H++],R=x[z>>>24]^f[c>>>16&255]^h[l>>>8&255]^i[V&255]^_[H++];c=D,l=P,V=j,z=R}var D=(Z0[c>>>24]<<24|Z0[l>>>16&255]<<16|Z0[V>>>8&255]<<8|Z0[z&255])^_[H++],P=(Z0[l>>>24]<<24|Z0[V>>>16&255]<<16|Z0[z>>>8&255]<<8|Z0[c&255])^_[H++],j=(Z0[V>>>24]<<24|Z0[z>>>16&255]<<16|Z0[c>>>8&255]<<8|Z0[l&255])^_[H++],R=(Z0[z>>>24]<<24|Z0[c>>>16&255]<<16|Z0[l>>>8&255]<<8|Z0[V&255])^_[H++];C[S]=D,C[S+1]=P,C[S+2]=j,C[S+3]=R},keySize:8});Z.AES=$._createHelper(B)}(),Q.AES})});var Pw=XQ((IK,Ew)=>{(function(Q,Z,Y){if(typeof IK==="object")Ew.exports=IK=Z(sQ(),u8(),p8(),d1(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],Z);else Z(Q.CryptoJS)})(IK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.WordArray,J=Y.BlockCipher,X=Z.algo,G=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],W=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],U=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],K=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],O=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],I=X.DES=J.extend({_doReset:function(){var k=this._key,B=k.words,C=[];for(var S=0;S<56;S++){var _=G[S]-1;C[S]=B[_>>>5]>>>31-_%32&1}var x=this._subKeys=[];for(var f=0;f<16;f++){var h=x[f]=[],i=U[f];for(var S=0;S<24;S++)h[S/6|0]|=C[(W[S]-1+i)%28]<<31-S%6,h[4+(S/6|0)]|=C[28+(W[S+24]-1+i)%28]<<31-S%6;h[0]=h[0]<<1|h[0]>>>31;for(var S=1;S<7;S++)h[S]=h[S]>>>(S-1)*4+3;h[7]=h[7]<<5|h[7]>>>27}var Z0=this._invSubKeys=[];for(var S=0;S<16;S++)Z0[S]=x[15-S]},encryptBlock:function(k,B){this._doCryptBlock(k,B,this._subKeys)},decryptBlock:function(k,B){this._doCryptBlock(k,B,this._invSubKeys)},_doCryptBlock:function(k,B,C){this._lBlock=k[B],this._rBlock=k[B+1],L.call(this,4,252645135),L.call(this,16,65535),A.call(this,2,858993459),A.call(this,8,16711935),L.call(this,1,1431655765);for(var S=0;S<16;S++){var _=C[S],x=this._lBlock,f=this._rBlock,h=0;for(var i=0;i<8;i++)h|=K[i][((f^_[i])&O[i])>>>0];this._lBlock=f,this._rBlock=x^h}var Z0=this._lBlock;this._lBlock=this._rBlock,this._rBlock=Z0,L.call(this,1,1431655765),A.call(this,8,16711935),A.call(this,2,858993459),L.call(this,16,65535),L.call(this,4,252645135),k[B]=this._lBlock,k[B+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function L(k,B){var C=(this._lBlock>>>k^this._rBlock)&B;this._rBlock^=C,this._lBlock^=C<<k}function A(k,B){var C=(this._rBlock>>>k^this._lBlock)&B;this._lBlock^=C,this._rBlock^=C<<k}Z.DES=J._createHelper(I);var M=X.TripleDES=J.extend({_doReset:function(){var k=this._key,B=k.words;if(B.length!==2&&B.length!==4&&B.length<6)throw Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var C=B.slice(0,2),S=B.length<4?B.slice(0,2):B.slice(2,4),_=B.length<6?B.slice(0,2):B.slice(4,6);this._des1=I.createEncryptor($.create(C)),this._des2=I.createEncryptor($.create(S)),this._des3=I.createEncryptor($.create(_))},encryptBlock:function(k,B){this._des1.encryptBlock(k,B),this._des2.decryptBlock(k,B),this._des3.encryptBlock(k,B)},decryptBlock:function(k,B){this._des3.decryptBlock(k,B),this._des2.encryptBlock(k,B),this._des1.decryptBlock(k,B)},keySize:6,ivSize:2,blockSize:2});Z.TripleDES=J._createHelper(M)}(),Q.TripleDES})});var Aw=XQ((RK,jw)=>{(function(Q,Z,Y){if(typeof RK==="object")jw.exports=RK=Z(sQ(),u8(),p8(),d1(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],Z);else Z(Q.CryptoJS)})(RK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.StreamCipher,J=Z.algo,X=J.RC4=$.extend({_doReset:function(){var U=this._key,K=U.words,O=U.sigBytes,I=this._S=[];for(var L=0;L<256;L++)I[L]=L;for(var L=0,A=0;L<256;L++){var M=L%O,k=K[M>>>2]>>>24-M%4*8&255;A=(A+I[L]+k)%256;var B=I[L];I[L]=I[A],I[A]=B}this._i=this._j=0},_doProcessBlock:function(U,K){U[K]^=G.call(this)},keySize:8,ivSize:0});function G(){var U=this._S,K=this._i,O=this._j,I=0;for(var L=0;L<4;L++){K=(K+1)%256,O=(O+U[K])%256;var A=U[K];U[K]=U[O],U[O]=A,I|=U[(U[K]+U[O])%256]<<24-L*8}return this._i=K,this._j=O,I}Z.RC4=$._createHelper(X);var W=J.RC4Drop=X.extend({cfg:X.cfg.extend({drop:192}),_doReset:function(){X._doReset.call(this);for(var U=this.cfg.drop;U>0;U--)G.call(this)}});Z.RC4Drop=$._createHelper(W)}(),Q.RC4})});var Tw=XQ((LK,Mw)=>{(function(Q,Z,Y){if(typeof LK==="object")Mw.exports=LK=Z(sQ(),u8(),p8(),d1(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],Z);else Z(Q.CryptoJS)})(LK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.StreamCipher,J=Z.algo,X=[],G=[],W=[],U=J.Rabbit=$.extend({_doReset:function(){var O=this._key.words,I=this.cfg.iv;for(var L=0;L<4;L++)O[L]=(O[L]<<8|O[L]>>>24)&16711935|(O[L]<<24|O[L]>>>8)&4278255360;var A=this._X=[O[0],O[3]<<16|O[2]>>>16,O[1],O[0]<<16|O[3]>>>16,O[2],O[1]<<16|O[0]>>>16,O[3],O[2]<<16|O[1]>>>16],M=this._C=[O[2]<<16|O[2]>>>16,O[0]&4294901760|O[1]&65535,O[3]<<16|O[3]>>>16,O[1]&4294901760|O[2]&65535,O[0]<<16|O[0]>>>16,O[2]&4294901760|O[3]&65535,O[1]<<16|O[1]>>>16,O[3]&4294901760|O[0]&65535];this._b=0;for(var L=0;L<4;L++)K.call(this);for(var L=0;L<8;L++)M[L]^=A[L+4&7];if(I){var k=I.words,B=k[0],C=k[1],S=(B<<8|B>>>24)&16711935|(B<<24|B>>>8)&4278255360,_=(C<<8|C>>>24)&16711935|(C<<24|C>>>8)&4278255360,x=S>>>16|_&4294901760,f=_<<16|S&65535;M[0]^=S,M[1]^=x,M[2]^=_,M[3]^=f,M[4]^=S,M[5]^=x,M[6]^=_,M[7]^=f;for(var L=0;L<4;L++)K.call(this)}},_doProcessBlock:function(O,I){var L=this._X;K.call(this),X[0]=L[0]^L[5]>>>16^L[3]<<16,X[1]=L[2]^L[7]>>>16^L[5]<<16,X[2]=L[4]^L[1]>>>16^L[7]<<16,X[3]=L[6]^L[3]>>>16^L[1]<<16;for(var A=0;A<4;A++)X[A]=(X[A]<<8|X[A]>>>24)&16711935|(X[A]<<24|X[A]>>>8)&4278255360,O[I+A]^=X[A]},blockSize:4,ivSize:2});function K(){var O=this._X,I=this._C;for(var L=0;L<8;L++)G[L]=I[L];I[0]=I[0]+1295307597+this._b|0,I[1]=I[1]+3545052371+(I[0]>>>0<G[0]>>>0?1:0)|0,I[2]=I[2]+886263092+(I[1]>>>0<G[1]>>>0?1:0)|0,I[3]=I[3]+1295307597+(I[2]>>>0<G[2]>>>0?1:0)|0,I[4]=I[4]+3545052371+(I[3]>>>0<G[3]>>>0?1:0)|0,I[5]=I[5]+886263092+(I[4]>>>0<G[4]>>>0?1:0)|0,I[6]=I[6]+1295307597+(I[5]>>>0<G[5]>>>0?1:0)|0,I[7]=I[7]+3545052371+(I[6]>>>0<G[6]>>>0?1:0)|0,this._b=I[7]>>>0<G[7]>>>0?1:0;for(var L=0;L<8;L++){var A=O[L]+I[L],M=A&65535,k=A>>>16,B=((M*M>>>17)+M*k>>>15)+k*k,C=((A&4294901760)*A|0)+((A&65535)*A|0);W[L]=B^C}O[0]=W[0]+(W[7]<<16|W[7]>>>16)+(W[6]<<16|W[6]>>>16)|0,O[1]=W[1]+(W[0]<<8|W[0]>>>24)+W[7]|0,O[2]=W[2]+(W[1]<<16|W[1]>>>16)+(W[0]<<16|W[0]>>>16)|0,O[3]=W[3]+(W[2]<<8|W[2]>>>24)+W[1]|0,O[4]=W[4]+(W[3]<<16|W[3]>>>16)+(W[2]<<16|W[2]>>>16)|0,O[5]=W[5]+(W[4]<<8|W[4]>>>24)+W[3]|0,O[6]=W[6]+(W[5]<<16|W[5]>>>16)+(W[4]<<16|W[4]>>>16)|0,O[7]=W[7]+(W[6]<<8|W[6]>>>24)+W[5]|0}Z.Rabbit=$._createHelper(U)}(),Q.Rabbit})});var Bw=XQ((EK,Nw)=>{(function(Q,Z,Y){if(typeof EK==="object")Nw.exports=EK=Z(sQ(),u8(),p8(),d1(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],Z);else Z(Q.CryptoJS)})(EK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.StreamCipher,J=Z.algo,X=[],G=[],W=[],U=J.RabbitLegacy=$.extend({_doReset:function(){var O=this._key.words,I=this.cfg.iv,L=this._X=[O[0],O[3]<<16|O[2]>>>16,O[1],O[0]<<16|O[3]>>>16,O[2],O[1]<<16|O[0]>>>16,O[3],O[2]<<16|O[1]>>>16],A=this._C=[O[2]<<16|O[2]>>>16,O[0]&4294901760|O[1]&65535,O[3]<<16|O[3]>>>16,O[1]&4294901760|O[2]&65535,O[0]<<16|O[0]>>>16,O[2]&4294901760|O[3]&65535,O[1]<<16|O[1]>>>16,O[3]&4294901760|O[0]&65535];this._b=0;for(var M=0;M<4;M++)K.call(this);for(var M=0;M<8;M++)A[M]^=L[M+4&7];if(I){var k=I.words,B=k[0],C=k[1],S=(B<<8|B>>>24)&16711935|(B<<24|B>>>8)&4278255360,_=(C<<8|C>>>24)&16711935|(C<<24|C>>>8)&4278255360,x=S>>>16|_&4294901760,f=_<<16|S&65535;A[0]^=S,A[1]^=x,A[2]^=_,A[3]^=f,A[4]^=S,A[5]^=x,A[6]^=_,A[7]^=f;for(var M=0;M<4;M++)K.call(this)}},_doProcessBlock:function(O,I){var L=this._X;K.call(this),X[0]=L[0]^L[5]>>>16^L[3]<<16,X[1]=L[2]^L[7]>>>16^L[5]<<16,X[2]=L[4]^L[1]>>>16^L[7]<<16,X[3]=L[6]^L[3]>>>16^L[1]<<16;for(var A=0;A<4;A++)X[A]=(X[A]<<8|X[A]>>>24)&16711935|(X[A]<<24|X[A]>>>8)&4278255360,O[I+A]^=X[A]},blockSize:4,ivSize:2});function K(){var O=this._X,I=this._C;for(var L=0;L<8;L++)G[L]=I[L];I[0]=I[0]+1295307597+this._b|0,I[1]=I[1]+3545052371+(I[0]>>>0<G[0]>>>0?1:0)|0,I[2]=I[2]+886263092+(I[1]>>>0<G[1]>>>0?1:0)|0,I[3]=I[3]+1295307597+(I[2]>>>0<G[2]>>>0?1:0)|0,I[4]=I[4]+3545052371+(I[3]>>>0<G[3]>>>0?1:0)|0,I[5]=I[5]+886263092+(I[4]>>>0<G[4]>>>0?1:0)|0,I[6]=I[6]+1295307597+(I[5]>>>0<G[5]>>>0?1:0)|0,I[7]=I[7]+3545052371+(I[6]>>>0<G[6]>>>0?1:0)|0,this._b=I[7]>>>0<G[7]>>>0?1:0;for(var L=0;L<8;L++){var A=O[L]+I[L],M=A&65535,k=A>>>16,B=((M*M>>>17)+M*k>>>15)+k*k,C=((A&4294901760)*A|0)+((A&65535)*A|0);W[L]=B^C}O[0]=W[0]+(W[7]<<16|W[7]>>>16)+(W[6]<<16|W[6]>>>16)|0,O[1]=W[1]+(W[0]<<8|W[0]>>>24)+W[7]|0,O[2]=W[2]+(W[1]<<16|W[1]>>>16)+(W[0]<<16|W[0]>>>16)|0,O[3]=W[3]+(W[2]<<8|W[2]>>>24)+W[1]|0,O[4]=W[4]+(W[3]<<16|W[3]>>>16)+(W[2]<<16|W[2]>>>16)|0,O[5]=W[5]+(W[4]<<8|W[4]>>>24)+W[3]|0,O[6]=W[6]+(W[5]<<16|W[5]>>>16)+(W[4]<<16|W[4]>>>16)|0,O[7]=W[7]+(W[6]<<8|W[6]>>>24)+W[5]|0}Z.RabbitLegacy=$._createHelper(U)}(),Q.RabbitLegacy})});var Cw=XQ((PK,kw)=>{(function(Q,Z,Y){if(typeof PK==="object")kw.exports=PK=Z(sQ(),u8(),p8(),d1(),EY());else if(typeof define==="function"&&define.amd)define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],Z);else Z(Q.CryptoJS)})(PK,function(Q){return function(){var Z=Q,Y=Z.lib,$=Y.BlockCipher,J=Z.algo;let X=16,G=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],W=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,2909710000,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409000,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var U={pbox:[],sbox:[]};function K(M,k){let B=k>>24&255,C=k>>16&255,S=k>>8&255,_=k&255,x=M.sbox[0][B]+M.sbox[1][C];return x=x^M.sbox[2][S],x=x+M.sbox[3][_],x}function O(M,k,B){let C=k,S=B,_;for(let x=0;x<X;++x)C=C^M.pbox[x],S=K(M,C)^S,_=C,C=S,S=_;return _=C,C=S,S=_,S=S^M.pbox[X],C=C^M.pbox[X+1],{left:C,right:S}}function I(M,k,B){let C=k,S=B,_;for(let x=X+1;x>1;--x)C=C^M.pbox[x],S=K(M,C)^S,_=C,C=S,S=_;return _=C,C=S,S=_,S=S^M.pbox[1],C=C^M.pbox[0],{left:C,right:S}}function L(M,k,B){for(let f=0;f<4;f++){M.sbox[f]=[];for(let h=0;h<256;h++)M.sbox[f][h]=W[f][h]}let C=0;for(let f=0;f<X+2;f++)if(M.pbox[f]=G[f]^k[C],C++,C>=B)C=0;let S=0,_=0,x=0;for(let f=0;f<X+2;f+=2)x=O(M,S,_),S=x.left,_=x.right,M.pbox[f]=S,M.pbox[f+1]=_;for(let f=0;f<4;f++)for(let h=0;h<256;h+=2)x=O(M,S,_),S=x.left,_=x.right,M.sbox[f][h]=S,M.sbox[f][h+1]=_;return!0}var A=J.Blowfish=$.extend({_doReset:function(){if(this._keyPriorReset===this._key)return;var M=this._keyPriorReset=this._key,k=M.words,B=M.sigBytes/4;L(U,k,B)},encryptBlock:function(M,k){var B=O(U,M[k],M[k+1]);M[k]=B.left,M[k+1]=B.right},decryptBlock:function(M,k){var B=I(U,M[k],M[k+1]);M[k]=B.left,M[k+1]=B.right},blockSize:2,keySize:4,ivSize:2});Z.Blowfish=$._createHelper(A)}(),Q.Blowfish})});var ww=XQ((jK,Sw)=>{(function(Q,Z,Y){if(typeof jK==="object")Sw.exports=jK=Z(sQ(),a6(),kS(),SS(),u8(),vS(),p8(),TD(),sW(),ND(),BD(),cS(),pS(),mS(),ZK(),oS(),d1(),EY(),rS(),eS(),Zw(),$w(),Gw(),Vw(),Fw(),Ww(),Uw(),Hw(),Iw(),Lw(),Pw(),Aw(),Tw(),Bw(),Cw());else if(typeof define==="function"&&define.amd)define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./enc-base64url","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy","./blowfish"],Z);else Q.CryptoJS=Z(Q.CryptoJS)})(jK,function(Q){return Q})});class kD{hash(Q){let Z=AK.SHA256(AK.lib.WordArray.create(Q));return mQ(Z.toString())}}var AK;var _w=w(()=>{I0();AK=JZ(ww(),1)});var vw=()=>new b0(({bind:Q})=>{Q(Y$.HasherService).to(kD),Q(Y$.MerkleTreeBuilder).to(jW),Q(Y$.MerkleMapBuilder).to(EW)});var xw=w(()=>{W0();tG();mk();sk();_w()});var sZ;var GX=w(()=>{sZ={KeySerializer:Symbol.for("KeySerializer"),KeyPairSerializer:Symbol.for("KeyPairSerializer"),PsbtMapper:Symbol.for("PsbtMapper"),PsbtV2Normalizer:Symbol.for("PsbtV2Normalizer"),PsbtSerializer:Symbol.for("PsbtSerializer"),ValueFactory:Symbol.for("ValueFactory"),ValueParser:Symbol.for("ValueParser")}});class PY{constructor(Q,Z=new Uint8Array){this.keyType=Q,this.keyData=Z}toHexaString(){let Q=new WQ().addBufferToData(UZ(this.keyType).unsafeCoerce()).addBufferToData(this.keyData).build();return DQ(Q,!1)}}var gV=w(()=>{I0();H$()});class CD{deserialize(Q){return C$(Q).filter((Z)=>Z.value>0).chain((Z)=>C$(Q).chain((Y)=>q0.fromNullable(Q.extractFieldByLength(Z.value-Y.sizeInBytes)).map(($)=>new PY(Y.value,$))))}serialize(Q,Z){UZ(Z.keyType).ifJust((Y)=>UZ(Y.length+Z.keyData.length).ifJust(($)=>{Q.addBufferToData($),Q.addBufferToData(Y),Q.addBufferToData(Z.keyData)}))}}var fw=w(()=>{R0();gV();H$()});class MK{constructor(Q,Z){this.key=Q,this.value=Z}}var yw=()=>{};class xY{constructor(Q){this.data=Q}}var r6=()=>{};var A00,M00,T00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?M00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&A00(Z,Y,J),J},N00=(Q,Z)=>(Y,$)=>Z(Y,$,Q),TK=class{constructor(Q){this.keySerializer=Q}deserialize(Q){return this.keySerializer.deserialize(Q).chain((Z)=>C$(Q).chain((Y)=>q0.fromNullable(Q.extractFieldByLength(Y.value)).map(($)=>new MK(Z,new xY($)))))}serialize(Q,Z){UZ(Z.value.data.length).ifJust((Y)=>{this.keySerializer.serialize(Q,Z.key),Q.addBufferToData(Y),Q.addBufferToData(Z.value.data)})}deserializeMap(Q){let Z=new Map;for(;this.deserialize(Q).ifJust((Y)=>Z.set(Y.key.toHexaString(),Y.value)).isJust(););return Z}serializeMap(Q,Z){for(let[Y,$]of[...Z]){let J=mQ(Y),X=new PY(J[0],J.slice(1)),G=new MK(X,$);this.serialize(Q,G)}Q.add8BitUIntToData(0)}};var gw=w(()=>{I0();W0();R0();GX();gV();yw();r6();H$();A00=Object.defineProperty,M00=Object.getOwnPropertyDescriptor;TK=T00([N00(0,g(sZ.KeySerializer))],TK)});var bw,B00,k00,C00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?k00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&B00(Z,Y,J),J},hw=(Q,Z)=>(Y,$)=>Z(Y,$,Q),NK=class{constructor(Q,Z){this.psbtSerializer=Q,this.psbtV2Normalizer=Z}map(Q){if(Q instanceof bw.Psbt&&(Q=Q.toHex()),typeof Q=="string"){let Z=mQ(Q);if(Z!==null)Q=Z;else if(Z=tz(Q),Z!==null)Q=Z;else return a(Error("PSBT mapper: format not supported"))}return this.psbtSerializer.deserialize(Q).chain((Z)=>this.psbtV2Normalizer.normalize(Z))}};var cw=w(()=>{I0();W0();R0();GX();bw=require("bitcoinjs-lib"),B00=Object.defineProperty,k00=Object.getOwnPropertyDescriptor;NK=C00([e(),hw(0,g(sZ.PsbtSerializer)),hw(1,g(sZ.PsbtV2Normalizer))],NK)});class SD{constructor(Q=new Map,Z=[],Y=[]){this.globalMap=Q,this.inputMaps=Z,this.outputMaps=Y}getGlobalValue(Q){return q0.fromNullable(this.globalMap.get(new PY(Q).toHexaString()))}getInputValue(Q,Z){return q0.fromNullable(this.inputMaps[Q]).chain((Y)=>q0.fromNullable(Y.get(new PY(Z).toHexaString())))}getInputKeyDatas(Q,Z){let Y=new PY(Z).toHexaString();return q0.fromNullable(this.inputMaps[Q]).map(($)=>Array.from($.keys()).filter((J)=>J.startsWith(Y)).map((J)=>J.slice(2)))}getOutputValue(Q,Z){return q0.fromNullable(this.outputMaps[Q]).chain((Y)=>q0.fromNullable(Y.get(new PY(Z).toHexaString())))}setGlobalValue(Q,Z){this.globalMap.set(new PY(Q).toHexaString(),Z)}setInputValue(Q,Z,Y,$){this.inputMaps[Q]?.set(new PY(Z,$).toHexaString(),Y)}getKeyDataInputValue(Q,Z,Y){return q0.fromNullable(this.inputMaps[Q]).chain(($)=>q0.fromNullable($.get(new PY(Z,Y).toHexaString())))}setOutputValue(Q,Z,Y){this.outputMaps[Q]?.set(new PY(Z).toHexaString(),Y)}deleteInputEntries(Q,Z){q0.fromNullable(this.inputMaps[Q]).map((Y)=>{Z.forEach(($)=>{let J=new PY($);Y.forEach((X,G,W)=>{G.startsWith(J.toHexaString())&&W.delete(G)})})})}}var yZ,eQ,XX;var VX=w(()=>{R0();gV();yZ=((Q)=>(Q[Q.UNSIGNED_TX=0]="UNSIGNED_TX",Q[Q.XPUB=1]="XPUB",Q[Q.TX_VERSION=2]="TX_VERSION",Q[Q.FALLBACK_LOCKTIME=3]="FALLBACK_LOCKTIME",Q[Q.INPUT_COUNT=4]="INPUT_COUNT",Q[Q.OUTPUT_COUNT=5]="OUTPUT_COUNT",Q[Q.TX_MODIFIABLE=6]="TX_MODIFIABLE",Q[Q.VERSION=251]="VERSION",Q))(yZ||{}),eQ=((Q)=>(Q[Q.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",Q[Q.WITNESS_UTXO=1]="WITNESS_UTXO",Q[Q.PARTIAL_SIG=2]="PARTIAL_SIG",Q[Q.SIGHASH_TYPE=3]="SIGHASH_TYPE",Q[Q.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",Q[Q.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",Q[Q.BIP32_DERIVATION=6]="BIP32_DERIVATION",Q[Q.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",Q[Q.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",Q[Q.POR_COMMITMENT=9]="POR_COMMITMENT",Q[Q.RIPEMD160=10]="RIPEMD160",Q[Q.SHA256=11]="SHA256",Q[Q.HASH160=12]="HASH160",Q[Q.HASH256=13]="HASH256",Q[Q.PREVIOUS_TXID=14]="PREVIOUS_TXID",Q[Q.OUTPUT_INDEX=15]="OUTPUT_INDEX",Q[Q.SEQUENCE=16]="SEQUENCE",Q[Q.REQUIRED_TIME_LOCKTIME=17]="REQUIRED_TIME_LOCKTIME",Q[Q.REQUIRED_HEIGHT_LOCKTIME=18]="REQUIRED_HEIGHT_LOCKTIME",Q[Q.TAP_KEY_SIG=19]="TAP_KEY_SIG",Q[Q.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",Q[Q.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",Q[Q.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",Q[Q.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",Q[Q.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT",Q[Q.MUSIG2_PARTICIPANT_PUBKEYS=26]="MUSIG2_PARTICIPANT_PUBKEYS",Q[Q.MUSIG2_PUB_NONCE=27]="MUSIG2_PUB_NONCE",Q[Q.MUSIG2_PARTIAL_SIG=28]="MUSIG2_PARTIAL_SIG",Q))(eQ||{}),XX=((Q)=>(Q[Q.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",Q[Q.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",Q[Q.BIP_32_DERIVATION=2]="BIP_32_DERIVATION",Q[Q.AMOUNT=3]="AMOUNT",Q[Q.SCRIPT=4]="SCRIPT",Q[Q.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",Q[Q.TAP_TREE=6]="TAP_TREE",Q[Q.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION",Q[Q.MUSIG2_PARTICIPANT_PUBKEYS=8]="MUSIG2_PARTICIPANT_PUBKEYS",Q[Q.DNSSEC_PROOF=53]="DNSSEC_PROOF",Q))(XX||{})});var lw,S00,w00,_00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?w00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&S00(Z,Y,J),J},uw=(Q,Z)=>(Y,$)=>Z(Y,$,Q),pw,BK=class{constructor(Q,Z){this.valueParser=Q,this.keyPairSerializer=Z}getValue(Q,Z){return q0.fromNullable(Q.get(new PY(Z).toHexaString()))}sortMap(Q){return new Map(Array.from(Q.entries()).sort((Z,Y)=>Z[0].localeCompare(Y[0])))}deserialize(Q){let Z=new BY(Q);for(let W of pw)if(Z.extract8BitUInt()!==W)return a(Error("PSBT deserializer: Invalid magic bytes"));let Y=[];for(;Z.getUnparsedRemainingLength();)Y.push(this.keyPairSerializer.deserializeMap(Z));if(Y.length===0)return a(Error("PSBT deserializer: No map found"));let $=Y[0],J=this.getValue($,yZ.UNSIGNED_TX).chain((W)=>GZ.encase(()=>lw.Transaction.fromHex(DQ(W.data,!1))).toMaybe()),X=this.getValue($,yZ.INPUT_COUNT).chain((W)=>this.valueParser.getVarint(W.data)).alt(J.map((W)=>W.ins.length)),G=this.getValue($,yZ.OUTPUT_COUNT).chain((W)=>this.valueParser.getVarint(W.data)).alt(J.map((W)=>W.outs.length));if(X.isJust()&&G.isJust()){if(Y.length===1+X.extract()+G.extract()){let W=Y.slice(1,1+X.extract()),U=Y.slice(1+X.extract());return U0(new SD($,W,U))}return a(Error("PSBT deserializer: map count don't match input and output count"))}return a(Error("PSBT deserializer: input or output count not found in global map or transaction"))}serialize(Q){let Z=new WQ;return Q.globalMap=this.sortMap(Q.globalMap),Q.inputMaps=Q.inputMaps.map((Y)=>this.sortMap(Y)),Q.outputMaps=Q.outputMaps.map((Y)=>this.sortMap(Y)),Z.addBufferToData(pw),this.keyPairSerializer.serializeMap(Z,Q.globalMap),Q.inputMaps.forEach((Y)=>this.keyPairSerializer.serializeMap(Z,Y)),Q.outputMaps.forEach((Y)=>this.keyPairSerializer.serializeMap(Z,Y)),Z.build()}};var mw=w(()=>{I0();W0();R0();GX();gV();VX();VX();lw=require("bitcoinjs-lib"),S00=Object.defineProperty,w00=Object.getOwnPropertyDescriptor,pw=Uint8Array.from([112,115,98,116,255]);BK=_00([uw(0,g(sZ.ValueParser)),uw(1,g(sZ.KeyPairSerializer))],BK)});var nw,v00,x00,f00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?x00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&v00(Z,Y,J),J},dw=(Q,Z)=>(Y,$)=>Z(Y,$,Q),kK=class{constructor(Q,Z){this.valueParser=Q,this.valueFactory=Z}normalize(Q){let Z=Q.getGlobalValue(yZ.VERSION).chain((X)=>this.valueParser.getInt32LE(X.data)).orDefault(0);if(Z===2)return U0(Q);if(Z!==0)return a(Error("PSBT normalizer: unsupported PSBT version"));let Y=Q.getGlobalValue(yZ.UNSIGNED_TX).toEither(Error("PSBT normalizer: PSBTv0 should contain a transaction")).chain((X)=>GZ.encase(()=>nw.Transaction.fromHex(DQ(X.data,!1))).mapLeft((G)=>Error(`PSBT normalizer: failed to parse transaction (${G})`)));if(Y.isLeft())return Y;let $=Y.unsafeCoerce(),J=[[yZ.VERSION,this.valueFactory.fromInt32LE(2)],[yZ.TX_VERSION,this.valueFactory.fromInt32LE($.version)],[yZ.FALLBACK_LOCKTIME,this.valueFactory.fromUInt32LE($.locktime)],[yZ.INPUT_COUNT,this.valueFactory.fromVarint($.ins.length)],[yZ.OUTPUT_COUNT,this.valueFactory.fromVarint($.outs.length)]].reduce((X,[G,W])=>(W.ifJust((U)=>Q.setGlobalValue(G,U)),X&&W.isJust()),!0);for(let X=0;X<$.ins.length;X++)J=[[eQ.PREVIOUS_TXID,HQ(new xY($.ins[X].hash))],[eQ.OUTPUT_INDEX,this.valueFactory.fromUInt32LE($.ins[X].index)],[eQ.SEQUENCE,this.valueFactory.fromUInt32LE($.ins[X].sequence)]].reduce((G,[W,U])=>(U.ifJust((K)=>Q.setInputValue(X,W,K)),G&&U.isJust()),J);for(let X=0;X<$.outs.length;X++)J=[[XX.AMOUNT,this.valueFactory.fromInt64LE($.outs[X].value)],[XX.SCRIPT,HQ(new xY($.outs[X].script))]].reduce((G,[W,U])=>(U.ifJust((K)=>Q.setOutputValue(X,W,K)),G&&U.isJust()),J);return Q.globalMap.delete(new PY(yZ.UNSIGNED_TX).toHexaString()),J?U0(Q):a(Error("PSBT normalizer: failed to update the ¨PSBT"))}};var ow=w(()=>{I0();W0();R0();GX();gV();VX();r6();nw=require("bitcoinjs-lib"),v00=Object.defineProperty,x00=Object.getOwnPropertyDescriptor;kK=f00([e(),dw(0,g(sZ.ValueParser)),dw(1,g(sZ.ValueFactory))],kK)});class wD{fromInt32LE(Q){return q0.fromNullable(new WQ().add32BitIntToData(Q,!1).tryBuild()).map((Z)=>new xY(Z))}fromUInt32LE(Q){return q0.fromNullable(new WQ().add32BitUIntToData(Q,!1).tryBuild()).map((Z)=>new xY(Z))}fromInt64LE(Q){return q0.fromNullable(new WQ().add64BitIntToData(Q,!1).tryBuild()).map((Z)=>new xY(Z))}fromVarint(Q){return UZ(Q).map((Z)=>new xY(Z))}}var sw=w(()=>{I0();R0();r6();H$()});class _D{getInt32LE(Q){return q0.fromNullable(new BY(Q).extract32BitInt(!1))}getUInt32LE(Q){return q0.fromNullable(new BY(Q).extract32BitUInt(!1))}getInt64LE(Q){return q0.fromNullable(new BY(Q).extract64BitInt(!1))}getVarint(Q){return C$(new BY(Q)).map((Z)=>Z.value)}}var iw=w(()=>{I0();R0();H$()});var aw=()=>new b0(({bind:Q})=>{Q(sZ.KeySerializer).to(CD),Q(sZ.KeyPairSerializer).to(TK),Q(sZ.PsbtMapper).to(NK),Q(sZ.PsbtV2Normalizer).to(kK),Q(sZ.PsbtSerializer).to(BK),Q(sZ.ValueFactory).to(wD),Q(sZ.ValueParser).to(_D)});var rw=w(()=>{W0();GX();fw();gw();cw();mw();ow();sw();iw()});var $$;var n1=w(()=>{$$={AppBinder:Symbol.for("AppBinder")}});var y00,g00,h00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?g00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&y00(Z,Y,J),J},b00=(Q,Z)=>(Y,$)=>Z(Y,$,Q),CK=class{constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.getExtendedPublicKey({derivationPath:Q,checkOnDevice:Z.checkOnDevice,skipOpenApp:Z.skipOpenApp})}};var tw=w(()=>{W0();n1();y00=Object.defineProperty,g00=Object.getOwnPropertyDescriptor;CK=h00([e(),b00(0,g($$.AppBinder))],CK)});var c00,u00,p00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?u00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&c00(Z,Y,J),J},l00=(Q,Z)=>(Y,$)=>Z(Y,$,Q),SK=class{constructor(Q){this._appBinder=Q}execute(Q){return this._appBinder.getMasterFingerprint({skipOpenApp:Q.skipOpenApp})}};var ew=w(()=>{W0();n1();c00=Object.defineProperty,u00=Object.getOwnPropertyDescriptor;SK=p00([e(),l00(0,g($$.AppBinder))],SK)});var m00,d00,n00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?d00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&m00(Z,Y,J),J},o00=(Q,Z)=>(Y,$)=>Z(Y,$,Q),wK=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y,$,J){return this._appBinder.getWalletAddress({wallet:Z,checkOnDevice:Q,change:Y,addressIndex:$,skipOpenApp:J})}};var Q_=w(()=>{W0();n1();m00=Object.defineProperty,d00=Object.getOwnPropertyDescriptor;wK=n00([e(),o00(0,g($$.AppBinder))],wK)});var s00,i00,a00=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?i00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&s00(Z,Y,J),J},r00=(Q,Z)=>(Y,$)=>Z(Y,$,Q),_K=class{constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.registerWallet({wallet:Q,skipOpenApp:Z})}};var Z_=w(()=>{W0();n1();s00=Object.defineProperty,i00=Object.getOwnPropertyDescriptor;_K=a00([e(),r00(0,g($$.AppBinder))],_K)});var t00,e00,QQ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?e00(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&t00(Z,Y,J),J},ZQ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),vK=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y){return this._appBinder.signMessage({derivationPath:Q,message:Z,skipOpenApp:Y})}};var Y_=w(()=>{W0();n1();t00=Object.defineProperty,e00=Object.getOwnPropertyDescriptor;vK=QQ0([e(),ZQ0(0,g($$.AppBinder))],vK)});var YQ0,$Q0,JQ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?$Q0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&YQ0(Z,Y,J),J},GQ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),xK=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y){return this._appBinder.signPsbt({wallet:Q,psbt:Z,skipOpenApp:Y})}};var $_=w(()=>{W0();n1();YQ0=Object.defineProperty,$Q0=Object.getOwnPropertyDescriptor;xK=JQ0([e(),GQ0(0,g($$.AppBinder))],xK)});var XQ0,VQ0,qQ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?VQ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&XQ0(Z,Y,J),J},FQ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),fK=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y){return this._appBinder.signTransaction({wallet:Q,psbt:Z,skipOpenApp:Y})}};var J_=w(()=>{W0();n1();XQ0=Object.defineProperty,VQ0=Object.getOwnPropertyDescriptor;fK=qQ0([e(),FQ0(0,g($$.AppBinder))],fK)});var G_=()=>new b0(({bind:Q})=>{Q(Z$.GetExtendedPublicKeyUseCase).to(CK),Q(Z$.GetMasterFingerprintUseCase).to(SK),Q(Z$.RegisterWalletUseCase).to(_K),Q(Z$.SignMessageUseCase).to(vK),Q(Z$.SignPsbtUseCase).to(xK),Q(Z$.SignTransactionUseCase).to(fK),Q(Z$.GetWalletAddressUseCase).to(wK)});var X_=w(()=>{W0();hH();tw();ew();Q_();Z_();Y_();$_();J_()});class xD{constructor(Q,Z){this.derivationPath=Q,this.template=Z}}class qX{constructor(Q,Z,Y,$){this.name=Q,this.descriptorTemplate=Z,this.keys=Y,this.hmac=$}}class fD{constructor(Q,Z,Y){this.name=Q,this.descriptorTemplate=Z,this.keys=Y}}var vD;var yK=w(()=>{vD=((Q)=>(Q.LEGACY="pkh(@0/**)",Q.NESTED_SEGWIT="sh(wpkh(@0/**))",Q.NATIVE_SEGWIT="wpkh(@0/**)",Q.TAPROOT="tr(@0/**)",Q))(vD||{})});class gK{name;descriptorTemplate;keys;hmac;keysTree;descriptorBuffer;constructor({name:Q,descriptorTemplate:Z,keys:Y,hmac:$,keysTree:J,descriptorBuffer:X}){this.name=Q,this.descriptorTemplate=Z,this.keys=Y,this.hmac=$,this.keysTree=J,this.descriptorBuffer=X}}var V_=()=>{};var zQ0,WQ0,KQ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?WQ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&zQ0(Z,Y,J),J},UQ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),hK=class{constructor(Q){this.merkleTreeBuilder=Q}fromRegisteredWallet(Q){let Z=new TextEncoder,Y=Q.keys.map((X)=>Z.encode(X)),$=this.merkleTreeBuilder.build(Y),J=Z.encode(Q.descriptorTemplate);return new gK({name:Q.name,descriptorTemplate:Q.descriptorTemplate,keys:Q.keys,hmac:Q.hmac,keysTree:$,descriptorBuffer:J})}fromDefaultWallet(Q,Z,Y){let $=`${`[${DQ(Q,!1)}/${Y.derivationPath}]`}${Z}`,X=new Uint8Array(32).fill(0);return this.fromRegisteredWallet(new qX("",Y.template,[$],X))}fromWalletPolicy(Q){let Z=new TextEncoder,Y=Q.keys.map((G)=>Z.encode(G)),$=this.merkleTreeBuilder.build(Y),J=Z.encode(Q.descriptorTemplate),X=new Uint8Array(32).fill(0);return new gK({name:Q.name,descriptorTemplate:Q.descriptorTemplate,keys:Q.keys,hmac:X,keysTree:$,descriptorBuffer:J})}};var q_=w(()=>{I0();W0();yK();tG();V_();zQ0=Object.defineProperty,WQ0=Object.getOwnPropertyDescriptor;hK=KQ0([e(),UQ0(0,g(Y$.MerkleTreeBuilder))],hK)});var OQ0,HQ0,DQ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?HQ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&OQ0(Z,Y,J),J},IQ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),RQ0=2,bK=class{constructor(Q){this.hasher=Q}serialize(Q){let Z=UZ(Q.descriptorBuffer.length).unsafeCoerce(),Y=UZ(Q.keys.length).unsafeCoerce();return new WQ().add8BitUIntToData(RQ0).encodeInLVFromAscii(Q.name).addBufferToData(Z).addBufferToData(this.hasher.hash(Q.descriptorBuffer)).addBufferToData(Y).addBufferToData(Q.keysTree.getRoot()).build()}getId(Q){return this.hasher.hash(this.serialize(Q))}};var F_=w(()=>{I0();W0();tG();H$();OQ0=Object.defineProperty,HQ0=Object.getOwnPropertyDescriptor;bK=DQ0([e(),IQ0(0,g(Y$.HasherService))],bK)});var z_=()=>new b0(({bind:Q})=>{Q(f8.WalletBuilder).to(hK),Q(f8.WalletSerializer).to(bK)});var W_=w(()=>{W0();IW();q_();F_()});class s0{constructor(Q,Z,Y=hQ.isSuccessResponse){this._errors=Q,this._errorFactory=Z,this._isSuccessResponse=Y}getError(Q){let Z=new FQ(Q).encodeToHexaString(Q.statusCode);if(kY(Z,this._errors))return o({error:this._errorFactory({...this._errors[Z],errorCode:Z})});if(!this._isSuccessResponse(Q))return o({error:NZ.handle(Q)})}}var K_=w(()=>{I0()});class QZ{static PADDING=2147483648;static splitPath(Q){let Z=[];return Q.split("/").forEach((Y)=>{let $=parseInt(Y,10);if(isNaN($))throw Error("invalid number provided");Y.length>1&&Y[Y.length-1]==="'"&&($+=this.PADDING),Z.push($)}),Z}}var U_=()=>{};var O_=w(()=>{I0()});function yD(){let Q="";for(let Z=0;Z<6;Z++)Q+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(Math.random()*62));return`${Q}-${Date.now()}`}var H_=()=>{};var IQ=w(()=>{K_();U_();O_();H_()});var x$,D_,f$=(Q)=>new D_(Q);var l8=w(()=>{I0();x$={"6a80":{message:"Incorrect data"},"6a82":{message:"Request not supported"},6985:{message:"Rejected by user"},"6a86":{message:"Either P1 or P2 is incorrect"},"6a87":{message:"Lc or minimum APDU length is incorrect"},"6d00":{message:"No command exists with the provided INS"},"6e00":{message:"Bad CLA used for this application"},b000:{message:"Wrong response length (buffer size problem)"},b007:{message:"Aborted due to unexpected state reached"},b008:{message:"Invalid signature or HMAC"}};D_=class D_ extends DZ{constructor(Q){super({tag:"BtcAppCommandError",...Q})}}});var y$=1,o1=32,gD=64,m8,hD;var $J=w(()=>{m8=((Q)=>(Q[Q.YIELD=16]="YIELD",Q[Q.GET_PREIMAGE=64]="GET_PREIMAGE",Q[Q.GET_MERKLE_LEAF_PROOF=65]="GET_MERKLE_LEAF_PROOF",Q[Q.GET_MERKLE_LEAF_INDEX=66]="GET_MERKLE_LEAF_INDEX",Q[Q.GET_MORE_ELEMENTS=160]="GET_MORE_ELEMENTS",Q))(m8||{}),hD=Uint8Array.from([224,0])});class gZ{static isContinueResponse(Q){return Q.statusCode[0]===hD[0]&&Q.statusCode[1]===hD[1]}static isSuccessResponse(Q){return hQ.isSuccessResponse(Q)||gZ.isContinueResponse(Q)}static getSignature(Q){let Z=new FQ(Q.data),Y=Z.extract8BitUInt();if(Y===void 0)return o({error:new C0("V is missing")});let $=Z.encodeToHexaString(Z.extractFieldByLength(LQ0),!0);if(!$)return o({error:new C0("R is missing")});let J=Z.encodeToHexaString(Z.extractFieldByLength(EQ0),!0);return J?o({data:{v:Y,r:$,s:J}}):o({error:new C0("S is missing")})}static getAddress(Q){let Z=new FQ(Q.data);if(!Q.data)return o({error:new C0("Failed to extract address from response")});let Y=Z.encodeToString(Q.data.data);return o({data:{address:Y}})}static getWalletRegistration(Q){let Z=new FQ(Q.data),Y=Z.extractFieldByLength(PQ0);if(!Y)return o({error:new C0("Wallet ID is missing")});let $=Z.extractFieldByLength(jQ0);return $?o({data:{walletId:Y,walletHmac:$}}):o({error:new C0("Wallet HMAC is missing")})}}var LQ0=32,EQ0=32,PQ0=32,jQ0=32;var IJ=w(()=>{I0();$J()});class t6{constructor(Q,Z=new s0(x$,f$,gZ.isSuccessResponse)){this._args=Q,this._errorHelper=Z}name="getExtendedPublicKey";getApdu(){let{checkOnDevice:Q,derivationPath:Z}=this._args,Y={cla:225,ins:0,p1:0,p2:y$},$=new w0(Y).add8BitUIntToData(Q?1:0),J=QZ.splitPath(Z);return $.add8BitUIntToData(J.length),J.forEach((X)=>{$.add32BitUIntToData(X)}),$.build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.getUnparsedRemainingLength();if(Y<=0)return o({error:new C0("Invalid response length")});let $=Z.encodeToString(Z.extractFieldByLength(Y));return o({data:{extendedPublicKey:$}})})}}var bD=w(()=>{I0();IQ();R0();l8();$J();IJ()});class e6{constructor(Q=new s0(x$,f$,gZ.isSuccessResponse)){this._errorHelper=Q}name="getMasterFingerprint";getApdu(){return new w0({cla:225,ins:5,p1:0,p2:y$}).build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q).extractFieldByLength(AQ0);return Z?o({data:{masterFingerprint:Z}}):o({error:new C0("Master fingerprint is missing")})})}}var AQ0=4;var cD=w(()=>{I0();IQ();R0();l8();$J();IJ()});var s1;var uD=w(()=>{s1=Object.freeze({OPEN_APP:"signer.btc.steps.openApp",PREPARE_WALLET_POLICY:"signer.btc.steps.prepareWalletPolicy",BUILD_PSBT:"signer.btc.steps.buildPsbt",SIGN_PSBT:"signer.btc.steps.signPsbt"})});var yJ="Bitcoin";var cK=()=>{};class i1{merkleTrees=new Map;preimages=new Map;addPreimage(Q,Z){this.preimages.set(DQ(Q),Z)}addMerkleTree(Q){for(let Z of Q.getLeaves())this.preimages.set(DQ(Z.hash),Z.value);this.merkleTrees.set(DQ(Q.getRoot()),Q)}addMerkleMap(Q){this.addMerkleTree(Q.keys),this.addMerkleTree(Q.values)}getPreimage(Q){return q0.fromNullable(this.preimages.get(DQ(Q)))}getMerkleLeafIndex(Q,Z){return q0.fromNullable(this.merkleTrees.get(DQ(Q))).chain((Y)=>{let $=Y.getLeaves().findIndex((J)=>DQ(J.hash)===DQ(Z));return $===-1?YQ:HQ($)})}getMerkleProof(Q,Z){return q0.fromNullable(this.merkleTrees.get(DQ(Q))).chain((Y)=>Y.getLeafHash(Z).chain(($)=>Y.getProof(Z).map((J)=>({leafHash:$,proof:J}))))}}var QF=w(()=>{I0();R0()});class pD{constructor(Q,Z,Y,$=()=>new i1){this._args=Q,this._dataStoreService=Z,this._psbtMapper=Y,this._dataStoreFactory=$}async run(){let Q=this._dataStoreFactory(),Z;return await EQ(async({liftEither:Y})=>(Z=await Y(this._psbtMapper.map(this._args.psbt)),this._dataStoreService.merklizeWallet(Q,this._args.wallet),Y(this._dataStoreService.merklizePsbt(Q,Z)))).caseOf({Left:(Y)=>o({error:new sY({error:Y})}),Right:(Y)=>o({data:{psbtCommitment:Y,dataStore:Q,psbt:Z}})})}}var I_=w(()=>{I0();R0();QF()});class ZF{constructor(Q,Z,Y){this._api=Q,this._args=Z,this._walletBuilder=Y}isDefaultWallet(Q){return"derivationPath"in Q}async run(){let{wallet:Q}=this._args;if(!this.isDefaultWallet(Q))return Promise.resolve(o({data:this._walletBuilder.fromRegisteredWallet(Q)}));let Z=await this._api.sendCommand(new t6({checkOnDevice:!1,derivationPath:Q.derivationPath}));if(!N0(Z))return Z;let Y=await this._api.sendCommand(new e6);return N0(Y)?o({data:this._walletBuilder.fromDefaultWallet(Y.data.masterFingerprint,Z.data.extendedPublicKey,Q)}):Y}}var lD=w(()=>{I0();bD();cD()});class mD{constructor(Q,Z=new s0(x$,f$,gZ.isSuccessResponse)){this._args=Q,this._errorHelper=Z}name="signPsbt";getApdu(){let Q=new w0({cla:225,ins:4,p1:0,p2:y$}),{globalCommitment:Z,inputsCount:Y,inputsRoot:$,outputsCount:J,outputsRoot:X,walletHmac:G,walletId:W}=this._args;return Q.addBufferToData(Z).add8BitUIntToData(Y).addBufferToData($).add8BitUIntToData(J).addBufferToData(X).addBufferToData(W).addBufferToData(G).build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefault(o({data:Q}))}}var R_=w(()=>{I0();IQ();R0();l8();$J();IJ()});class dD{constructor(Q,Z=new s0(x$,f$,gZ.isSuccessResponse)){this._args=Q,this._errorHelper=Z}name="continue";getApdu(){return new w0({cla:248,ins:1,p1:0,p2:y$}).addBufferToData(this._args.payload).build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefault(o({data:Q}))}}var L_=w(()=>{I0();IQ();R0();l8();$J();IJ()});class g${_tag="ClientCommandHandlerError";originalError;constructor(Q){Q instanceof Error?this.originalError=Q:Q!==void 0&&(this.originalError=Error(String(Q)))}}var YF=()=>{};var E_=(Q,Z)=>{let Y=Q.slice(1,o1+1),$=Q.slice(o1+1,o1*2+1);return Z.dataStore.getMerkleLeafIndex(Y,$).mapOrDefault((J)=>{let X=UZ(J).unsafeCoerce(),G=new Uint8Array(1+X.length);return G[0]=1,G.set(X,1),U0(G)},U0(Uint8Array.from([0])))};var P_=w(()=>{R0();$J();H$()});var j_=(Q,Z)=>{let Y=Q.slice(1,o1+1),$=new BY(Q.slice(o1+1));return C$($).mapOrDefault(()=>C$($).mapOrDefault((J)=>Z.dataStore.getMerkleProof(Y,J.value).mapOrDefault(({proof:X,leafHash:G})=>{let W=YZ-o1-1-1,U=Math.floor(W/o1),K=Math.min(X.length,U),O=new WQ().addBufferToData(G).add8BitUIntToData(X.length).add8BitUIntToData(K);for(let L=0;L<K;L++){let A=X[L];A&&O.addBufferToData(A)}let I=O.build();if(K<X.length)for(let L=K;L<X.length;L++){let A=X[L];A instanceof Uint8Array&&Z.queue.push(A)}return U0(I)},a(new g$("Merkle proof not found in dataStore"))),a(new g$("Failed to extract the proofIndex varint"))),a(new g$("Failed to extract the numberOfElements varint")))};var A_=w(()=>{I0();R0();$J();H$();YF()});var M_=(Q,Z)=>{if(Z.queue.length===0)return a(new g$("No more elements in queue"));let Y=Z.queue[0]?.length;if(Y===void 0)return a(new g$("Queue is empty"));if(!Z.queue.every((K)=>K.length===Y))return a(new g$("Elements in queue have varying lengths"));let $=YZ-1-1,J=Math.floor($/Y),X=Math.min(J,Z.queue.length),G=2+X*Y,W=new Uint8Array(G),U=0;W[U++]=X,W[U++]=Y;for(let K=0;K<X;K++){let O=Z.queue[K];O&&(W.set(O,U),U+=Y)}return Z.queue.splice(0,X),U0(W)};var T_=w(()=>{I0();R0();YF()});var N_=(Q,Z)=>{let Y=Q.slice(2,34),$=Z.dataStore.getPreimage(Y);if($.isJust()){let J=$.extract(),X=UZ(J.length).unsafeCoerce(),G=YZ-X.length-1,W=Math.min(G,J.length),U=new WQ().addBufferToData(X).add8BitUIntToData(W).addBufferToData(J.slice(0,W)).build();if(W<J.length)for(let K=W;K<J.length;K++)Z.queue.push(J.slice(K,K+1));return U0(U)}return a(new g$("Preimage not found in dataStore"))};var B_=w(()=>{I0();R0();H$();YF()});var k_=(Q,Z)=>{let Y=Q.slice(1);return Z.yieldedResults.push(Y),U0(new Uint8Array([]))};var C_=w(()=>{R0()});class nD{getClientCommandPayload(Q,Z){let Y=Q[0];if(Y===void 0||!Object.values(m8).includes(Y))return a(new g$(`Unexpected command code ${Y}`));switch(Y){case m8.YIELD:return k_(Q,Z);case m8.GET_PREIMAGE:return N_(Q,Z);case m8.GET_MERKLE_LEAF_PROOF:return j_(Q,Z);case m8.GET_MERKLE_LEAF_INDEX:return E_(Q,Z);case m8.GET_MORE_ELEMENTS:return M_(Q,Z);default:return a(new g$(`Unhandled command code ${Y}`))}}}var S_=w(()=>{R0();YF();P_();A_();T_();B_();C_();$J()});class a1{constructor(Q,Z,Y=new nD){this._api=Q,this._clientCommandInterpreter=Y,this._context={dataStore:Z,queue:[],yieldedResults:[]}}_context;async run(Q){let Z=Q;for(;this.isApduResult(Z)&&gZ.isContinueResponse(Z.data);)Z=await this._clientCommandInterpreter.getClientCommandPayload(Z.data.data,this._context).caseOf({Left:(Y)=>Promise.resolve(o({error:new sY(Y)})),Right:(Y)=>this._api.sendCommand(new dD({payload:Y}))});return Z}getYieldedResults(){return this._context.yieldedResults}isApduResult=(Q)=>N0(Q)&&typeof Q.data=="object"&&Q.data!==null&&("statusCode"in Q.data)&&("data"in Q.data)}var $F=w(()=>{I0();L_();S_();IJ()});class sD{constructor(Q,Z,Y,$,J=(X,G)=>new a1(X,G)){this._api=Q,this._args=Z,this._walletSerializer=Y,this._valueParser=$,this._continueTaskFactory=J}async run(){let{psbtCommitment:{globalCommitment:Q,inputsRoot:Z,outputsRoot:Y},psbt:$,wallet:J,dataStore:X}=this._args,G=await this._api.sendCommand(new mD({globalCommitment:Q,inputsRoot:Z,outputsRoot:Y,inputsCount:$.getGlobalValue(yZ.INPUT_COUNT).chain((K)=>this._valueParser.getVarint(K.data)).orDefault(0),outputsCount:$.getGlobalValue(yZ.OUTPUT_COUNT).chain((K)=>this._valueParser.getVarint(K.data)).orDefault(0),walletId:this._walletSerializer.getId(J),walletHmac:J.hmac})),W=this._continueTaskFactory(this._api,X),U=await W.run(G);if(N0(U)){let K=W.getYieldedResults(),O=[];for(let I of K){let L=this._decodePsbtSignature(I);if(L.isLeft())return o({error:L.extract()});L.isRight()&&O.push(L.extract())}return o({data:O})}return U}_decodePsbtSignature(Q){let Z=new BY(Q),Y=C$(Z).map((J)=>J.value).toEither(new C0("Invalid input index or tag"));if(Y.isLeft())return Y;let $=Y.unsafeCoerce();return $===MQ0?this._decodeMusigPubNonce(Z):$===TQ0?this._decodeMusigPartialSignature(Z):$<=NQ0?this._decodePartialSignature(Z,$):a(new C0(`Invalid input index or tag returned: ${$}`))}_decodeMusigPubNonce(Q){let Z=C$(Q).map((G)=>G.value).toEither(new C0("Invalid input index")),Y=q0.fromNullable(Q.extractFieldByLength(CQ0)).toEither(new C0("Pubnonce is missing")),$=q0.fromNullable(Q.extractFieldByLength(JF)).toEither(new C0("Participant pubkey is missing")),J=q0.fromNullable(Q.extractFieldByLength(JF)).toEither(new C0("Aggregated pubkey is missing")),X=q0.fromNullable(Q.extractFieldByLength(Q.getUnparsedRemainingLength())).orDefault(Uint8Array.from([]));return Z.chain((G)=>GZ.sequence([Y,$,J]).map((W)=>({inputIndex:G,pubnonce:W[0],participantPubkey:W[1],aggregatedPubkey:W[2],tapleafHash:X})))}_decodeMusigPartialSignature(Q){let Z=C$(Q).map((G)=>G.value).toEither(new C0("Invalid input index")),Y=q0.fromNullable(Q.extractFieldByLength(kQ0)).toEither(new C0("Partial signature is missing")),$=q0.fromNullable(Q.extractFieldByLength(JF)).toEither(new C0("Participant pubkey is missing")),J=q0.fromNullable(Q.extractFieldByLength(JF)).toEither(new C0("Aggregated pubkey is missing")),X=q0.fromNullable(Q.extractFieldByLength(Q.getUnparsedRemainingLength())).orDefault(Uint8Array.from([]));return Z.chain((G)=>GZ.sequence([Y,$,J]).map((W)=>({inputIndex:G,partialSignature:W[0],participantPubkey:W[1],aggregatedPubkey:W[2],tapleafHash:X})))}_decodePartialSignature(Q,Z){let Y=q0.fromNullable(Q.extract8BitUInt()).toEither(new C0("Pubkey length is missing")).chain((J)=>q0.fromNullable(Q.extractFieldByLength(J)).toEither(new C0("Pubkey is missing"))),$=q0.fromNullable(Q.extractFieldByLength(Q.getUnparsedRemainingLength())).toEither(new C0("Signature is missing"));return GZ.sequence([Y,$]).chain((J)=>{let X=J[0],G=J[1];return X.length===BQ0?U0({inputIndex:Z,signature:G,pubkey:X.slice(0,oD),tapleafHash:X.slice(oD)}):[oD,JF].includes(X.length)?U0({inputIndex:Z,signature:G,pubkey:X}):a(new C0(`Invalid pubkey length returned: ${X.length}`))})}}var MQ0=4294967295,TQ0=4294967294,NQ0=65535,oD=32,JF=33,BQ0=64,kQ0=32,CQ0=66;var w_=w(()=>{I0();R0();R_();$F();VX();H$()});var GF;var iD=w(()=>{I0();R0();KZ();uD();cK();I_();lD();w_();GF=class GF extends AQ{makeStateMachine(Q){let{signPsbt:Z,prepareWalletPolicy:Y,buildPsbt:$}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:yJ}}).makeStateMachine(Q),prepareWalletPolicy:VQ(Y),buildPsbt:VQ($),signPsbt:VQ(Z)},guards:{noInternalError:({context:J})=>J._internalState.error===null,skipOpenApp:({context:J})=>J.input.skipOpenApp},actions:{assignErrorFromEvent:r({_internalState:(J)=>({...J.context._internalState,error:J.event.error})})}}).createMachine({id:"SignPsbtDeviceAction",initial:"InitialState",context:({input:J})=>({input:J,intermediateValue:{requiredUserInteraction:k0.None,step:s1.OPEN_APP},_internalState:{error:null,wallet:null,buildPsbtResult:null,signatures:null,signedPsbt:null}}),states:{InitialState:{always:[{target:"PrepareWalletPolicy",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:s1.OPEN_APP})}),invoke:{id:"openAppStateMachine",input:{appName:yJ},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:({event:J})=>({...J.snapshot.context.intermediateValue,step:s1.OPEN_APP})})},onDone:{actions:r({_internalState:(J)=>J.event.output.caseOf({Right:()=>J.context._internalState,Left:(X)=>({...J.context._internalState,error:X})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"PrepareWalletPolicy",guard:"noInternalError"},"Error"]},PrepareWalletPolicy:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:s1.PREPARE_WALLET_POLICY})}),invoke:{id:"prepareWalletPolicy",src:"prepareWalletPolicy",input:({context:J})=>({wallet:J.input.wallet,walletBuilder:J.input.walletBuilder}),onDone:{target:"PrepareWalletPolicyResultCheck",actions:r({_internalState:({event:J,context:X})=>N0(J.output)?{...X._internalState,wallet:J.output.data}:{...X._internalState,error:J.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},PrepareWalletPolicyResultCheck:{always:[{guard:"noInternalError",target:"BuildPsbt"},{target:"Error"}]},BuildPsbt:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:s1.BUILD_PSBT})}),invoke:{id:"buildPsbt",src:"buildPsbt",input:({context:J})=>({psbt:J.input.psbt,wallet:J._internalState.wallet,dataStoreService:J.input.dataStoreService,psbtMapper:J.input.psbtMapper}),onDone:{target:"BuildPsbtResultCheck",actions:r({_internalState:({event:J,context:X})=>N0(J.output)?{...X._internalState,buildPsbtResult:J.output.data}:{...X._internalState,error:J.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},BuildPsbtResultCheck:{always:[{guard:"noInternalError",target:"SignPsbt"},{target:"Error"}]},SignPsbt:{entry:r({intermediateValue:{requiredUserInteraction:k0.SignTransaction,step:s1.SIGN_PSBT}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:s1.SIGN_PSBT}}),invoke:{id:"signPsbt",src:"signPsbt",input:({context:J})=>({walletSerializer:J.input.walletSerializer,valueParser:J.input.valueParser,buildPsbtResult:J._internalState.buildPsbtResult,wallet:J._internalState.wallet}),onDone:{target:"SignPsbtResultCheck",actions:r({_internalState:({event:J,context:X})=>N0(J.output)?{...X._internalState,signatures:J.output.data}:{...X._internalState,error:J.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},SignPsbtResultCheck:{always:[{guard:"noInternalError",target:"Success"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:{_internalState:{signatures:J,error:X}}})=>J?U0(J):a(X||new xQ("No error in final state"))})}extractDependencies(Q){return{prepareWalletPolicy:async(Z)=>{let{input:{walletBuilder:Y,wallet:$}}=Z;return await new ZF(Q,{wallet:$},Y).run()},buildPsbt:async(Z)=>{let{input:{psbt:Y,wallet:$,dataStoreService:J,psbtMapper:X}}=Z;return new pD({psbt:Y,wallet:$},J,X).run()},signPsbt:async(Z)=>{let{input:{wallet:Y,buildPsbtResult:$,walletSerializer:J,valueParser:X}}=Z;return await new sD(Q,{wallet:Y,...$},J,X).run()}}}}});var d8;var aD=w(()=>{d8=Object.freeze({SIGN_PSBT:"signer.btc.steps.signPsbt",UPDATE_PSBT:"signer.btc.steps.updatePsbt",EXTRACT_TRANSACTION:"signer.btc.steps.extractTransaction"})});class rD{constructor(Q,Z){this._args=Q,this._valueParser=Z}run(){let{psbt:Q}=this._args,Z=new WQ,Y=Q.getGlobalValue(yZ.VERSION).chain((U)=>this._valueParser.getUInt32LE(U.data)).orDefault(0);Z.add32BitUIntToData(Y,!1);let $=Q.getInputValue(0,eQ.WITNESS_UTXO).isJust();$&&Z.addBufferToData(Uint8Array.from([0,1]));let J=Q.getGlobalValue(yZ.INPUT_COUNT).chain((U)=>this._valueParser.getVarint(U.data)).orDefault(0);Z.addBufferToData(UZ(J).extract());let X=new WQ;for(let U=0;U<J;U++){Z.addBufferToData(Q.getInputValue(U,eQ.PREVIOUS_TXID).mapOrDefault((L)=>L.data,new Uint8Array));let K=Q.getInputValue(U,eQ.OUTPUT_INDEX).chain((L)=>this._valueParser.getUInt32LE(L.data)).orDefault(0);Z.add32BitUIntToData(K,!1);let O=Q.getInputValue(U,eQ.FINAL_SCRIPTSIG).mapOrDefault((L)=>L.data,Uint8Array.from([]));Z.addBufferToData(UZ(O.length).extract()),Z.addBufferToData(O);let I=Q.getInputValue(U,eQ.SEQUENCE).chain((L)=>this._valueParser.getUInt32LE(L.data)).orDefault(0);if(Z.add32BitUIntToData(I,!1),$){let L=Q.getInputValue(U,eQ.FINAL_SCRIPTWITNESS).mapOrDefault((A)=>A.data,Uint8Array.from([]));X.addBufferToData(L)}}let G=Q.getGlobalValue(yZ.OUTPUT_COUNT).chain((U)=>this._valueParser.getVarint(U.data)).orDefault(0);Z.addBufferToData(UZ(G).extract());for(let U=0;U<G;U++){let K=Q.getOutputValue(U,XX.AMOUNT).chain((I)=>this._valueParser.getInt64LE(I.data)).orDefault(0n),O=Q.getOutputValue(U,XX.SCRIPT).mapOrDefault((I)=>I.data,new Uint8Array);Z.add64BitIntToData(K,!1),Z.addBufferToData(UZ(O.length).extract()),Z.addBufferToData(O)}Z.addBufferToData(X.build());let W=Q.getGlobalValue(yZ.FALLBACK_LOCKTIME).chain((U)=>this._valueParser.getUInt32LE(U.data)).orDefault(0);return Z.add32BitUIntToData(W,!1),o({data:DQ(Z.build())})}}var __=w(()=>{I0();VX();H$()});var v_=(Q)=>("pubkey"in Q);var x_=()=>{};function tD(Q){let Z=new WQ;if(Q.length<=_Q0)Z.add8BitUIntToData(Q.length);else if(Q.length<=vQ0)Z.add8BitUIntToData(SQ0),Z.add8BitUIntToData(Q.length);else if(Q.length<=xQ0){Z.add8BitUIntToData(wQ0);let Y=new WQ().add16BitUIntToData(Q.length,!1).build();Z.addBufferToData(Y)}return Z.addBufferToData(Q),Z.build()}var SQ0=76,wQ0=77,_Q0=78,vQ0=255,xQ0=65535;var f_=w(()=>{I0()});class eD{constructor(Q,Z,Y){this._args=Q,this._valueParser=Z,this._psbtMapper=Y}async run(){let{psbt:Q,signatures:Z}=this._args,Y=Z.filter(($)=>v_($));return Y.length===0?o({error:new sY("No signature provided")}):await EQ(async({liftEither:$})=>{let J=await $(this._psbtMapper.map(Q)),X=await $(this.getSignedPsbt(J,Y));return $(this.getUpdatedPsbt(X))}).caseOf({Left:($)=>o({error:new sY($)}),Right:($)=>o({data:$})})}getSignedPsbt(Q,Z){return GZ.encase(()=>{for(let Y of Z)Q.getInputKeyDatas(Y.inputIndex,eQ.BIP32_DERIVATION).map(($)=>$.map((J)=>new WQ().addHexaStringToData(J).build())).map(($)=>{$.length===0?Q.getInputKeyDatas(Y.inputIndex,eQ.TAP_BIP32_DERIVATION).map((J)=>J.map((X)=>new WQ().addHexaStringToData(X).build())).map((J)=>{if(J.length===0)throw Error(`Missing pubkey derivation for input ${Y.inputIndex}`);if(Y.tapleafHash!==void 0)throw Error("Unhandled psbt key type PSBT_IN_TAP_SCRIPT_SIG");Q.setInputValue(Y.inputIndex,eQ.TAP_KEY_SIG,new xY(Y.signature))}):Q.setInputValue(Y.inputIndex,eQ.PARTIAL_SIG,new xY(Y.signature),Y.pubkey)});return Q})}getUpdatedPsbt(Q){return GZ.encase(()=>{let Z=Q,Y=Z.getGlobalValue(yZ.INPUT_COUNT).mapOrDefault(($)=>this._valueParser.getVarint($.data).orDefault(0),0);for(let $=0;$<Y;$++){let J=Z.getInputKeyDatas($,eQ.PARTIAL_SIG).mapOrDefault((G)=>G.map((W)=>new WQ().addHexaStringToData(W).build()),[]),X=Z.getInputValue($,eQ.TAP_KEY_SIG);if(J.length===0&&X.isNothing())throw Error(`No signature for input ${$} present`);J.length>0?Z=this.getLegacyUpdatedPsbtInput(Z,$,J):Z=this.getTaprootUpdatedPsbtInput(Z,$),this.clearUpdatedPsbtInput(Z,$)}return Z})}clearUpdatedPsbtInput(Q,Z){let Y=Q,$=[eQ.BIP32_DERIVATION,eQ.PARTIAL_SIG,eQ.TAP_BIP32_DERIVATION,eQ.TAP_KEY_SIG],J=Y.getInputValue(Z,eQ.WITNESS_UTXO).isJust(),X=Y.getInputValue(Z,eQ.NON_WITNESS_UTXO).isJust();return J&&X&&$.push(eQ.NON_WITNESS_UTXO),Y.deleteInputEntries(Z,$),Y}getLegacyUpdatedPsbtInput(Q,Z,Y){let $=Q,J=$.getInputValue(Z,eQ.TAP_KEY_SIG);if(Y.length>1)throw Error(`Expected exactly one signature, got ${Y.length}`);if(J.isJust())throw Error("Both taproot and non-taproot signatures present.");let X=$.getInputValue(Z,eQ.WITNESS_UTXO).isJust(),G=$.getInputValue(Z,eQ.REDEEM_SCRIPT),W=G.isJust(),U=$.getKeyDataInputValue(Z,eQ.PARTIAL_SIG,Y[0]);if(U.isNothing())throw Error("Expected partial signature for input "+Z);let K=U.mapOrDefault((O)=>O.data,Uint8Array.from([]));if(X){let O=new WQ;if(O.addBufferToData(UZ(2).mapOrDefault((I)=>I,Uint8Array.from([2]))),O.addBufferToData(UZ(K.length).orDefault(Uint8Array.from([0]))),O.addBufferToData(K),O.addBufferToData(UZ(Y[0].length).orDefault(Uint8Array.from([0]))),O.addBufferToData(Y[0]),$.setInputValue(Z,eQ.FINAL_SCRIPTWITNESS,new xY(O.build())),W){let I=G.mapOrDefault((A)=>A.data,Uint8Array.from([]));if(I.length==0)throw Error("Expected non-empty redeemscript. Can't finalize intput "+Z);let L=new WQ;L.add8BitUIntToData(I.length),L.addBufferToData(I),$.setInputValue(Z,eQ.FINAL_SCRIPTSIG,new xY(L.build()))}}else{let O=new WQ;O.addBufferToData(tD(K)),O.addBufferToData(tD(Y[0])),$.setInputValue(Z,eQ.FINAL_SCRIPTSIG,new xY(O.build()))}return $}getTaprootUpdatedPsbtInput(Q,Z){let Y=Q,$=Y.getInputValue(Z,eQ.TAP_KEY_SIG);if($.isNothing())throw Error("No signature for taproot input "+Z);let J=$.mapOrDefault((G)=>G.data,Uint8Array.from([]));if(![fQ0,yQ0].includes(J.length))throw Error("Unexpected length of schnorr signature.");let X=new WQ;return X.add8BitUIntToData(1),X.encodeInLVFromBuffer(J),Y.setInputValue(Z,eQ.FINAL_SCRIPTWITNESS,new xY(X.build())),Y}}var fQ0=64,yQ0=65;var y_=w(()=>{I0();R0();x_();VX();r6();f_();H$()});var QI;var g_=w(()=>{I0();R0();KZ();aD();iD();__();y_();QI=class QI extends AQ{makeStateMachine(Q){let{updatePsbt:Z,extractTransaction:Y}=this.extractDependencies();return NQ({types:{input:{},context:{},output:{}},actors:{signPsbtStateMachine:new GF({input:this.input,loggerFactory:this.getLoggerFactory(Q)}).makeStateMachine(Q),updatePsbt:VQ(Z),extractTransaction:VQ(Y)},guards:{noInternalError:({context:$})=>$._internalState.error===null},actions:{assignErrorFromEvent:r({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"SignTransactionDeviceAction",initial:"SignPsbtDeviceAction",context:({input:$})=>({input:$,intermediateValue:{requiredUserInteraction:k0.None,step:d8.SIGN_PSBT},_internalState:{error:null,signatures:null,signedPsbt:null,transaction:null}}),states:{SignPsbtDeviceAction:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:d8.SIGN_PSBT})}),exit:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:d8.SIGN_PSBT})}),invoke:{id:"signPsbtStateMachine",src:"signPsbtStateMachine",input:({context:$})=>$.input,onSnapshot:{actions:r({intermediateValue:({event:$})=>({...$.snapshot.context.intermediateValue,step:d8.SIGN_PSBT})})},onDone:{target:"SignPsbtResultCheck",actions:r({_internalState:({event:$,context:J})=>$.output.caseOf({Right:(X)=>({...J._internalState,signatures:X}),Left:(X)=>({...J._internalState,error:X})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},SignPsbtResultCheck:{always:[{guard:"noInternalError",target:"UpdatePsbt"},{target:"Error"}]},UpdatePsbt:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:d8.UPDATE_PSBT})}),invoke:{id:"updatePsbt",src:"updatePsbt",input:({context:$})=>({psbt:$.input.psbt,valueParser:$.input.valueParser,psbtMapper:$.input.psbtMapper,signatures:$._internalState.signatures}),onDone:{target:"UpdatePsbtResultCheck",actions:r({_internalState:({event:$,context:J})=>N0($.output)?{...J._internalState,signedPsbt:$.output.data}:{...J._internalState,error:$.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},UpdatePsbtResultCheck:{always:[{guard:"noInternalError",target:"ExtractTransaction"},{target:"Error"}]},ExtractTransaction:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:d8.EXTRACT_TRANSACTION})}),invoke:{id:"extractTransaction",src:"extractTransaction",input:({context:$})=>({valueParser:$.input.valueParser,psbt:$._internalState.signedPsbt}),onDone:{target:"ExtractTransactionResultCheck",actions:r({_internalState:({event:$,context:J})=>N0($.output)?{...J._internalState,transaction:$.output.data}:{...J._internalState,error:$.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ExtractTransactionResultCheck:{always:[{guard:"noInternalError",target:"Success"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:$})=>$._internalState.transaction?U0($._internalState.transaction):a($._internalState.error||new xQ("No error in final state"))})}extractDependencies(){return{updatePsbt:async(Q)=>{let{input:{psbt:Z,signatures:Y,valueParser:$,psbtMapper:J}}=Q;return await new eD({psbt:Z,signatures:Y},$,J).run()},extractTransaction:async(Q)=>{let{input:{psbt:Z,valueParser:Y}}=Q;return new rD({psbt:Z},Y).run()}}}}});class ZI{constructor(Q,Z=new s0(x$,f$,gZ.isSuccessResponse)){this._args=Q,this._errorHelper=Z}name="registerWalletAddress";getApdu(){let Q=new w0({cla:225,ins:2,p1:0,p2:y$}),{walletPolicy:Z}=this._args;return Q.encodeInLVFromBuffer(Z).build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefault(o({data:Q}))}}var h_=w(()=>{I0();IQ();R0();l8();$J();IJ()});class YI{constructor(Q,Z,Y,$,J,X=(G,W)=>new a1(G,W)){this._api=Q,this._args=Z,this._walletBuilder=Y,this._walletSerializer=$,this._dataStoreService=J,this._continueTaskFactory=X,this._logger=this._args.loggerFactory("RegisterWalletTask")}_logger;async run(){let{walletPolicy:Q}=this._args;this._logger.debug("[run] Starting RegisterWalletTask",{data:{walletName:Q.name,descriptorTemplate:Q.descriptorTemplate,keysCount:Q.keys?.length??0}});let Z=this._walletBuilder.fromWalletPolicy(Q),Y=new i1;this._dataStoreService.merklizeWallet(Y,Z);let $=this._walletSerializer.serialize(Z);this._logger.debug("[run] Sending RegisterWalletAddressCommand",{data:{walletName:Q.name,serializedWalletLength:$?.length??0}});let J=await this._api.sendCommand(new ZI({walletPolicy:$})),X=await this._continueTaskFactory(this._api,Y).run(J);if(N0(X)){let G=gZ.getWalletRegistration(X);if(!N0(G))return this._logger.error("[run] Wallet registration parsing failed",{data:{error:G.error}}),o({error:G.error});let{walletHmac:W}=G.data;return this._logger.debug("[run] RegisterWalletTask completed successfully",{data:{walletName:Q.name,walletHmac:Array.from(W).map((U)=>U.toString(16).padStart(2,"0")).join("")}}),o({data:new qX(Q.name,Q.descriptorTemplate,Q.keys,W)})}return this._logger.error("[run] RegisterWalletTask failed",{data:{error:X.error}}),X}}var b_=w(()=>{I0();yK();h_();$F();QF();IJ()});class $I{constructor(Q,Z=new s0(x$,f$,gZ.isSuccessResponse)){this._args=Q,this._errorHelper=Z}name="signMessage";getApdu(){let{derivationPath:Q,messageLength:Z,messageMerkleRoot:Y}=this._args,$=new w0({cla:225,ins:16,p1:0,p2:y$}),J=QZ.splitPath(Q);return $.add8BitUIntToData(J.length),J.forEach((X)=>{$.add32BitUIntToData(X)}),$.addBufferToData(UZ(Z).unsafeCoerce()).addBufferToData(Y).build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefault(o({data:Q}))}}var c_=w(()=>{I0();IQ();R0();$J();IJ();H$();l8()});class JI{constructor(Q,Z,Y,$=(J,X)=>new a1(J,X)){this._api=Q,this._args=Z,this._dataStoreService=Y,this._continueTaskFactory=$,this._logger=this._args.loggerFactory("SendSignMessageTask")}_logger;async run(){let{derivationPath:Q,message:Z}=this._args;this._logger.debug("[run] Starting SendSignMessageTask",{data:{derivationPath:Q,message:Z}});let Y=new i1,$=new TextEncoder().encode(Z),J=[];for(let U=0;U<$.length;U+=gD)J.push($.subarray(U,U+gD));let X=this._dataStoreService.merklizeChunks(Y,J);this._logger.debug("[run] Sending SignMessageCommand",{data:{derivationPath:Q,chunksCount:J.length,merkleRoot:X?Array.from(X).map((U)=>U.toString(16).padStart(2,"0")).join(""):null}});let G=await this._api.sendCommand(new $I({derivationPath:Q,messageLength:$.length,messageMerkleRoot:X})),W=await this._continueTaskFactory(this._api,Y).run(G);if(N0(W)){let U=gZ.getSignature(W);return N0(U)&&this._logger.debug("[run] SendSignMessageTask completed successfully",{data:{signature:U.data}}),U}return this._logger.error("[run] SendSignMessageTask failed",{data:{error:W.error}}),W}}var u_=w(()=>{I0();c_();$J();$F();QF();IJ()});var n8;var GI=w(()=>{n8=Object.freeze({OPEN_APP:"signer.btc.steps.openApp",PREPARE_WALLET_POLICY:"signer.btc.steps.prepareWalletPolicy",GET_WALLET_ADDRESS:"signer.btc.steps.getWalletAddress"})});class XI{constructor(Q,Z=new s0(x$,f$,gZ.isSuccessResponse)){this.args=Q,this._errorHelper=Z}name="getWalletAddress";getApdu(){return new w0({cla:225,ins:3,p1:0,p2:y$}).addBufferToData(Uint8Array.from([this.args.checkOnDevice?1:0])).addBufferToData(this.args.walletId).addBufferToData(this.args.walletHmac).addBufferToData(Uint8Array.from([this.args.change?1:0])).add32BitUIntToData(this.args.addressIndex).build()}parseResponse(Q){return q0.fromNullable(this._errorHelper.getError(Q)).orDefault(o({data:Q}))}}var p_=w(()=>{I0();IQ();R0();$J();IJ();l8()});class VI{constructor(Q,Z,Y,$,J=(G,W)=>new a1(G,W),X=gZ.getAddress){this._api=Q,this._args=Z,this._walletSerializer=Y,this._dataStoreService=$,this._continueTaskFactory=J,this._getAddress=X}async run(){let{checkOnDevice:Q,change:Z,addressIndex:Y,wallet:$}=this._args,J=new i1;this._dataStoreService.merklizeWallet(J,$);let X=this._walletSerializer.getId($),G=await this._api.sendCommand(new XI({checkOnDevice:Q,walletId:X,walletHmac:$.hmac,change:Z,addressIndex:Y})),W=await this._continueTaskFactory(this._api,J).run(G);return N0(W)?this._getAddress(W):W}}var l_=w(()=>{I0();p_();QF();IJ();$F()});var qI;var m_=w(()=>{I0();R0();KZ();GI();cK();l_();lD();qI=class qI extends AQ{makeStateMachine(Q){let{getWalletAddress:Z,prepareWalletPolicy:Y}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:yJ}}).makeStateMachine(Q),prepareWalletPolicy:VQ(Y),getWalletAddress:VQ(Z)},guards:{noInternalError:({context:$})=>$._internalState.error===null,skipOpenApp:({context:$})=>$.input.skipOpenApp},actions:{assignErrorFromEvent:r({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"GetWalletAddressDeviceAction",initial:"InitialState",context:({input:$})=>({input:$,intermediateValue:{requiredUserInteraction:k0.None,step:n8.OPEN_APP},_internalState:{error:null,wallet:null,walletAddress:null}}),states:{InitialState:{always:[{target:"PrepareWalletPolicy",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:n8.OPEN_APP})}),invoke:{id:"openAppStateMachine",input:{appName:yJ},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:({event:$})=>({...$.snapshot.context.intermediateValue,step:n8.OPEN_APP})})},onDone:{actions:r({_internalState:({event:$,context:J})=>$.output.caseOf({Right:()=>J._internalState,Left:(X)=>({...J._internalState,error:X})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"PrepareWalletPolicy",guard:"noInternalError"},"Error"]},PrepareWalletPolicy:{entry:r({intermediateValue:()=>({requiredUserInteraction:k0.None,step:n8.PREPARE_WALLET_POLICY})}),invoke:{id:"prepareWalletPolicy",src:"prepareWalletPolicy",input:({context:$})=>({wallet:$.input.wallet,walletBuilder:$.input.walletBuilder}),onDone:{target:"PrepareWalletPolicyResultCheck",actions:r({_internalState:({event:$,context:J})=>N0($.output)?{...J._internalState,wallet:$.output.data}:{...J._internalState,error:$.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},PrepareWalletPolicyResultCheck:{always:[{guard:"noInternalError",target:"GetWalletAddress"},{target:"Error"}]},GetWalletAddress:{entry:r(({context:$})=>({intermediateValue:{requiredUserInteraction:$.input.checkOnDevice?k0.VerifyAddress:k0.None,step:n8.GET_WALLET_ADDRESS}})),exit:r({intermediateValue:{requiredUserInteraction:k0.None,step:n8.GET_WALLET_ADDRESS}}),invoke:{id:"getWalletAddress",src:"getWalletAddress",input:({context:$})=>({checkOnDevice:$.input.checkOnDevice,wallet:$._internalState.wallet,change:$.input.change,addressIndex:$.input.addressIndex,dataStoreService:$.input.dataStoreService,walletSerializer:$.input.walletSerializer,walletBuilder:$.input.walletBuilder}),onDone:{target:"GetWalletAddressResultCheck",actions:r({_internalState:({event:$,context:J})=>N0($.output)?{...J._internalState,walletAddress:$.output.data}:{...J._internalState,error:$.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetWalletAddressResultCheck:{always:[{guard:"noInternalError",target:"Success"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:$})=>$._internalState.walletAddress?U0($._internalState.walletAddress):a($._internalState.error||new xQ("No error in final state"))})}extractDependencies(Q){return{getWalletAddress:async(Z)=>{let{checkOnDevice:Y,wallet:$,change:J,addressIndex:X,walletSerializer:G,dataStoreService:W}=Z.input;return await new VI(Q,{checkOnDevice:Y,wallet:$,change:J,addressIndex:X},G,W).run()},prepareWalletPolicy:async(Z)=>{let{input:{walletBuilder:Y,wallet:$}}=Z;return await new ZF(Q,{wallet:$},Y).run()}}}}});var gQ0,hQ0,bQ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?hQ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&gQ0(Z,Y,J),J},o8=(Q,Z)=>(Y,$)=>Z(Y,$,Q),uK=class{constructor(Q,Z,Y,$,J,X,G,W){this._dmk=Q,this._sessionId=Z,this._walletBuilder=Y,this._walletSerializer=$,this._dataStoreService=J,this._psbtMapper=X,this._valueParser=G,this._dmkLoggerFactory=W}getExtendedPublicKey(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new QJ({input:{command:new t6(Q),appName:yJ,requiredUserInteraction:Q.checkOnDevice?k0.VerifyAddress:k0.None,skipOpenApp:Q.skipOpenApp},logger:this._dmkLoggerFactory("GetExtendedPublicKeyCommand")})})}getMasterFingerprint(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new QJ({input:{command:new e6,appName:yJ,requiredUserInteraction:k0.None,skipOpenApp:Q.skipOpenApp},logger:this._dmkLoggerFactory("GetMasterFingerprintCommand")})})}signMessage(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new nZ({input:{task:async(Z)=>new JI(Z,{derivationPath:Q.derivationPath,message:Q.message,loggerFactory:this._dmkLoggerFactory},this._dataStoreService).run(),appName:yJ,requiredUserInteraction:k0.SignPersonalMessage,skipOpenApp:Q.skipOpenApp},logger:this._dmkLoggerFactory("SendSignMessageTask")})})}signPsbt(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new GF({input:{psbt:Q.psbt,wallet:Q.wallet,walletBuilder:this._walletBuilder,walletSerializer:this._walletSerializer,dataStoreService:this._dataStoreService,psbtMapper:this._psbtMapper,valueParser:this._valueParser,skipOpenApp:Q.skipOpenApp},loggerFactory:this._dmkLoggerFactory})})}getWalletAddress(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new qI({input:{wallet:Q.wallet,skipOpenApp:Q.skipOpenApp,checkOnDevice:Q.checkOnDevice,change:Q.change,addressIndex:Q.addressIndex,walletBuilder:this._walletBuilder,walletSerializer:this._walletSerializer,dataStoreService:this._dataStoreService},loggerFactory:this._dmkLoggerFactory})})}signTransaction(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new QI({input:{psbt:Q.psbt,wallet:Q.wallet,walletBuilder:this._walletBuilder,walletSerializer:this._walletSerializer,dataStoreService:this._dataStoreService,psbtMapper:this._psbtMapper,valueParser:this._valueParser,skipOpenApp:Q.skipOpenApp},loggerFactory:this._dmkLoggerFactory})})}registerWallet(Q){return this._dmk.executeDeviceAction({sessionId:this._sessionId,deviceAction:new nZ({input:{task:async(Z)=>new YI(Z,{walletPolicy:Q.wallet,loggerFactory:this._dmkLoggerFactory},this._walletBuilder,this._walletSerializer,this._dataStoreService).run(),appName:yJ,requiredUserInteraction:k0.RegisterWallet,skipOpenApp:Q.skipOpenApp},logger:this._dmkLoggerFactory("RegisterWalletTask")})})}};var d_=w(()=>{I0();W0();bD();cD();iD();g_();b_();u_();bH();cH();GX();IW();m_();cK();gQ0=Object.defineProperty,hQ0=Object.getOwnPropertyDescriptor;uK=bQ0([e(),o8(0,g(y8.Dmk)),o8(1,g(y8.SessionId)),o8(2,g(f8.WalletBuilder)),o8(3,g(f8.WalletSerializer)),o8(4,g(DW.DataStoreService)),o8(5,g(sZ.PsbtMapper)),o8(6,g(sZ.ValueParser)),o8(7,g(y8.DmkLoggerFactory))],uK)});var n_=()=>new b0(({bind:Q})=>{Q($$.AppBinder).to(uK)});var o_=w(()=>{W0();d_();n1()});var s_=({dmk:Q,sessionId:Z})=>{let Y=new T$;return Y.bind(y8.Dmk).toConstantValue(Q),Y.bind(y8.SessionId).toConstantValue(Z),Y.bind(y8.DmkLoggerFactory).toConstantValue(($)=>Q.getLoggerFactory()(["SignerBtc",$])),Y.loadSync(n_(),G_(),z_(),aw(),uk(),vw()),Y};var i_=w(()=>{W0();pk();cH();xw();rw();X_();W_();o_()});class FI{_container;constructor({dmk:Q,sessionId:Z}){this._container=s_({dmk:Q,sessionId:Z})}getWalletAddress(Q,Z,Y){return this._container.get(Z$.GetWalletAddressUseCase).execute(Y?.checkOnDevice??!1,Q,Y?.change??!1,Z,Y?.skipOpenApp??!1)}signPsbt(Q,Z,Y){return this._container.get(Z$.SignPsbtUseCase).execute(Q,Z,Y?.skipOpenApp??!1)}getExtendedPublicKey(Q,Z){return this._container.get(Z$.GetExtendedPublicKeyUseCase).execute(Q,{checkOnDevice:Z?.checkOnDevice??!1,skipOpenApp:Z?.skipOpenApp??!1})}getMasterFingerprint(Q){return this._container.get(Z$.GetMasterFingerprintUseCase).execute({skipOpenApp:Q?.skipOpenApp??!1})}registerWallet(Q,Z){return this._container.get(Z$.RegisterWalletUseCase).execute(Q,Z?.skipOpenApp??!1)}signMessage(Q,Z,Y){return this._container.get(Z$.SignMessageUseCase).execute(Q,Z,Y?.skipOpenApp??!1)}signTransaction(Q,Z,Y){return this._container.get(Z$.SignTransactionUseCase).execute(Q,Z,Y?.skipOpenApp??!1)}}var a_=w(()=>{hH();i_()});class zI{_dmk;_sessionId;constructor({dmk:Q,sessionId:Z}){this._dmk=Q,this._sessionId=Z}build(){return new FI({dmk:this._dmk,sessionId:this._sessionId})}}var WI=w(()=>{a_()});var r_=w(()=>{WI();yK();GI();uD();aD();WI()});var pK={};j$(pK,{signTransactionDAStateSteps:()=>d8,signPsbtDAStateSteps:()=>s1,getWalletAddressDAStateSteps:()=>n8,WalletPolicy:()=>fD,SignerBtcBuilder:()=>zI,RegisteredWallet:()=>qX,DefaultWallet:()=>xD,DefaultDescriptorTemplate:()=>vD});var Fw0;var lK=w(()=>{Fw0=JZ(mJ(),1);r_()});var iQ0,bV,$v,cV=(Q)=>new $v(Q);var dK=w(()=>{I0();iQ0=((Q)=>(Q.EXECUTION_ERROR="0x6400",Q.EMPTY_BUFFER="0x6982",Q.OUTPUT_BUFFER_TOO_SMALL="0x6983",Q.COMMAND_NOT_ALLOWED="0x6986",Q.DATA_INVALID="0x6984",Q.TRANSACTION_DATA_EXCEEDS_BUFFER_CAPACITY="0x6988",Q.WRONG_HRP_LENGTH="0x698A",Q.INVALID_HD_PATH_COIN_VALUE="0x698B",Q.CHAIN_CONFIG_NOT_SUPPORTED="0x698C",Q.EXPERT_MODE_REQUIRED_FOR_ETH_CHAIN="0x698D",Q.INS_NOT_SUPPORTED="0x6D00",Q.CLA_NOT_SUPPORTED="0x6E00",Q.UNKNOWN_ERROR="0x6F00",Q))(iQ0||{}),bV={"0x6400":{message:"Execution Error"},"0x6982":{message:"Empty buffer"},"0x6983":{message:"Output buffer too small"},"0x6986":{message:"Command not allowed"},"0x6984":{message:"Data Invalid"},"0x6988":{message:"Transaction data exceeds buffer capacity"},"0x698A":{message:"Wrong HRP Length"},"0x698B":{message:"Invalid HD path coin value"},"0x698C":{message:"Chain Config not supported"},"0x698D":{message:"Expert Mode required for Eth chain"},"0x6D00":{message:"INS not supported"},"0x6E00":{message:"CLA not supported"},"0x6F00":{message:"Unknown error"}};$v=class $v extends DZ{constructor(Q){super({tag:"CosmosAppCommandError",...Q})}}});var nK=(Q)=>{let Z=new DataView(new ArrayBuffer(20));for(let Y=0;Y<Q.length;Y++){let $=Q[Y]&2147483647,J=Y<3?(2147483648|$)>>>0:$>>>0;Z.setUint32(Y*4,J,!0)}return new Uint8Array(Z.buffer)};var OI=()=>{};class HI{name="GetAddress";args;errorHelper=new s0(bV,cV);constructor(Q){this.args=Q}getApdu(){let Q=new w0(aQ0(this.args.checkOnDevice?rQ0:tQ0));Q.encodeInLVFromAscii(this.args.hrp);let Z=QZ.splitPath(this.args.derivationPath);if(Z.length!==eQ0)throw Error(`GetAddressCommand: expected cosmos style number of path elements, got ${Z.length}`);let Y=nK(Z);return Q.addBufferToData(Y),Q.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extractFieldByLength(33),$=Z.getUnparsedRemainingLength(),J=Z.extractFieldByLength($);if(Y===void 0||J===void 0)return o({error:new C0("Public key is missing")});let X=J.filter((W)=>W!==0),G=Z.encodeToString(X);return o({data:{publicKey:Y,address:G}})})}}var aQ0=(Q)=>({cla:85,ins:4,p1:Q,p2:0}),rQ0=1,tQ0=0,eQ0=5;var Jv=w(()=>{I0();IQ();R0();dK();OI()});class DI{name="GetAppConfig";errorHelper=new s0(bV,cV);getApdu(){return new w0(QZ0).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q);Z.extract8BitUInt();let Y=Z.extract8BitUInt(),$=Z.extract8BitUInt(),J=Z.extract8BitUInt();return Y===void 0||$===void 0||J===void 0?o({error:new C0("Cannot extract version")}):o({data:{major:Y,minor:$,patch:J}})})}}var QZ0;var Gv=w(()=>{I0();I0();IQ();R0();dK();QZ0={cla:85,ins:0,p1:0,p2:0}});var oK="Cosmos";var Xv=()=>{};class sK{name="SignTransaction";args;apduBuilder;errorHelper=new s0(bV,cV);constructor(Q){this.args=Q,this.apduBuilder=new w0(ZZ0(this.p1()))}getApdu(){return this.isFirstChunk()?this.firstChunk():this.nextChunk()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.getUnparsedRemainingLength(),$=Z.extractFieldByLength(Y);return o({data:$})})}p1(){switch(this.args.phase){case"init":return YZ0;case"add":return $Z0;case"last":return JZ0}}isFirstChunk(){return this.args.phase==="init"}firstChunk(){let{derivationPath:Q,hrp:Z}=this.args;if(!Q||!Z)throw Error("SignTransactionCommand: derivation path and human readable prefix are required for 'init' phase.");let Y=QZ.splitPath(Q);if(Y.length!==GZ0)throw Error(`SignTransactionCommand: expected cosmos style number of path elements, got ${Y.length}`);let $=nK(Y);return this.apduBuilder.addBufferToData($),this.apduBuilder.encodeInLVFromAscii(Z),this.apduBuilder.build()}nextChunk(){if(!this.args.transactionChunk)throw Error("SignTransactionCommand: transaction chunk is required for 'add' and 'last' phases.");return this.apduBuilder.addBufferToData(this.args.transactionChunk),this.apduBuilder.build()}}var ZZ0=(Q)=>({cla:85,ins:2,p1:Q,p2:0}),YZ0=0,$Z0=1,JZ0=2,GZ0=5,XF;var Vv=w(()=>{I0();IQ();R0();dK();OI();XF=((Q)=>(Q.INIT="init",Q.ADD="add",Q.LAST="last",Q))(XF||{})});class II{constructor(Q,Z,Y){this.api=Q,this.args=Z,this.logger=Y}async run(){this.logger.debug("[run] Starting SignTransactionTask",{data:{derivationPath:this.args.derivationPath,hrp:this.args.hrp,transactionLength:this.args.transaction.length}});let{derivationPath:Q,hrp:Z,transaction:Y}=this.args,$=await this.api.sendCommand(new sK({phase:XF.INIT,derivationPath:Q,hrp:Z}));if(!N0($))return this.logger.debug("[run] Failed to sign transaction",{data:{error:$.error}}),o({error:new C0("Failed to sign transaction")});for(let J=0;J<Y.length;J+=YZ){let X=J+YZ>=Y.length,G=X?XF.LAST:XF.ADD,W=Y.slice(J,J+YZ),U=await this.api.sendCommand(new sK({phase:G,transactionChunk:W}));if(!N0(U))return this.logger.debug("[run] Failed to sign transaction",{data:{chunkIndex:J,error:U.error}}),U;if(X)return this.logger.debug("[run] Transaction signed successfully",{data:{signature:U.data}}),o({data:U.data})}return o({error:new C0("No signature returned")})}}var qv=w(()=>{I0();Vv()});var i8;var RI=w(()=>{i8={Dmk:Symbol.for("Dmk"),SessionId:Symbol.for("SessionId"),DmkLoggerFactory:Symbol.for("DmkLoggerFactory")}});var XZ0,VZ0,qZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?VZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&XZ0(Z,Y,J),J},LI=(Q,Z)=>(Y,$)=>Z(Y,$,Q),iK=class{constructor(Q,Z,Y){this.dmk=Q,this.sessionId=Z,this.dmkLoggerFactory=Y}getAppConfig(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new QJ({input:{command:new DI,appName:oK,requiredUserInteraction:k0.None,skipOpenApp:Q.skipOpenApp},logger:this.dmkLoggerFactory("GetAppConfigCommand")})})}getAddress(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new QJ({input:{command:new HI(Q),appName:oK,requiredUserInteraction:Q.checkOnDevice?k0.VerifyAddress:k0.None,skipOpenApp:Q.skipOpenApp},logger:this.dmkLoggerFactory("GetAddressCommand")})})}signTransaction(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Z)=>new II(Z,Q,this.dmkLoggerFactory("SignTransactionTask")).run(),appName:oK,requiredUserInteraction:k0.SignTransaction,skipOpenApp:Q.skipOpenApp??!1},logger:this.dmkLoggerFactory("SignTransactionCommand")})})}};var Fv=w(()=>{I0();W0();Jv();Gv();Xv();qv();RI();XZ0=Object.defineProperty,VZ0=Object.getOwnPropertyDescriptor;iK=qZ0([e(),LI(0,g(i8.Dmk)),LI(1,g(i8.SessionId)),LI(2,g(i8.DmkLoggerFactory))],iK)});var a8;var VF=w(()=>{a8={AppBinding:Symbol.for("AppBinding")}});var zv=()=>new b0(({bind:Q})=>{Q(a8.AppBinding).to(iK)});var Wv=w(()=>{W0();Fv();VF()});var aK;var EI=w(()=>{aK={GetAddressUseCase:Symbol.for("GetAddressUseCase")}});var FZ0,zZ0,WZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?zZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&FZ0(Z,Y,J),J},KZ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),rK=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y){return this._appBinder.getAddress({derivationPath:Q,hrp:Z,checkOnDevice:Y?.checkOnDevice??!1,skipOpenApp:Y?.skipOpenApp??!1})}};var Kv=w(()=>{W0();VF();FZ0=Object.defineProperty,zZ0=Object.getOwnPropertyDescriptor;rK=WZ0([e(),KZ0(0,g(a8.AppBinding))],rK)});var Uv=()=>new b0(({bind:Q})=>{Q(aK.GetAddressUseCase).to(rK)});var Ov=w(()=>{W0();EI();Kv()});var tK;var PI=w(()=>{tK={GetAppConfigUseCase:Symbol.for("GetAppConfigUseCase")}});var UZ0,OZ0,HZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?OZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&UZ0(Z,Y,J),J},DZ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),eK=class{_appBinder;constructor(Q){this._appBinder=Q}execute(){return this._appBinder.getAppConfig({skipOpenApp:!1})}};var Hv=w(()=>{W0();VF();UZ0=Object.defineProperty,OZ0=Object.getOwnPropertyDescriptor;eK=HZ0([e(),DZ0(0,g(a8.AppBinding))],eK)});var Dv=()=>new b0(({bind:Q})=>{Q(tK.GetAppConfigUseCase).to(eK)});var Iv=w(()=>{W0();PI();Hv()});var QU;var jI=w(()=>{QU={SignTransactionUseCase:Symbol.for("SignTransactionUseCase")}});var IZ0,RZ0,LZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?RZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&IZ0(Z,Y,J),J},EZ0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),ZU=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y,$){return this._appBinder.signTransaction({derivationPath:Q,transaction:Y,hrp:Z,skipOpenApp:$?.skipOpenApp})}};var Rv=w(()=>{W0();VF();IZ0=Object.defineProperty,RZ0=Object.getOwnPropertyDescriptor;ZU=LZ0([e(),EZ0(0,g(a8.AppBinding))],ZU)});var Lv=()=>new b0(({bind:Q})=>{Q(QU.SignTransactionUseCase).to(ZU)});var Ev=w(()=>{W0();jI();Rv()});var Pv=({dmk:Q,sessionId:Z})=>{let Y=new T$;return Y.bind(i8.Dmk).toConstantValue(Q),Y.bind(i8.SessionId).toConstantValue(Z),Y.bind(i8.DmkLoggerFactory).toConstantValue(($)=>Q.getLoggerFactory()(["SignerCosmos",$])),Y.loadSync(zv(),Dv(),Uv(),Lv()),Y};var jv=w(()=>{W0();Wv();RI();Ov();Iv();Ev()});class AI{_container;constructor({dmk:Q,sessionId:Z}){this._container=Pv({dmk:Q,sessionId:Z})}getAppConfig(){return this._container.get(tK.GetAppConfigUseCase).execute()}getAddress(Q,Z,Y){return this._container.get(aK.GetAddressUseCase).execute(Q,Z,Y)}signTransaction(Q,Z,Y,$){return this._container.get(QU.SignTransactionUseCase).execute(Q,Z,Y,$)}}var Av=w(()=>{jv();EI();PI();jI()});class MI{_dmk;_sessionId;constructor({dmk:Q,sessionId:Z}){this._dmk=Q,this._sessionId=Z}build(){return new AI({dmk:this._dmk,sessionId:this._sessionId})}}var Mv=w(()=>{Av()});var Tv=w(()=>{Mv()});var Nv={};j$(Nv,{SignerCosmosBuilder:()=>MI});var s_0;var Bv=w(()=>{s_0=JZ(mJ(),1);Tv()});var i0;var SQ=w(()=>{i0={Config:Symbol.for("config"),OriginToken:Symbol.for("originToken"),ContextModuleLoggerFactory:Symbol.for("contextModuleLoggerFactory")}});var Cv=(Q)=>new b0(({bind:Z})=>{Z(i0.Config).toConstantValue(Q)});var Sv=w(()=>{W0();SQ()});var r8;var NI=w(()=>{r8=class r8 extends Error{kind;constructor(Q,Z){super(Z),this.name="AccountOwnershipError",this.kind=Q}}});var PQ;var OZ=w(()=>{PQ={NetworkClient:Symbol.for("networkClient")}});var jZ0,AZ0,MZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?AZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&jZ0(Z,Y,J),J},wv=(Q,Z)=>(Y,$)=>Z(Y,$,Q),qF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getDescriptor({publicKey:Q,address:Z,challenge:Y,network:$}){try{let J=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/concordium/owner/${Q}/${Z}`,{params:{challenge:Y,network:$}});return J?this.isAccountOwnershipDto(J)?U0({signedDescriptor:J.signedDescriptor,keyId:J.keyId,keyUsage:J.keyUsage}):a(new r8("service_unavailable","[ContextModule] HttpAccountOwnershipDataSource: invalid response format")):a(new r8("service_unavailable","[ContextModule] HttpAccountOwnershipDataSource: unexpected empty response"))}catch(J){return a(this.classifyError(J))}}classifyError(Q){if(this.hasNumericStatus(Q)){let Z=Q.status,Y=this.extractErrorMessage(Q);return this.classifyFromStatus(Z,Y)}return new r8("service_unavailable","[ContextModule] HttpAccountOwnershipDataSource: Failed to fetch account ownership descriptor")}classifyFromStatus(Q,Z){return Q>=400&&Q<500?new r8("verification_failed",Z):new r8("service_unavailable",`[ContextModule] HttpAccountOwnershipDataSource: backend ${Q}: ${Z}`)}hasNumericStatus(Q){return typeof Q=="object"&&Q!==null&&"status"in Q&&typeof Q.status=="number"}extractErrorMessage(Q){let Z=this.extractResponseBodyMessage(Q);return Z!==null?Z:typeof Q=="object"&&Q!==null&&("message"in Q)&&typeof Q.message=="string"&&Q.message.length>0?Q.message:typeof Q=="string"?Q:"Unknown error"}extractResponseBodyMessage(Q){if(typeof Q!="object"||Q===null||!("responseBody"in Q)||typeof Q.responseBody!="string")return null;let Z=Q.responseBody;if(Z.length===0)return null;try{let Y=JSON.parse(Z);if(typeof Y=="object"&&Y!==null&&"message"in Y&&typeof Y.message=="string"&&Y.message.length>0)return Y.message}catch{}return Z}isAccountOwnershipDto(Q){return typeof Q=="object"&&Q!==null&&"signedDescriptor"in Q&&"keyId"in Q&&"keyUsage"in Q&&typeof Q.signedDescriptor=="string"&&typeof Q.keyId=="string"&&typeof Q.keyUsage=="string"}};var BI=w(()=>{W0();R0();SQ();NI();OZ();jZ0=Object.defineProperty,AZ0=Object.getOwnPropertyDescriptor;qF=MZ0([e(),wv(0,g(i0.Config)),wv(1,g(PQ.NetworkClient))],qF)});var FX;var $U=w(()=>{FX={AccountOwnershipDataSource:Symbol.for("AccountOwnershipDataSource"),AccountOwnershipContextLoader:Symbol.for("AccountOwnershipContextLoader")}});var BQ;var RZ=w(()=>{BQ={PkiCertificateDataSource:Symbol.for("PkiCertificateDataSource"),PkiCertificateLoader:Symbol.for("PkiCertificateLoader")}});var u;var iQ=w(()=>{u=((Q)=>(Q.ERROR="error",Q.CONCORDIUM_ACCOUNT_OWNERSHIP="concordiumAccountOwnership",Q.ETHEREUM_TOKEN="ethereumToken",Q.ETHEREUM_NFT="ethereumNft",Q.ETHEREUM_TRUSTED_NAME="ethereumTrustedName",Q.ETHEREUM_PLUGIN="ethereumPlugin",Q.ETHEREUM_EXTERNAL_PLUGIN="ethereumExternalPlugin",Q.ETHEREUM_TRANSACTION_INFO="ethereumTransactionInfo",Q.ETHEREUM_PROXY_INFO="ethereumProxyInfo",Q.ETHEREUM_ENUM="ethereumEnum",Q.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION="ethereumTransactionFieldDescription",Q.ETHEREUM_TRANSACTION_CHECK="ethereumTransactionCheck",Q.ETHEREUM_DYNAMIC_NETWORK="ethereumDynamicNetwork",Q.ETHEREUM_DYNAMIC_NETWORK_ICON="ethereumDynamicNetworkIcon",Q.ETHEREUM_SAFE="ethereumSafe",Q.ETHEREUM_SIGNER="ethereumSigner",Q.ETHEREUM_GATED_SIGNING="ethereumGatedSigning",Q.SOLANA_TOKEN="solanaToken",Q.SOLANA_LIFI="solanaLifi",Q.SOLANA_TRUSTED_NAME="solanaTrustedName",Q.SOLANA_BASIC_TRUSTED_NAME="solanaBasicTrustedName",Q.SOLANA_TRANSACTION_CHECK="solanaTransactionCheck",Q.SOLANA_INSTRUCTION_INFO="solanaInstructionInfo",Q.SOLANA_ENUM_VARIANT="solanaEnumVariant",Q.SOLANA_TOKEN_INFO="solanaTokenInfo",Q.SOLANA_TOKEN_ACCOUNT_STATE="solanaTokenAccountState",Q.SOLANA_ALT_RESOLUTION="solanaAltResolution",Q.TRON_TOKEN="tronToken",Q))(u||{})});var TZ0,NZ0,BZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?NZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&TZ0(Z,Y,J),J},_v=(Q,Z)=>(Y,$)=>Z(Y,$,Q),kZ0,FF=class{constructor(Q,Z){this._dataSource=Q,this._certificateLoader=Z}canHandle(Q,Z){return kZ0.every((Y)=>Z.includes(Y))&&typeof Q=="object"&&Q!==null&&"publicKey"in Q&&typeof Q.publicKey=="string"&&Q.publicKey.length>0&&"address"in Q&&typeof Q.address=="string"&&Q.address.length>0&&"network"in Q&&(Q.network==="mainnet"||Q.network==="testnet")&&"deviceModelId"in Q&&Q.deviceModelId!==void 0&&"challenge"in Q&&typeof Q.challenge=="string"&&Q.challenge.length>0}async load({publicKey:Q,address:Z,network:Y,deviceModelId:$,challenge:J}){return(await this._dataSource.getDescriptor({publicKey:Q,address:Z,challenge:J,network:Y})).caseOf({Left:(X)=>Promise.resolve([{type:u.ERROR,error:X}]),Right:async(X)=>[{type:u.CONCORDIUM_ACCOUNT_OWNERSHIP,payload:X.signedDescriptor,certificate:await this._certificateLoader.loadCertificate({keyId:X.keyId,keyUsage:X.keyUsage,targetDevice:$})}]})}};var kI=w(()=>{W0();$U();RZ();iQ();TZ0=Object.defineProperty,NZ0=Object.getOwnPropertyDescriptor,kZ0=[u.CONCORDIUM_ACCOUNT_OWNERSHIP];FF=BZ0([e(),_v(0,g(FX.AccountOwnershipDataSource)),_v(1,g(BQ.PkiCertificateLoader))],FF)});var vv=()=>new b0(({bind:Q})=>{Q(FX.AccountOwnershipDataSource).to(qF),Q(FX.AccountOwnershipContextLoader).to(FF)});var xv=w(()=>{W0();BI();kI();$U()});function hJ(Q){return yv.has(Q.type)}var iZ,fv,yv;var CI=w(()=>{iQ();iZ=((Q)=>(Q[Q.TOKEN=u.ETHEREUM_TOKEN]="TOKEN",Q[Q.NFT=u.ETHEREUM_NFT]="NFT",Q[Q.TRUSTED_NAME=u.ETHEREUM_TRUSTED_NAME]="TRUSTED_NAME",Q[Q.ENUM=u.ETHEREUM_ENUM]="ENUM",Q.CALLDATA="calldata",Q))(iZ||{}),fv={TOKEN:u.ETHEREUM_TOKEN,NFT:u.ETHEREUM_NFT,TRUSTED_NAME:u.ETHEREUM_TRUSTED_NAME,PLUGIN:u.ETHEREUM_PLUGIN,EXTERNAL_PLUGIN:u.ETHEREUM_EXTERNAL_PLUGIN,TRANSACTION_INFO:u.ETHEREUM_TRANSACTION_INFO,PROXY_INFO:u.ETHEREUM_PROXY_INFO,ENUM:u.ETHEREUM_ENUM,TRANSACTION_FIELD_DESCRIPTION:u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION,TRANSACTION_CHECK:u.ETHEREUM_TRANSACTION_CHECK,DYNAMIC_NETWORK:u.ETHEREUM_DYNAMIC_NETWORK,DYNAMIC_NETWORK_ICON:u.ETHEREUM_DYNAMIC_NETWORK_ICON,SAFE:u.ETHEREUM_SAFE,SIGNER:u.ETHEREUM_SIGNER,GATED_SIGNING:u.ETHEREUM_GATED_SIGNING},yv=new Set(Object.values(fv))});var LZ;var h$=w(()=>{LZ=((Q)=>(Q.Test="test",Q.PersoV2="persov2",Q.LedgerRootV3="ledger_root_v3",Q.PluginSelectorKey="plugin_selector_key",Q.NftMetadataKey="nft_metadata_key",Q.TokenMetadataKey="token_metadata_key",Q.PartnerMetadataKey="partner_metadata_key",Q.Erc20MetadataKey="erc20_metadata_key",Q.DomainMetadataKey="domain_metadata_key",Q.CalCalldataKey="cal_calldata_key",Q.CalTrustedNameKey="cal_trusted_name_key",Q.CalNetwork="cal_network",Q.CalGatedSigning="cal_gated_signing",Q.SwapTemplateKey="swap_template_key",Q))(LZ||{})});var wQ;var jY=w(()=>{wQ=((Q)=>(Q.GenuineCheck="genuine_check",Q.ExchangePayload="exchange_payload",Q.NftMeta="nft_meta",Q.TrustedName="trusted_name",Q.BackupProvider="backup_provider",Q.ProtectOrchestrator="protect_orchestrator",Q.PluginMeta="plugin_meta",Q.CoinMeta="coin_meta",Q.SeedIdAuth="seed_id_auth",Q.TxSimulationSigner="tx_simu_signer",Q.Calldata="calldata",Q.Network="network",Q.LESMultisig="les_multisig",Q.GatedSigning="gated_signing",Q.SwapTemplate="swap_template",Q))(wQ||{})});var zX="15",SI="81ff";var zF=()=>{};class fY{static hexToBytes(Q){let Z=Q.startsWith("0x")||Q.startsWith("0X")?Q.slice(2):Q;if(Z.length===0)throw Error("HexStringUtils.hexToBytes: empty hex string");if(Z.length%2!==0)throw Error(`HexStringUtils.hexToBytes: odd-length hex string (${Z.length})`);if(!/^[0-9a-fA-F]+$/.test(Z))throw Error("HexStringUtils.hexToBytes: non-hex characters");let Y=new Uint8Array(Z.length/2);for(let $=0;$<Y.length;$++)Y[$]=Number.parseInt(Z.slice($*2,$*2+2),16);return Y}static stringToHex(Q){let Z="";for(let Y=0;Y<Q.length;Y++){let $=Q.charCodeAt(Y).toString(16);Z+=$.padStart(2,"0")}return Z}static appendSignatureToPayload(Q,Z,Y){Z.length%2!==0&&(Z="0"+Z);let $=(Z.length/2).toString(16);return $.length%2!==0&&($="0"+$),`${Q}${Y}${$}${Z}`}}var t8=()=>{};var CZ0,SZ0,wZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?SZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&CZ0(Z,Y,J),J},wI=(Q,Z)=>(Y,$)=>Z(Y,$,Q),uV=class{constructor(Q,Z,Y,$){this.config=Q,this._certificateLoader=Z,this.endpoint=Y,this.http=$}async getCalldataDescriptors({chainId:Q,address:Z,selector:Y,deviceModelId:$}){let J;try{J=await this.http.get(`${this.config.cal.url}/${this.endpoint}`,{params:{output:"descriptors_calldata",chain_id:Q,contracts:Z,contract_address:Z,ref:`branch:${this.config.cal.branch}`}})}catch(X){return a(Error(`[ContextModule] HttpCalldataDescriptorDataSource: Failed to fetch calldata descriptors: ${X}`))}if(!Array.isArray(J))return a(Error("[ContextModule] HttpCalldataDescriptorDataSource: Response is not an array"));if(J.length===0)return a(Error(`[ContextModule] HttpCalldataDescriptorDataSource: No data for contract ${Z} and selector ${Y}`));for(let X of J){Z=Z.toLowerCase(),Y=`0x${Y.slice(2).toLowerCase()}`;let G=X.descriptors_calldata?.[Z]?.[Y];if(!G||!this.isCalldataDescriptorV1(G,this.config.cal.mode))continue;let W=G.transaction_info.descriptor.data,U=G.transaction_info.descriptor.signatures[this.config.cal.mode],K={targetDevice:$,keyUsage:wQ.Calldata,keyId:LZ.CalCalldataKey},O=await this._certificateLoader.loadCertificate(K),I={type:u.ETHEREUM_TRANSACTION_INFO,payload:fY.appendSignatureToPayload(W,U,SI),certificate:O},L=[];for(let[M,k]of Object.entries(G.enums))for(let[B,{data:C,signatures:S}]of Object.entries(k))L.push({type:u.ETHEREUM_ENUM,id:Number(M),value:Number(B),payload:fY.appendSignatureToPayload(C,S[this.config.cal.mode],SI),certificate:O});let A=G.fields.map((M)=>({type:u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION,payload:M.descriptor,reference:this.getReference(M.param)}));return U0([I,...L,...A])}return a(Error(`[ContextModule] HttpCalldataDescriptorDataSource: Invalid response for contract ${Z} and selector ${Y}`))}getReference(Q){if(Q.type==="TOKEN_AMOUNT"&&Q.token!==void 0&&Q.token.type==="path")return{type:iZ.TOKEN,valuePath:this.toGenericPath(Q.token.binary_path)};if(Q.type==="TOKEN_AMOUNT"&&Q.token!==void 0&&Q.token.type==="constant")return{type:iZ.TOKEN,value:Q.token.value};if(Q.type==="NFT"&&Q.collection.type==="path")return{type:iZ.NFT,valuePath:this.toGenericPath(Q.collection.binary_path)};if(Q.type==="NFT"&&Q.collection.type==="constant")return{type:iZ.NFT,value:Q.collection.value};if(Q.type==="TRUSTED_NAME"&&Q.value.type==="path")return{type:iZ.TRUSTED_NAME,valuePath:this.toGenericPath(Q.value.binary_path),types:Q.types,sources:Q.sources};if(Q.type==="ENUM"&&Q.value.type==="path")return{type:iZ.ENUM,valuePath:this.toGenericPath(Q.value.binary_path),id:Q.id};if(Q.type==="CALLDATA"&&Q.value.type==="path"&&Q.callee.type==="path")return{type:iZ.CALLDATA,valuePath:this.toGenericPath(Q.value.binary_path),callee:this.toGenericPath(Q.callee.binary_path),selector:Q.selector?.type==="path"?this.toGenericPath(Q.selector.binary_path):void 0,amount:Q.amount?.type==="path"?this.toGenericPath(Q.amount.binary_path):void 0,spender:Q.spender?.type==="path"?this.toGenericPath(Q.spender.binary_path):void 0,chainId:Q.chainId?.type==="path"?this.toGenericPath(Q.chainId.binary_path):void 0}}toGenericPath(Q){return Q.type==="CONTAINER"?Q.value:Q.elements.map((Z)=>{if(Z.type==="ARRAY"){let{weight:Y,...$}=Z;return{itemSize:Y,...$}}else if(Z.type==="LEAF"){let{leaf_type:Y,...$}=Z;return{leafType:Y,...$}}return Z})}isCalldataDescriptorV1(Q,Z){return typeof Q=="object"&&Q.type==="calldata"&&Q.version==="v1"&&this.isTransactionInfoV1(Q.transaction_info,Z)&&this.isEnumV1(Q.enums,Z)&&Array.isArray(Q.fields)&&Q.fields.every((Y)=>this.isFieldV1(Y))}isTransactionInfoV1(Q,Z){return typeof Q=="object"&&typeof Q.descriptor=="object"&&typeof Q.descriptor.data=="string"&&typeof Q.descriptor.signatures=="object"&&typeof Q.descriptor.signatures[Z]=="string"}isEnumV1(Q,Z){return typeof Q=="object"&&Object.entries(Q).every(([Y,$])=>typeof Y=="string"&&typeof $=="object"&&Object.entries($).every(([J,X])=>typeof J=="string"&&typeof X=="object"&&typeof X.data=="string"&&X.signatures!==void 0&&this.isCalldataSignatures(X.signatures,Z)))}isCalldataSignatures(Q,Z){return typeof Q=="object"&&typeof Q[Z]=="string"}isFieldV1(Q){return typeof Q=="object"&&typeof Q.descriptor=="string"&&typeof Q.param=="object"&&typeof Q.param.value=="object"&&this.isDescriptorValueV1(Q.param.value)&&(Q.param.type==="RAW"||Q.param.type==="AMOUNT"||Q.param.type==="DATETIME"||Q.param.type==="DURATION"||Q.param.type==="UNIT"||Q.param.type==="ENUM"||Q.param.type==="NFT"&&this.isDescriptorValueV1(Q.param.collection)||Q.param.type==="TOKEN_AMOUNT"&&(Q.param.token===void 0||this.isDescriptorValueV1(Q.param.token))||Q.param.type==="TRUSTED_NAME"&&Array.isArray(Q.param.types)&&Array.isArray(Q.param.sources)&&Q.param.types.every((Z)=>typeof Z=="string")&&Q.param.sources.every((Z)=>typeof Z=="string")||Q.param.type==="CALLDATA"&&this.isDescriptorValueV1(Q.param.value)&&this.isDescriptorValueV1(Q.param.callee)&&(Q.param.selector===void 0||this.isDescriptorValueV1(Q.param.selector))&&(Q.param.amount===void 0||this.isDescriptorValueV1(Q.param.amount))&&(Q.param.spender===void 0||this.isDescriptorValueV1(Q.param.spender))&&(Q.param.chainId===void 0||this.isDescriptorValueV1(Q.param.chainId)))}isDescriptorValueV1(Q){return typeof Q=="object"&&typeof Q.type_family=="string"&&["UINT","INT","UFIXED","FIXED","ADDRESS","BOOL","BYTES","STRING"].includes(Q.type_family)&&(typeof Q.type_size>"u"||typeof Q.type_size=="number")&&(Q.type==="path"&&this.isCalldataDescriptorValueBinaryPathV1(Q)||Q.type==="constant"&&this.isCalldataDescriptorValueConstantV1(Q))}isCalldataDescriptorValueConstantV1(Q){return typeof Q=="object"&&Q.type==="constant"&&typeof Q.value=="string"}isCalldataDescriptorValueBinaryPathV1(Q){return typeof Q=="object"&&(Q.type==="path"&&Q.binary_path.type==="CONTAINER"&&["FROM","TO","VALUE"].includes(Q.binary_path.value)||Q.binary_path.type==="DATA"&&Array.isArray(Q.binary_path.elements)&&Q.binary_path.elements.every((Z)=>this.isPathElementV1(Z)))}isPathElementV1(Q){return typeof Q=="object"&&(Q.type==="REF"||Q.type==="TUPLE"&&typeof Q.offset=="number"||Q.type==="ARRAY"&&typeof Q.weight=="number"&&(typeof Q.start>"u"||typeof Q.start=="number")&&(typeof Q.end>"u"||typeof Q.end=="number")||Q.type==="LEAF"&&typeof Q.leaf_type=="string"&&["ARRAY_LEAF","TUPLE_LEAF","STATIC_LEAF","DYNAMIC_LEAF"].includes(Q.leaf_type)||Q.type==="SLICE"&&(typeof Q.start>"u"||typeof Q.start=="number")&&(typeof Q.end>"u"||typeof Q.end=="number"))}};var _I=w(()=>{W0();R0();SQ();CI();RZ();h$();jY();iQ();zF();OZ();t8();CZ0=Object.defineProperty,SZ0=Object.getOwnPropertyDescriptor;uV=wZ0([e(),wI(0,g(i0.Config)),wI(1,g(BQ.PkiCertificateLoader)),wI(3,g(PQ.NetworkClient))],uV)});var r1;var JU=w(()=>{r1={CalldataContextLoader:Symbol.for("CalldataContextLoader"),DappCalldataDescriptorDataSource:Symbol.for("DappCalldataDescriptorDataSource"),TokenCalldataDescriptorDataSource:Symbol.for("TokenCalldataDescriptorDataSource")}});var J$;var e8=w(()=>{J$={ProxyDataSource:Symbol.for("ProxyDataSource"),ProxyContextFieldLoader:Symbol.for("ProxyContextFieldLoader")}});var _Z0,vZ0,xZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?vZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&_Z0(Z,Y,J),J},GU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),fZ0,WF=class{constructor(Q,Z,Y,$){this.dappDataSource=Q,this.tokenDataSource=Z,this.proxyDataSource=Y,this.logger=$("CalldataContextLoader")}logger;canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"to"in Q&&"data"in Q&&"selector"in Q&&"chainId"in Q&&"deviceModelId"in Q&&Q.deviceModelId!==void 0&&Q.deviceModelId!==JQ.NANO_S&&typeof Q.chainId=="number"&&dQ(Q.to)&&Q.to!=="0x"&&dQ(Q.data)&&dQ(Q.selector)&&Q.selector!=="0x"&&fZ0.every((Y)=>Z.includes(Y))}async load(Q){let{to:Z,data:Y,selector:$,chainId:J,deviceModelId:X}=Q,G={address:Z,chainId:J,selector:$,deviceModelId:X,data:Y},W=(await this._getContexts(G,this.dappDataSource).alt(this._getContexts(G,this.tokenDataSource)).alt(this._getContextsWithProxy(G,this.dappDataSource)).run()).caseOf({Just:(U)=>U,Nothing:()=>[{type:u.ERROR,error:Error("[ContextModule] CalldataContextLoader: No calldata contexts found")}]});return this.logger.debug("load result",{data:{result:W}}),W}_getContexts({address:Q,chainId:Z,selector:Y,deviceModelId:$},J){return QY(async({liftMaybe:X})=>{let G=await J.getCalldataDescriptors({deviceModelId:$,address:Q,chainId:Z,selector:Y});return X(G.toMaybe().filter((W)=>W.length>0))})}_getContextsWithProxy({address:Q,chainId:Z,selector:Y,deviceModelId:$,data:J},X){return QY(async({liftMaybe:G})=>{let W=await this.proxyDataSource.getProxyImplementationAddress({calldata:J,proxyAddress:Q,chainId:Z,challenge:""});return G(W.toMaybe())}).map(({implementationAddress:G})=>{let W={address:G,chainId:Z,selector:Y,deviceModelId:$,data:J};return this._getContexts(W,X).map((U)=>[{type:u.ETHEREUM_PROXY_INFO,payload:"0x"},...U])}).join()}};var vI=w(()=>{I0();W0();R0();SQ();JU();e8();iQ();_Z0=Object.defineProperty,vZ0=Object.getOwnPropertyDescriptor,fZ0=[u.ETHEREUM_TRANSACTION_INFO,u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION,u.ETHEREUM_PROXY_INFO,u.ETHEREUM_ENUM];WF=xZ0([e(),GU(0,g(r1.DappCalldataDescriptorDataSource)),GU(1,g(r1.TokenCalldataDescriptorDataSource)),GU(2,g(J$.ProxyDataSource)),GU(3,g(i0.ContextModuleLoggerFactory))],WF)});var gv=()=>new b0(({bind:Q})=>{Q(r1.DappCalldataDescriptorDataSource).toDynamicValue((Z)=>new uV(Z.get(i0.Config),Z.get(BQ.PkiCertificateLoader),"dapps",Z.get(PQ.NetworkClient))),Q(r1.TokenCalldataDescriptorDataSource).toDynamicValue((Z)=>new uV(Z.get(i0.Config),Z.get(BQ.PkiCertificateLoader),"tokens",Z.get(PQ.NetworkClient))),Q(r1.CalldataContextLoader).to(WF)});var hv=w(()=>{W0();SQ();_I();JU();vI();RZ();OZ()});var yZ0,gZ0,hZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?gZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&yZ0(Z,Y,J),J},bv=(Q,Z)=>(Y,$)=>Z(Y,$,Q),bZ0,KF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getDynamicNetworkConfiguration(Q){let Z;try{Z=await this.http.get(`${this.config.cal.url}/networks`,{params:{output:"id,descriptors,icons",chain_id:Q}})}catch(J){return a(J instanceof Error?Error(J.message):Error("Failed to fetch network configuration"))}let Y=Z?.[0];if(!Y)return a(Error(`Network configuration not found for chain ID: ${Q}`));if(!this.isValidNetworkData(Y))return a(Error(`Invalid network configuration response for chain ID: ${Q}`));let $=this.transformToNetworkConfiguration(Y);return U0($)}isValidNetworkData(Q){if(!Q||typeof Q!="object")return!1;let Z=Q;if(typeof Z.id!="string"||!Z.descriptors||typeof Z.descriptors!="object")return!1;for(let Y of Object.values(Z.descriptors))if(!this.isValidDescriptor(Y))return!1;return!(Z.icons&&typeof Z.icons!="object")}isValidDescriptor(Q){if(!Q||typeof Q!="object")return!1;let Z=Q;if(typeof Z.data!="string"||typeof Z.descriptorType!="string"||typeof Z.descriptorVersion!="string"||!Z.signatures||typeof Z.signatures!="object")return!1;let Y=Z.signatures;return!(typeof Y.prod!="string"||typeof Y.test!="string")}transformToNetworkConfiguration(Q){let Z=Object.entries(Q.descriptors).reduce((Y,[$,J])=>{let X=bZ0[$.toLowerCase()];return X===void 0||(Y[X]={descriptorType:J.descriptorType,descriptorVersion:J.descriptorVersion,data:J.data,signatures:J.signatures,icon:Q.icons?.[$]}),Y},{});return{id:Q.id,descriptors:Z}}};var xI=w(()=>{I0();W0();R0();SQ();OZ();yZ0=Object.defineProperty,gZ0=Object.getOwnPropertyDescriptor,bZ0={nanos:JQ.NANO_S,nanosp:JQ.NANO_SP,nanox:JQ.NANO_X,stax:JQ.STAX,flex:JQ.FLEX,apexp:JQ.APEX};KF=hZ0([e(),bv(0,g(i0.Config)),bv(1,g(PQ.NetworkClient))],KF)});var WX;var XU=w(()=>{WX={DynamicNetworkDataSource:Symbol("DynamicNetworkDataSource"),DynamicNetworkContextLoader:Symbol("DynamicNetworkContextLoader")}});var cZ0,uZ0,pZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?uZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&cZ0(Z,Y,J),J},VU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),lZ0="15",qU,UF=class{_networkDataSource;_config;_certificateLoader;logger;constructor(Q,Z,Y,$){this._networkDataSource=Q,this._config=Z,this._certificateLoader=Y,this.logger=$("DynamicNetworkContextLoader")}canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"chainId"in Q&&"deviceModelId"in Q&&Q.deviceModelId!==void 0&&Q.deviceModelId!==JQ.NANO_S&&typeof Q.chainId=="number"&&qU.every((Y)=>Z.includes(Y))}async load(Q){let{chainId:Z,deviceModelId:Y}=Q,$=await this._networkDataSource.getDynamicNetworkConfiguration(Z),J=await this._certificateLoader.loadCertificate({keyId:LZ.CalNetwork,keyUsage:wQ.Network,targetDevice:Y}),X=$.caseOf({Left:()=>[],Right:(G)=>{let W=[],U=G.descriptors[Y];if(!U)return[];let K=U.signatures[this._config.cal.mode];if(!K)return[];let O=fY.appendSignatureToPayload(U.data,K,lZ0);return W.push({type:u.ETHEREUM_DYNAMIC_NETWORK,payload:O,certificate:J}),U.icon&&W.push({type:u.ETHEREUM_DYNAMIC_NETWORK_ICON,payload:U.icon}),W}});return this.logger.debug("load result",{data:{result:X}}),X}};var fI=w(()=>{I0();W0();SQ();XU();RZ();h$();jY();iQ();t8();cZ0=Object.defineProperty,uZ0=Object.getOwnPropertyDescriptor,qU=[u.ETHEREUM_DYNAMIC_NETWORK,u.ETHEREUM_DYNAMIC_NETWORK_ICON];UF=pZ0([e(),VU(0,g(WX.DynamicNetworkDataSource)),VU(1,g(i0.Config)),VU(2,g(BQ.PkiCertificateLoader)),VU(3,g(i0.ContextModuleLoggerFactory))],UF)});var cv=()=>new b0(({bind:Q})=>{Q(WX.DynamicNetworkDataSource).to(KF),Q(WX.DynamicNetworkContextLoader).to(UF)});var uv=w(()=>{W0();xI();fI();XU()});var mZ0,dZ0,nZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?dZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&mZ0(Z,Y,J),J},pv=(Q,Z)=>(Y,$)=>Z(Y,$,Q),OF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getDappInfos({chainId:Q,address:Z,selector:Y}){try{let $=await this.http.get(`${this.config.cal.url}/dapps`,{params:{output:"b2c,b2c_signatures,abis",chain_id:Q,contracts:Z}});if(!$[0])return U0(void 0);Z=Z.toLowerCase(),Y=`0x${Y.slice(2).toLowerCase()}`;let{erc20OfInterest:J,method:X,plugin:G}=$[0].b2c?.contracts?.find((O)=>O.address===Z)?.selectors?.[Y]||{},{signature:W,serialized_data:U}=$[0].b2c_signatures?.[Z]?.[Y]||{};if(!J||!X||!G||!W||!U)return U0(void 0);let K=$[0].abis?.[Z];return K?U0({selectorDetails:{method:X,plugin:G,erc20OfInterest:J,signature:W,serializedData:U},abi:K}):U0(void 0)}catch{return a(Error("[ContextModule] HttpExternalPluginDataSource: Error fetching dapp infos"))}}};var yI=w(()=>{W0();R0();SQ();OZ();mZ0=Object.defineProperty,dZ0=Object.getOwnPropertyDescriptor;OF=nZ0([e(),pv(0,g(i0.Config)),pv(1,g(PQ.NetworkClient))],OF)});var KX;var FU=w(()=>{KX={ExternalPluginDataSource:Symbol.for("ExternalPluginDataSource"),ExternalPluginContextLoader:Symbol.for("ExternalPluginContextLoader")}});var lY;var QG=w(()=>{lY={TokenDataSource:Symbol.for("TokenDataSource"),TokenContextLoader:Symbol.for("TokenContextLoader"),TokenContextFieldLoader:Symbol.for("TokenContextFieldLoader")}});var q1;var HF=w(()=>{q1={AbiDecoderDataSource:Symbol.for("AbiDecoderDataSource"),CommandDecoderDataSource:Symbol.for("CommandDecoderDataSource"),UniswapContextLoader:Symbol.for("UniswapContextLoader")}});var lv,oZ0,sZ0,iZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?sZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&oZ0(Z,Y,J),J},zU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),aZ0,DF=class{constructor(Q,Z,Y,$){this._externalPluginDataSource=Q,this._tokenDataSource=Z,this._uniswapLoader=Y,this._customPluginLoaders={Uniswap:this._uniswapLoader},this.logger=$("ExternalPluginContextLoader")}_customPluginLoaders;logger;canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"to"in Q&&"data"in Q&&"selector"in Q&&"chainId"in Q&&typeof Q.chainId=="number"&&dQ(Q.to)&&Q.to!=="0x"&&dQ(Q.data)&&Q.data!=="0x"&&dQ(Q.selector)&&Q.selector!=="0x"&&aZ0.every((Y)=>Z.includes(Y))}async load(Q){let{to:Z,data:Y,selector:$,chainId:J}=Q,X=await this._externalPluginDataSource.getDappInfos({address:Z,chainId:J,selector:$}),G=await EQ(async({liftEither:W})=>{let U=await W(X);if(!U)return[];let K={type:u.ETHEREUM_EXTERNAL_PLUGIN,payload:U.selectorDetails.serializedData.concat(U.selectorDetails.signature)},O=this._customPluginLoaders[U.selectorDetails.plugin];if(O!==void 0&&O.canHandle(Q,[u.ETHEREUM_TOKEN])){let M=await O.load(Q);return[K,...M]}let I=this.getDecodedCallData(U.abi,U.selectorDetails.method,Y);if(I.isLeft())return[{type:u.ERROR,error:I.extract()},K];let L=I.extract(),A=U.selectorDetails.erc20OfInterest.map(async(M)=>this.getTokenPayload(Q,M,L));return[...(await Promise.all(A)).map((M)=>M.caseOf({Left:(k)=>({type:u.ERROR,error:k}),Right:(k)=>({type:u.ETHEREUM_TOKEN,payload:k})})),K]}).caseOf({Left:(W)=>[{type:u.ERROR,error:W}],Right:(W)=>W});return this.logger.debug("load result",{data:{result:G}}),G}getTokenPayload(Q,Z,Y){let $=this.getAddressFromPath(Z,Y);return EQ(({fromPromise:J})=>J(this._tokenDataSource.getTokenInfosPayload({address:$,chainId:Q.chainId})))}getDecodedCallData(Q,Z,Y){try{let $=new lv.Interface(Q);return U0($.decodeFunctionData(Z,Y))}catch{return a(Error("[ContextModule] ExternalPluginContextLoader: Unable to parse abi"))}}getAddressFromPath(Q,Z){let Y=Z;for(let $ of Q.split("."))$==="-1"?Y=Y[Y.length-1]:Y=Y[$];if(!dQ(Y))throw Error("[ContextModule] ExternalPluginContextLoader: Unable to get address");return Y}};var gI=w(()=>{I0();W0();R0();SQ();FU();QG();HF();iQ();lv=require("ethers"),oZ0=Object.defineProperty,sZ0=Object.getOwnPropertyDescriptor,aZ0=[u.ETHEREUM_EXTERNAL_PLUGIN,u.ETHEREUM_TOKEN];DF=iZ0([e(),zU(0,g(KX.ExternalPluginDataSource)),zU(1,g(lY.TokenDataSource)),zU(2,g(q1.UniswapContextLoader)),zU(3,g(i0.ContextModuleLoggerFactory))],DF)});var mv=()=>new b0(({bind:Q})=>{Q(KX.ExternalPluginDataSource).to(OF),Q(KX.ExternalPluginContextLoader).to(DF)});var dv=w(()=>{W0();yI();FU();gI()});var rZ0,tZ0,eZ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?tZ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&rZ0(Z,Y,J),J},nv=(Q,Z)=>(Y,$)=>Z(Y,$,Q),IF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getGatedDescriptor({contractAddress:Q,selector:Z,chainId:Y}){let $;try{$=await this.http.get(`${this.config.cal.url}/gated_dapps`,{params:{ref:`branch:${this.config.cal.branch}`,output:"gated_descriptors,app,category",contracts:Q,chain_id:Y}})}catch(W){return a(Error(`[ContextModule] HttpGatedDescriptorDataSource: Failed to fetch gated descriptors: ${W}`))}if(!this.isGatedDappsDto($))return a(Error("[ContextModule] HttpGatedDescriptorDataSource: Invalid gated descriptors response"));let J=Q.toLowerCase(),X=Z.startsWith("0x")?Z.slice(2).toLowerCase():Z.toLowerCase(),G=`0x${X}`;for(let W of $){let U=W.gated_descriptors?.[J];if(!U)continue;let K=U[X]??U[G]??U[Z];if(K?.descriptor)return U0({signedDescriptor:fY.appendSignatureToPayload(K.descriptor,K.signatures[this.config.cal.mode],zX)})}return a(Error(`[ContextModule] HttpGatedDescriptorDataSource: No gated descriptor for contract ${Q} and selector ${Z}`))}async getGatedDescriptorForTypedData({contractAddress:Q,schemaHash:Z,chainId:Y}){let $;try{$=await this.http.get(`${this.config.cal.url}/gated_dapps`,{params:{ref:`branch:${this.config.cal.branch}`,output:"gated_descriptors",contracts:Q,chain_id:Y}})}catch(G){return a(Error(`[ContextModule] HttpGatedDescriptorDataSource: Failed to fetch gated descriptors: ${G}`))}if(!this.isGatedDappsDto($))return a(Error("[ContextModule] HttpGatedDescriptorDataSource: Invalid gated descriptors response"));let J=Q.toLowerCase(),X=Z.toLowerCase();for(let G of $){let W=G.gated_descriptors?.[J];if(!W)continue;let U=W[X];if(U?.descriptor)return U0({signedDescriptor:fY.appendSignatureToPayload(U.descriptor,U.signatures[this.config.cal.mode],zX)})}return a(Error(`[ContextModule] HttpGatedDescriptorDataSource: No gated descriptor for contract ${Q} and schema hash ${Z}`))}isGatedDappsDto(Q){if(!Array.isArray(Q)||Q.length===0)return!1;for(let Z of Q)if(!this.isGatedDappsResponseItemDto(Z))return!1;return!0}isGatedDappsResponseItemDto(Q){if(!Q||typeof Q!="object")return!1;let Z=Q;if(!Z.gated_descriptors||typeof Z.gated_descriptors!="object")return!1;let Y=Z.gated_descriptors;for(let $ of Object.values(Y)){if(typeof $!="object"||$===null)return!1;for(let J of Object.values($))if(!this.isGatedDescriptorEntryDto(J))return!1}return!0}isGatedDescriptorEntryDto(Q){if(!Q||typeof Q!="object")return!1;let Z=Q;if(typeof Z.network!="string"||typeof Z.chain_id!="number"||typeof Z.address!="string"||typeof Z.selector!="string"||typeof Z.version!="string"||typeof Z.descriptor!="string")return!1;if(Z.signatures!==void 0){if(typeof Z.signatures!="object"||Z.signatures===null)return!1;let Y=Z.signatures;for(let $ of Object.values(Y))if(typeof $!="string")return!1}return!0}};var hI=w(()=>{W0();R0();SQ();zF();OZ();t8();rZ0=Object.defineProperty,tZ0=Object.getOwnPropertyDescriptor;IF=eZ0([e(),nv(0,g(i0.Config)),nv(1,g(PQ.NetworkClient))],IF)});var bJ;var RF=w(()=>{bJ={GatedDescriptorDataSource:Symbol.for("GatedDescriptorDataSource"),GatedSigningContextLoader:Symbol.for("GatedSigningContextLoader"),GatedSigningTypedDataContextLoader:Symbol.for("GatedSigningTypedDataContextLoader")}});function JY0(Q){let Z=Q.toLowerCase();return Z.startsWith("0x")?Z:`0x${Z}`}var QY0,ZY0,YY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?ZY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&QY0(Z,Y,J),J},WU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),$Y0,LF=class{constructor(Q,Z,Y,$){this._dataSource=Q,this._certificateLoader=Z,this._proxyDataSource=Y,this.logger=$("GatedSigningContextLoader")}logger;canHandle(Q,Z){return $Y0.every((Y)=>Z.includes(Y))&&typeof Q=="object"&&Q!==null&&"to"in Q&&dQ(Q.to)&&Q.to!=="0x"&&"selector"in Q&&dQ(Q.selector)&&"chainId"in Q&&typeof Q.chainId=="number"&&"deviceModelId"in Q&&Q.deviceModelId!==void 0}async load({to:Q,selector:Z,chainId:Y,deviceModelId:$}){let J=await this._dataSource.getGatedDescriptor({contractAddress:Q,selector:Z,chainId:Y});if(J.isRight()){let{signedDescriptor:M}=J.unsafeCoerce(),k=await this._loadGatedCertificate($);return this.logger.debug("load result",{data:{path:"direct",to:Q,selector:Z,chainId:Y,contextTypes:[u.ETHEREUM_GATED_SIGNING]}}),[{type:u.ETHEREUM_GATED_SIGNING,payload:M,certificate:k}]}let X=J.extract(),G={type:u.ERROR,error:X},W=await this._proxyDataSource.getProxyImplementationAddress({proxyAddress:Q,chainId:Y,challenge:"",calldata:"0x"});if(W.isLeft()){let M=W.extract();return this.logger.warn("No gated descriptor found and proxy resolution failed",{data:{to:Q,selector:Z,chainId:Y,directError:X.message,proxyError:M.message}}),[G]}let U=W.unsafeCoerce(),K=JY0(U.implementationAddress),O=await this._dataSource.getGatedDescriptor({contractAddress:K,selector:Z,chainId:Y});if(O.isLeft()){let M=O.extract();return this.logger.warn("No gated descriptor found for proxy implementation address",{data:{to:Q,implementationAddress:K,selector:Z,chainId:Y,directError:X.message,implError:M.message}}),[G]}let{signedDescriptor:I}=O.unsafeCoerce(),[L,A]=await Promise.all([this._certificateLoader.loadCertificate({keyId:U.keyId,keyUsage:U.keyUsage,targetDevice:$}),this._loadGatedCertificate($)]);return this.logger.debug("load result",{data:{path:"proxy",to:Q,implementationAddress:K,selector:Z,chainId:Y,contextTypes:[u.ETHEREUM_PROXY_INFO,u.ETHEREUM_GATED_SIGNING]}}),[{type:u.ETHEREUM_PROXY_INFO,payload:U.signedDescriptor,certificate:L},{type:u.ETHEREUM_GATED_SIGNING,payload:I,certificate:A}]}_loadGatedCertificate(Q){return this._certificateLoader.loadCertificate({keyId:LZ.CalGatedSigning,keyUsage:wQ.GatedSigning,targetDevice:Q})}};var bI=w(()=>{I0();W0();SQ();RF();e8();RZ();h$();jY();iQ();QY0=Object.defineProperty,ZY0=Object.getOwnPropertyDescriptor,$Y0=[u.ETHEREUM_GATED_SIGNING];LF=YY0([e(),WU(0,g(bJ.GatedDescriptorDataSource)),WU(1,g(BQ.PkiCertificateLoader)),WU(2,g(J$.ProxyDataSource)),WU(3,g(i0.ContextModuleLoggerFactory))],LF)});function GY0(Q){return Object.fromEntries(Object.entries(Q).sort(([Z],[Y])=>Z.localeCompare(Y)).map(([Z,Y])=>[Z,Y.map(($)=>({name:$.name,type:$.type}))]))}function EF(Q){let Z=GY0(Q),Y=JSON.stringify(Z);return ov.default(Y).toString()}var ov;var KU=w(()=>{ov=JZ(ND(),1)});function WY0(Q){if(!Q||typeof Q!="object")return!1;let Z=Q;if(!Z.types||typeof Z.types!="object"||Array.isArray(Z.types))return!1;let Y=Z.types;for(let $ of Object.keys(Y)){if(typeof $!="string")return!1;let J=Y[$];if(!Array.isArray(J))return!1;for(let X of J)if(!X||typeof X!="object"||typeof X.name!="string"||typeof X.type!="string")return!1}return!0}var XY0,VY0,qY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?VY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&XY0(Z,Y,J),J},UU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),FY0="0x0000000000000000000000000000000000000000",zY0,PF=class{constructor(Q,Z,Y,$){this._dataSource=Q,this._certificateLoader=Z,this._proxyDataSource=Y,this.logger=$("GatedSigningTypedDataContextLoader")}logger;canHandle(Q,Z){return zY0.every((Y)=>Z.includes(Y))&&typeof Q=="object"&&Q!==null&&"data"in Q&&WY0(Q.data)&&"chainId"in Q&&"deviceModelId"in Q&&Q.deviceModelId!==void 0&&"challenge"in Q&&typeof Q.challenge=="string"}async load({data:Q,chainId:Z,deviceModelId:Y,challenge:$}){let J=Q.domain?.verifyingContract?.toLowerCase()??FY0,X=J.startsWith("0x")?J:`0x${J}`,G=EF(Q.types),W=await this._dataSource.getGatedDescriptorForTypedData({contractAddress:X,schemaHash:G,chainId:Z});if(W.isRight()){let{signedDescriptor:C}=W.unsafeCoerce(),S=await this._certificateLoader.loadCertificate({keyId:LZ.CalGatedSigning,keyUsage:wQ.GatedSigning,targetDevice:Y});return this.logger.debug("load result",{data:{path:"direct",verifyingContract:X,schemaHash:G,chainId:Z,contextTypes:[u.ETHEREUM_GATED_SIGNING]}}),[{type:u.ETHEREUM_GATED_SIGNING,payload:C,certificate:S}]}let U=W.caseOf({Left:(C)=>C,Right:()=>Error("unreachable")}),K=await this._proxyDataSource.getProxyImplementationAddress({proxyAddress:X,chainId:Z,challenge:$,calldata:"0x"});if(K.isLeft()){let C=K.extract();return this.logger.warn("Direct gated descriptor lookup failed and proxy resolution failed",{data:{verifyingContract:X,schemaHash:G,chainId:Z,directError:U.message,proxyError:C.message}}),[{type:u.ERROR,error:U}]}let O=K.unsafeCoerce(),I=O.implementationAddress.toLowerCase(),L=I.startsWith("0x")?I:`0x${I}`,A=await this._dataSource.getGatedDescriptorForTypedData({contractAddress:L,schemaHash:G,chainId:Z});if(A.isLeft()){let C=A.extract();return this.logger.warn("No gated descriptor found for proxy implementation address",{data:{verifyingContract:X,implementationAddress:L,schemaHash:G,chainId:Z,directError:U.message,implError:C.message}}),[{type:u.ERROR,error:U}]}let{signedDescriptor:M}=A.unsafeCoerce(),[k,B]=await Promise.all([this._certificateLoader.loadCertificate({keyId:O.keyId,keyUsage:O.keyUsage,targetDevice:Y}),this._certificateLoader.loadCertificate({keyId:LZ.CalGatedSigning,keyUsage:wQ.GatedSigning,targetDevice:Y})]);return this.logger.debug("load result",{data:{path:"proxy",verifyingContract:X,implementationAddress:L,schemaHash:G,chainId:Z,contextTypes:[u.ETHEREUM_PROXY_INFO,u.ETHEREUM_GATED_SIGNING]}}),[{type:u.ETHEREUM_PROXY_INFO,payload:O.signedDescriptor,certificate:k},{type:u.ETHEREUM_GATED_SIGNING,payload:M,certificate:B}]}};var cI=w(()=>{W0();SQ();RF();e8();KU();RZ();h$();jY();iQ();XY0=Object.defineProperty,VY0=Object.getOwnPropertyDescriptor,zY0=[u.ETHEREUM_GATED_SIGNING];PF=qY0([e(),UU(0,g(bJ.GatedDescriptorDataSource)),UU(1,g(BQ.PkiCertificateLoader)),UU(2,g(J$.ProxyDataSource)),UU(3,g(i0.ContextModuleLoggerFactory))],PF)});var sv=()=>new b0(({bind:Q})=>{Q(bJ.GatedDescriptorDataSource).to(IF),Q(bJ.GatedSigningContextLoader).to(LF),Q(bJ.GatedSigningTypedDataContextLoader).to(PF)});var iv=w(()=>{W0();hI();bI();cI();RF()});var KY0,UY0,OY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?UY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&KY0(Z,Y,J),J},av=(Q,Z)=>(Y,$)=>Z(Y,$,Q),jF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getSetPluginPayload({chainId:Q,address:Z,selector:Y}){try{let $=await this.http.get(`${this.config.metadataServiceDomain.url}/v1/ethereum/${Q}/contracts/${Z}/plugin-selector/${Y}`);return $.payload?U0($.payload):a(Error("[ContextModule] HttpNftDataSource: unexpected empty response"))}catch{return a(Error("[ContextModule] HttpNftDataSource: Failed to fetch set plugin payload"))}}async getNftInfosPayload({chainId:Q,address:Z}){try{let Y=await this.http.get(`${this.config.metadataServiceDomain.url}/v1/ethereum/${Q}/contracts/${Z}`);return Y.payload?U0(Y.payload):a(Error("[ContextModule] HttpNftDataSource: no nft metadata"))}catch{return a(Error("[ContextModule] HttpNftDataSource: Failed to fetch nft informations"))}}};var uI=w(()=>{W0();R0();SQ();OZ();KY0=Object.defineProperty,UY0=Object.getOwnPropertyDescriptor;jF=OY0([e(),av(0,g(i0.Config)),av(1,g(PQ.NetworkClient))],jF)});var cJ;var AF=w(()=>{cJ={NftDataSource:Symbol.for("NftDataSource"),NftContextLoader:Symbol.for("NftContextLoader"),NftContextFieldLoader:Symbol.for("NftContextFieldLoader")}});var HY0,DY0,IY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?DY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&HY0(Z,Y,J),J},RY0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),MF=class{constructor(Q){this._dataSource=Q}canHandle(Q,Z){return Z===u.ETHEREUM_NFT&&typeof Q=="object"&&Q!==null&&"chainId"in Q&&"address"in Q}async loadField(Q){return(await this._dataSource.getNftInfosPayload({address:Q.address,chainId:Q.chainId})).caseOf({Left:(Z)=>({type:u.ERROR,error:Z}),Right:(Z)=>({type:u.ETHEREUM_NFT,payload:Z})})}};var pI=w(()=>{W0();AF();iQ();HY0=Object.defineProperty,DY0=Object.getOwnPropertyDescriptor;MF=IY0([e(),RY0(0,g(cJ.NftDataSource))],MF)});var LY0,EY0,PY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?EY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&LY0(Z,Y,J),J},rv=(Q,Z)=>(Y,$)=>Z(Y,$,Q),tv,ev,jY0,AY0,TF=class{_dataSource;logger;constructor(Q,Z){this._dataSource=Q,this.logger=Z("NftContextLoader")}canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"to"in Q&&"selector"in Q&&"chainId"in Q&&typeof Q.chainId=="number"&&dQ(Q.to)&&Q.to!=="0x"&&dQ(Q.selector)&&this.isSelectorSupported(Q.selector)&&AY0.every((Y)=>Z.includes(Y))}async load(Q){let Z=[],{to:Y,selector:$,chainId:J}=Q,X=(await this._dataSource.getSetPluginPayload({chainId:J,address:Y,selector:$})).caseOf({Left:(W)=>({type:u.ERROR,error:W}),Right:(W)=>({type:u.ETHEREUM_PLUGIN,payload:W})});if(X.type===u.ERROR)return this.logger.debug("load result",{data:{result:[X]}}),[X];Z.push(X);let G=(await this._dataSource.getNftInfosPayload({chainId:J,address:Y})).caseOf({Left:(W)=>({type:u.ERROR,error:W}),Right:(W)=>({type:u.ETHEREUM_NFT,payload:W})});return G.type===u.ERROR?(this.logger.debug("load result",{data:{result:[G]}}),[G]):(Z.push(G),this.logger.debug("load result",{data:{result:Z}}),Z)}isSelectorSupported(Q){return Object.values(jY0).includes(Q)}};var lI=w(()=>{I0();W0();SQ();AF();iQ();LY0=Object.defineProperty,EY0=Object.getOwnPropertyDescriptor,tv=((Q)=>(Q.Approve="0x095ea7b3",Q.SetApprovalForAll="0xa22cb465",Q.TransferFrom="0x23b872dd",Q.SafeTransferFrom="0x42842e0e",Q.SafeTransferFromWithData="0xb88d4fde",Q))(tv||{}),ev=((Q)=>(Q.SetApprovalForAll="0xa22cb465",Q.SafeTransferFrom="0xf242432a",Q.SafeBatchTransferFrom="0x2eb2c2d6",Q))(ev||{}),jY0=[...Object.values(tv),...Object.values(ev)],AY0=[u.ETHEREUM_PLUGIN,u.ETHEREUM_NFT];TF=PY0([e(),rv(0,g(cJ.NftDataSource)),rv(1,g(i0.ContextModuleLoggerFactory))],TF)});var Qx=()=>new b0(({bind:Q})=>{Q(cJ.NftDataSource).to(jF),Q(cJ.NftContextLoader).to(TF),Q(cJ.NftContextFieldLoader).to(MF)});var Zx=w(()=>{W0();uI();AF();pI();lI()});var MY0,TY0,NY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?TY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&MY0(Z,Y,J),J},Yx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),NF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getProxyImplementationAddress({proxyAddress:Q,chainId:Z,challenge:Y,calldata:$}){let J;try{J=await this.http.post(`${this.config.metadataServiceDomain.url}/v2/ethereum/${Z}/contract/proxy/delegate`,{proxy:Q,data:$,challenge:Y})}catch{return a(Error("[ContextModule] HttpProxyDataSource: Failed to fetch delegate proxy"))}return J?this.isProxyDelegateCallDto(J)?J.addresses[0]?U0({implementationAddress:J.addresses[0],signedDescriptor:J.signedDescriptor,keyId:LZ.DomainMetadataKey,keyUsage:wQ.TrustedName}):a(Error(`[ContextModule] HttpProxyDataSource: No implementation address found for proxy ${Q} on chain ${Z}`)):a(Error(`[ContextModule] HttpProxyDataSource: Invalid proxy delegate call response format for proxy ${Q} on chain ${Z}`)):a(Error(`[ContextModule] HttpProxyDataSource: No data received for proxy ${Q} on chain ${Z}`))}isProxyDelegateCallDto(Q){return typeof Q=="object"&&Q!==null&&"addresses"in Q&&"signedDescriptor"in Q&&Array.isArray(Q.addresses)&&Q.addresses.every((Z)=>typeof Z=="string")&&typeof Q.signedDescriptor=="string"}};var mI=w(()=>{W0();R0();SQ();h$();jY();OZ();MY0=Object.defineProperty,TY0=Object.getOwnPropertyDescriptor;NF=NY0([e(),Yx(0,g(i0.Config)),Yx(1,g(PQ.NetworkClient))],NF)});var BY0,kY0,CY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?kY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&BY0(Z,Y,J),J},$x=(Q,Z)=>(Y,$)=>Z(Y,$,Q),BF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getProxyImplementationAddress({proxyAddress:Q,chainId:Z,challenge:Y}){let $;try{$=await this.http.get(`${this.config.metadataServiceDomain.url}/v3/ethereum/${Z}/contract/proxy/${Q}`,{params:{challenge:Y,resolver:"SAFE_GATEWAY"}})}catch{return a(Error("[ContextModule] HttpSafeProxyDataSource: Failed to fetch safe proxy implementation"))}return $?this.isSafeProxyImplementationAddressDto($)?U0({implementationAddress:$.implementationAddress,signedDescriptor:$.signedDescriptor,keyId:$.keyId,keyUsage:$.keyUsage}):a(Error(`[ContextModule] HttpSafeProxyDataSource: Invalid safe proxy response format for proxy ${Q} on chain ${Z}`)):a(Error(`[ContextModule] HttpSafeProxyDataSource: No data received for proxy ${Q} on chain ${Z}`))}isSafeProxyImplementationAddressDto(Q){return typeof Q=="object"&&Q!==null&&"proxyAddress"in Q&&"implementationAddress"in Q&&"standard"in Q&&"signedDescriptor"in Q&&"providedBy"in Q&&"keyId"in Q&&"keyUsage"in Q&&typeof Q.proxyAddress=="string"&&typeof Q.implementationAddress=="string"&&typeof Q.standard=="string"&&typeof Q.signedDescriptor=="string"&&typeof Q.providedBy=="string"&&typeof Q.keyId=="string"&&typeof Q.keyUsage=="string"}};var dI=w(()=>{W0();R0();SQ();OZ();BY0=Object.defineProperty,kY0=Object.getOwnPropertyDescriptor;BF=CY0([e(),$x(0,g(i0.Config)),$x(1,g(PQ.NetworkClient))],BF)});var SY0,wY0,_Y0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?wY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&SY0(Z,Y,J),J},Jx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),kF=class{constructor(Q,Z){this._proxyDataSource=Q,this._certificateLoader=Z}canHandle(Q,Z){return Z===u.ETHEREUM_PROXY_INFO&&typeof Q=="object"&&Q!==null&&"chainId"in Q&&"proxyAddress"in Q&&"calldata"in Q&&"challenge"in Q&&"deviceModelId"in Q}async loadField(Q){return(await this._proxyDataSource.getProxyImplementationAddress({calldata:Q.calldata,proxyAddress:Q.proxyAddress,chainId:Q.chainId,challenge:Q.challenge})).caseOf({Left:(Z)=>Promise.resolve({type:u.ERROR,error:Z}),Right:async({signedDescriptor:Z,keyId:Y,keyUsage:$})=>{let J=await this._certificateLoader.loadCertificate({keyId:Y,keyUsage:$,targetDevice:Q.deviceModelId});return{type:u.ETHEREUM_PROXY_INFO,payload:Z,certificate:J}}})}};var nI=w(()=>{W0();e8();RZ();iQ();SY0=Object.defineProperty,wY0=Object.getOwnPropertyDescriptor;kF=_Y0([e(),Jx(0,g(J$.ProxyDataSource)),Jx(1,g(BQ.PkiCertificateLoader))],kF)});var Gx=(Q)=>new b0(({bind:Z})=>{Q?.proxy==="safe"?Z(J$.ProxyDataSource).to(BF):Z(J$.ProxyDataSource).to(NF),Z(J$.ProxyContextFieldLoader).to(kF)});var Xx=w(()=>{W0();mI();dI();e8();nI()});var vY0,xY0,fY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?xY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&vY0(Z,Y,J),J},Vx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),OU=class{constructor(Q,Z){this.config=Q,this.http=Z}async getDescriptors({safeContractAddress:Q,chainId:Z,challenge:Y}){try{let $=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/ethereum/${Z}/safe/account/${Q}`,{params:{challenge:Y}});return $?this.isSafeAccountDto($)?U0({account:{signedDescriptor:$.accountDescriptor.signedDescriptor,keyId:$.accountDescriptor.keyId,keyUsage:$.accountDescriptor.keyUsage},signers:{signedDescriptor:$.signersDescriptor.signedDescriptor,keyId:$.signersDescriptor.keyId,keyUsage:$.signersDescriptor.keyUsage}}):a(Error("[ContextModule] HttpSafeAccountDataSource: invalid safe account response format")):a(Error("[ContextModule] HttpSafeAccountDataSource: unexpected empty response"))}catch{return a(Error("[ContextModule] HttpSafeAccountDataSource: Failed to fetch safe account descriptors"))}}isSafeAccountDto(Q){return typeof Q=="object"&&Q!==null&&"accountDescriptor"in Q&&"signersDescriptor"in Q&&typeof Q.accountDescriptor=="object"&&typeof Q.signersDescriptor=="object"&&this.isSafeDescriptorDto(Q.accountDescriptor)&&this.isSafeDescriptorDto(Q.signersDescriptor)}isSafeDescriptorDto(Q){return typeof Q=="object"&&Q!==null&&"signedDescriptor"in Q&&"keyId"in Q&&"keyUsage"in Q&&typeof Q.signedDescriptor=="string"&&typeof Q.keyId=="string"&&typeof Q.keyUsage=="string"}};var qx=w(()=>{W0();R0();SQ();OZ();vY0=Object.defineProperty,xY0=Object.getOwnPropertyDescriptor;OU=fY0([Vx(0,g(i0.Config)),Vx(1,g(PQ.NetworkClient))],OU)});var UX;var HU=w(()=>{UX={SafeAddressDataSource:Symbol.for("SafeAddressDataSource"),SafeAddressLoader:Symbol.for("SafeAddressLoader")}});var yY0,gY0,hY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?gY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&yY0(Z,Y,J),J},Fx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),bY0,DU=class{constructor(Q,Z){this._dataSource=Q,this._certificateLoader=Z}canHandle(Q,Z){return Z.every((Y)=>bY0.includes(Y))&&typeof Q=="object"&&Q!==null&&"safeContractAddress"in Q&&dQ(Q.safeContractAddress)&&Q.safeContractAddress!=="0x"&&"chainId"in Q&&typeof Q.chainId=="number"&&"deviceModelId"in Q&&Q.deviceModelId!==void 0&&"challenge"in Q&&typeof Q.challenge=="string"&&Q.challenge.length>0}async load({safeContractAddress:Q,chainId:Z,deviceModelId:Y,challenge:$}){return(await this._dataSource.getDescriptors({safeContractAddress:Q,chainId:Z,challenge:$})).caseOf({Left:(J)=>Promise.resolve([{type:u.ERROR,error:J}]),Right:async({account:J,signers:X})=>[{type:u.ETHEREUM_SAFE,payload:J.signedDescriptor,certificate:await this._certificateLoader.loadCertificate({keyId:J.keyId,keyUsage:J.keyUsage,targetDevice:Y})},{type:u.ETHEREUM_SIGNER,payload:X.signedDescriptor,certificate:await this._certificateLoader.loadCertificate({keyId:X.keyId,keyUsage:X.keyUsage,targetDevice:Y})}]})}};var zx=w(()=>{I0();W0();HU();RZ();iQ();yY0=Object.defineProperty,gY0=Object.getOwnPropertyDescriptor,bY0=[u.ETHEREUM_SAFE,u.ETHEREUM_SIGNER];DU=hY0([e(),Fx(0,g(UX.SafeAddressDataSource)),Fx(1,g(BQ.PkiCertificateLoader))],DU)});var Wx=()=>new b0(({bind:Q})=>{Q(UX.SafeAddressDataSource).to(OU),Q(UX.SafeAddressLoader).to(DU)});var Kx=w(()=>{W0();qx();zx();HU()});var cY0,uY0,pY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?uY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&cY0(Z,Y,J),J},Ux=(Q,Z)=>(Y,$)=>Z(Y,$,Q),CF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getTokenInfosPayload({chainId:Q,address:Z}){try{let Y=(await this.http.get(`${this.config.cal.url}/tokens`,{params:{contract_address:Z,chain_id:Q,output:"descriptor",ref:`branch:${this.config.cal.branch}`}}))?.[0];if(!Y||!Y.descriptor||!Y.descriptor.data||!Y.descriptor.signatures||typeof Y.descriptor.signatures[this.config.cal.mode]!="string")return a(Error(`[ContextModule] HttpTokenDataSource: no token metadata for address ${Z} on chain ${Q}`));let $=(Y.descriptor.data.length/2-20-4-4).toString(16).padStart(2,"0");return U0([$,Y.descriptor.data,Y.descriptor.signatures[this.config.cal.mode]].join(""))}catch{return a(Error("[ContextModule] HttpTokenDataSource: Failed to fetch token informations"))}}};var oI=w(()=>{W0();R0();SQ();OZ();cY0=Object.defineProperty,uY0=Object.getOwnPropertyDescriptor;CF=pY0([e(),Ux(0,g(i0.Config)),Ux(1,g(PQ.NetworkClient))],CF)});var lY0,mY0,dY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?mY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&lY0(Z,Y,J),J},Ox=(Q,Z)=>(Y,$)=>Z(Y,$,Q),SF=class{constructor(Q,Z){this._dataSource=Q,this._certificateLoader=Z}canHandle(Q,Z){return Z===u.ETHEREUM_TOKEN&&typeof Q=="object"&&Q!==null&&"chainId"in Q&&"address"in Q&&"deviceModelId"in Q&&Q.deviceModelId!==void 0}async loadField(Q){let Z=await this._dataSource.getTokenInfosPayload({address:Q.address,chainId:Q.chainId}),Y=await this._certificateLoader.loadCertificate({keyId:LZ.Erc20MetadataKey,keyUsage:wQ.CoinMeta,targetDevice:Q.deviceModelId});return Z.caseOf({Left:($)=>({type:u.ERROR,error:$}),Right:($)=>({type:u.ETHEREUM_TOKEN,payload:$,certificate:Y})})}};var sI=w(()=>{W0();QG();RZ();h$();jY();iQ();lY0=Object.defineProperty,mY0=Object.getOwnPropertyDescriptor;SF=dY0([e(),Ox(0,g(lY.TokenDataSource)),Ox(1,g(BQ.PkiCertificateLoader))],SF)});var nY0,oY0,sY0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?oY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&nY0(Z,Y,J),J},Hx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),iI,iY0,aY0,wF=class{_dataSource;logger;constructor(Q,Z){this._dataSource=Q,this.logger=Z("TokenContextLoader")}canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"to"in Q&&"selector"in Q&&"chainId"in Q&&typeof Q.chainId=="number"&&dQ(Q.to)&&Q.to!=="0x"&&dQ(Q.selector)&&this.isSelectorSupported(Q.selector)&&aY0.every((Y)=>Z.includes(Y))}async load(Q){let{to:Z,chainId:Y}=Q,$=[(await this._dataSource.getTokenInfosPayload({address:Z,chainId:Y})).caseOf({Left:(J)=>({type:u.ERROR,error:J}),Right:(J)=>({type:u.ETHEREUM_TOKEN,payload:J})})];return this.logger.debug("load result",{data:{result:$}}),$}isSelectorSupported(Q){return Object.values(iY0).includes(Q)}};var aI=w(()=>{I0();W0();SQ();QG();iQ();nY0=Object.defineProperty,oY0=Object.getOwnPropertyDescriptor,iI=((Q)=>(Q.Approve="0x095ea7b3",Q.Transfer="0xa9059cbb",Q))(iI||{}),iY0=Object.values(iI),aY0=[u.ETHEREUM_TOKEN];wF=sY0([e(),Hx(0,g(lY.TokenDataSource)),Hx(1,g(i0.ContextModuleLoggerFactory))],wF)});var Dx=()=>new b0(({bind:Q})=>{Q(lY.TokenDataSource).to(CF),Q(lY.TokenContextLoader).to(wF),Q(lY.TokenContextFieldLoader).to(SF)});var Ix=w(()=>{W0();oI();QG();sI();aI()});var Rx="X-Ledger-Client-Version",Lx="X-Ledger-Client-Origin";var Ex=()=>{};var jx;var Px=w(()=>{jx={dependencies:{bs58:"catalog:","crypto-js":"catalog:",ethers:"catalog:",inversify:"catalog:","purify-ts":"catalog:","reflect-metadata":"catalog:"},devDependencies:{"@ledgerhq/device-management-kit":"workspace:^","@ledgerhq/eslint-config-dsdk":"workspace:^","@ledgerhq/ldmk-tool":"workspace:^","@ledgerhq/prettier-config-dsdk":"workspace:^","@ledgerhq/tsconfig-dsdk":"workspace:^","@ledgerhq/vitest-config-dmk":"workspace:^","@types/crypto-js":"catalog:","ts-node":"catalog:"},exports:{".":{import:"./lib/esm/index.js",require:"./lib/cjs/index.js",types:"./lib/types/index.d.ts"},"./*":{import:"./lib/esm/*",require:"./lib/cjs/*",types:"./lib/types/*"}},files:["./lib"],license:"Apache-2.0",name:"@ledgerhq/context-module",peerDependencies:{"@ledgerhq/device-management-kit":"workspace:^"},private:!1,repository:{type:"git",url:"https://github.com/LedgerHQ/device-sdk-ts.git"},scripts:{build:"pnpm ldmk-tool build --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",dev:'concurrently "pnpm watch:builds" "pnpm watch:types"',lint:"eslint","lint:fix":"pnpm lint --fix",postpack:"find . -name '*.tgz' -exec cp {} ../../../dist/ \\; ",prebuild:"rimraf lib",prettier:"prettier . --check","prettier:fix":"prettier . --write",test:"vitest run","test:coverage":"vitest run --coverage","test:watch":"vitest",typecheck:"tsc --noEmit","watch:builds":"pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json","watch:types":'concurrently "tsc --watch -p tsconfig.prod.json" "tsc-alias --watch -p tsconfig.prod.json"'},version:"2.6.0"}});var ZG=(Q)=>new oG({headers:{[Rx]:`context-module/${jx.version}`,...Q.originToken&&{[Lx]:Q.originToken}}});var _F=w(()=>{I0();Ex();Px()});var tY0,eY0,Q$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?eY0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&tY0(Z,Y,J),J},Ax=(Q,Z)=>(Y,$)=>Z(Y,$,Q),vF=class{constructor(Q,Z){this.config=Q,this.http=Z??ZG(Q)}http;async getDomainNamePayload({chainId:Q,domain:Z,challenge:Y}){let $;try{$=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/names/ethereum/${Q}/forward/${Z}`,{params:{types:"eoa",sources:"ens",challenge:Y}})}catch{return a(Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name"))}return $?this.isTrustedNameDto($)?U0({data:$.signedDescriptor.data,keyId:$.keyId,keyUsage:$.keyUsage}):a(Error(`[ContextModule] HttpTrustedNameDataSource: Invalid trusted name response format for domain ${Z} on chain ${Q}`)):a(Error(`[ContextModule] HttpTrustedNameDataSource: No data received for domain ${Z} on chain ${Q}`))}async getTrustedNamePayload({chainId:Q,address:Z,challenge:Y,sources:$,types:J}){let X;try{$=$.filter((W)=>W==="ens"||W==="crypto_asset_list"),X=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/names/ethereum/${Q}/reverse/${Z}`,{params:{types:J.join(","),sources:$.join(","),challenge:Y}})}catch{return a(Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name"))}if(!X)return a(Error(`[ContextModule] HttpTrustedNameDataSource: No data received for address ${Z} on chain ${Q}`));if(!this.isTrustedNameDto(X))return a(Error(`[ContextModule] HttpTrustedNameDataSource: Invalid trusted name response format for address ${Z} on chain ${Q}`));if(typeof X.signedDescriptor.signatures[this.config.cal.mode]!="string")return U0({data:X.signedDescriptor.data,keyId:X.keyId,keyUsage:X.keyUsage});let G=X.signedDescriptor.signatures[this.config.cal.mode];return U0({data:this.formatTrustedName(X.signedDescriptor.data,G),keyId:X.keyId,keyUsage:X.keyUsage})}formatTrustedName(Q,Z){Z.length%2!==0&&(Z="0"+Z);let Y="15",$=(Z.length/2).toString(16);return`${Q}${Y}${$}${Z}`}isTrustedNameDto(Q){return typeof Q=="object"&&Q!==null&&"signedDescriptor"in Q&&"keyId"in Q&&"keyUsage"in Q&&typeof Q.keyId=="string"&&typeof Q.keyUsage=="string"&&typeof Q.signedDescriptor=="object"&&Q.signedDescriptor!==null&&"data"in Q.signedDescriptor&&"signatures"in Q.signedDescriptor&&typeof Q.signedDescriptor.data=="string"&&typeof Q.signedDescriptor.signatures=="object"}};var rI=w(()=>{W0();R0();SQ();OZ();_F();tY0=Object.defineProperty,eY0=Object.getOwnPropertyDescriptor;vF=Q$0([e(),Ax(0,g(i0.Config)),Ax(1,g(PQ.NetworkClient))],vF)});var LJ;var xF=w(()=>{LJ={TrustedNameDataSource:Symbol.for("TrustedNameDataSource"),TrustedNameContextLoader:Symbol.for("TrustedNameContextLoader"),TrustedNameContextFieldLoader:Symbol.for("TrustedNameContextFieldLoader")}});var Z$0,Y$0,$$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Y$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Z$0(Z,Y,J),J},Mx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),fF=class{constructor(Q,Z){this._dataSource=Q,this._certificateLoader=Z}canHandle(Q,Z){return Z===u.ETHEREUM_TRUSTED_NAME&&typeof Q=="object"&&Q!==null&&"chainId"in Q&&"address"in Q&&"challenge"in Q&&"types"in Q&&"sources"in Q&&"deviceModelId"in Q&&Q.deviceModelId!==void 0}async loadField(Q){return await(await this._dataSource.getTrustedNamePayload({chainId:Q.chainId,address:Q.address,challenge:Q.challenge,types:Q.types,sources:Q.sources})).caseOf({Left:(Z)=>Promise.resolve({type:u.ERROR,error:Z}),Right:async({data:Z,keyId:Y,keyUsage:$})=>{let J=await this._certificateLoader.loadCertificate({keyId:Y,keyUsage:$,targetDevice:Q.deviceModelId});return{type:u.ETHEREUM_TRUSTED_NAME,payload:Z,certificate:J}}})}};var tI=w(()=>{W0();xF();RZ();iQ();Z$0=Object.defineProperty,Y$0=Object.getOwnPropertyDescriptor;fF=$$0([e(),Mx(0,g(LJ.TrustedNameDataSource)),Mx(1,g(BQ.PkiCertificateLoader))],fF)});var J$0,G$0,X$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?G$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&J$0(Z,Y,J),J},eI=(Q,Z)=>(Y,$)=>Z(Y,$,Q),V$0,yF=class{constructor(Q,Z,Y){this._dataSource=Q,this._certificateLoader=Z,this.logger=Y("TrustedNameContextLoader")}logger;canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"chainId"in Q&&Q.chainId!==void 0&&typeof Q.chainId=="number"&&"to"in Q&&Q.to!==void 0&&dQ(Q.to)&&Q.to!=="0x"&&"deviceModelId"in Q&&Q.deviceModelId!==void 0&&V$0.every((Y)=>Z.includes(Y))}async load(Q){let Z=await this._dataSource.getTrustedNamePayload({chainId:Q.chainId,address:Q.to,challenge:"",types:["eoa"],sources:["ens"]});return this.logger.debug("[ContextModule]: load result",{data:{payload:Z}}),await Z.caseOf({Left:(Y)=>Promise.resolve([{type:u.ERROR,error:Y}]),Right:async({data:Y,keyId:$,keyUsage:J})=>{let X=await this._certificateLoader.loadCertificate({keyId:$,keyUsage:J,targetDevice:Q.deviceModelId});return[{type:u.ETHEREUM_TRUSTED_NAME,payload:Y,certificate:X}]}})}};var QR=w(()=>{I0();W0();SQ();xF();RZ();iQ();J$0=Object.defineProperty,G$0=Object.getOwnPropertyDescriptor,V$0=[u.ETHEREUM_TRUSTED_NAME];yF=X$0([e(),eI(0,g(LJ.TrustedNameDataSource)),eI(1,g(BQ.PkiCertificateLoader)),eI(2,g(i0.ContextModuleLoggerFactory))],yF)});var Tx=(Q)=>new b0(({bind:Z})=>{Q?Z(LJ.TrustedNameDataSource).toConstantValue(Q):Z(LJ.TrustedNameDataSource).to(vF),Z(LJ.TrustedNameContextLoader).to(yF),Z(LJ.TrustedNameContextFieldLoader).to(fF)});var Nx=w(()=>{W0();rI();xF();tI();QR()});var pV=255,b$;var IU=w(()=>{b$=((Q)=>(Q.None="none",Q.Present="present",Q.VerifyingContract="verifying_contract",Q))(b$||{})});var q$0,F$0,z$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?F$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&q$0(Z,Y,J),J},Bx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),gF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getTypedDataFilters({chainId:Q,address:Z,schema:Y,version:$}){let J;try{let X=await this.http.get(`${this.config.cal.url}/dapps`,{params:{contracts:Z,chain_id:Q,output:"descriptors_eip712",descriptors_eip712_version:$,descriptors_eip712:"<set>",ref:`branch:${this.config.cal.branch}`}}),G=EF(Y);Z=Z.toLowerCase();let W=(X??[]).map((O)=>O?.descriptors_eip712?.[Z]?.[G]).find(Boolean);if(!W)return a(Error(`[ContextModule] HttpTypedDataDataSource: no typed data filters for address ${Z} on chain ${Q} for schema ${G}`));if(!Array.isArray(W.instructions))return a(Error(`[ContextModule] HttpTypedDataDataSource: no message info for address ${Z} on chain ${Q} for schema ${G}`));let U=[],K={};for(let O of W.instructions)if(this.isInstructionContractInfo(O,this.config.cal.mode))J={displayName:O.display_name,signature:O.signatures[this.config.cal.mode],filtersCount:O.field_mappers_count};else if($==="v1"&&this.isInstructionFieldV1(O,this.config.cal.mode))U.push({type:"raw",displayName:O.display_name,path:O.field_path,signature:O.signatures[this.config.cal.mode]});else if(this.isInstructionFieldV2(O,this.config.cal.mode))U.push({type:O.format,displayName:O.display_name,path:O.field_path,signature:O.signatures[this.config.cal.mode]});else if(this.isInstructionFieldV2WithCoinRef(O,this.config.cal.mode))U.push({type:O.format,displayName:O.display_name,path:O.field_path,signature:O.signatures[this.config.cal.mode],tokenIndex:O.coin_ref});else if(this.isInstructionFieldV2WithName(O,this.config.cal.mode))U.push({type:O.format,displayName:O.display_name,path:O.field_path,signature:O.signatures[this.config.cal.mode],types:O.name_types,sources:O.name_sources,typesAndSourcesPayload:this.formatTrustedNameTypesAndSources(O)});else if(this.isInstructionCalldataInfo(O,this.config.cal.mode))K[O.calldata_index]={displayName:O.display_name,calldataIndex:O.calldata_index,valueFlag:O.value_filter_flag,calleeFlag:this.convertCalldataPresenceFlag(O.callee_filter_flag),amountFlag:O.amount_filter_flag,spenderFlag:this.convertCalldataPresenceFlag(O.spender_filter_flag),chainIdFlag:O.chain_id_filter_flag,selectorFlag:O.selector_filter_flag,signature:O.signatures[this.config.cal.mode]};else if(this.isInstructionFieldV2Calldata(O,this.config.cal.mode))U.push({type:O.format,displayName:O.display_name,path:O.field_path,signature:O.signatures[this.config.cal.mode],calldataIndex:O.calldata_index});else return a(Error(`[ContextModule] HttpTypedDataDataSource: invalid typed data field for address ${Z} on chain ${Q} for schema ${G}`));return J?U0({messageInfo:J,filters:U,calldatasInfos:K}):a(Error(`[ContextModule] HttpTypedDataDataSource: no message info for address ${Z} on chain ${Q} for schema ${G}`))}catch{return a(Error("[ContextModule] HttpTypedDataDataSource: Failed to fetch typed data informations"))}}convertCalldataPresenceFlag(Q){switch(Q){case"none":return b$.None;case"present":return b$.Present;case"verifying_contract":return b$.VerifyingContract;default:throw Error(`Unhandled flag: ${Q}`)}}formatTrustedNameTypesAndSources(Q){let Z=Q.name_types.length,Y=Q.name_sources.length,$=Q.descriptor.slice((Z+Y)*2*-1,Y*2*-1),J=Q.descriptor.slice(Y*2*-1),X=Z.toString(16).padStart(2,"0"),G=Y.toString(16).padStart(2,"0");return X+$+G+J}isInstructionFieldV1(Q,Z){return typeof Q=="object"&&typeof Q.display_name=="string"&&typeof Q.field_path=="string"&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"}isInstructionFieldV2(Q,Z){return typeof Q=="object"&&typeof Q.display_name=="string"&&typeof Q.field_path=="string"&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"&&typeof Q.format=="string"&&["raw","datetime"].includes(Q.format)&&Q.coin_ref===void 0}isInstructionFieldV2WithCoinRef(Q,Z){return typeof Q=="object"&&typeof Q.display_name=="string"&&typeof Q.field_path=="string"&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"&&typeof Q.format=="string"&&["token","amount"].includes(Q.format)&&typeof Q.coin_ref=="number"}isInstructionFieldV2WithName(Q,Z){return typeof Q=="object"&&typeof Q.display_name=="string"&&typeof Q.field_path=="string"&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"&&typeof Q.format=="string"&&Q.format==="trusted-name"&&Q.coin_ref===void 0&&Array.isArray(Q.name_types)&&Array.isArray(Q.name_sources)&&Q.name_types.every((Y)=>typeof Y=="string")&&Q.name_sources.every((Y)=>typeof Y=="string")}isInstructionContractInfo(Q,Z){return typeof Q=="object"&&typeof Q.display_name=="string"&&typeof Q.field_mappers_count=="number"&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"&&Q.field_path===void 0}isInstructionCalldataInfo(Q,Z){return typeof Q=="object"&&typeof Q.type=="string"&&Q.type==="calldata"&&typeof Q.display_name=="string"&&typeof Q.calldata_index=="number"&&typeof Q.value_filter_flag=="boolean"&&typeof Q.chain_id_filter_flag=="boolean"&&typeof Q.selector_filter_flag=="boolean"&&typeof Q.amount_filter_flag=="boolean"&&["none","present","verifying_contract"].includes(Q.callee_filter_flag)&&["none","present","verifying_contract"].includes(Q.spender_filter_flag)&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"}isInstructionFieldV2Calldata(Q,Z){return typeof Q=="object"&&typeof Q.display_name=="string"&&typeof Q.field_path=="string"&&typeof Q.signatures=="object"&&typeof Q.signatures[Z]=="string"&&typeof Q.format=="string"&&["calldata-value","calldata-callee","calldata-chain-id","calldata-selector","calldata-amount","calldata-spender"].includes(Q.format)&&typeof Q.calldata_index=="number"}};var ZR=w(()=>{W0();R0();SQ();IU();KU();OZ();q$0=Object.defineProperty,F$0=Object.getOwnPropertyDescriptor;gF=z$0([e(),Bx(0,g(i0.Config)),Bx(1,g(PQ.NetworkClient))],gF)});var OX;var RU=w(()=>{OX={TypedDataDataSource:Symbol.for("TypedDataDataSource"),TypedDataContextLoader:Symbol.for("TypedDataContextLoader")}});var W$0,K$0,U$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?K$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&W$0(Z,Y,J),J},hF=(Q,Z)=>(Y,$)=>Z(Y,$,Q),bF=class{constructor(Q,Z,Y,$,J){this.dataSource=Q,this.tokenDataSource=Z,this.proxyDataSource=Y,this._certificateLoader=$,this.logger=J("DefaultTypedDataContextLoader")}logger;async load(Q){let Z,Y=await this.dataSource.getTypedDataFilters({address:Q.verifyingContract,chainId:Q.chainId,version:Q.version,schema:Q.schema});if(Y.isLeft()){let{resolvedAddress:K,context:O}=await this.resolveProxy(Q);if(O!==void 0&&(Z=O,Y=await this.dataSource.getTypedDataFilters({address:K,chainId:Q.chainId,version:Q.version,schema:Q.schema})),Y.isLeft()){let I={type:"error",error:Y.extract()};return this.logger.debug("load result",{data:{result:I}}),I}}let{messageInfo:$,filters:J,calldatasInfos:X}=Y.unsafeCoerce(),G=J.reduce((K,O)=>(K[O.path]=O,K),{}),W=await this._certificateLoader.loadCertificate({keyId:LZ.Erc20MetadataKey,keyUsage:wQ.CoinMeta,targetDevice:Q.deviceModelId}),U={type:"success",messageInfo:$,filters:G,trustedNamesAddresses:this.extractTrustedNames(J,Q),tokens:await this.extractTokens(J,Q),calldatas:this.extractCalldatas(J,X,Q),certificate:W,proxy:Z};return this.logger.debug("load result",{data:{result:U}}),U}async resolveProxy(Q){let Z=await this.proxyDataSource.getProxyImplementationAddress({calldata:"0x",proxyAddress:Q.verifyingContract,chainId:Q.chainId,challenge:Q.challenge??""});if(Z.isLeft())return{resolvedAddress:Q.verifyingContract,context:void 0};let Y=Z.unsafeCoerce(),$=await this._certificateLoader.loadCertificate({keyId:Y.keyId,keyUsage:Y.keyUsage,targetDevice:Q.deviceModelId});return{resolvedAddress:Y.implementationAddress,context:{type:u.ETHEREUM_PROXY_INFO,payload:Y.signedDescriptor,certificate:$}}}extractTrustedNames(Q,Z){return Q.filter((Y)=>Y.type==="trusted-name").reduce((Y,$)=>{let J=Z.fieldsValues.filter((X)=>X.path===$.path);if(J.length!==0){let X=J[0],G=this.convertAddressToHexaString(X.value);Y[$.path]=G}return Y},{})}async extractTokens(Q,Z){let Y={};for(let $ of Q){if($.type!=="token"&&$.type!=="amount")continue;let J=$.tokenIndex;if(Y[J]===void 0){if($.type==="token"){let X=Z.fieldsValues.filter((U)=>U.path===$.path);if(X.length===0)continue;let G=X[0],W=this.convertAddressToHexaString(G.value);if(X.every((U)=>this.convertAddressToHexaString(U.value)===W)){let U=Z.chainId;(await this.tokenDataSource.getTokenInfosPayload({address:W,chainId:U})).ifRight((K)=>{Y[J]=K})}}else if($.type==="amount"&&J===pV){let{verifyingContract:X,chainId:G}=Z;(await this.tokenDataSource.getTokenInfosPayload({address:X,chainId:G})).ifRight((W)=>{Y[J]=W})}}}return Y}extractCalldatas(Q,Z,Y){let $=Q.reduce((X,G)=>{if(G.type==="calldata-value"||G.type==="calldata-callee"||G.type==="calldata-chain-id"||G.type==="calldata-selector"||G.type==="calldata-amount"||G.type==="calldata-spender"){let W=X[G.calldataIndex];W===void 0?X[G.calldataIndex]=[G]:W.push(G)}return X},{}),J={};for(let X in Z){let G=Z[X],W=$[X];if(!W)continue;let U=this.extractHexaString(W.find((k)=>k.type==="calldata-value"),Y,"0x"),K=this.extractHexaString(W.find((k)=>k.type==="calldata-selector"),Y,U.slice(0,10)),O=this.extractAddress(W.find((k)=>k.type==="calldata-callee"),Y,G.calleeFlag),I=this.extractAddress(W.find((k)=>k.type==="calldata-spender"),Y,G.spenderFlag),L=this.extractBigint(W.find((k)=>k.type==="calldata-amount"),Y,void 0),A=this.extractBigint(W.find((k)=>k.type==="calldata-chain-id"),Y,void 0),M=A!==void 0&&A<Number.MAX_SAFE_INTEGER?Number(A):Y.chainId;J[X]={filter:G,subset:{chainId:M,data:U,selector:K,to:O,value:L,from:I}}}return J}extractHexaString(Q,Z,Y){if(Q!==void 0){let $=Z.fieldsValues.filter((J)=>J.path===Q.path);if($.length!==0)return DQ($[0].value)}return Y}extractAddress(Q,Z,Y,$){if(Y===b$.VerifyingContract)return Z.verifyingContract;if(Q!==void 0){let J=Z.fieldsValues.filter((X)=>X.path===Q.path);if(J.length!==0)return this.convertAddressToHexaString(J[0].value)}return $}extractBigint(Q,Z,Y){if(Q!==void 0){let $=Z.fieldsValues.filter((J)=>J.path===Q.path);if($.length!==0)return BigInt(DQ($[0].value))}return Y}convertAddressToHexaString(Q){return`0x${Array.from(Q,(Z)=>Z.toString(16).padStart(2,"0")).join("").padStart(40,"0")}`}};var YR=w(()=>{I0();W0();SQ();IU();e8();QG();RU();RZ();h$();jY();iQ();W$0=Object.defineProperty,K$0=Object.getOwnPropertyDescriptor;bF=U$0([e(),hF(0,g(OX.TypedDataDataSource)),hF(1,g(lY.TokenDataSource)),hF(2,g(J$.ProxyDataSource)),hF(3,g(BQ.PkiCertificateLoader)),hF(4,g(i0.ContextModuleLoggerFactory))],bF)});var kx=()=>new b0(({bind:Q})=>{Q(OX.TypedDataDataSource).to(gF),Q(OX.TypedDataContextLoader).to(bF)});var Cx=w(()=>{W0();ZR();RU();YR()});var Sx,wx="0x3593564c",c$,_x,vx;var $R=w(()=>{Sx=["function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable"],c$=((Q)=>(Q.V2_SWAP_EXACT_IN="V2_SWAP_EXACT_IN",Q.V2_SWAP_EXACT_OUT="V2_SWAP_EXACT_OUT",Q.V3_SWAP_EXACT_IN="V3_SWAP_EXACT_IN",Q.V3_SWAP_EXACT_OUT="V3_SWAP_EXACT_OUT",Q.WRAP_ETH="WRAP_ETH",Q.UNWRAP_ETH="UNWRAP_ETH",Q.PERMIT2_PERMIT="PERMIT2_PERMIT",Q.PERMIT2_TRANSFER_FROM="PERMIT2_TRANSFER_FROM",Q.PERMIT2_PERMIT_BATCH="PERMIT2_PERMIT_BATCH",Q.PERMIT2_TRANSFER_FROM_BATCH="PERMIT2_TRANSFER_FROM_BATCH",Q.PAY_PORTION="PAY_PORTION",Q.SWEEP="SWEEP",Q))(c$||{}),_x={"0x08":"V2_SWAP_EXACT_IN","0x09":"V2_SWAP_EXACT_OUT","0x00":"V3_SWAP_EXACT_IN","0x01":"V3_SWAP_EXACT_OUT","0x0b":"WRAP_ETH","0x0c":"UNWRAP_ETH","0x0a":"PERMIT2_PERMIT","0x0d":"PERMIT2_TRANSFER_FROM","0x02":"PERMIT2_PERMIT_BATCH","0x03":"PERMIT2_TRANSFER_FROM_BATCH","0x06":"PAY_PORTION","0x04":"SWEEP"},vx=["V2_SWAP_EXACT_IN","V2_SWAP_EXACT_OUT","V3_SWAP_EXACT_IN","V3_SWAP_EXACT_OUT"]});var JR,xx;var fx=w(()=>{JR=((Q)=>(Q[Q.ETHEREUM_MAINNET=1]="ETHEREUM_MAINNET",Q[Q.ETHEREUM_GOERLI=5]="ETHEREUM_GOERLI",Q[Q.ETHEREUM_SEPOLIA=11155111]="ETHEREUM_SEPOLIA",Q[Q.ARBITRUM_ONE=42161]="ARBITRUM_ONE",Q[Q.ARBITRUM_GOERLI=421613]="ARBITRUM_GOERLI",Q[Q.AVALANCHE_C_CHAIN=43114]="AVALANCHE_C_CHAIN",Q[Q.BSC=56]="BSC",Q[Q.BASE=8453]="BASE",Q[Q.BASE_GOERLI=84531]="BASE_GOERLI",Q[Q.BLAST=23888]="BLAST",Q[Q.OPTIMISM=10]="OPTIMISM",Q[Q.OPTIMISM_GOERLI=420]="OPTIMISM_GOERLI",Q[Q.POLYGON=137]="POLYGON",Q[Q.POLYGON_MUMBAI=80001]="POLYGON_MUMBAI",Q))(JR||{}),xx={1:"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",5:"0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6",11155111:"0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14",42161:"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",421613:"0xe39Ab88f8A4777030A534146A9Ca3B52bd5D43A3",43114:"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7",56:"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",8453:"0x4200000000000000000000000000000000000006",84531:"0x44D627f900da8AdaC7561bD73aA745F132450798",23888:"0x4300000000000000000000000000000000000004",10:"0x4200000000000000000000000000000000000006",420:"0x4200000000000000000000000000000000000006",137:"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270",80001:"0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889"}});var O$0,H$0,D$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?H$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&O$0(Z,Y,J),J},I$0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),GR=40,yx=6,cF=class{constructor(Q){this.abiDecoder=Q}decode(Q,Z,Y){switch(Q){case c$.V2_SWAP_EXACT_IN:return this._decodeSwapV2(Z);case c$.V2_SWAP_EXACT_OUT:return this._decodeSwapV2(Z);case c$.V3_SWAP_EXACT_IN:return this._decodeSwapV3(Z);case c$.V3_SWAP_EXACT_OUT:return this._decodeSwapV3(Z);case c$.WRAP_ETH:return this._decodeWrappedEth(Z,Y);case c$.UNWRAP_ETH:return this._decodeWrappedEth(Z,Y);case c$.SWEEP:return this._decodeSweep(Z);case c$.PERMIT2_PERMIT:case c$.PERMIT2_TRANSFER_FROM:case c$.PERMIT2_PERMIT_BATCH:case c$.PERMIT2_TRANSFER_FROM_BATCH:case c$.PAY_PORTION:return[];default:return[]}}_decodeSwapV2(Q){let[,,,Z]=this.abiDecoder.decode(["address","uint256","uint256","address[]","bool"],Q);return!Array.isArray(Z)||!Z.every(dQ)?[]:Z.map((Y)=>Y.toLowerCase())}_decodeSwapV3(Q){let[,,,Z]=this.abiDecoder.decode(["address","uint256","uint256","bytes","bool"],Q);if(typeof Z!="string"||!dQ(Z)||Z.length<2+GR*2+yx)return[];let Y=[];for(let $=2;$<Z.length;$+=GR+yx)Y.push(Z.slice($,$+GR));return Y.map(($)=>$.toLowerCase()).map(($)=>`0x${$}`)}_isSupportedChainId(Q){return Object.values(JR).includes(Q)}_decodeWrappedEth(Q,Z){return this._isSupportedChainId(Z)?[xx[Z].toLowerCase()]:[]}_decodeSweep=(Q)=>{let[Z]=this.abiDecoder.decode(["address","address","uint256"],Q);return typeof Z!="string"||!dQ(Z)?[]:[Z.toLowerCase()]}};var XR=w(()=>{I0();W0();$R();fx();HF();O$0=Object.defineProperty,H$0=Object.getOwnPropertyDescriptor;cF=D$0([e(),I$0(0,g(q1.AbiDecoderDataSource))],cF)});var gx,R$0,L$0,E$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?L$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&R$0(Z,Y,J),J},uF=class{decode(Q,Z){try{return gx.AbiCoder.defaultAbiCoder().decode(Q,Z)}catch{return[]}}};var VR=w(()=>{W0();gx=require("ethers"),R$0=Object.defineProperty,L$0=Object.getOwnPropertyDescriptor;uF=E$0([e()],uF)});var hx,P$0,j$0,A$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?j$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&P$0(Z,Y,J),J},qR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),M$0,pF=class{constructor(Q,Z,Y){this.commandDecoderDataSource=Q,this.tokenDataSource=Z,this.logger=Y("UniswapContextLoader")}logger;canHandle(Q,Z){return typeof Q=="object"&&Q!==null&&"data"in Q&&"selector"in Q&&"chainId"in Q&&typeof Q.chainId=="number"&&dQ(Q.data)&&Q.data!=="0x"&&dQ(Q.selector)&&Q.selector===wx&&M$0.every((Y)=>Z.includes(Y))}async load(Q){let{data:Z,chainId:Y}=Q,$=await this._extractClearSignContexts(Z,Y);return this.logger.debug("load result",{data:{result:$}}),$}async _extractClearSignContexts(Q,Z){try{let Y=new hx.Interface(Sx).parseTransaction({data:Q}),$=Y?.args[0],J=Y?.args[1];if(!dQ($)||!this._isHexaStringArray(J))return[];let X=this._extractCommands($).orDefault([]);if($.length===0||J.length!==X.length)return[];let G=X.reduce((U,K,O)=>{let I=J[O],L=this.commandDecoderDataSource.decode(K,I,Z);return U.push([K,L]),U},[]);if(!this._isChainingSwapSupported(G))return[];let W=[...new Set(G.flatMap(([,U])=>U))];return(await Promise.all(W.map((U)=>this.tokenDataSource.getTokenInfosPayload({address:U,chainId:Z})))).map((U)=>U.caseOf({Left:(K)=>({type:u.ERROR,error:K}),Right:(K)=>({type:u.ETHEREUM_TOKEN,payload:K})}))}catch{return[]}}_extractCommands(Q){return q0.fromNullable(Q.slice(2).match(/../g)).map((Z)=>Z.map((Y)=>`0x${Y}`)).map((Z)=>Z.map((Y)=>_x[Y])).chain((Z)=>Z.every((Y)=>Y!==void 0)?q0.of(Z):YQ)}_isChainingSwapSupported(Q){let Z,Y;for(let[$,J]of Q){if(!vx.includes($))continue;let X=$.slice(0,2);if(Z&&(Z!==J[0]||Y!==X))return!1;Z=J[J.length-1],Y=X}return!0}_isHexaStringArray(Q){return Array.isArray(Q)&&Q.every((Z)=>typeof Z=="string"&&dQ(Z))}};var FR=w(()=>{I0();W0();R0();SQ();QG();$R();HF();iQ();hx=require("ethers"),P$0=Object.defineProperty,j$0=Object.getOwnPropertyDescriptor,M$0=[u.ETHEREUM_TOKEN];pF=A$0([e(),qR(0,g(q1.CommandDecoderDataSource)),qR(1,g(lY.TokenDataSource)),qR(2,g(i0.ContextModuleLoggerFactory))],pF)});var bx=()=>new b0(({bind:Q})=>{Q(q1.AbiDecoderDataSource).to(uF),Q(q1.CommandDecoderDataSource).to(cF),Q(q1.UniswapContextLoader).to(pF)});var cx=w(()=>{W0();XR();VR();FR();HF()});var zR;var ux=w(()=>{jY();zR=class zR{static keyUsageMap=new Map([[wQ.GenuineCheck,1],[wQ.ExchangePayload,2],[wQ.NftMeta,3],[wQ.TrustedName,4],[wQ.BackupProvider,5],[wQ.ProtectOrchestrator,6],[wQ.PluginMeta,7],[wQ.CoinMeta,8],[wQ.SeedIdAuth,9],[wQ.TxSimulationSigner,10],[wQ.Calldata,11],[wQ.Network,12],[wQ.SwapTemplate,13],[wQ.LESMultisig,14],[wQ.GatedSigning,15]]);static mapKeyUsageForFirmware(Q){return Object.values(wQ).includes(Q)?this.keyUsageMap.get(Q)??-1:-1}}});var T$0,N$0,B$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?N$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&T$0(Z,Y,J),J},px=(Q,Z)=>(Y,$)=>Z(Y,$,Q),lF=class{constructor(Q,Z){this.config=Q,this.http=Z}async fetchCertificate(Q){let Z={output:"descriptor",target_device:Q.targetDevice,latest:!0,public_key_id:Q.keyId,public_key_usage:Q.keyUsage};try{let Y=await this.http.get(`${this.config.cal.url}/certificates`,{params:{output:Z.output,target_device:Z.target_device,latest:Z.latest,public_key_id:Z.public_key_id,public_key_usage:Z.public_key_usage}});if(Array.isArray(Y)&&Y.length>0&&this.isValidPkiCertificateResponse(Y[0],this.config.cal.mode)){let $=mQ(fY.appendSignatureToPayload(Y[0].descriptor.data,Y[0].descriptor.signatures[this.config.cal.mode],zX));if(!$)return a(Error("[ContextModule] HttpPkiCertificateDataSource: Cannot generate payload from fetched PKI Certificate"));let J={payload:$,keyUsageNumber:zR.mapKeyUsageForFirmware(Q.keyUsage)};return U0(J)}else return a(Error("[ContextModule] HttpPkiCertificateDataSource: failed to fetch PKI for given descriptor"))}catch{return a(Error("[ContextModule] HttpPkiCertificateDataSource: failed to fetch PKI for given descriptor"))}}isValidPkiCertificateResponse(Q,Z){if(!this.isRecord(Q)||!this.isRecord(Q.descriptor))return!1;let Y=Q.descriptor;return typeof Y.data!="string"||!this.isRecord(Y.signatures)?!1:typeof Y.signatures[Z]=="string"}isRecord(Q){return typeof Q=="object"&&Q!==null}};var WR=w(()=>{I0();W0();R0();SQ();zF();OZ();t8();ux();T$0=Object.defineProperty,N$0=Object.getOwnPropertyDescriptor;lF=B$0([e(),px(0,g(i0.Config)),px(1,g(PQ.NetworkClient))],lF)});var k$0,C$0,S$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?C$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&k$0(Z,Y,J),J},w$0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),mF=class{_dataSource;constructor(Q){this._dataSource=Q}async loadCertificate(Q){return(await this._dataSource.fetchCertificate(Q)).orDefault(void 0)}};var KR=w(()=>{W0();RZ();k$0=Object.defineProperty,C$0=Object.getOwnPropertyDescriptor;mF=S$0([e(),w$0(0,g(BQ.PkiCertificateDataSource))],mF)});var LU=()=>new b0(({bind:Q})=>{Q(BQ.PkiCertificateDataSource).to(lF),Q(BQ.PkiCertificateLoader).to(mF)});var lx=w(()=>{W0();WR();KR();RZ()});var _$0,v$0,x$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?v$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&_$0(Z,Y,J),J},mx=(Q,Z)=>(Y,$)=>Z(Y,$,Q),dF=class{constructor(Q,Z){this.config=Q,this.http=Z??ZG(Q)}http;async report(Q){try{await this.http.post(`${this.config.reporter.url}/v1/blind-signing-events`,{...Q,source:this.config.appSource},{responseType:"void"})}catch{return a(Error("[ContextModule] HttpBlindSigningReporterDatasource: Failed to report blind signing event"))}return U0(void 0)}};var UR=w(()=>{W0();R0();SQ();OZ();_F();_$0=Object.defineProperty,v$0=Object.getOwnPropertyDescriptor;dF=x$0([e(),mx(0,g(i0.Config)),mx(1,g(PQ.NetworkClient))],dF)});var YG;var EU=w(()=>{YG={BlindSigningReporterDatasource:Symbol.for("BlindSigningReporterDatasource"),BlindSigningReporter:Symbol.for("BlindSigningReporter")}});var f$0,y$0,g$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?y$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&f$0(Z,Y,J),J},h$0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),nF=class{constructor(Q){this.dataSource=Q}async report(Q){return this.dataSource.report(Q)}};var OR=w(()=>{W0();EU();f$0=Object.defineProperty,y$0=Object.getOwnPropertyDescriptor;nF=g$0([e(),h$0(0,g(YG.BlindSigningReporterDatasource))],nF)});var dx=()=>new b0(({bind:Q})=>{Q(YG.BlindSigningReporterDatasource).to(dF),Q(YG.BlindSigningReporter).to(nF)});var nx=w(()=>{W0();UR();EU();OR()});var b$0,c$0,u$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?c$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&b$0(Z,Y,J),J},HR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),PU=class{constructor(Q,Z,Y){this.config=Q,this.http=Y??ZG(Q),this.logger=Z("HttpSignReporterDatasource")}http;logger;async report(Q){try{let Z=this.buildDto(Q,this.config.appSource);this.logger.debug("[report] Posting signing event",{data:Z}),await this.http.post(`${this.config.reporter.url}/v2/blind-signing-events`,Z,{responseType:"void"})}catch{return a(Error("[ContextModule] HttpSignReporterDatasource: Failed to report signing event"))}return U0(void 0)}buildDto(Q,Z){let Y={isBlindSign:Q.isBlindSign,sessionId:Q.sessionId??null,envData:{modelId:Q.modelId,signerAppVersion:Q.signerAppVersion,deviceVersion:Q.deviceVersion,source:Z,...Q.platform!==void 0&&{platform:Q.platform},...Q.appVersion!==void 0&&{appVersion:Q.appVersion},...Q.platformOS!==void 0&&{platformOS:Q.platformOS},...Q.platformVersion!==void 0&&{platformVersion:Q.platformVersion},...Q.liveAppContext!==void 0&&{liveAppContext:Q.liveAppContext}}};switch(Q.chain){case"ETH":return{...Y,chain:"ETH",chainData:{chain:"ETH",signatureId:Q.signatureId,signingMethod:Q.signingMethod,targetAddress:Q.targetAddress,chainId:Q.chainId,blindSignReason:Q.blindSignReason,...Q.selectorId!==void 0&&{selectorId:Q.selectorId},...Q.clearSigningType!==void 0&&{clearSigningType:Q.clearSigningType},...Q.partialContextErrors!==void 0&&{partialContextErrors:Q.partialContextErrors}}};case"SOL":return{...Y,chain:"SOL",chainData:{chain:"SOL",signatureId:Q.signatureId,signingMethod:Q.signingMethod,targetAddress:Q.targetAddress,blindSignReason:Q.blindSignReason,programIds:Q.programIds,unrecognizedPrograms:Q.unrecognizedPrograms,...Q.transactionSignature!==void 0&&{transactionSignature:Q.transactionSignature}}}}}};var ox=w(()=>{W0();R0();SQ();OZ();_F();b$0=Object.defineProperty,c$0=Object.getOwnPropertyDescriptor;PU=u$0([e(),HR(0,g(i0.Config)),HR(1,g(i0.ContextModuleLoggerFactory)),HR(2,g(PQ.NetworkClient))],PU)});var oF;var DR=w(()=>{oF={SignReporterDatasource:Symbol.for("SignReporterDatasource"),SignReporter:Symbol.for("SignReporter")}});var p$0,l$0,m$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?l$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&p$0(Z,Y,J),J},d$0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),jU=class{constructor(Q){this.dataSource=Q}async report(Q){return this.dataSource.report(Q)}};var sx=w(()=>{W0();DR();p$0=Object.defineProperty,l$0=Object.getOwnPropertyDescriptor;jU=m$0([e(),d$0(0,g(oF.SignReporterDatasource))],jU)});var IR=()=>new b0(({bind:Q})=>{Q(oF.SignReporterDatasource).to(PU),Q(oF.SignReporter).to(jU)});var ix=w(()=>{W0();ox();DR();sx()});var n$0,o$0,s$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?o$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&n$0(Z,Y,J),J},ax=(Q,Z)=>(Y,$)=>Z(Y,$,Q),lV=class{constructor(Q,Z){this.config=Q,this.http=Z}async check({path:Q,body:Z}){let Y;try{Y=await this.http.post(`${this.config.web3checks.url}${Q}`,Z)}catch{return a(Error("[ContextModule] HttpTransactionCheckDataSource: Failed to fetch web3 check"))}return this._isDto(Y)?U0({publicKeyId:Y.public_key_id,descriptor:Y.descriptor}):a(Error("[ContextModule] HttpTransactionCheckDataSource: Invalid web3 check response"))}_isDto(Q){return Q!=null&&typeof Q=="object"&&"public_key_id"in Q&&Q.public_key_id!=null&&typeof Q.public_key_id=="string"&&"descriptor"in Q&&Q.descriptor!=null&&typeof Q.descriptor=="string"}};var RR=w(()=>{W0();R0();SQ();OZ();n$0=Object.defineProperty,o$0=Object.getOwnPropertyDescriptor;lV=s$0([e(),ax(0,g(i0.Config)),ax(1,g(PQ.NetworkClient))],lV)});var mY;var HX=w(()=>{mY={TransactionCheckDataSource:Symbol.for("TransactionCheckDataSource"),TransactionCheckLoader:Symbol.for("TransactionCheckLoader"),TypedDataCheckLoader:Symbol.for("TypedDataCheckLoader")}});var $G;var sF=w(()=>{$G=((Q)=>(Q.ETHEREUM_TRANSACTION="/ethereum/scan/tx",Q.ETHEREUM_TYPED_DATA="/ethereum/scan/eip-712",Q.SOLANA_TRANSACTION="/solana/scan/tx",Q))($G||{})});var i$0,a$0,r$0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?a$0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&i$0(Z,Y,J),J},LR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),t$0,AU=class{constructor(Q,Z,Y){this.transactionCheckDataSource=Q,this.certificateLoader=Z,this.logger=Y("EthereumTransactionCheckLoader")}logger;canHandle(Q,Z){return!t$0.every((Y)=>Z.includes(Y))||typeof Q!="object"||Q===null?!1:("from"in Q)&&dQ(Q.from)&&Q.from!=="0x"&&("chainId"in Q)&&typeof Q.chainId=="number"&&("transaction"in Q)&&Q.transaction!==void 0&&("deviceModelId"in Q)&&Q.deviceModelId!==void 0&&Q.deviceModelId!==JQ.NANO_S}async load(Q){let{from:Z,chainId:Y,transaction:$}=Q,J=DQ($);if(!Z||!J)return this.logger.debug("load result",{data:{result:[]}}),[];let X=[await(await this.transactionCheckDataSource.check({path:$G.ETHEREUM_TRANSACTION,body:{tx:{from:Z,raw:J},chain:Y}})).caseOf({Left:(G)=>Promise.resolve({type:u.ERROR,error:G}),Right:async(G)=>{let W=await this.certificateLoader.loadCertificate({keyId:G.publicKeyId,keyUsage:wQ.TxSimulationSigner,targetDevice:Q.deviceModelId});return{type:u.ETHEREUM_TRANSACTION_CHECK,payload:G.descriptor,certificate:W}}})];return this.logger.debug("load result",{data:{result:X}}),X}};var rx=w(()=>{I0();W0();SQ();RZ();jY();HX();sF();iQ();i$0=Object.defineProperty,a$0=Object.getOwnPropertyDescriptor,t$0=[u.ETHEREUM_TRANSACTION_CHECK];AU=r$0([e(),LR(0,g(mY.TransactionCheckDataSource)),LR(1,g(BQ.PkiCertificateLoader)),LR(2,g(i0.ContextModuleLoggerFactory))],AU)});var e$0,QJ0,ZJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?QJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&e$0(Z,Y,J),J},ER=(Q,Z)=>(Y,$)=>Z(Y,$,Q),YJ0,MU=class{constructor(Q,Z,Y){this.transactionCheckDataSource=Q,this.certificateLoader=Z,this.logger=Y("EthereumTypedDataCheckLoader")}logger;canHandle(Q,Z){return!YJ0.every((Y)=>Z.includes(Y))||typeof Q!="object"||Q===null?!1:("from"in Q)&&dQ(Q.from)&&Q.from!=="0x"&&("data"in Q)&&typeof Q.data=="object"&&("deviceModelId"in Q)&&Q.deviceModelId!==void 0&&Q.deviceModelId!==JQ.NANO_S}async load(Q){let{from:Z,data:Y}=Q;if(!Z||!Y)return this.logger.debug("load result",{data:{result:[]}}),[];let $=[await(await this.transactionCheckDataSource.check({path:$G.ETHEREUM_TYPED_DATA,body:{msg:{from:Z,data:Y}}})).caseOf({Left:(J)=>Promise.resolve({type:u.ERROR,error:J}),Right:async(J)=>{let X=await this.certificateLoader.loadCertificate({keyId:J.publicKeyId,keyUsage:wQ.TxSimulationSigner,targetDevice:Q.deviceModelId});return{type:u.ETHEREUM_TRANSACTION_CHECK,payload:J.descriptor,certificate:X}}})];return this.logger.debug("load result",{data:{result:$}}),$}};var tx=w(()=>{I0();W0();SQ();RZ();jY();HX();sF();iQ();e$0=Object.defineProperty,QJ0=Object.getOwnPropertyDescriptor,YJ0=[u.ETHEREUM_TRANSACTION_CHECK];MU=ZJ0([e(),ER(0,g(mY.TransactionCheckDataSource)),ER(1,g(BQ.PkiCertificateLoader)),ER(2,g(i0.ContextModuleLoggerFactory))],MU)});var ex=()=>new b0(({bind:Q})=>{Q(mY.TransactionCheckDataSource).to(lV),Q(mY.TransactionCheckLoader).to(AU),Q(mY.TypedDataCheckLoader).to(MU)});var Qf=w(()=>{W0();RR();HX();rx();tx()});function $J0(Q){if(Q.length>=255)throw TypeError("Alphabet too long");let Z=new Uint8Array(256);for(let K=0;K<Z.length;K++)Z[K]=255;for(let K=0;K<Q.length;K++){let O=Q.charAt(K),I=O.charCodeAt(0);if(Z[I]!==255)throw TypeError(O+" is ambiguous");Z[I]=K}let Y=Q.length,$=Q.charAt(0),J=Math.log(Y)/Math.log(256),X=Math.log(256)/Math.log(Y);function G(K){if(K instanceof Uint8Array);else if(ArrayBuffer.isView(K))K=new Uint8Array(K.buffer,K.byteOffset,K.byteLength);else if(Array.isArray(K))K=Uint8Array.from(K);if(!(K instanceof Uint8Array))throw TypeError("Expected Uint8Array");if(K.length===0)return"";let O=0,I=0,L=0,A=K.length;while(L!==A&&K[L]===0)L++,O++;let M=(A-L)*X+1>>>0,k=new Uint8Array(M);while(L!==A){let S=K[L],_=0;for(let x=M-1;(S!==0||_<I)&&x!==-1;x--,_++)S+=256*k[x]>>>0,k[x]=S%Y>>>0,S=S/Y>>>0;if(S!==0)throw Error("Non-zero carry");I=_,L++}let B=M-I;while(B!==M&&k[B]===0)B++;let C=$.repeat(O);for(;B<M;++B)C+=Q.charAt(k[B]);return C}function W(K){if(typeof K!=="string")throw TypeError("Expected String");if(K.length===0)return new Uint8Array;let O=0,I=0,L=0;while(K[O]===$)I++,O++;let A=(K.length-O)*J+1>>>0,M=new Uint8Array(A);while(O<K.length){let S=K.charCodeAt(O);if(S>255)return;let _=Z[S];if(_===255)return;let x=0;for(let f=A-1;(_!==0||x<L)&&f!==-1;f--,x++)_+=Y*M[f]>>>0,M[f]=_%256>>>0,_=_/256>>>0;if(_!==0)throw Error("Non-zero carry");L=x,O++}let k=A-L;while(k!==A&&M[k]===0)k++;let B=new Uint8Array(I+(A-k)),C=I;while(k!==A)B[C++]=M[k++];return B}function U(K){let O=W(K);if(O)return O;throw Error("Non-base"+Y+" character")}return{encode:G,decodeUnsafe:W,decode:U}}var Zf;var Yf=w(()=>{Zf=$J0});var JJ0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",PR;var $f=w(()=>{Yf();PR=Zf(JJ0)});class jR{static encode(Q){return PR.encode(Q)}static decode(Q){return PR.decode(Q)}}var Jf=w(()=>{$f()});var u$;var JG=w(()=>{I0();R0();u$=iO([lX(JQ.NANO_X),lX(JQ.NANO_SP),lX(JQ.STAX),lX(JQ.FLEX),lX(JQ.APEX)])});var Gf;var Xf=w(()=>{R0();Gf=RQ.custom({decode:(Q)=>Q instanceof Uint8Array?U0(Q):a("Expected a Uint8Array"),encode:(Q)=>Q})});var GJ0,XJ0,VJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?XJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&GJ0(Z,Y,J),J},AR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),qJ0,FJ0,TU=class{constructor(Q,Z,Y,$=jR){this.transactionCheckDataSource=Q,this.certificateLoader=Z,this.bs58Encoder=$,this.logger=Y("SolanaTransactionCheckLoader")}logger;canHandle(Q,Z){return qJ0.every((Y)=>Z.includes(Y))?FJ0.decode(Q).caseOf({Left:()=>!1,Right:({transactionCheck:{from:Y,transactionBytes:$}})=>Y.length>0&&$.length>0}):!1}async load(Q){let{from:Z,transactionBytes:Y,chain:$}=Q.transactionCheck,J=this.bs58Encoder.encode(Y),X=[await(await this.transactionCheckDataSource.check({path:$G.SOLANA_TRANSACTION,body:{tx:{from:Z,raw:J},chain:$}})).caseOf({Left:(G)=>Promise.resolve({type:u.ERROR,error:G}),Right:async(G)=>{let W=await this.certificateLoader.loadCertificate({keyId:G.publicKeyId,keyUsage:wQ.TxSimulationSigner,targetDevice:Q.deviceModelId});return{type:u.SOLANA_TRANSACTION_CHECK,payload:{descriptor:G.descriptor},certificate:W}}})];return this.logger.debug("load result",{data:{result:X}}),X}};var Vf=w(()=>{W0();R0();SQ();RZ();jY();HX();sF();iQ();Jf();JG();Xf();GJ0=Object.defineProperty,XJ0=Object.getOwnPropertyDescriptor,qJ0=[u.SOLANA_TRANSACTION_CHECK],FJ0=RQ.interface({deviceModelId:u$,transactionCheck:RQ.interface({from:TQ,transactionBytes:Gf,chain:I8})});TU=VJ0([e(),AR(0,g(mY.TransactionCheckDataSource)),AR(1,g(BQ.PkiCertificateLoader)),AR(2,g(i0.ContextModuleLoggerFactory))],TU)});var qf=()=>new b0(({bind:Q})=>{Q(mY.TransactionCheckDataSource).to(lV),Q(mY.TransactionCheckLoader).to(TU)});var Ff=w(()=>{W0();RR();HX();Vf()});var zJ0,NU;var MR=w(()=>{R0();zJ0=RQ.custom({decode:(Q)=>typeof Q=="string"&&Q.length>0?U0(Q):a("Expected a non-empty string"),encode:(Q)=>Q}),NU=RQ.interface({signedDescriptor:zJ0,keyId:TQ,keyUsage:TQ})});var zf=(Q)=>{let Z=2**Q-1;return RQ.custom({decode:(Y)=>typeof Y=="number"&&Number.isInteger(Y)&&Y>=0&&Y<=Z?U0(Y):a(`Expected a u${Q} integer (0..=${Z})`),encode:(Y)=>Y})},BU,kU;var iF=w(()=>{R0();BU=zf(8),kU=zf(16)});var WJ0,KJ0,UJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?KJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&WJ0(Z,Y,J),J},Wf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),aF=class{constructor(Q,Z){this.config=Q,this.http=Z}async getAltResolution({altAddress:Q,entryIndex:Z,challenge:Y}){let $=BU.decode(Z);if($.isLeft())return a(Error(`[ContextModule] HttpAltResolutionDataSource: invalid entryIndex (got ${Z}): ${$.leftOrDefault("")}`));let J;try{J=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/solana/alt-resolution/${Q}/${Z}`,{params:{challenge:Y}})}catch(X){let G=X instanceof Error?X.message:String(X);return a(Error(`[ContextModule] HttpAltResolutionDataSource: Failed to fetch ALT resolution: ${G}`))}return NU.decode(J).caseOf({Left:(X)=>a(Error(`[ContextModule] HttpAltResolutionDataSource: malformed response for (${Q}, ${Z}): ${X}`)),Right:(X)=>{let G;try{G=fY.hexToBytes(X.signedDescriptor)}catch(W){return a(Error(`[ContextModule] HttpAltResolutionDataSource: invalid hex in signedDescriptor for (${Q}, ${Z}): ${W.message}`))}return U0({altAddress:Q,entryIndex:Z,descriptor:G,resolvedAddress:J.resolvedAddress,keyId:X.keyId,keyUsage:X.keyUsage})}})}};var TR=w(()=>{W0();R0();SQ();OZ();t8();MR();iF();WJ0=Object.defineProperty,KJ0=Object.getOwnPropertyDescriptor;aF=UJ0([e(),Wf(0,g(i0.Config)),Wf(1,g(PQ.NetworkClient))],aF)});var DX;var CU=w(()=>{DX={AltResolutionDataSource:Symbol.for("AltResolutionDataSource"),AltResolutionContextLoader:Symbol.for("AltResolutionContextLoader")}});function Kf(Q,Z){let Y=new Map;return($,J)=>{let X=`${$}::${J}`,G=Y.get(X);return G||(G=Q.loadCertificate({keyId:$,keyUsage:J,targetDevice:Z}),Y.set(X,G)),G}}var Uf=()=>{};async function mV({requests:Q,deviceModelId:Z,certificateLoader:Y,logger:$,label:J,fetch:X,toContext:G,describe:W}){$.debug(`[load] Fetching ${J} descriptors`,{data:{count:Q.length}});let U=await Promise.all(Q.map(async(O)=>({request:O,either:await X(O)}))),K=Kf(Y,Z);return Promise.all(U.map(({request:O,either:I})=>I.caseOf({Left:async(L)=>($.warn(`[load] ${J} fetch failed`,{data:{...W(O),error:L.message}}),{type:u.ERROR,error:L}),Right:async(L)=>{let A;try{A=await K(L.keyId,L.keyUsage)}catch(M){let k=M instanceof Error?M:Error(String(M));return $.warn(`[load] ${J} certificate load failed`,{data:{...W(O),error:k.message}}),{type:u.ERROR,error:k}}if(!A){let M=Error(`[ContextModule] ${J}: certificate is missing`);return $.warn(`[load] ${J} certificate missing`,{data:W(O)}),{type:u.ERROR,error:M}}return G(L,A)}})))}var SU=w(()=>{iQ();Uf()});var OJ0,HJ0,DJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?HJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&OJ0(Z,Y,J),J},NR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),IJ0,RJ0,LJ0,rF=class{constructor(Q,Z,Y){this.dataSource=Q,this.certificateLoader=Z,this.logger=Y("AltResolutionContextLoader")}logger;canHandle(Q,Z){return IJ0.every((Y)=>Z.includes(Y))?LJ0.decode(Q).caseOf({Left:()=>!1,Right:({requests:Y})=>Y.length>0&&Y.every(($)=>$.altAddress.length>0&&$.challenge.length>0)}):!1}async load(Q){return mV({requests:Q.requests,deviceModelId:Q.deviceModelId,certificateLoader:this.certificateLoader,logger:this.logger,label:"ALT_RESOLUTION",fetch:(Z)=>this.dataSource.getAltResolution(Z),toContext:(Z,Y)=>{let $={descriptor:Z.descriptor,resolvedAddress:Z.resolvedAddress};return{type:u.SOLANA_ALT_RESOLUTION,payload:$,certificate:Y}},describe:(Z)=>({altAddress:Z.altAddress,entryIndex:Z.entryIndex})})}};var BR=w(()=>{W0();R0();SQ();RZ();CU();iQ();SU();JG();iF();OJ0=Object.defineProperty,HJ0=Object.getOwnPropertyDescriptor,IJ0=[u.SOLANA_ALT_RESOLUTION],RJ0=RQ.interface({altAddress:TQ,entryIndex:BU,challenge:TQ}),LJ0=RQ.interface({deviceModelId:u$,requests:bZ(RJ0)});rF=DJ0([e(),NR(0,g(DX.AltResolutionDataSource)),NR(1,g(BQ.PkiCertificateLoader)),NR(2,g(i0.ContextModuleLoggerFactory))],rF)});var Of=()=>new b0(({bind:Q})=>{Q(DX.AltResolutionDataSource).to(aF),Q(DX.AltResolutionContextLoader).to(rF)});var Hf=w(()=>{W0();TR();CU();BR()});var wU;var kR=w(()=>{wU={EnumVariantContextLoader:Symbol.for("EnumVariantContextLoader")}});var t1;var tF=w(()=>{t1={InstructionInfoDataSource:Symbol.for("InstructionInfoDataSource"),InstructionInfoContextLoader:Symbol.for("InstructionInfoContextLoader")}});function dV(Q,Z){return Q.loadCertificate(Z).then((Y)=>({ok:!0,value:Y}),(Y)=>({ok:!1,error:Y instanceof Error?Y:Error(typeof Y=="string"?Y:JSON.stringify(Y))}))}var _U=()=>{};var EJ0,PJ0,jJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?PJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&EJ0(Z,Y,J),J},vU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),AJ0,MJ0="solana-mainnet",TJ0,NJ0,eF=class{constructor(Q,Z,Y,$){this.dataSource=Q,this.config=Z,this.certificateLoader=Y,this.logger=$("EnumVariantContextLoader")}logger;canHandle(Q,Z){return AJ0.every((Y)=>Z.includes(Y))?NJ0.decode(Q).caseOf({Left:()=>!1,Right:({selections:Y})=>Y.length>0&&Y.every(($)=>$.programId.length>0&&$.enumId.length>0)}):!1}async load(Q){let Z=Q.network||MJ0,Y=Array.from(new Set(Q.selections.map((O)=>O.programId)));this.logger.debug("[load] Fetching enum variants",{data:{network:Z,programCount:Y.length,selectionCount:Q.selections.length}});let $=dV(this.certificateLoader,{keyId:LZ.CalCalldataKey,keyUsage:wQ.Calldata,targetDevice:Q.deviceModelId}),J=Promise.all(Y.map((O)=>this.dataSource.getInstructionInfo({programId:O,network:Z}))),[X,G]=await Promise.all([$,J]);if(!X.ok||!X.value){let O=X.ok?Error("[ContextModule] EnumVariantContextLoader: certificate is missing"):X.error;return this.logger.warn("[load] ENUM_VARIANT certificate unavailable",{data:{error:O.message}}),Q.selections.map(()=>({type:u.ERROR,error:O}))}let W=X.value,U=new Map(Y.map((O,I)=>[O,G[I]])),K=this.config.cal.mode??"prod";return Q.selections.map((O)=>{let I=U.get(O.programId);if(!I){let L=Error(`[ContextModule] EnumVariantContextLoader: no CAL response for program ${O.programId}`);return this.logger.warn("[load] ENUM_VARIANT fetch failed",{data:{programId:O.programId,enumId:O.enumId,variantIndex:O.variantIndex,error:L.message}}),{type:u.ERROR,error:L}}return I.caseOf({Left:(L)=>(this.logger.warn("[load] ENUM_VARIANT fetch failed",{data:{programId:O.programId,enumId:O.enumId,variantIndex:O.variantIndex,error:L.message}}),{type:u.ERROR,error:L}),Right:(L)=>{let A=this.lookupVariant(L,O);if(!A){let k=Error(`[ContextModule] EnumVariantContextLoader: CAL has no enum variant for (${O.programId}, ${O.enumId}, ${O.variantIndex})`);return this.logger.warn("[load] ENUM_VARIANT not found in CAL response",{data:{programId:O.programId,enumId:O.enumId,variantIndex:O.variantIndex}}),{type:u.ERROR,error:k}}if(!A.descriptor.signature){let k=Error(`[ContextModule] EnumVariantContextLoader: missing '${K}' signature for (${O.programId}, ${O.enumId}, ${O.variantIndex})`);return this.logger.warn("[load] ENUM_VARIANT missing signature",{data:{programId:O.programId,enumId:O.enumId,variantIndex:O.variantIndex,mode:K}}),{type:u.ERROR,error:k}}let M={programId:O.programId,enumId:O.enumId,variantIndex:O.variantIndex,descriptor:A.descriptor};return{type:u.SOLANA_ENUM_VARIANT,payload:M,certificate:W}}})})}lookupVariant(Q,Z){return Q.enumVariants.find((Y)=>Y.enumId===Z.enumId&&Y.variantIndex===Z.variantIndex)}};var CR=w(()=>{W0();R0();SQ();RZ();h$();jY();tF();iQ();_U();JG();iF();EJ0=Object.defineProperty,PJ0=Object.getOwnPropertyDescriptor,AJ0=[u.SOLANA_ENUM_VARIANT],TJ0=RQ.interface({programId:TQ,enumId:TQ,variantIndex:kU}),NJ0=RQ.interface({deviceModelId:u$,selections:bZ(TJ0),network:WZ(TQ)});eF=jJ0([e(),vU(0,g(t1.InstructionInfoDataSource)),vU(1,g(i0.Config)),vU(2,g(BQ.PkiCertificateLoader)),vU(3,g(i0.ContextModuleLoggerFactory))],eF)});var Df=()=>new b0(({bind:Q})=>{Q(wU.EnumVariantContextLoader).to(eF)});var If=w(()=>{W0();kR();CR()});var EJ;var xU=w(()=>{EJ=((Q)=>(Q[Q.MAINNET=900]="MAINNET",Q[Q.DEVNET=901]="DEVNET",Q[Q.TESTNET=902]="TESTNET",Q))(EJ||{})});var BJ0,Lf,kJ0,fU,Rf,CJ0,SJ0,Ef;var Pf=w(()=>{R0();BJ0=RQ.interface({prod:WZ(TQ),test:WZ(TQ)}),Lf=RQ.interface({data:TQ,signatures:BJ0}),kJ0=RQ.interface({descriptor:Lf}),fU=RQ.interface({descriptor:TQ}),Rf=RQ.interface({signer:TQ,writable:TQ}),CJ0=RQ.interface({count_min:WZ(I8),count_max:WZ(I8),remaining_policy:WZ(Rf),slots:WZ(bZ(Rf))}),SJ0=RQ.interface({discriminator_hex:WZ(TQ),descriptor:Lf,enum_variants:WZ(aO(TQ,aO(TQ,kJ0))),display_fields:WZ(bZ(fU)),value_flow_ports:WZ(bZ(fU)),hide_rules:WZ(bZ(fU)),account_resets:WZ(bZ(fU)),account_schema:WZ(CJ0)}),Ef=RQ.interface({id:TQ,chain_id:I8,instructions:bZ(SJ0)})});var GG;var SR=w(()=>{GG=((Q)=>(Q[Q.DISPLAY_FIELD=0]="DISPLAY_FIELD",Q[Q.VALUE_FLOW_PORT=1]="VALUE_FLOW_PORT",Q[Q.HIDE_RULE=2]="HIDE_RULE",Q[Q.ACCOUNT_RESET=3]="ACCOUNT_RESET",Q))(GG||{})});function Mf(Q,Z){return Q[Z]}function wJ0(Q=[]){return Q.map((Z)=>({account_indices:Z.account_indices,optional_account_strategy:Z.optional_account_strategy,token_value:Z.token_value,active_when:Z.active_when}))}function _J0(Q=[]){return Q.flatMap((Z)=>Z.account_index===void 0?[]:[{account_index:Z.account_index,require_pre_balance_zero:Z.require_pre_balance_zero,value_kind:Z.value_kind,token:Z.token,require_native_pre_balance_zero:Z.require_native_pre_balance_zero}])}function vJ0(Q=[]){return Q.map((Z)=>({rule_set_index:Z.rule_set_index,target:Z.target,condition:Z.condition}))}function xJ0(Q){return Q===void 0?[]:Q.account_index===void 0||Q.owner===void 0?[]:[{account_index:Q.account_index,owner:Q.owner}]}function Af(Q){let Z=jf.has(Q.signer)?Q.signer:"EITHER",Y=jf.has(Q.writable)?Q.writable:"EITHER";return{signer:Z,writable:Y}}function fJ0(Q){if(Q!==void 0)return{count_min:Q.count_min??0,count_max:Q.count_max??255,remaining_policy:Q.remaining_policy?Af(Q.remaining_policy):{signer:"EITHER",writable:"EITHER"},slots:(Q.slots??[]).map(Af)}}function yJ0(Q=[]){return Q.map((Z)=>({name:Z.name,param:Z.param??{type:""}}))}function gJ0(Q){return[...(Q.display_fields??[]).map((Z)=>({kind:GG.DISPLAY_FIELD,data:Z.descriptor})),...(Q.value_flow_ports??[]).map((Z)=>({kind:GG.VALUE_FLOW_PORT,data:Z.descriptor})),...(Q.hide_rules??[]).map((Z)=>({kind:GG.HIDE_RULE,data:Z.descriptor})),...(Q.account_resets??[]).map((Z)=>({kind:GG.ACCOUNT_RESET,data:Z.descriptor}))]}function Tf(Q,Z){let Y=[];for(let[$,J]of Object.entries(Q.enum_variants??{}))for(let[X,G]of Object.entries(J)){let W=Number(X);kU.decode(W).isLeft()||Y.push({enumId:$,variantIndex:W,descriptor:{data:G.descriptor.data,signature:Mf(G.descriptor.signatures,Z)??""}})}return Y}function Nf(Q,Z){return Object.values(Q).flatMap((Y)=>Tf(Y,Z))}function Bf(Q,Z,Y,$){let J=Mf(Y.descriptor.signatures,$);return J?U0({programId:Q,discriminator:Z,instructionName:Y.instruction_name,instructionInfo:{data:Y.descriptor.data,signature:J},substructures:gJ0(Y),enumVariants:Tf(Y,$),idlDescriptor:{typePool:Y.idl_descriptor?.type_pool??[],rootType:Y.idl_descriptor?.root_type??0},mintAssociations:Y.mint_association?[Y.mint_association]:[],ownerAssociations:xJ0(Y.owner_association),valueFlowPorts:wJ0(Y.value_flow_ports),accountResets:_J0(Y.account_resets),displayFields:yJ0(Y.display_fields),hideRules:vJ0(Y.hide_rules),accountSchema:fJ0(Y.account_schema)}):a(Error(`[ContextModule] InstructionInfoDataSource: missing '${$}' signature for (${Q}, ${Z})`))}var jf;var kf=w(()=>{R0();SR();iF();jf=new Set(["FORBIDDEN","EITHER","REQUIRED"])});var hJ0,bJ0,cJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?bJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&hJ0(Z,Y,J),J},Cf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),uJ0,Q4=class{constructor(Q,Z){this.config=Q,this.http=Z}async getInstructionInfo({programId:Q,network:Z}){let Y=uJ0[Z]??EJ.MAINNET,$;try{$=await this.http.get(`${this.config.cal.url}/solana_programs`,{params:{id:Q,chain_id:Y,output:"id,chain_id,instructions",ref:`branch:${this.config.cal.branch}`}})}catch(X){let G=X instanceof Error?X.message:String(X);return a(Error(`[ContextModule] HttpInstructionInfoDataSource: Failed to fetch instruction descriptors: ${G}`))}if(!Array.isArray($)||$.length===0)return a(Error(`[ContextModule] HttpInstructionInfoDataSource: empty response for program ${Q}`));let J=$.find((X)=>X!=null&&typeof X=="object"&&X.id===Q);return J===void 0?a(Error(`[ContextModule] HttpInstructionInfoDataSource: no descriptors for program ${Q}`)):Ef.decode(J).caseOf({Left:(X)=>a(Error(`[ContextModule] HttpInstructionInfoDataSource: malformed descriptors for program ${Q}: ${X}`)),Right:()=>{let X=this.config.cal.mode??"prod",G=J.instructions,W=Object.fromEntries(G.map((K)=>[K.discriminator_hex??"",K])),U=Object.fromEntries(Object.entries(W).map(([K,O])=>[K,Bf(Q,K,O,X)]));return U0({programId:Q,descriptors:U,enumVariants:Nf(W,X)})}})}};var wR=w(()=>{W0();R0();SQ();xU();OZ();Pf();kf();hJ0=Object.defineProperty,bJ0=Object.getOwnPropertyDescriptor,uJ0={"solana-mainnet":EJ.MAINNET,"solana-devnet":EJ.DEVNET,"solana-testnet":EJ.TESTNET};Q4=cJ0([e(),Cf(0,g(i0.Config)),Cf(1,g(PQ.NetworkClient))],Q4)});var pJ0,lJ0,mJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?lJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&pJ0(Z,Y,J),J},_R=(Q,Z)=>(Y,$)=>Z(Y,$,Q),dJ0,nJ0="solana-mainnet",oJ0,sJ0,Z4=class{constructor(Q,Z,Y){this.dataSource=Q,this.certificateLoader=Z,this.logger=Y("InstructionInfoContextLoader")}logger;canHandle(Q,Z){return dJ0.every((Y)=>Z.includes(Y))?sJ0.decode(Q).caseOf({Left:()=>!1,Right:({instructions:Y})=>Y.length>0&&Y.every(($)=>$.programId.length>0)}):!1}async load(Q){let Z=Q.network||nJ0,Y=Array.from(new Set(Q.instructions.map((K)=>K.programId)));this.logger.debug("[load] Fetching instruction descriptors",{data:{network:Z,programCount:Y.length,instructionCount:Q.instructions.length}});let $=dV(this.certificateLoader,{keyId:LZ.CalCalldataKey,keyUsage:wQ.Calldata,targetDevice:Q.deviceModelId}),J=Promise.all(Y.map(async(K)=>({programId:K,either:await this.dataSource.getInstructionInfo({programId:K,network:Z})}))),[X,G]=await Promise.all([$,J]);if(!X.ok||!X.value){let K=X.ok?Error("[ContextModule] InstructionInfoContextLoader: certificate is missing"):X.error;return this.logger.warn("[load] INSTRUCTION_INFO certificate unavailable",{data:{error:K.message}}),Y.map(()=>({type:u.ERROR,error:K}))}let W=X.value,U=[];for(let{programId:K,either:O}of G)O.caseOf({Left:(I)=>{this.logger.warn("[load] Failed to fetch instruction descriptors for program",{data:{programId:K,error:I.message}}),U.push({type:u.ERROR,error:I})},Right:(I)=>{let L=this.collectWantedDiscriminators(K,Q.instructions);for(let[A,M]of Object.entries(I.descriptors))L!==null&&!L.has(A)||U.push(M.caseOf({Left:(k)=>(this.logger.warn("[load] INSTRUCTION_INFO descriptor error",{data:{programId:K,discriminator:A,error:k.message}}),{type:u.ERROR,error:k}),Right:(k)=>({type:u.SOLANA_INSTRUCTION_INFO,payload:k,certificate:W})}))}});return this.logger.debug("[load] Emitted contexts",{data:{count:U.length}}),U}collectWantedDiscriminators(Q,Z){let Y=new Set,$=!1;for(let J of Z)J.programId===Q&&(J.discriminator===void 0?$=!0:Y.add(J.discriminator));return $?null:Y}};var vR=w(()=>{W0();R0();SQ();RZ();h$();jY();tF();iQ();_U();JG();pJ0=Object.defineProperty,lJ0=Object.getOwnPropertyDescriptor,dJ0=[u.SOLANA_INSTRUCTION_INFO],oJ0=RQ.interface({programId:TQ,discriminator:WZ(TQ)}),sJ0=RQ.interface({deviceModelId:u$,instructions:bZ(oJ0),network:WZ(TQ)});Z4=mJ0([e(),_R(0,g(t1.InstructionInfoDataSource)),_R(1,g(BQ.PkiCertificateLoader)),_R(2,g(i0.ContextModuleLoggerFactory))],Z4)});var Sf=()=>new b0(({bind:Q})=>{Q(t1.InstructionInfoDataSource).to(Q4),Q(t1.InstructionInfoContextLoader).to(Z4)});var wf=w(()=>{W0();wR();tF();vR()});var iJ0,aJ0,rJ0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?aJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&iJ0(Z,Y,J),J},xR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),yU=class{constructor(Q,Z,Y){this.config=Q,this.http=Y,this.logger=Z("HttpLifiDataSource")}logger;async getTransactionDescriptorsPayload({templateId:Q}){this.logger.debug("[getTransactionDescriptorsPayload] Fetching transaction descriptors",{data:{templateId:Q}});try{let Z=await this.http.get(`${this.config.cal.url}/swap_templates`,{params:{template_id:Q,output:"id,chain_id,instructions,descriptors"}});return this.logger.debug("[getTransactionDescriptorsPayload] Received response",{data:{templateId:Q,responseLength:Z?.length??0,hasData:!!Z&&Z.length>0}}),!Z||Z.length===0||!Z[0]?(this.logger.warn("[getTransactionDescriptorsPayload] No transaction descriptors found",{data:{templateId:Q,responseLength:Z?.length??0}}),a(Error(`[ContextModule] HttpLifiDataSource: no transaction descriptors for id ${Q}`))):(this.logger.info("[getTransactionDescriptorsPayload] Successfully fetched transaction descriptors",{data:{templateId:Q,descriptorsCount:Z[0].descriptors?.length??0}}),U0(Z[0]))}catch(Z){return this.logger.error("[getTransactionDescriptorsPayload] Failed to fetch transaction descriptors",{data:{templateId:Q,error:Z instanceof Error?Z.message:String(Z)}}),a(Error("[ContextModule] HttpLifiDataSource: Failed to fetch transaction descriptors"))}}};var _f=w(()=>{W0();R0();SQ();OZ();iJ0=Object.defineProperty,aJ0=Object.getOwnPropertyDescriptor;yU=rJ0([e(),xR(0,g(i0.Config)),xR(1,g(i0.ContextModuleLoggerFactory)),xR(2,g(PQ.NetworkClient))],yU)});var IX;var gU=w(()=>{IX={LifiDataSource:Symbol.for("LifiDataSource"),LifiContextLoader:Symbol.for("LifiContextLoader")}});var tJ0,eJ0,Q10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?eJ0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&tJ0(Z,Y,J),J},hU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Z10,bU=class{constructor(Q,Z,Y,$){this.dataSource=Q,this.config=Z,this._certificateLoader=Y,this.logger=$("LifiContextLoader")}logger;canHandle(Q,Z){if(!Z10.every((Y)=>Z.includes(Y)))return this.logger.debug("[canHandle] Skipping, expected type does not match",{data:{expectedTypes:Z,required:u.SOLANA_LIFI}}),!1;if(typeof Q=="object"&&Q!==null&&"templateId"in Q){let Y=Q.templateId,$=typeof Y=="string"&&Y.length>0;return this.logger.debug("[canHandle] Field validation result",{data:{templateId:Y,isValid:$}}),$}return this.logger.debug("[canHandle] Field does not contain a valid templateId",{data:{input:Q}}),!1}async load(Q){this.logger.debug("[load] Loading solana Lifi context",{data:{input:Q}});let Z=await this._loadInternal(Q);if(Z.type===u.ERROR)return[{type:u.ERROR,error:Z.error}];let Y=Z;return[{type:u.SOLANA_LIFI,payload:Y.payload,certificate:Y.certificate}]}async _loadInternal(Q){this.logger.debug("[_loadInternal] Loading solana Lifi context",{data:{input:Q}});let{templateId:Z,deviceModelId:Y}=Q;if(!Z)return{type:u.ERROR,error:Error("[ContextModule] LifiContextLoader: templateId is missing")};let $=await this.dataSource.getTransactionDescriptorsPayload({templateId:Z}),J=await this._certificateLoader.loadCertificate({keyId:LZ.SwapTemplateKey,keyUsage:wQ.SwapTemplate,targetDevice:Y});return $.caseOf({Left:(X)=>(this.logger.error("[_loadInternal] Error loading solana Lifi context",{data:{error:X}}),{type:u.ERROR,error:X}),Right:(X)=>{let G=this.buildPayload(X);return this.logger.debug("[_loadInternal] Successfully loaded solana Lifi context",{data:{descriptors:G.descriptors,instructionsCount:G.instructions.length,certificate:J}}),{type:u.SOLANA_LIFI,payload:G,certificate:J}}})}buildPayload(Q){return{descriptors:this.pluckTransactionData(Q),instructions:this.extractInstructionsMeta(Q)}}pluckTransactionData(Q){let Z=this.config.cal.mode||"prod",Y={},$=Q.descriptors??[];this.logger.debug("[pluckTransactionData] Processing descriptors",{data:{descriptorsCount:$.length,signatureKind:Z}});for(let J of $){let X=`${J.program_id}:${J.discriminator_hex??""}`,G={data:J.descriptor.data,descriptorType:J.descriptor.descriptorType,descriptorVersion:J.descriptor.descriptorVersion,signature:J.descriptor.signatures[Z]??"",...J.has_basis_point!==void 0&&{has_basis_point:J.has_basis_point}};(Y[X]??=[]).push(G),this.logger.debug("[pluckTransactionData] Mapped program descriptor",{data:{programId:J.program_id,discriminatorHex:J.discriminator_hex??"",key:X}})}return this.logger.debug("[pluckTransactionData] Completed processing",{data:{outputKeys:Object.keys(Y)}}),Y}extractInstructionsMeta(Q){let Z=Q.instructions??[];this.logger.debug("[extractInstructionsMeta] Extracting instructions metadata",{data:{instructionsCount:Z.length}});let Y=Z.map(($)=>({program_id:$.program_id,...$.discriminator_hex!==void 0&&{discriminator_hex:$.discriminator_hex},...$.amount!==void 0&&{has_basis_point:$.amount.capped_bps!==void 0}}));return this.logger.debug("[extractInstructionsMeta] Completed extracting instructions metadata",{data:{meta:Y.map(($)=>({programId:$.program_id,discriminatorHex:$.discriminator_hex}))}}),Y}};var vf=w(()=>{W0();SQ();RZ();h$();jY();gU();iQ();tJ0=Object.defineProperty,eJ0=Object.getOwnPropertyDescriptor,Z10=[u.SOLANA_LIFI];bU=Q10([e(),hU(0,g(IX.LifiDataSource)),hU(1,g(i0.Config)),hU(2,g(BQ.PkiCertificateLoader)),hU(3,g(i0.ContextModuleLoggerFactory))],bU)});var xf=()=>new b0(({bind:Q})=>{Q(IX.LifiDataSource).to(yU),Q(IX.LifiContextLoader).to(bU)});var ff=w(()=>{W0();_f();vf();gU()});var Y10,$10,J10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?$10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Y10(Z,Y,J),J},yf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),Y4=class{constructor(Q,Z){this.config=Q,this.http=Z}isSolanaSPLOwnerInfo(Q){return typeof Q!="object"||Q===null?!1:typeof Q.tokenAccount=="string"&&typeof Q.owner=="string"&&typeof Q.contract=="string"&&typeof Q.signedDescriptor=="string"}async fetchAddressMetadata(Q,Z){try{let Y=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/solana/owner/${Q}`,{params:{challenge:Z}});return this.isSolanaSPLOwnerInfo(Y)?U0(Y):a(Error("[ContextModule] - HttpOwnerInfoDataSource: invalid fetchAddressMetadata response shape"))}catch{return a(Error("[ContextModule] - HttpOwnerInfoDataSource: Failed to fetch address metadata"))}}async computeAddressMetadata(Q,Z,Y){try{let $=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/solana/computed-token-account/${Q}/${Z}`,{params:{challenge:Y}});return this.isSolanaSPLOwnerInfo($)?U0($):a(Error("[ContextModule] - HttpOwnerInfoDataSource: invalid computeAddressMetadata response shape"))}catch{return a(Error("[ContextModule] - HttpOwnerInfoDataSource: Failed to compute address metadata"))}}async getOwnerInfo(Q){let{tokenAddress:Z,challenge:Y,createATA:$}=Q;if(!Y)return a(Error("[ContextModule] - HttpOwnerInfoDataSource: challenge is required"));let J;if(Z)J=await this.fetchAddressMetadata(Z,Y);else if($?.address&&$?.mintAddress)J=await this.computeAddressMetadata($.address,$.mintAddress,Y);else return a(Error("[ContextModule] - HttpOwnerInfoDataSource: either tokenAddress or valid createATA must be provided"));return J.chain((X)=>{let G=mQ(X.signedDescriptor);return G?U0({tlvDescriptor:G}):a(Error("[ContextModule] - HttpOwnerInfoDataSource: invalid base64 tlvDescriptor received"))})}};var fR=w(()=>{I0();W0();R0();SQ();OZ();Y10=Object.defineProperty,$10=Object.getOwnPropertyDescriptor;Y4=J10([e(),yf(0,g(i0.Config)),yf(1,g(PQ.NetworkClient))],Y4)});var RX;var cU=w(()=>{RX={OwnerInfoDataSource:Symbol.for("OwnerInfoDataSource"),OwnerInfoContextLoader:Symbol.for("OwnerInfoContextLoader")}});var G10,X10,V10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?X10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&G10(Z,Y,J),J},yR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),q10,$4=class{constructor(Q,Z,Y){this._dataSource=Q,this._certificateLoader=Z,this.logger=Y("OwnerInfoContextLoader")}logger;canHandle(Q,Z){if(!q10.every(($)=>Z.includes($))||typeof Q!="object"||Q===null)return!1;let Y=Q;return!!(Y.tokenAddress||Y.createATA)}async load(Q){this.logger.debug("[load] Loading solana owner info context",{data:{input:Q}});let{deviceModelId:Z}=Q,Y=await this._certificateLoader.loadCertificate({keyId:"domain_metadata_key",keyUsage:wQ.TrustedName,targetDevice:Z});return Y?(await this._dataSource.getOwnerInfo(Q)).caseOf({Left:($)=>[{type:u.ERROR,error:$}],Right:({tlvDescriptor:$})=>$!==void 0?[{type:u.SOLANA_BASIC_TRUSTED_NAME,payload:$,certificate:Y}]:[]}):[{type:u.ERROR,error:Error("[ContextModule] OwnerInfoContextLoader: trustedNamePKICertificate is missing")}]}};var gR=w(()=>{W0();SQ();RZ();jY();cU();iQ();G10=Object.defineProperty,X10=Object.getOwnPropertyDescriptor,q10=[u.SOLANA_BASIC_TRUSTED_NAME];$4=V10([e(),yR(0,g(RX.OwnerInfoDataSource)),yR(1,g(BQ.PkiCertificateLoader)),yR(2,g(i0.ContextModuleLoggerFactory))],$4)});var gf=()=>new b0(({bind:Q})=>{Q(RX.OwnerInfoDataSource).to(Y4),Q(RX.OwnerInfoContextLoader).to($4)});var hf=w(()=>{W0();fR();cU();gR()});var F10,z10,W10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?z10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&F10(Z,Y,J),J},bf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),uU=class{constructor(Q,Z){this.config=Q,this.http=Z}async getIdFromMint({mintAddress:Q}){try{let Z=await this.http.get(`${this.config.cal.url}/tokens`,{params:{contract_address:Q,network:"solana",output:"id",ref:`branch:${this.config.cal.branch}`}});return!Z||Z.length===0||!Z[0]?.id?a(Error(`[ContextModule] HttpMintToIdDataSource: no token id found for mint ${Q}`)):U0(Z[0].id)}catch{return a(Error("[ContextModule] HttpMintToIdDataSource: failed to fetch token id from mint address"))}}};var cf=w(()=>{W0();R0();SQ();OZ();F10=Object.defineProperty,z10=Object.getOwnPropertyDescriptor;uU=W10([e(),bf(0,g(i0.Config)),bf(1,g(PQ.NetworkClient))],uU)});var K10,U10,O10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?U10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&K10(Z,Y,J),J},uf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),pU=class{constructor(Q,Z){this.config=Q,this.http=Z}async getTokenInfosPayload({tokenInternalId:Q}){try{let Z=await this.http.get(`${this.config.cal.url}/tokens`,{params:{id:Q,output:"id,name,network,network_family,network_type,exchange_app_config_serialized,live_signature,ticker,decimals,blockchain_name,chain_id,contract_address,descriptor,descriptor_exchange_app,units,symbol",ref:`branch:${this.config.cal.branch}`}});return!Z||Z.length===0||!Z[0]?a(Error(`[ContextModule] HttpTokenDataSource: no token metadata for id ${Q}`)):U0(Z[0])}catch{return a(Error("[ContextModule] HttpTokenDataSource: Failed to fetch token informations"))}}};var pf=w(()=>{W0();R0();SQ();OZ();K10=Object.defineProperty,U10=Object.getOwnPropertyDescriptor;pU=O10([e(),uf(0,g(i0.Config)),uf(1,g(PQ.NetworkClient))],pU)});var e1;var lU=w(()=>{e1={TokenDataSource:Symbol.for("TokenDataSource"),MintToIdDataSource:Symbol.for("MintToIdDataSource"),TokenContextLoader:Symbol.for("TokenContextLoader")}});var H10,D10,I10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?D10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&H10(Z,Y,J),J},J4=(Q,Z)=>(Y,$)=>Z(Y,$,Q),R10,mU=class{constructor(Q,Z,Y,$,J){this.dataSource=Q,this.mintToIdDataSource=Z,this.config=Y,this._certificateLoader=$,this.logger=J("TokenContextLoader")}logger;canHandle(Q,Z){if(!R10.every((X)=>Z.includes(X))||typeof Q!="object"||Q===null)return!1;let Y=Q,$=typeof Y.tokenInternalId=="string"&&Y.tokenInternalId.length>0,J=typeof Y.mintAddress=="string"&&Y.mintAddress.length>0;return $||J}async load(Q){this.logger.debug("[load] Loading solana token context",{data:{input:Q}});let Z=await this._loadInternal(Q);if(Z.type===u.ERROR)return[{type:u.ERROR,error:Z.error}];let Y=Z;return[{type:u.SOLANA_TOKEN,payload:Y.payload,certificate:Y.certificate}]}async _loadInternal(Q){let{deviceModelId:Z,mintAddress:Y}=Q,{tokenInternalId:$}=Q;if(!$){if(!Y)return{type:u.ERROR,error:Error("[ContextModule] TokenContextLoader: tokenInternalId and mintAddress are missing")};this.logger.debug("[_loadInternal] Resolving tokenInternalId from mintAddress",{data:{mintAddress:Y}});let G=await this.mintToIdDataSource.getIdFromMint({mintAddress:Y});if(G.isLeft())return{type:u.ERROR,error:G.extract()};$=G.extract()}let J=await this.dataSource.getTokenInfosPayload({tokenInternalId:$}),X=await this._certificateLoader.loadCertificate({keyId:LZ.TokenMetadataKey,keyUsage:wQ.CoinMeta,targetDevice:Z});return X?J.caseOf({Left:(G)=>(this.logger.error("[_loadInternal] Error loading solana token context",{data:{error:G}}),{type:u.ERROR,error:G}),Right:(G)=>(this.logger.debug("[_loadInternal] Successfully loaded solana token context",{data:{payload:this.pluckTokenData(G),certificate:X}}),{type:u.SOLANA_TOKEN,payload:this.pluckTokenData(G),certificate:X})}):{type:u.ERROR,error:Error("[ContextModule] TokenContextLoader: tokenMetadataCertificate is missing")}}pluckTokenData(Q){let Z=this.config.cal.mode||"prod";return{solanaTokenDescriptor:{data:Q.descriptor.data,signature:Q.descriptor.signatures[Z]}}}};var lf=w(()=>{W0();SQ();RZ();h$();jY();lU();iQ();H10=Object.defineProperty,D10=Object.getOwnPropertyDescriptor,R10=[u.SOLANA_TOKEN];mU=I10([e(),J4(0,g(e1.TokenDataSource)),J4(1,g(e1.MintToIdDataSource)),J4(2,g(i0.Config)),J4(3,g(BQ.PkiCertificateLoader)),J4(4,g(i0.ContextModuleLoggerFactory))],mU)});var mf=()=>new b0(({bind:Q})=>{Q(e1.TokenDataSource).to(pU),Q(e1.MintToIdDataSource).to(uU),Q(e1.TokenContextLoader).to(mU)});var df=w(()=>{W0();cf();pf();lU();lf()});var L10,E10,P10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?E10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&L10(Z,Y,J),J},hR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),G4=class{constructor(Q,Z,Y){this.config=Q,this.http=Y,this.logger=Z("HttpTokenAccountStateDataSource")}logger;async getTokenAccountState({tokenAccount:Q,challenge:Z}){let Y;try{Y=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/solana/token-account-state/${Q}`,{params:{challenge:Z}})}catch($){let J=$ instanceof Error?$.message:String($);return a(Error(`[ContextModule] HttpTokenAccountStateDataSource: Failed to fetch token account state: ${J}`))}return NU.decode(Y).caseOf({Left:($)=>a(Error(`[ContextModule] HttpTokenAccountStateDataSource: malformed response for ${Q}: ${$}`)),Right:($)=>{Y.owner!==void 0&&Y.mint===void 0&&this.logger.warn("[getTokenAccountState] response has owner but no mint — canonical-ATA check will fail and the OWNER binding will be dropped by the device",{data:{tokenAccount:Q}});let J;try{J=fY.hexToBytes($.signedDescriptor)}catch(X){return a(Error(`[ContextModule] HttpTokenAccountStateDataSource: invalid hex in signedDescriptor for ${Q}: ${X.message}`))}return Y.nativePreBalance===void 0&&this.logger.debug("[getTokenAccountState] nativePreBalance absent in response — native resets will not attest wrappable excess",{data:{tokenAccount:Q}}),U0({tokenAccount:Q,descriptor:J,mint:Y.mint,keyId:$.keyId,keyUsage:$.keyUsage})}})}};var bR=w(()=>{W0();R0();SQ();OZ();t8();MR();L10=Object.defineProperty,E10=Object.getOwnPropertyDescriptor;G4=P10([e(),hR(0,g(i0.Config)),hR(1,g(i0.ContextModuleLoggerFactory)),hR(2,g(PQ.NetworkClient))],G4)});var LX;var dU=w(()=>{LX={TokenAccountStateDataSource:Symbol.for("TokenAccountStateDataSource"),TokenAccountStateContextLoader:Symbol.for("TokenAccountStateContextLoader")}});var j10,A10,M10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?A10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&j10(Z,Y,J),J},cR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),T10,N10,B10,X4=class{constructor(Q,Z,Y){this.dataSource=Q,this.certificateLoader=Z,this.logger=Y("TokenAccountStateContextLoader")}logger;canHandle(Q,Z){return T10.every((Y)=>Z.includes(Y))?B10.decode(Q).caseOf({Left:()=>!1,Right:({requests:Y})=>Y.length>0&&Y.every(($)=>$.tokenAccount.length>0&&$.challenge.length>0)}):!1}async load(Q){return mV({requests:Q.requests,deviceModelId:Q.deviceModelId,certificateLoader:this.certificateLoader,logger:this.logger,label:"TOKEN_ACCOUNT_STATE",fetch:(Z)=>this.dataSource.getTokenAccountState(Z),toContext:(Z,Y)=>{let $={descriptor:Z.descriptor,mint:Z.mint};return{type:u.SOLANA_TOKEN_ACCOUNT_STATE,payload:$,certificate:Y}},describe:(Z)=>({tokenAccount:Z.tokenAccount})})}};var uR=w(()=>{W0();R0();SQ();RZ();dU();iQ();SU();JG();j10=Object.defineProperty,A10=Object.getOwnPropertyDescriptor,T10=[u.SOLANA_TOKEN_ACCOUNT_STATE],N10=RQ.interface({tokenAccount:TQ,challenge:TQ}),B10=RQ.interface({deviceModelId:u$,requests:bZ(N10)});X4=M10([e(),cR(0,g(LX.TokenAccountStateDataSource)),cR(1,g(BQ.PkiCertificateLoader)),cR(2,g(i0.ContextModuleLoggerFactory))],X4)});var nf=()=>new b0(({bind:Q})=>{Q(LX.TokenAccountStateDataSource).to(G4),Q(LX.TokenAccountStateContextLoader).to(X4)});var of=w(()=>{W0();bR();dU();uR()});var k10,C10,S10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?C10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&k10(Z,Y,J),J},sf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),w10,_10,v10,V4=class{constructor(Q,Z){this.config=Q,this.http=Z}async getTokenInfo({mint:Q,network:Z}){let Y;try{Y=await this.http.get(`${this.config.cal.url}/tokens`,{params:{contract_address:Q,network:_10[Z]??Z,output:"contract_address,network,descriptor",ref:`branch:${this.config.cal.branch}`}})}catch($){let J=$ instanceof Error?$.message:String($);return a(Error(`[ContextModule] HttpTokenInfoDataSource: Failed to fetch token info: ${J}`))}return!Array.isArray(Y)||Y.length===0?a(Error(`[ContextModule] HttpTokenInfoDataSource: no token info for mint ${Q}`)):v10.decode(Y[0]).caseOf({Left:($)=>a(Error(`[ContextModule] HttpTokenInfoDataSource: malformed descriptor for mint ${Q}: ${$}`)),Right:($)=>U0({mint:Q,descriptor:$.descriptor})})}};var pR=w(()=>{W0();R0();SQ();OZ();k10=Object.defineProperty,C10=Object.getOwnPropertyDescriptor,w10=RQ.interface({prod:WZ(TQ),test:WZ(TQ)}),_10={"solana-mainnet":"solana","solana-devnet":"solana-devnet"},v10=RQ.interface({descriptor:RQ.interface({data:TQ,signatures:w10})});V4=S10([e(),sf(0,g(i0.Config)),sf(1,g(PQ.NetworkClient))],V4)});var EX;var nU=w(()=>{EX={TokenInfoDataSource:Symbol.for("TokenInfoDataSource"),TokenInfoContextLoader:Symbol.for("TokenInfoContextLoader")}});var x10,f10,y10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?f10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&x10(Z,Y,J),J},oU=(Q,Z)=>(Y,$)=>Z(Y,$,Q),g10,h10="solana-mainnet",b10,q4=class{constructor(Q,Z,Y,$){this.dataSource=Q,this.config=Z,this.certificateLoader=Y,this.logger=$("TokenInfoContextLoader")}logger;canHandle(Q,Z){return g10.every((Y)=>Z.includes(Y))?b10.decode(Q).caseOf({Left:()=>!1,Right:({mints:Y})=>Y.length>0&&Y.every(($)=>$.length>0)}):!1}async load(Q){let Z=Q.network||h10,Y=Array.from(new Set(Q.mints));this.logger.debug("[load] Fetching TOKEN_INFO descriptors",{data:{network:Z,mintCount:Y.length}});let $=dV(this.certificateLoader,{keyId:LZ.TokenMetadataKey,keyUsage:wQ.CoinMeta,targetDevice:Q.deviceModelId}),J=Promise.all(Y.map(async(K)=>({mint:K,either:await this.dataSource.getTokenInfo({mint:K,network:Z})}))),[X,G]=await Promise.all([$,J]);if(!X.ok||!X.value){let K=X.ok?Error("[ContextModule] TokenInfoContextLoader: certificate is missing"):X.error;return this.logger.warn("[load] TOKEN_INFO certificate unavailable",{data:{error:K.message}}),Y.map(()=>({type:u.ERROR,error:K}))}let W=X.value,U=this.config.cal.mode??"prod";return G.map(({mint:K,either:O})=>O.caseOf({Left:(I)=>(this.logger.warn("[load] TOKEN_INFO fetch failed",{data:{mint:K,error:I.message}}),{type:u.ERROR,error:I}),Right:(I)=>{let L=I.descriptor.signatures[U];if(!L){let M=Error(`[ContextModule] TokenInfoContextLoader: missing '${U}' signature for mint ${K}`);return this.logger.warn("[load] TOKEN_INFO missing signature",{data:{mint:K,mode:U}}),{type:u.ERROR,error:M}}let A={mint:K,descriptor:{data:I.descriptor.data,signature:L}};return{type:u.SOLANA_TOKEN_INFO,payload:A,certificate:W}}}))}};var lR=w(()=>{W0();R0();SQ();RZ();h$();jY();nU();iQ();_U();JG();x10=Object.defineProperty,f10=Object.getOwnPropertyDescriptor,g10=[u.SOLANA_TOKEN_INFO],b10=RQ.interface({deviceModelId:u$,mints:bZ(TQ),network:WZ(TQ)});q4=y10([e(),oU(0,g(EX.TokenInfoDataSource)),oU(1,g(i0.Config)),oU(2,g(BQ.PkiCertificateLoader)),oU(3,g(i0.ContextModuleLoggerFactory))],q4)});var af=()=>new b0(({bind:Q})=>{Q(EX.TokenInfoDataSource).to(V4),Q(EX.TokenInfoContextLoader).to(q4)});var rf=w(()=>{W0();pR();nU();lR()});var c10,u10,p10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?u10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&c10(Z,Y,J),J},tf=(Q,Z)=>(Y,$)=>Z(Y,$,Q),l10,F4=class{constructor(Q,Z){this.config=Q,this.http=Z}async getTrustedName({address:Q,network:Z,challenge:Y,types:$,sources:J}){let X;try{X=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/names/solana/${Z}/reverse/${Q}`,{params:{types:$.join(","),sources:J.join(","),challenge:Y}})}catch(G){let W=G instanceof Error?G.message:String(G);return a(Error(`[ContextModule] HttpSolanaTrustedNameDataSource: Failed to fetch trusted name: ${W}`))}return l10.decode(X).caseOf({Left:(G)=>a(Error(`[ContextModule] HttpSolanaTrustedNameDataSource: malformed response for ${Q}: ${G}`)),Right:(G)=>{let W=this.config.cal.mode??"prod",U=G.signedDescriptor.signatures[W];if(!U)return a(Error(`[ContextModule] HttpSolanaTrustedNameDataSource: missing ${W} signature for ${Q}`));let K;try{K=fY.hexToBytes(fY.appendSignatureToPayload(G.signedDescriptor.data,U,zX))}catch(O){return a(Error(`[ContextModule] HttpSolanaTrustedNameDataSource: invalid signed descriptor for ${Q}: ${O.message}`))}return U0({address:Q,descriptor:K,keyId:G.keyId,keyUsage:G.keyUsage})}})}};var mR=w(()=>{W0();R0();SQ();zF();OZ();t8();c10=Object.defineProperty,u10=Object.getOwnPropertyDescriptor,l10=RQ.interface({signedDescriptor:RQ.interface({data:TQ,signatures:RQ.interface({prod:WZ(TQ),test:WZ(TQ)})}),keyId:TQ,keyUsage:TQ});F4=p10([e(),tf(0,g(i0.Config)),tf(1,g(PQ.NetworkClient))],F4)});var PX;var sU=w(()=>{PX={SolanaTrustedNameDataSource:Symbol.for("SolanaTrustedNameDataSource"),SolanaTrustedNameContextLoader:Symbol.for("SolanaTrustedNameContextLoader")}});var m10,d10,n10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?d10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&m10(Z,Y,J),J},dR=(Q,Z)=>(Y,$)=>Z(Y,$,Q),o10,s10,ef,i10,a10,z4=class{constructor(Q,Z,Y){this.dataSource=Q,this.certificateLoader=Z,this.logger=Y("SolanaTrustedNameContextLoader")}logger;canHandle(Q,Z){return o10.every((Y)=>Z.includes(Y))?a10.decode(Q).caseOf({Left:()=>!1,Right:({requests:Y})=>Y.length>0&&Y.every(($)=>$.address.length>0&&$.challenge.length>0)}):!1}async load(Q){let Z=Q.network?s10[Q.network]??ef:ef,Y=String(Z);return mV({requests:Q.requests,deviceModelId:Q.deviceModelId,certificateLoader:this.certificateLoader,logger:this.logger,label:"TRUSTED_NAME",fetch:($)=>this.dataSource.getTrustedName({address:$.address,challenge:$.challenge,types:$.types,sources:$.sources,network:Y}),toContext:($,J)=>({type:u.SOLANA_TRUSTED_NAME,payload:$.descriptor,certificate:J}),describe:($)=>({address:$.address})})}};var nR=w(()=>{W0();R0();SQ();RZ();xU();sU();iQ();SU();JG();m10=Object.defineProperty,d10=Object.getOwnPropertyDescriptor,o10=[u.SOLANA_TRUSTED_NAME],s10={"solana-mainnet":EJ.MAINNET,"solana-devnet":EJ.DEVNET,"solana-testnet":EJ.TESTNET},ef=EJ.MAINNET,i10=RQ.interface({address:TQ,challenge:TQ,types:bZ(TQ),sources:bZ(TQ)}),a10=RQ.interface({deviceModelId:u$,network:WZ(TQ),requests:bZ(i10)});z4=n10([e(),dR(0,g(PX.SolanaTrustedNameDataSource)),dR(1,g(BQ.PkiCertificateLoader)),dR(2,g(i0.ContextModuleLoggerFactory))],z4)});var Qy=()=>new b0(({bind:Q})=>{Q(PX.SolanaTrustedNameDataSource).to(F4),Q(PX.SolanaTrustedNameContextLoader).to(z4)});var Zy=w(()=>{W0();mR();sU();nR()});var Yy;var $y=w(()=>{R0();Yy=bZ(RQ.interface({descriptor:RQ.interface({signatures:RQ.interface({prod:TQ,test:TQ})})}))});var r10,t10,e10=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?t10(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&r10(Z,Y,J),J},Jy=(Q,Z)=>(Y,$)=>Z(Y,$,Q),iU=class{constructor(Q,Z){this.config=Q,this.http=Z}async getTokenInfosPayload({assetId:Q}){let Z=()=>a(Error(`[ContextModule] HttpTokenDataSource: no token metadata for asset id ${Q}`));try{let Y=await this.http.get(`${this.config.cal.url}/tokens`,{params:{id:`tron/trc10/${Q}`,output:"id,ticker,decimals,descriptor",ref:`branch:${this.config.cal.branch}`}});return Yy.decode(Y).caseOf({Left:Z,Right:($)=>{let J=$[0]?.descriptor.signatures[this.config.cal.mode];return J===void 0||J.length===0?Z():U0(J)}})}catch{return a(Error("[ContextModule] HttpTokenDataSource: Failed to fetch token informations"))}}};var Gy=w(()=>{W0();R0();SQ();$y();OZ();r10=Object.defineProperty,t10=Object.getOwnPropertyDescriptor;iU=e10([e(),Jy(0,g(i0.Config)),Jy(1,g(PQ.NetworkClient))],iU)});var jX;var aU=w(()=>{jX={TokenDataSource:Symbol.for("TokenDataSource"),TokenContextLoader:Symbol.for("TokenContextLoader")}});function oR(Q,Z){let Y=0,$=1;for(let J=0;J<10;J++){let X=Q[Z+J];if(X===void 0)return;if(Y+=(X&127)*$,(X&128)===0)return{value:Y,next:Z+J+1};$*=128}}function Xy(Q,Z){let Y=oR(Q,Z);if(Y===void 0)return;let $=Math.floor(Y.value/8),J=Y.value%8;switch(J){case 0:{let X=oR(Q,Y.next);return X===void 0?void 0:{fieldNumber:$,wireType:J,value:X.value,next:X.next}}case 2:{let X=oR(Q,Y.next);if(X===void 0)return;let G=X.next+X.value;return G>Q.length?void 0:{fieldNumber:$,wireType:J,data:Q.subarray(X.next,G),next:G}}case 1:case 5:{let X=Y.next+(J===1?8:4);return X>Q.length?void 0:{fieldNumber:$,wireType:J,next:X}}default:return}}function rU(Q,Z){let Y=0;for(;Y<Q.length;){let $=Xy(Q,Y);if($===void 0)return;if($.fieldNumber===Z&&$.data!==void 0)return $.data;Y=$.next}}function Q80(Q,Z){let Y=0;for(;Y<Q.length;){let $=Xy(Q,Y);if($===void 0)return;if($.fieldNumber===Z&&$.wireType===0)return $.value;Y=$.next}}function Vy(Q){let Z=rU(Q,11);if(Z===void 0||Q80(Z,1)!==2)return;let Y=rU(Z,2);if(Y===void 0)return;let $=rU(Y,2);if($===void 0)return;let J=rU($,1);if(!(J===void 0||J.length===0||!J.every((X)=>X>=48&&X<=57)))return String.fromCharCode(...J)}var qy=()=>{};var Z80,Y80,$80=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Y80(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Z80(Z,Y,J),J},J80=(Q,Z)=>(Y,$)=>Z(Y,$,Q),G80,tU=class{constructor(Q){this.dataSource=Q}canHandle(Q,Z){return G80.every((Y)=>Z.includes(Y))&&typeof Q=="object"&&Q!==null&&"rawTransaction"in Q&&Q.rawTransaction instanceof Uint8Array&&Q.rawTransaction.length>0}async load({rawTransaction:Q}){let Z=Vy(Q);return Z===void 0?[]:(await this.dataSource.getTokenInfosPayload({assetId:Z})).caseOf({Left:(Y)=>[{type:u.ERROR,error:Y}],Right:(Y)=>[{type:u.TRON_TOKEN,payload:Y}]})}};var Fy=w(()=>{W0();aU();qy();iQ();Z80=Object.defineProperty,Y80=Object.getOwnPropertyDescriptor,G80=[u.TRON_TOKEN];tU=$80([e(),J80(0,g(jX.TokenDataSource))],tU)});var zy=()=>new b0(({bind:Q})=>{Q(jX.TokenDataSource).to(iU),Q(jX.TokenContextLoader).to(tU)});var Wy=w(()=>{W0();Gy();aU();Fy()});var G$;var eU=w(()=>{G$=((Q)=>(Q.Ethereum="ethereum",Q.Solana="solana",Q.Concordium="concordium",Q.Tron="tron",Q))(G$||{})});var Ky=(Q)=>new b0(({bind:Z})=>{Z(PQ.NetworkClient).toConstantValue(ZG(Q))});var Uy=w(()=>{W0();OZ();_F()});var Oy=({config:Q})=>{let Z=new T$;Z.bind(i0.ContextModuleLoggerFactory).toConstantValue(Q.loggerFactory);let{chain:Y}=Q;switch(Z.loadSync(Cv(Q),Ky(Q)),Y){case G$.Ethereum:Z.loadSync(LU(),dx(),IR(),Tx(Q.customTrustedNameDataSource),mv(),cv(),Qx(),Gx(Q.datasource),Wx(),sv(),Dx(),gv(),kx(),bx(),ex());break;case G$.Solana:Z.loadSync(LU(),IR(),gf(),mf(),xf(),qf(),Sf(),Df(),af(),nf(),Of(),Qy());break;case G$.Concordium:Z.loadSync(LU(),vv());break;case G$.Tron:Z.loadSync(zy());break;default:{let $=Y}}return Z};var Hy=w(()=>{W0();Sv();SQ();xv();hv();uv();dv();iv();Zx();Xx();Kx();Ix();Nx();Cx();cx();lx();nx();ix();Qf();Ff();Hf();If();wf();ff();hf();df();of();rf();Zy();Wy();eU();Uy()});class Q5{_container;_config;_loaders;_typedDataLoader;_fieldLoaders;_blindSigningReporter;_signReporter;constructor(Q){this._config=Q,this._container=Oy({config:Q}),this._loaders=Q.defaultLoaders?this._getDefaultLoaders():[],this._loaders.push(...Q.customLoaders),this._fieldLoaders=Q.defaultFieldLoaders?this._getDefaultFieldLoaders():[],this._fieldLoaders.push(...Q.customFieldLoaders),this._typedDataLoader=Q.customTypedDataLoader??this._getDefaultTypedDataLoader(),this._blindSigningReporter=Q.customBlindSigningReporter??this._getBlindSigningReporter(),this._signReporter=null}_getDefaultFieldLoaders(){return this._config.chain!==G$.Ethereum?[]:[this._container.get(cJ.NftContextFieldLoader),this._container.get(lY.TokenContextFieldLoader),this._container.get(LJ.TrustedNameContextFieldLoader),this._container.get(J$.ProxyContextFieldLoader)]}_getDefaultLoaders(){let{chain:Q}=this._config;switch(Q){case G$.Ethereum:return[this._container.get(KX.ExternalPluginContextLoader),this._container.get(LJ.TrustedNameContextLoader),this._container.get(cJ.NftContextLoader),this._container.get(lY.TokenContextLoader),this._container.get(r1.CalldataContextLoader),this._container.get(WX.DynamicNetworkContextLoader),this._container.get(UX.SafeAddressLoader),this._container.get(bJ.GatedSigningContextLoader),this._container.get(bJ.GatedSigningTypedDataContextLoader),this._container.get(mY.TransactionCheckLoader),this._container.get(mY.TypedDataCheckLoader)];case G$.Solana:return[this._container.get(e1.TokenContextLoader),this._container.get(IX.LifiContextLoader),this._container.get(RX.OwnerInfoContextLoader),this._container.get(mY.TransactionCheckLoader),this._container.get(t1.InstructionInfoContextLoader),this._container.get(wU.EnumVariantContextLoader),this._container.get(EX.TokenInfoContextLoader),this._container.get(LX.TokenAccountStateContextLoader),this._container.get(DX.AltResolutionContextLoader),this._container.get(PX.SolanaTrustedNameContextLoader)];case G$.Concordium:return[this._container.get(FX.AccountOwnershipContextLoader)];case G$.Tron:return[this._container.get(jX.TokenContextLoader)];default:{let Z=Q;return[]}}}_getDefaultTypedDataLoader(){return this._config.chain!==G$.Ethereum?{load:()=>Promise.reject(Error("[ContextModule] getTypedDataFilters is not supported for this chain"))}:this._container.get(OX.TypedDataContextLoader)}_getBlindSigningReporter(){return this._container.isBound(YG.BlindSigningReporter)?this._container.get(YG.BlindSigningReporter):null}async getContexts(Q,Z){let Y=Object.values(u),$=this._loaders.filter((J)=>J.canHandle(Q,Z??Y)).map((J)=>J.load(Q));return(await Promise.all($)).flat()}async getFieldContext(Q,Z){let Y=this._fieldLoaders.filter(($)=>$.canHandle(Q,Z));if(Y.length===0)return Promise.resolve({type:u.ERROR,error:Error(`Loader not found for field: ${Q} and expected type: ${Z}`)});for(let $ of Y){let J=await $.loadField(Q);if(J.type!==u.ERROR)return J}return{type:u.ERROR,error:Error(`Loader not found for field: ${Q} and expected type: ${Z}`)}}async getTypedDataFilters(Q){return this._typedDataLoader.load(Q)}async report(Q){await this._blindSigningReporter?.report(Q)}async signReport(Q){await this._signReporter?.report(Q)}}var sR=w(()=>{Hy();$U();JU();XU();FU();RF();AF();e8();HU();QG();xF();RU();EU();HX();CU();kR();tF();gU();cU();lU();dU();nU();sU();aU();eU();iQ()});class Z5{config;constructor({originToken:Q,loggerFactory:Z}){this.config={...Dy,...z80,customLoaders:[],customFieldLoaders:[],originToken:Q??"",loggerFactory:Z??aX}}removeDefaultLoaders(){return this.config.defaultLoaders=!1,this}addLoader(Q){return this.config.customLoaders.push(Q),this}addTypedDataLoader(Q){return this.config.customTypedDataLoader=Q,this}setCalConfig(Q){return this.config.cal=Q,this}setMetadataServiceConfig(Q){return this.config.metadataServiceDomain=Q,this}setWeb3ChecksConfig(Q){return this.config.web3checks=Q,this}setDatasourceConfig(Q){return this.config.datasource=Q,this}setReporterConfig(Q){return this.config.reporter=Q,this}setAppSource(Q){return this.config.appSource=Q,this}setBlindSigningReporter(Q){return this.config.customBlindSigningReporter=Q,this}setTrustedNameDataSource(Q){return this.config.customTrustedNameDataSource=Q,this}setLoggerFactory(Q){return this.config.loggerFactory=Q,this}setChain(Q){return this.config.chain=Q,this}build(){if(!this.config.chain)throw Error("[ContextModuleBuilder] setChain() must be called before build()");return new Q5(this.config)}}var X80="https://global.api.prd.ledger.com/cal/v1",V80="https://global.api.prd.ledger.com/transaction-checks/v3",q80="https://nft.api.live.ledger.com",F80="https://blind-signing.api.ledger.com/ingest",Dy,z80;var Iy=w(()=>{I0();sR();Dy=Object.freeze({cal:Object.freeze({url:X80,mode:"prod",branch:"main"}),web3checks:Object.freeze({url:V80}),metadataServiceDomain:Object.freeze({url:q80}),reporter:Object.freeze({url:F80}),datasource:Object.freeze({proxy:"default"}),appSource:"third-party"}),z80={defaultLoaders:!0,defaultFieldLoaders:!0,customLoaders:[],customFieldLoaders:[],customTypedDataLoader:void 0,customBlindSigningReporter:void 0,customTrustedNameDataSource:void 0}});var Y5,$5,W80,K80;var Ry=w(()=>{Y5=Object.freeze({ETH_SIGN_TRANSACTION:"eth_signTransaction",ETH_SIGN_TYPED_DATA:"eth_signTypedData"}),$5=Object.freeze({NO_CLEAR_SIGNING_CONTEXT:"no_clear_signing_context",DEVICE_REJECTED_CONTEXT:"device_rejected_context",UNRECOGNIZED_PROGRAM:"unrecognized_program",STALE_DESCRIPTOR:"stale_descriptor"}),W80=Object.freeze({BASIC:"basic",EIP7730:"eip7730"}),K80=Object.freeze({DESKTOP:"desktop",MOBILE:"mobile"})});var J5;var Ly=w(()=>{J5=Object.freeze({ETH_SIGN_TRANSACTION:"eth_signTransaction",ETH_SIGN_TYPED_DATA:"eth_signTypedData",SOL_SIGN_TRANSACTION:"sol_signTransaction"})});function U80(Q){return Py.has(Q.type)}var Ey,Py;var jy=w(()=>{iQ();SR();Ey={TOKEN:u.SOLANA_TOKEN,LIFI:u.SOLANA_LIFI,TRUSTED_NAME:u.SOLANA_TRUSTED_NAME,BASIC_TRUSTED_NAME:u.SOLANA_BASIC_TRUSTED_NAME,TRANSACTION_CHECK:u.SOLANA_TRANSACTION_CHECK,INSTRUCTION_INFO:u.SOLANA_INSTRUCTION_INFO,ENUM_VARIANT:u.SOLANA_ENUM_VARIANT,TOKEN_INFO:u.SOLANA_TOKEN_INFO,TOKEN_ACCOUNT_STATE:u.SOLANA_TOKEN_ACCOUNT_STATE,ALT_RESOLUTION:u.SOLANA_ALT_RESOLUTION},Py=new Set(Object.values(Ey))});function G5(Q){return O80[Q]}var AX,O80;var Ay=w(()=>{I0();AX=Object.freeze({NANO_S:"nanoS",NANO_SP:"nanoSP",NANO_X:"nanoX",STAX:"stax",FLEX:"flex",APEX_P:"apexP"}),O80={[JQ.NANO_S]:AX.NANO_S,[JQ.NANO_SP]:AX.NANO_SP,[JQ.NANO_X]:AX.NANO_X,[JQ.STAX]:AX.STAX,[JQ.FLEX]:AX.FLEX,[JQ.APEX]:AX.APEX_P}});var nV,Q8,MX;var My=w(()=>{nV=((Q)=>(Q.FROM="FROM",Q.TO="TO",Q.VALUE="VALUE",Q))(nV||{}),Q8=((Q)=>(Q.TUPLE="TUPLE",Q.ARRAY="ARRAY",Q.REF="REF",Q.LEAF="LEAF",Q.SLICE="SLICE",Q))(Q8||{}),MX=((Q)=>(Q.STATIC_LEAF="STATIC_LEAF",Q.DYNAMIC_LEAF="DYNAMIC_LEAF",Q.TUPLE_LEAF="TUPLE_LEAF",Q.ARRAY_LEAF="ARRAY_LEAF",Q))(MX||{})});var Ty=w(()=>{Iy();sR();NI();BI();kI();_I();vI();xI();fI();yI();gI();hI();bI();cI();CI();IU();uI();pI();lI();mI();dI();nI();oI();sI();aI();rI();tI();QR();ZR();YR();KU();XR();VR();FR();WR();KR();h$();jY();UR();OR();Ry();Ly();sF();TR();BR();CR();wR();vR();jy();xU();fR();gR();bR();uR();pR();lR();mR();nR();eU();Ay();iQ();My()});var Ny={};j$(Ny,{mapDeviceModelId:()=>G5,isSolanaContextSuccess:()=>U80,isEthereumClearSignContextSuccess:()=>hJ,getSchemaHash:()=>EF,VERIFYING_CONTRACT_TOKEN_INDEX:()=>pV,UniswapContextLoader:()=>pF,TypedDataCalldataParamPresence:()=>b$,TrustedNameContextLoader:()=>yF,TrustedNameContextFieldLoader:()=>fF,TransactionCheckPaths:()=>$G,TokenInfoContextLoader:()=>q4,TokenContextLoader:()=>wF,TokenContextFieldLoader:()=>SF,TokenAccountStateContextLoader:()=>X4,SolanaTrustedNameContextLoader:()=>z4,SolanaTransactionScanChainId:()=>EJ,SolanaInstructionSubstructureKind:()=>GG,SolanaContextType:()=>Ey,SigningMethod:()=>J5,SOLANA_CLEAR_SIGN_CONTEXT_SUCCESS_TYPES:()=>Py,ProxyContextFieldLoader:()=>kF,OwnerInfoContextLoader:()=>$4,NftContextLoader:()=>TF,NftContextFieldLoader:()=>MF,KeyUsage:()=>wQ,KeyId:()=>LZ,InstructionInfoContextLoader:()=>Z4,HttpTypedDataDataSource:()=>gF,HttpTrustedNameDataSource:()=>vF,HttpTokenInfoDataSource:()=>V4,HttpTokenDataSource:()=>CF,HttpTokenAccountStateDataSource:()=>G4,HttpSolanaTrustedNameDataSource:()=>F4,HttpSafeProxyDataSource:()=>BF,HttpProxyDataSource:()=>NF,HttpPkiCertificateDataSource:()=>lF,HttpOwnerInfoDataSource:()=>Y4,HttpNftDataSource:()=>jF,HttpInstructionInfoDataSource:()=>Q4,HttpGatedDescriptorDataSource:()=>IF,HttpExternalPluginDataSource:()=>OF,HttpDynamicNetworkDataSource:()=>KF,HttpCalldataDescriptorDataSource:()=>uV,HttpBlindSigningReporterDatasource:()=>dF,HttpAltResolutionDataSource:()=>aF,HttpAccountOwnershipDataSource:()=>qF,GatedSigningTypedDataContextLoader:()=>PF,GatedSigningContextLoader:()=>LF,ExternalPluginContextLoader:()=>DF,EthersAbiDecoderDataSource:()=>uF,EthereumClearSignContextType:()=>fv,EnumVariantContextLoader:()=>eF,ETHEREUM_CLEAR_SIGN_CONTEXT_SUCCESS_TYPES:()=>yv,ERC20_SUPPORTED_SELECTORS:()=>iI,DynamicNetworkContextLoader:()=>UF,DefaultTypedDataContextLoader:()=>bF,DefaultPkiCertificateLoader:()=>mF,DefaultContextModule:()=>Q5,DefaultCommandDecoderDataSource:()=>cF,DefaultBlindSigningReporter:()=>nF,DataPathLeafType:()=>MX,DataPathElementType:()=>Q8,DYNAMIC_NETWORK_CONTEXT_TYPES:()=>qU,DEFAULT_CONFIG:()=>Dy,ContextModuleChainID:()=>G$,ContextModuleBuilder:()=>Z5,ContainerPath:()=>nV,ClearSigningType:()=>W80,ClearSignContextType:()=>u,ClearSignContextReferenceType:()=>iZ,CalldataContextLoader:()=>WF,BlindSigningPlatform:()=>K80,BlindSigningModelId:()=>AX,BlindSigningMethod:()=>Y5,BlindSignReason:()=>$5,AltResolutionContextLoader:()=>rF,AccountOwnershipError:()=>r8,AccountOwnershipContextLoader:()=>FF});var Ii0;var X$=w(()=>{Ii0=JZ(mJ(),1);Ty()});var AY="Ethereum",By=10;var XG=()=>{};var _Q,ky,vQ=(Q)=>new ky(Q);var EZ=w(()=>{I0();_Q={6001:{message:"Mode check fail"},6501:{message:"TransactionType not supported"},6502:{message:"Output buffer too small for chainId conversion"},6800:{message:"Internal error (Please report)"},6982:{message:"Security status not satisfied (Canceled by user)"},6983:{message:"Wrong Data length"},6984:{message:"Plugin not installed"},6985:{message:"Condition not satisfied"},"6a00":{message:"Error without info"},"6a80":{message:"Invalid data"},"6a84":{message:"Insufficient memory"},"6a88":{message:"Data not found"},"6b00":{message:"Incorrect parameter P1 or P2"},"6d00":{message:"Incorrect parameter INS"},"6e00":{message:"Incorrect parameter CLA"},"6f00":{message:"Technical problem (Internal error, please report)"},"911c":{message:"Command code not supported (i.e., Ledger-PKI not yet available)"}};ky=class ky extends DZ{constructor(Q){super({tag:"EthAppCommandError",...Q})}}});class TX{name="getAddress";args;errorHelper=new s0(_Q,vQ);constructor(Q){this.args=Q}getApdu(){let Q={cla:224,ins:2,p1:this.args.checkOnDevice?1:0,p2:this.args.returnChainCode?1:0},Z=new w0(Q),Y=this.args.derivationPath,$=QZ.splitPath(Y);if(Z.add8BitUIntToData($.length),$.forEach((J)=>{Z.add32BitUIntToData(J)}),this.args.checkOnDevice){let J=this.args.chainId??1;Z.add64BitUIntToData(J)}return Z.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({error:new C0("Public key length is missing")});if(Z.testMinimalLength(Y)===!1)return o({error:new C0("Public key is missing")});let $=Z.encodeToHexaString(Z.extractFieldByLength(Y)),J=Z.extract8BitUInt();if(J===void 0)return o({error:new C0("Ethereum address length is missing")});if(Z.testMinimalLength(J)===!1)return o({error:new C0("Ethereum address is missing")});let X=`0x${Z.encodeToString(Z.extractFieldByLength(J))}`;if(dQ(X)===!1)return o({error:new C0("Invalid Ethereum address")});let G;if(this.args.returnChainCode){if(Z.testMinimalLength(Cy)===!1)return o({error:new C0("Invalid Chaincode")});G=Z.encodeToHexaString(Z.extractFieldByLength(Cy))}return o({data:{publicKey:$,address:X,chainCode:G}})})}}var Cy=32;var X5=w(()=>{I0();IQ();R0();EZ()});class iR{constructor(Q){this.args=Q}name="provideEnum";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:36,p1:this.args.isFirstChunk?1:0,p2:0};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var Sy=w(()=>{I0();IQ();R0();EZ()});class W4{constructor(Q){this.args=Q}name="provideGatedSigning";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:56,p1:this.args.isFirstChunk?1:0,p2:0};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var aR=w(()=>{I0();IQ();R0();EZ()});class BX{constructor(Q){this.args=Q}name="provideNetworkConfiguration";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:48,p1:this.args.isFirstChunk?1:0,p2:this.args.configurationType};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var NX;var rR=w(()=>{I0();IQ();R0();EZ();NX=((Q)=>(Q[Q.CONFIGURATION=0]="CONFIGURATION",Q[Q.ICON=1]="ICON",Q))(NX||{})});class tR{constructor(Q){this.args=Q}name="provideNFTInformation";errorHelper=new s0(_Q,vQ);getApdu(){return new w0({cla:224,ins:20,p1:0,p2:0}).addHexaStringToData(this.args.payload).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var wy=w(()=>{I0();IQ();R0();EZ()});class K4{constructor(Q){this.args=Q}name="provideProxyInfo";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:42,p1:this.args.isFirstChunk?1:0,p2:0};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var eR=w(()=>{I0();IQ();R0();EZ()});class q5{constructor(Q){this.args=Q}name="provideSafeAccount";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:54,p1:this.args.isFirstChunk?1:0,p2:this.args.type};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var V5;var _y=w(()=>{I0();IQ();R0();EZ();V5=((Q)=>(Q[Q.SAFE_DESCRIPTOR=0]="SAFE_DESCRIPTOR",Q[Q.SIGNER_DESCRIPTOR=1]="SIGNER_DESCRIPTOR",Q))(V5||{})});class U4{constructor(Q){this.args=Q}name="provideTokenInformation";errorHelper=new s0(_Q,vQ);getApdu(){return new w0({cla:224,ins:10,p1:0,p2:0}).addHexaStringToData(this.args.payload).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q).extract8BitUInt()??0;return o({data:{tokenIndex:Z}})})}}var QL=w(()=>{I0();IQ();R0();EZ()});class ZL{constructor(Q){this.args=Q}name="provideTransactionFieldDescription";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:40,p1:this.args.isFirstChunk?1:0,p2:0};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var vy=w(()=>{I0();IQ();R0();EZ()});class YL{constructor(Q){this.args=Q}name="provideTransactionInformation";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:38,p1:this.args.isFirstChunk?1:0,p2:0};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var xy=w(()=>{I0();IQ();R0();EZ()});class O4{constructor(Q){this.args=Q}name="provideTrustedName";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:34,p1:this.args.isFirstChunk?1:0,p2:0};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var $L=w(()=>{I0();IQ();R0();EZ()});class H4{constructor(Q){this.args=Q}name="provideWeb3Check";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:50,p1:0,p2:this.args.isFirstChunk?1:0};return new w0(Q).addBufferToData(this.args.payload).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var JL=w(()=>{I0();IQ();R0();EZ()});class GL{constructor(Q){this.args=Q}name="setExternalPlugin";errorHelper=new s0(_Q,vQ);getApdu(){return new w0({cla:224,ins:18,p1:0,p2:0}).addHexaStringToData(this.args.payload).addHexaStringToData(this.args.signature??"").build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var fy=w(()=>{I0();IQ();R0();EZ()});class XL{constructor(Q){this.args=Q}name="setPlugin";errorHelper=new s0(_Q,vQ);getApdu(){return new w0({cla:224,ins:22,p1:0,p2:0}).addHexaStringToData(this.args.payload).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var yy=w(()=>{I0();IQ();R0();EZ()});class VL{static PAYLOAD_LENGTH_BYTES=2;static getBufferFromPayload(Q){let Z=mQ(Q);return Z===null||Z.length===0?null:new WQ(Z.length+this.PAYLOAD_LENGTH_BYTES).add16BitUIntToData(Z.length).addBufferToData(Z).build()}}var gy=w(()=>{I0()});class Z8{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let{data:Q,commandFactory:Z}=this.args,Y=new WQ(Q.length).addBufferToData(Q).build();for(let $=0;$<Y.length;$+=YZ){let J=$+YZ>=Y.length,X=await this.api.sendCommand(Z({chunkedData:Y.slice($,$+YZ),isFirstChunk:$===0}));if(!N0(X))return X;if(J)return o({data:X.data})}throw new C0("No result")}}var D4=w(()=>{I0()});class F1{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let{payload:Q,withPayloadLength:Z=!0}=this.args,Y=null;return Z?Y=VL.getBufferFromPayload(Q):Y=mQ(Q),Y?new Z8(this.api,{data:Y,commandFactory:this.args.commandFactory}).run():o({error:new C0("Invalid payload")})}}var qL=w(()=>{I0();gy();D4()});class kX{constructor(Q,Z,Y=($,J)=>new F1($,J)){this._api=Q,this._args=Z,this._sendPayloadInChunksTaskFactory=Y,this._logger=Z.loggerFactory("ProvideContextTask")}_logger;async run(){let{type:Q,payload:Z,certificate:Y}=this._args.context;switch(this._logger.debug("[run] Providing context",{data:{type:Q,payloadLength:typeof Z=="string"?Z.length:void 0,hasCertificate:!!Y}}),Y&&await this._api.sendCommand(new L1({keyUsage:Y.keyUsageNumber,certificate:Y.payload})),Q){case u.ETHEREUM_PLUGIN:return await this._api.sendCommand(new XL({payload:Z}));case u.ETHEREUM_EXTERNAL_PLUGIN:return await this._api.sendCommand(new GL({payload:Z}));case u.ETHEREUM_NFT:return await this._api.sendCommand(new tR({payload:Z}));case u.ETHEREUM_TOKEN:return await this._api.sendCommand(new U4({payload:Z}));case u.ETHEREUM_TRANSACTION_INFO:return await this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new YL({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();case u.ETHEREUM_TRUSTED_NAME:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new O4({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();case u.ETHEREUM_ENUM:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new iR({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();case u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new ZL({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();case u.ETHEREUM_TRANSACTION_CHECK:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new H4({payload:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();case u.ETHEREUM_PROXY_INFO:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new K4({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();case u.ETHEREUM_DYNAMIC_NETWORK:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new BX({data:$.chunkedData,isFirstChunk:$.isFirstChunk,configurationType:NX.CONFIGURATION})}).run();case u.ETHEREUM_DYNAMIC_NETWORK_ICON:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new BX({data:$.chunkedData,isFirstChunk:$.isFirstChunk,configurationType:NX.ICON}),withPayloadLength:!1}).run();case u.ETHEREUM_SAFE:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new q5({data:$.chunkedData,isFirstChunk:$.isFirstChunk,type:V5.SAFE_DESCRIPTOR})}).run();case u.ETHEREUM_SIGNER:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new q5({data:$.chunkedData,isFirstChunk:$.isFirstChunk,type:V5.SIGNER_DESCRIPTOR})}).run();case u.ETHEREUM_GATED_SIGNING:return this._sendPayloadInChunksTaskFactory(this._api,{payload:Z,commandFactory:($)=>new W4({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();default:return o({error:new C0(`The context type [${Q}] is not covered`)})}}}var F5=w(()=>{X$();I0();Sy();aR();rR();wy();eR();_y();QL();vy();xy();$L();JL();fy();yy();qL()});class I4{constructor(Q,Z){this._api=Q,this._args=Z,this._logger=Z.loggerFactory("SendGetAddressTask")}_logger;async run(){let{contextModule:Q,derivationPath:Z,checkOnDevice:Y,returnChainCode:$,chainId:J}=this._args,X=Y&&J!==void 0?J:void 0;if(X!==void 0){let G=this._api.getDeviceModel().id,W={chainId:X,deviceModelId:G};this._logger.debug("[run] Loading dynamic network context",{data:{chainId:X,deviceModelId:G}});let U=(await Q.getContexts(W,qU)).filter(hJ);for(let K of U){let O=await new kX(this._api,{context:K,loggerFactory:this._args.loggerFactory}).run();N0(O)||this._logger.debug("[run] Ignoring context provision error, continuing to getAddress",{data:{contextType:K.type,error:O.error}})}}return this._api.sendCommand(new TX({derivationPath:Z,checkOnDevice:Y,returnChainCode:$,...X!==void 0&&{chainId:X}}))}}var FL=w(()=>{X$();I0();X5();F5()});var hy=(Q)=>new nZ({input:{task:async(Z)=>new I4(Z,{contextModule:Q.contextModule,derivationPath:Q.derivationPath,checkOnDevice:Q.checkOnDevice,returnChainCode:Q.returnChainCode,chainId:Q.chainId,loggerFactory:Q.loggerFactory}).run(),appName:AY,requiredUserInteraction:Q.checkOnDevice?k0.VerifyAddress:k0.None,skipOpenApp:Q.skipOpenApp}});var by=w(()=>{I0();XG();FL()});class zL{name="signPersonalMessage";args;errorHelper=new s0(_Q,vQ);constructor(Q){this.args=Q}getApdu(){let{data:Q,isFirstChunk:Z}=this.args;return new w0({cla:224,ins:8,p1:Z?0:128,p2:0}).addBufferToData(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({data:YQ});let $=Z.encodeToHexaString(Z.extractFieldByLength(H80),!0);if(!$)return o({error:new C0("R is missing")});let J=Z.encodeToHexaString(Z.extractFieldByLength(D80),!0);return J?o({data:HQ({r:$,s:J,v:Y})}):o({error:new C0("S is missing")})})}}var H80=32,D80=32;var cy=w(()=>{I0();IQ();R0();EZ()});class R4{constructor(Q,Z){this.api=Q,this.args=Z,this._logger=Z.logger}_logger;async run(){let{derivationPath:Q,message:Z}=this.args;this._logger.debug("[run] Starting SendSignPersonalMessageTask",{data:{derivationPath:Q,messageLength:Z.length,messageType:typeof Z=="string"?"string":"Uint8Array"}});let Y=QZ.splitPath(Q),$=new WQ(Z.length+1+(Y.length+1)*I80);$.add8BitUIntToData(Y.length),Y.forEach((G)=>{$.add32BitUIntToData(G)}),$.add32BitUIntToData(Z.length),typeof Z=="string"?$.addAsciiStringToData(Z):$.addBufferToData(Z);let J=$.build();this._logger.debug("[run] Sending message in chunks",{data:{bufferLength:J.length}});let X=await new Z8(this.api,{data:J,commandFactory:(G)=>new zL({data:G.chunkedData,isFirstChunk:G.isFirstChunk})}).run();return N0(X)?(this._logger.debug("[run] Personal message signed successfully"),X.data.mapOrDefault((G)=>o({data:G}),o({error:new C0("no signature returned")}))):(this._logger.error("[run] Failed to sign personal message",{data:{error:X.error}}),X)}}var I80=4;var WL=w(()=>{I0();IQ();cy();D4()});var uy=(Q)=>{let Z=Q.loggerFactory("SendSignPersonalMessageTask");return new nZ({input:{task:async(Y)=>new R4(Y,{derivationPath:Q.derivationPath,message:Q.message,logger:Z}).run(),appName:AY,requiredUserInteraction:k0.SignPersonalMessage,skipOpenApp:Q.skipOpenApp}})};var py=w(()=>{I0();XG();WL()});var V$;var KL=w(()=>{V$=((Q)=>(Q.OPEN_APP="signer.eth.steps.openApp",Q.GET_APP_CONFIG="signer.eth.steps.getAppConfig",Q.GET_ADDRESS="signer.eth.steps.getAddress",Q.WEB3_CHECKS_OPT_IN="signer.eth.steps.web3ChecksOptIn",Q.WEB3_CHECKS_OPT_IN_RESULT="signer.eth.steps.web3ChecksOptInResult",Q.PARSE_TRANSACTION="signer.eth.steps.parseTransaction",Q.BUILD_CONTEXTS="signer.eth.steps.buildContexts",Q.PROVIDE_CONTEXTS="signer.eth.steps.provideContexts",Q.SIGN_TRANSACTION="signer.eth.steps.signTransaction",Q.BLIND_SIGN_TRANSACTION_FALLBACK="signer.eth.steps.blindSignTransactionFallback",Q.DETECT_BLIND_SIGNING="signer.eth.steps.detectBlindSigning",Q))(V$||{})});var JJ;var L4=w(()=>{JJ=((Q)=>(Q.BASIC="basic",Q.EIP7730="eip7730",Q))(JJ||{})});var E4;var z5=w(()=>{E4=Object.freeze({contactGroups:Object.freeze([]),ledgerAccounts:Object.freeze([])})});class P4{name="getAppConfiguration";errorHelper=new s0(_Q,vQ);constructor(){}getApdu(){return new w0({cla:224,ins:6,p1:0,p2:0}).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({error:new C0("Cannot extract config flags")});let $=Z.extract8BitUInt(),J=Z.extract8BitUInt(),X=Z.extract8BitUInt();if($===void 0||J===void 0||X===void 0)return o({error:new C0("Cannot extract version")});let G=!!(Y&1),W=!!(Y&16),U=!!(Y&32),K={blindSigningEnabled:G,web3ChecksEnabled:W,web3ChecksOptIn:U,version:`${$}.${J}.${X}`};return o({data:K})})}}var UL=w(()=>{I0();IQ();R0();EZ()});class j4{name="web3CheckOptIn";errorHelper=new s0(_Q,vQ);constructor(){}getApdu(){return new w0({cla:224,ins:50,p1:1,p2:0}).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q).extract8BitUInt();return Z===void 0?o({data:{enabled:!1}}):o({data:{enabled:Z!==0}})})}}var OL=w(()=>{I0();IQ();R0();EZ()});class p${resolve(Q,Z){if(Q.sessionStateType===CQ.Connected)return{isCompatible:!1,version:HL};let Y=Q.currentApp,$=Y?.name;return $?$==="Exchange"?{isCompatible:!1,version:HL}:{isCompatible:!0,version:$===AY?Y.version:Z.version}:{isCompatible:!1,version:HL}}}var HL="0.0.1";var oV=w(()=>{I0();XG()});function L80(Q){return Q.usedFallback||Q.contextTypes&&Q.hasContext&&Q.contextTypes.length>0&&!Q.contextTypes.some((Z)=>!R80.has(Z))?!0:!Q.hasContext}function ly(Q){return Q.usedFallback?$5.DEVICE_REJECTED_CONTEXT:$5.NO_CLEAR_SIGNING_CONTEXT}function E80(Q,Z){let Y=Q.type==="transaction"?Y5.ETH_SIGN_TRANSACTION:Y5.ETH_SIGN_TYPED_DATA;return{signatureId:yD(),signingMethod:Y,isBlindSign:Z,chainId:Q.chainId,targetAddress:Q.targetAddress,blindSignReason:Z?ly(Q):null,modelId:G5(Q.deviceModelId),signerAppVersion:Q.signerAppVersion,deviceVersion:Q.deviceVersion,ethContext:Q.clearSigningType!==null?{clearSigningType:Q.clearSigningType,partialContextErrors:Q.partialContextErrors}:null}}function P80(Q,Z){let Y=Q.type==="transaction"?J5.ETH_SIGN_TRANSACTION:J5.ETH_SIGN_TYPED_DATA;return{chain:"ETH",signatureId:yD(),signingMethod:Y,isBlindSign:Z,chainId:Q.chainId,targetAddress:Q.targetAddress,blindSignReason:Z?ly(Q):null,modelId:G5(Q.deviceModelId),signerAppVersion:Q.signerAppVersion,deviceVersion:Q.deviceVersion,...Q.type==="transaction"&&Q.selectorId!==null&&{selectorId:Q.selectorId},...Q.clearSigningType!==null&&{clearSigningType:Q.clearSigningType,partialContextErrors:Q.partialContextErrors}}}class A4{constructor(Q){this._args=Q,this._logger=Q.loggerFactory("BlindSigningDetectionTask")}_logger;async run(){let{input:Q,contextModule:Z}=this._args,Y=L80(Q);this._logger.debug("[run] Blind signing detection result",{data:{isBlindSign:Y,type:Q.type}});try{let $=E80(Q,Y);await Z.report($)}catch($){this._logger.error("[run] Failed to report blind signing event",{data:{error:$}})}try{let $=P80(Q,Y);await Z.signReport?.($)}catch($){this._logger.error("[run] Failed to report signing event",{data:{error:$}})}return{isBlindSign:Y}}}var R80;var DL=w(()=>{X$();IQ();R80=new Set([u.ETHEREUM_TRANSACTION_CHECK,u.ETHEREUM_DYNAMIC_NETWORK,u.ETHEREUM_DYNAMIC_NETWORK_ICON,u.ETHEREUM_GATED_SIGNING])});class GJ{name="getChallenge";errorHelper=new s0(_Q,vQ);constructor(){}getApdu(){return new w0({cla:224,ins:32,p1:0,p2:0}).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q);if(Z.testMinimalLength(my)===!1)return o({error:new C0("Challenge key is missing")});let Y=Z.encodeToHexaString(Z.extractFieldByLength(my));return o({data:{challenge:Y}})})}}var my=4;var sV=w(()=>{I0();IQ();R0();EZ()});var W5="1.22.0",dy="1.14.0",K5="1.15.0";var M4=()=>{};class IL{constructor(Q,Z){this._api=Q,this._args=Z}async run(){let{contextModule:Q,appConfig:Z,transaction:Y,subset:$}=this._args,J=Y===void 0,X=!J&&Z.web3ChecksEnabled,G=this._api.getDeviceSessionState(),W;if(G.deviceModelId!==JQ.NANO_S){let L=await this._api.sendCommand(new GJ);N0(L)&&(W=L.data.challenge)}let U=await Q.getContexts({challenge:W,deviceModelId:G.deviceModelId,transaction:X?Y:void 0,...$},J?j80:A80),K=U.filter((L)=>L.type===u.ERROR).length,O=U.filter((L)=>L.type!==u.ERROR).filter(hJ),I=new YY(G,Z,new p$).withMinVersionInclusive(W5).excludeDeviceModel(JQ.NANO_S).check()?O:O.filter((L)=>L.type!==u.ETHEREUM_GATED_SIGNING);return this._supportsGenericParser(G,Z)&&this._hasValidTransactionInfo(I)?this._getERC7730Contexts(I,K):this._getBasicContexts(I,K)}_getERC7730Contexts(Q,Z){let Y=Q.filter((J)=>this._isContextNeededForERC7730ClearSigning(J)).sort((J,X)=>this._getContextPriority(J)-this._getContextPriority(X)),$=Q.filter((J)=>J.type===u.ETHEREUM_ENUM);return{clearSignContexts:Y,clearSignContextsOptional:$,clearSigningType:JJ.EIP7730,contextErrorCount:Z}}_getBasicContexts(Q,Z){return{clearSignContexts:Q.filter((Y)=>this._isContextNeededForBasicClearSigning(Y)).sort((Y,$)=>this._getContextPriority(Y)-this._getContextPriority($)),clearSignContextsOptional:[],clearSigningType:JJ.BASIC,contextErrorCount:Z}}_isContextNeededForBasicClearSigning({type:Q}){switch(Q){case u.ETHEREUM_TRANSACTION_CHECK:case u.ETHEREUM_PLUGIN:case u.ETHEREUM_EXTERNAL_PLUGIN:case u.ETHEREUM_DYNAMIC_NETWORK:case u.ETHEREUM_DYNAMIC_NETWORK_ICON:case u.ETHEREUM_TRUSTED_NAME:case u.ETHEREUM_TOKEN:case u.ETHEREUM_NFT:case u.ETHEREUM_GATED_SIGNING:case u.ETHEREUM_PROXY_INFO:return!0;case u.ETHEREUM_TRANSACTION_INFO:case u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION:case u.ETHEREUM_ENUM:case u.ETHEREUM_SAFE:case u.ETHEREUM_SIGNER:return!1;default:throw Error(`Unhandled context type ${String(Q)}`)}}_isContextNeededForERC7730ClearSigning({type:Q}){switch(Q){case u.ETHEREUM_TRANSACTION_INFO:case u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION:case u.ETHEREUM_PROXY_INFO:case u.ETHEREUM_DYNAMIC_NETWORK:case u.ETHEREUM_DYNAMIC_NETWORK_ICON:case u.ETHEREUM_TRANSACTION_CHECK:case u.ETHEREUM_GATED_SIGNING:return!0;case u.ETHEREUM_ENUM:case u.ETHEREUM_TRUSTED_NAME:case u.ETHEREUM_TOKEN:case u.ETHEREUM_NFT:case u.ETHEREUM_PLUGIN:case u.ETHEREUM_EXTERNAL_PLUGIN:case u.ETHEREUM_SAFE:case u.ETHEREUM_SIGNER:return!1;default:throw Error(`Unhandled context type ${String(Q)}`)}}_hasValidTransactionInfo(Q){return Q.find((Z)=>Z.type===u.ETHEREUM_TRANSACTION_INFO)?.certificate!==void 0}_supportsGenericParser(Q,Z){return new YY(Q,Z,new p$).withMinVersionExclusive(dy).excludeDeviceModel(JQ.NANO_S).check()}_getContextPriority({type:Q}){switch(Q){case u.ETHEREUM_PROXY_INFO:return 5;case u.ETHEREUM_TRANSACTION_CHECK:case u.ETHEREUM_GATED_SIGNING:return 10;case u.ETHEREUM_DYNAMIC_NETWORK:case u.ETHEREUM_DYNAMIC_NETWORK_ICON:return 30;case u.ETHEREUM_TRANSACTION_INFO:return 50;case u.ETHEREUM_PLUGIN:case u.ETHEREUM_EXTERNAL_PLUGIN:case u.ETHEREUM_TOKEN:case u.ETHEREUM_NFT:case u.ETHEREUM_TRUSTED_NAME:case u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION:case u.ETHEREUM_ENUM:return 70;case u.ETHEREUM_SAFE:case u.ETHEREUM_SIGNER:return 90;default:throw Error(`Unhandled context type for priority: ${String(Q)}`)}}}var j80,A80;var ny=w(()=>{X$();I0();L4();sV();oV();M4();j80=[u.ETHEREUM_TRUSTED_NAME,u.ETHEREUM_TRANSACTION_INFO,u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION,u.ETHEREUM_ENUM,u.ETHEREUM_PROXY_INFO],A80=[u.ETHEREUM_TRANSACTION_INFO,u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION,u.ETHEREUM_PROXY_INFO,u.ETHEREUM_TRANSACTION_CHECK,u.ETHEREUM_DYNAMIC_NETWORK,u.ETHEREUM_DYNAMIC_NETWORK_ICON,u.ETHEREUM_ENUM,u.ETHEREUM_TRUSTED_NAME,u.ETHEREUM_TOKEN,u.ETHEREUM_NFT,u.ETHEREUM_PLUGIN,u.ETHEREUM_EXTERNAL_PLUGIN,u.ETHEREUM_GATED_SIGNING]});class RL{constructor(Q,Z){this.api=Q,this.args=Z}run(){let Q=this.args.context,Z=Q.type;switch(Z){case u.ETHEREUM_TRANSACTION_CHECK:case u.ETHEREUM_TRANSACTION_INFO:case u.ETHEREUM_PLUGIN:case u.ETHEREUM_EXTERNAL_PLUGIN:case u.ETHEREUM_DYNAMIC_NETWORK:case u.ETHEREUM_DYNAMIC_NETWORK_ICON:case u.ETHEREUM_ENUM:case u.ETHEREUM_TOKEN:case u.ETHEREUM_NFT:case u.ETHEREUM_SAFE:case u.ETHEREUM_SIGNER:case u.ETHEREUM_GATED_SIGNING:return{subcontextCallbacks:[]};case u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION:return{subcontextCallbacks:Q.reference?this._getSubcontextsFromReference(Q.reference):[]};case u.ETHEREUM_PROXY_INFO:return{subcontextCallbacks:this._getSubcontextFromProxy(Q)};case u.ETHEREUM_TRUSTED_NAME:return{subcontextCallbacks:this._getSubcontextFromTrustedName(Q)};default:throw Error(`Uncovered type: ${Z}`)}}_getSubcontextsFromReference(Q){let Z=Q.type;switch(Z){case iZ.TOKEN:case iZ.NFT:return this._getSubcontextsFromTokenOrNftReference(Q);case iZ.ENUM:return this._getSubcontextsFromEnumReference(Q);case iZ.TRUSTED_NAME:return this._getSubcontextsFromTrustedNameReference(Q);case iZ.CALLDATA:return[];default:throw Error(`Uncovered reference type: ${Z}`)}}_getSubcontextsFromTokenOrNftReference(Q){if(Q.value!==void 0){let Y={chainId:this.args.subset.chainId,address:Q.value,deviceModelId:this.args.deviceModelId},$=Q.type===iZ.TOKEN?u.ETHEREUM_TOKEN:u.ETHEREUM_NFT;return[()=>this.args.contextModule.getFieldContext(Y,$)]}let Z=[];if(Q.valuePath!==void 0){let Y=this.args.transactionParser.extractValue(this.args.subset,Q.valuePath).orDefault([]);for(let $ of Y){let J=DQ($.slice(Math.max(0,$.length-20))),X=Q.type===iZ.TOKEN?u.ETHEREUM_TOKEN:u.ETHEREUM_NFT;Z.push(()=>this.args.contextModule.getFieldContext({chainId:this.args.subset.chainId,address:J,deviceModelId:this.args.deviceModelId},X))}}return Z}_getSubcontextsFromEnumReference(Q){let Z=[];if(!Q.valuePath)return Z;let Y=this.args.transactionParser.extractValue(this.args.subset,Q.valuePath).orDefault([]);for(let $ of Y){let J=$[$.length-1];if(J===void 0)continue;let X=this.args.contextOptional.filter((G)=>G.type===u.ETHEREUM_ENUM).find((G)=>G.value===J&&G.id===Q.id);X&&Z.push(()=>Promise.resolve(X))}return Z}_getSubcontextsFromTrustedNameReference(Q){let Z=[];if(!Q.valuePath)return Z;let Y=this.args.transactionParser.extractValue(this.args.subset,Q.valuePath).orDefault([]);for(let $ of Y)Z.push(async()=>{let J=DQ($.slice(Math.max(0,$.length-20))),X=await this.api.sendCommand(new GJ);return N0(X)?await this.args.contextModule.getFieldContext({chainId:this.args.subset.chainId,address:J,challenge:X.data.challenge,types:Q.types,sources:Q.sources,deviceModelId:this.args.deviceModelId},u.ETHEREUM_TRUSTED_NAME):{type:u.ERROR,error:Error("Failed to get challenge")}});return Z}_getSubcontextFromTrustedName(Q){return[async()=>{let Z=await this.api.sendCommand(new GJ);return N0(Z)?await this.args.contextModule.getFieldContext({chainId:this.args.subset.chainId,address:this.args.subset.to,challenge:Z.data.challenge,types:["eoa"],sources:["ens"],deviceModelId:this.args.deviceModelId},u.ETHEREUM_TRUSTED_NAME):{type:u.ERROR,error:Error("Failed to get challenge")}}]}_getSubcontextFromProxy(Q){return[async()=>{let Z=await this.api.sendCommand(new GJ);return N0(Z)?this.args.subset.to===void 0?{type:u.ERROR,error:Error("Failed to get proxy address")}:await this.args.contextModule.getFieldContext({chainId:this.args.subset.chainId,proxyAddress:this.args.subset.to,calldata:this.args.subset.data,deviceModelId:this.args.deviceModelId,challenge:Z.data.challenge},u.ETHEREUM_PROXY_INFO):{type:u.ERROR,error:Error("Failed to get challenge")}}]}}var oy=w(()=>{X$();I0();sV()});class LL{constructor(Q){this._args=Q}run(){let{parser:Q,subset:Z,context:Y}=this._args,$=[];if(!Y.reference||Y.reference.type!==iZ.CALLDATA||!Y.reference.valuePath)throw Error("Invalid reference for nested call data. Expected a reference with type CALLDATA and a value path.");let{valuePath:J}=Y.reference,X=Q.extractValue(Z,J).unsafeCoerce(),G=Q.extractValue(Z,Y.reference.callee).unsafeCoerce(),W=Y.reference.selector?Q.extractValue(Z,Y.reference.selector).orDefault([]):[],U=Y.reference.chainId?Q.extractValue(Z,Y.reference.chainId).orDefault([]):[];for(let K=0;K<X.length;K++){let O=X[K],I=U[K],L=G[K]?.slice(Math.max(0,G[K].length-20)),A=W[K],M={data:O?DQ(O):"0x",chainId:I?Number(I):Z.chainId,to:L?DQ(L):Z.to,selector:A?DQ(A):O?DQ(O).slice(0,M80):"0x"};$.push(M)}return{subsets:$}}}var M80=10;var sy=w(()=>{X$();I0()});class iV{constructor(Q,Z,Y=(X,G)=>new RL(X,G),$=(X,G)=>new IL(X,G),J=(X)=>new LL(X)){this._api=Q,this._args=Z,this._buildSubcontextsTaskFactory=Y,this._buildBaseContextsTaskFactory=$,this._preBuildNestedCallDataTaskFactory=J,this._logger=Z.loggerFactory("BuildFullContextsTask")}_logger;async run(){this._logger.debug("[run] Starting BuildFullContextsTask");let{clearSignContexts:Q,clearSigningType:Z,clearSignContextsOptional:Y,contextErrorCount:$}=await this._buildBaseContextsTaskFactory(this._api,this._args).run();this._logger.debug("[run] Base contexts built",{data:{clearSigningType:Z,contextTypes:Q.map((G)=>G.type)}});let J=Q.map((G)=>{let{subcontextCallbacks:W}=this._buildSubcontextsTaskFactory(this._api,{context:G,contextOptional:Y,contextModule:this._args.contextModule,subset:this._args.subset,transactionParser:this._args.parser,deviceModelId:this._args.deviceModelId}).run();return{context:G,subcontextCallbacks:W}}),X=[];for(let G of J)if(X.push(G),G.context.type===u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION&&G.context.reference?.type===iZ.CALLDATA){let{subsets:W}=this._preBuildNestedCallDataTaskFactory({parser:this._args.parser,subset:this._args.subset,context:G.context}).run();for(let U of W){let{clearSignContexts:K}=await new iV(this._api,{...this._args,transaction:void 0,subset:U},this._buildSubcontextsTaskFactory,this._buildBaseContextsTaskFactory,this._preBuildNestedCallDataTaskFactory).run();X.push(...K)}}return this._logger.debug("[run] BuildFullContextsTask completed",{data:{clearSigningType:Z,contextTypes:X.map((G)=>G.context.type),hasNestedContexts:X.length>Q.length}}),{clearSignContexts:X,clearSigningType:Z,contextErrorCount:$}}}var EL=w(()=>{X$();ny();oy();sy()});class PL{constructor(Q){this._args=Q}run(){let{mapper:Q,transaction:Z}=this._args,{subset:Y,type:$}=Q.mapTransactionToSubset(Z).unsafeCoerce();return{subset:Y,type:$}}}var iy=()=>{};function aV(Q){return jL[Q]}function AL(Q,Z){let Y=PJ.valid(PJ.coerce(Q)),$=PJ.valid(PJ.coerce(Z));return Y===null||$===null?!1:PJ.gte(Y,$)}function v80(Q,Z){let Y=PJ.valid(Q),$=PJ.valid(Z);return Y===null||$===null?!1:PJ.lt(Y,$)}function Yg(Q,Z){let Y=jL[Q];if(!Y.supported)return!1;let $=Y.renameDerivationPathRequiredBelowOsVersion;return $===void 0?!1:v80(Z,$)}var PJ,U5="Ethereum",ay="Tron",T80,ry="1.11.0",ty="1.7.0",ey="1.2.0",Qg="2.8.0",Zg="1.7.0",N80="1.23.0",B80="0.8.0",T4,k80,C80,S80,w80,_80,jL;var O5=w(()=>{I0();PJ=JZ(kG(),1),T80={supported:!1},T4={[U5]:N80,[ay]:B80},k80=`${ry}-rc3`,C80=`${ty}-rc3`,S80=`${ey}-rc3`,w80=`${Qg}-rc3`,_80=`${Zg}-rc3`,jL={[JQ.NANO_S]:T80,[JQ.NANO_SP]:{supported:!0,minOsVersion:Zg,minAppVersion:T4,renameDerivationPathRequiredBelowOsVersion:_80},[JQ.NANO_X]:{supported:!0,minOsVersion:Qg,minAppVersion:T4,renameDerivationPathRequiredBelowOsVersion:w80},[JQ.STAX]:{supported:!0,minOsVersion:ry,minAppVersion:T4,renameDerivationPathRequiredBelowOsVersion:k80},[JQ.FLEX]:{supported:!0,minOsVersion:ty,minAppVersion:T4,renameDerivationPathRequiredBelowOsVersion:C80},[JQ.APEX]:{supported:!0,minOsVersion:ey,minAppVersion:T4,renameDerivationPathRequiredBelowOsVersion:S80}}});class ML{resolve(Q,Z){return Q.sessionStateType===CQ.Connected?{isCompatible:!1,version:$g}:Q.currentApp?.name?{isCompatible:!0,version:Z.version}:{isCompatible:!1,version:$g}}}var $g="0.0.0";var Jg=w(()=>{I0()});function Gg(Q){return Q.supported}function Xg(Q,Z){let Y=Q.getDeviceSessionState(),$=aV(Y.deviceModelId);return Gg($)?AL(Z,$.minOsVersion):!1}function rV(Q,Z){let Y=Q.getDeviceSessionState(),$=aV(Y.deviceModelId);if(!Gg($))return!1;let J=$.minAppVersion[Z.name];return J===void 0?!1:new YY(Y,{version:Z.version},new ML).withMinVersionInclusiveAcceptingPrerelease(J).check()}var N4=w(()=>{I0();O5();Jg()});class Y8{constructor(Q="The connected device or app does not meet the Contacts version requirements."){this.message=Q}_tag="ContactsVersionRequirementError";originalError}var x80="6982",f80,Vg,y80=(Q)=>new Vg(Q),uJ;var z1=w(()=>{I0();IQ();f80={[x80]:{message:"This address-book entry was registered with a different seed. Connect the Ledger device that registered it to modify this contact."},6800:{message:"Internal error (Please report)"},6983:{message:"Wrong data length"},6984:{message:"Unsupported address-book operation for this device or app configuration"},6985:{message:"Condition not satisfied"},"686a":{message:"This device's firmware is out of date for the address book. Update your Ledger device to the latest firmware, then try again."},"6a80":{message:"Invalid contact data, or operation refused on device"},"6a84":{message:"Insufficient memory: the device address book is full"},"6a88":{message:"Contact data not found"},"6af0":{message:"Invalid value for this contact entry"},"6b00":{message:"The app rejected the contact data"},"6f00":{message:"Technical problem (Internal error, please report)"}};Vg=class Vg extends DZ{constructor(Q){super({tag:"ContactsCommandError",...Q})}};uJ=class uJ extends s0{constructor(){super(f80,y80)}getError(Q){let Z=super.getError(Q);if(Z===void 0||N0(Z)||Z.error._tag!=="UnknownDeviceExchangeError")return Z;let Y=new FQ(Q).encodeToHexaString(Q.statusCode);return zQ({error:new C0(`The device returned an unexpected status word (0x${Y}) for this address-book operation. Update your Ledger device and Ethereum app to the latest version, then try again.`)})}}});var VG=176,qG=16,H5=1,D5=32,I5=3,R5=4,qg=224,Fg=46,L5=0,zg=64,Wg=32,tV=32,Kg=32,l$;var m$=w(()=>{l$={bitcoin:0,ethereum:1,solana:2,polkadot:3,cosmos:4,cardano:5,tron:6}});function TL(Q,Z){if(Z<128)Q.add8BitUIntToData(Z);else if(Z<=255)Q.add16BitUIntToData(g80+Z);else throw Error(`TLV tag ${Z} exceeds supported single-byte range`)}function Hg(Q,Z){if(Z<128)Q.add8BitUIntToData(Z);else if(Z<=255)Q.add8BitUIntToData(129),Q.add8BitUIntToData(Z);else if(Z<=65535)Q.add8BitUIntToData(130),Q.add16BitUIntToData(Z);else throw Error(`TLV length ${Z} exceeds supported range`)}function h80(Q){let Z=typeof Q=="bigint"?Q:BigInt(Q);if(Z<=0n)throw Error(`chainId must be positive, got ${Q}`);if(Z>0xffffffffffffffffn)throw Error(`chainId ${Q} exceeds uint64 range`);let Y=[],$=Z;for(;$>0n;)Y.unshift(Number($&0xffn)),$>>=8n;return Uint8Array.from(Y)}function MY(Q,Z,Y){TL(Q,Z),Q.add8BitUIntToData(1),Q.add8BitUIntToData(Y)}function q$(Q,Z,Y){TL(Q,Z);let $=new TextEncoder().encode(Y);Hg(Q,$.length),Q.addBufferToData($)}function wZ(Q,Z,Y){TL(Q,Z),Hg(Q,Y.length),Q.addBufferToData(Y)}function FG(Q,Z,Y){wZ(Q,Z,h80(Y))}function Dg(Q){let Z=new WQ;return Z.add8BitUIntToData(Q.length),Q.forEach((Y)=>Z.add32BitUIntToData(Y)),Z.build()}var g80=33024,kQ,Ug=45,E5=46,P5=49,j5=50,Og=51,W1=1;var $8=w(()=>{I0();kQ={STRUCT_TYPE:1,STRUCT_VERSION:2,DERIVATION_PATH:105,CHAIN_ID:35,HMAC_PROOF:41,BLOCKCHAIN_FAMILY:81,CONTACT_NAME:240,SCOPE:241,ACCOUNT_IDENTIFIER:242,PREVIOUS_CONTACT_NAME:243,PREVIOUS_IDENTIFIER:244,PREVIOUS_SCOPE:245,GROUP_HANDLE:246,HMAC_REST:247}});function b80(Q,Z){let Y=Q.extractFieldByLength(Z);if(!(!Y||Y.length!==Z))return Uint8Array.from(Y)}class NL{name="editExternalAddressIdentifier";args;errorHelper=new uJ;constructor(Q){this.args=Q}getApdu(){return new w0({cla:VG,ins:qG,p1:I5,p2:this.args.p2}).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{if(Q.data.length===0)return o({data:{}});let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y!==Ig)return o({error:new C0(`Expected struct_type 0x${Ig.toString(16)}, got ${Y===void 0?"undefined":`0x${Y.toString(16)}`}`)});let $=b80(Z,tV);return $?o({data:{hmacRest:$}}):o({error:new C0("hmac_rest missing or truncated")})})}}var Ig;var Rg=w(()=>{I0();R0();m$();z1();$8();Ig=P5});async function K1(Q,{payload:Z,makeCommand:Y,logger:$,commandTag:J}){let X=u80(Z),G=p80(X,c80),W=J??"framed-contacts";for(let I=0;I<G.length-1;I++){let L=I===0?Lg:Eg,A=G[I];Pg($,W,I,G.length,L,A.length,X.length);let M=await Q.sendCommand(Y(A,L));if(!t$(M))return M}let U=G.length-1,K=U===0?Lg:Eg,O=G[U];return Pg($,W,U,G.length,K,O.length,X.length),await Q.sendCommand(Y(O,K))}function Pg(Q,Z,Y,$,J,X,G){Q&&Q.debug(`[chunk ${Y+1}/${$}] sending`,{tag:Z,data:{chunkIndex:Y,chunkCount:$,p2:`0x${J.toString(16).padStart(2,"0")}`,chunkLen:X,framedPayloadLen:G,isFirst:Y===0,isLast:Y===$-1}})}function u80(Q){let Z=Q.length,Y=new Uint8Array(Z+2);return Y[0]=Z>>8&255,Y[1]=Z&255,Y.set(Q,2),Y}function p80(Q,Z){if(Q.length===0)return[Q];let Y=[];for(let $=0;$<Q.length;$+=Z)Y.push(Q.slice($,Math.min($+Z,Q.length)));return Y}var c80=255,Lg=0,Eg=128;var eV=w(()=>{I0()});class BL{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=this.buildPayload(this.args),Z=await K1(this.api,{payload:Q,p1:I5,makeCommand:($,J)=>new NL({data:$,p2:J}),logger:this.args.logger,commandTag:"SendEditExternalAddressIdentifierTask"});if(!N0(Z))return Z;let{hmacRest:Y}=Z.data;return Y?zQ({data:{hmacRest:Y}}):zQ({error:new C0("EditIdentifier final-chunk response did not carry hmac_rest")})}buildPayload(Q){let Z=l$[Q.blockchainFamily.toLowerCase()];if(Z===void 0)throw Error(`Unsupported blockchain family: ${Q.blockchainFamily}`);let Y=new WQ;return MY(Y,kQ.STRUCT_TYPE,P5),MY(Y,kQ.STRUCT_VERSION,W1),q$(Y,kQ.CONTACT_NAME,Q.contactName),q$(Y,kQ.SCOPE,Q.scope),wZ(Y,kQ.ACCOUNT_IDENTIFIER,Q.newIdentifier),wZ(Y,kQ.PREVIOUS_IDENTIFIER,Q.previousIdentifier),wZ(Y,kQ.GROUP_HANDLE,Q.groupHandle),Q.chainId!==void 0&&FG(Y,kQ.CHAIN_ID,Q.chainId),wZ(Y,kQ.HMAC_PROOF,Q.hmacProof),wZ(Y,kQ.HMAC_REST,Q.hmacRest),MY(Y,kQ.BLOCKCHAIN_FAMILY,Z),Y.build()}}var jg=w(()=>{I0();Rg();m$();$8();eV()});function XJ(Q,Z){let{field:Y,bufferLength:$}=Z;if(!Q)throw new PZ(`${Y} must not be empty (firmware rejects empty strings).`);let J=d80.encode(Q),X=$-1;if(J.length>X)throw new PZ(`${Y} ${JSON.stringify(Q)} is too long: ${J.length} bytes encoded (max ${X}). The device buffer is ${$} bytes including the trailing NUL.`);let G=[];for(let W=0;W<J.length;W++){let U=J[W];(U<l80||U>m80)&&G.push(W)}if(G.length>0){let W=Array.from(new Set(G.map((U)=>J[U]))).sort((U,K)=>U-K).map((U)=>`0x${U.toString(16).padStart(2,"0")}`).join(", ");throw new PZ(`${Y} ${JSON.stringify(Q)} contains ${G.length} non-ASCII byte(s) at position(s) [${G.join(", ")}]: ${W}. The device buffer is byte-level isprint() — only 0x20-0x7E are accepted, no UTF-8 / accents / emoji.`)}}function yY(Q,Z){let{field:Y,expectedBytes:$}=Z;if(Q.length!==$)throw new PZ(`${Y} is ${Q.length} bytes, expected ${$}.`)}function Qq(Q){let Z=typeof Q=="number";if(!Z&&typeof Q!="bigint")throw new PZ(`chainId must be number or bigint, got ${typeof Q}.`);if(Z&&!Number.isInteger(Q))throw new PZ(`chainId must be an integer, got ${Q}.`);let Y=typeof Q=="bigint"?Q:BigInt(Q);if(Y<=0n)throw new PZ(`chainId must be positive, got ${Q}.`);let $=(1n<<64n)-1n;if(Y>$)throw new PZ(`chainId ${Q} exceeds uint64 range (max ${$}).`)}var J8=33,CX=33,zG=64,U1=32,SX=20,PZ,l80=32,m80=126,d80;var B4=w(()=>{PZ=class PZ extends Error{_tag="ContactsValidationError";originalError;constructor(Q){super(Q),this.name="ContactsValidationError"}};d80=new TextEncoder});function Ag(Q){try{XJ(Q.contactName,{field:"contactName",bufferLength:J8}),XJ(Q.scope,{field:"scope",bufferLength:CX});let Z=Q.blockchainFamily.toLowerCase();if(!(Z in l$))throw new PZ(`Unsupported blockchain family: ${Q.blockchainFamily}`);if(Z==="ethereum"){if(yY(Q.previousIdentifier,{field:"previousIdentifier",expectedBytes:SX}),yY(Q.newIdentifier,{field:"newIdentifier",expectedBytes:SX}),Q.chainId===void 0)throw new PZ("chainId is required for the Ethereum blockchain family.")}else{if(Q.previousIdentifier.length===0)throw new PZ("previousIdentifier must not be empty.");if(Q.newIdentifier.length===0)throw new PZ("newIdentifier must not be empty.")}return Q.chainId!==void 0&&Qq(Q.chainId),yY(Q.groupHandle,{field:"groupHandle",expectedBytes:zG}),yY(Q.hmacProof,{field:"hmacProof",expectedBytes:U1}),yY(Q.hmacRest,{field:"hmacRest",expectedBytes:n80}),null}catch(Z){if(Z instanceof PZ)return Z;throw Z}}var n80;var Mg=w(()=>{m$();B4();n80=U1});var kL;var Tg=w(()=>{I0();R0();KZ();N4();z1();jg();Mg();kL=class kL extends AQ{makeStateMachine(Q){let{isSupported:Z,editIdentifier:Y}=this.extractDependencies(Q),$=this.input.appName;return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:$}}).makeStateMachine(Q),waitForAppAndVersionStateMachine:new kJ({input:{}}).makeStateMachine(Q),editIdentifier:VQ(({input:J})=>Y(J))},guards:{skipOpenApp:({context:J})=>J.input.skipOpenApp===!0,noInternalError:({context:J})=>J._internalState.error===null,contactsSupported:({context:J})=>{let{appAndVersion:X}=J._internalState;return X!==null&&Z(X)}},actions:{assignValidationError:r({_internalState:({context:J})=>{let X=Ag(J.input);return X?{...J._internalState,error:X}:J._internalState}}),assignVersionError:r({_internalState:({context:J})=>({...J._internalState,error:new Y8})}),assignErrorFromEvent:r({_internalState:({context:J,event:X})=>({...J._internalState,error:new xQ(X.error instanceof Error?X.error.message:String(X.error))})})}}).createMachine({id:"EditExternalAddressIdentifierDeviceAction",initial:"InitialState",context:({input:J})=>({input:J,intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,appAndVersion:null,hmacRest:null}}),states:{InitialState:{always:[{target:"ValidateInput",guard:"skipOpenApp"},{target:"OpenAppDeviceAction"}]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",src:"openAppStateMachine",input:()=>({appName:$}),onSnapshot:{actions:r({intermediateValue:({event:J})=>J.snapshot.context.intermediateValue})},onDone:{target:"CheckOpenAppResult",actions:r({_internalState:({event:J,context:X})=>J.output.caseOf({Right:()=>X._internalState,Left:(G)=>({...X._internalState,error:G})})})}}},CheckOpenAppResult:{always:[{target:"ValidateInput",guard:"noInternalError"},{target:"Error"}]},ValidateInput:{entry:"assignValidationError",always:[{target:"WaitForAppAndVersion",guard:"noInternalError"},{target:"Error"}]},WaitForAppAndVersion:{entry:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"waitForAppAndVersion",src:"waitForAppAndVersionStateMachine",input:()=>({}),onSnapshot:{actions:r({intermediateValue:({event:J})=>J.snapshot.context.intermediateValue})},onDone:{target:"CheckAppAndVersion",actions:r({_internalState:({event:J,context:X})=>J.output.caseOf({Right:(G)=>({...X._internalState,appAndVersion:{name:G.name,version:G.version}}),Left:(G)=>({...X._internalState,error:G})})})}}},CheckAppAndVersion:{always:[{target:"VersionGuard",guard:"noInternalError"},{target:"Error"}]},VersionGuard:{always:[{target:"EditIdentifier",guard:"contactsSupported"},{target:"Error",actions:"assignVersionError"}]},EditIdentifier:{entry:r({intermediateValue:{requiredUserInteraction:k0.RegisterWallet}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"editIdentifier",src:"editIdentifier",input:({context:J})=>J.input,onDone:{target:"EditIdentifierResultCheck",actions:r({_internalState:({event:J,context:X})=>N0(J.output)?{...X._internalState,hmacRest:J.output.data.hmacRest}:{...X._internalState,error:J.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},EditIdentifierResultCheck:{always:[{target:"Success",guard:"noInternalError"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:J})=>{let{hmacRest:X,error:G}=J._internalState;if(X){let{input:W}=J;return U0({contactName:W.contactName,scope:W.scope,previousIdentifier:W.previousIdentifier,identifier:W.newIdentifier,blockchainFamily:W.blockchainFamily,chainId:W.chainId,groupHandle:W.groupHandle,hmacProof:W.hmacProof,hmacRest:X})}return a(G??new xQ("No error in final state"))}})}extractDependencies(Q){return{isSupported:(Z)=>rV(Q,Z),editIdentifier:(Z)=>new BL(Q,{contactName:Z.contactName,scope:Z.scope,previousIdentifier:Z.previousIdentifier,newIdentifier:Z.newIdentifier,blockchainFamily:Z.blockchainFamily,chainId:Z.chainId,groupHandle:Z.groupHandle,hmacProof:Z.hmacProof,hmacRest:Z.hmacRest}).run()}}}});function o80(Q,Z){let Y=Q.extractFieldByLength(Z);if(!(!Y||Y.length!==Z))return Uint8Array.from(Y)}class CL{name="editExternalAddressScope";args;errorHelper=new uJ;constructor(Q){this.args=Q}getApdu(){return new w0({cla:VG,ins:qG,p1:R5,p2:this.args.p2}).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{if(Q.data.length===0)return o({data:{}});let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y!==Ng)return o({error:new C0(`Expected struct_type 0x${Ng.toString(16)}, got ${Y===void 0?"undefined":`0x${Y.toString(16)}`}`)});let $=o80(Z,tV);return $?o({data:{hmacRest:$}}):o({error:new C0("hmac_rest missing or truncated")})})}}var Ng;var Bg=w(()=>{I0();R0();m$();z1();$8();Ng=j5});class SL{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=this.buildPayload(this.args),Z=await K1(this.api,{payload:Q,p1:R5,makeCommand:($,J)=>new CL({data:$,p2:J}),logger:this.args.logger,commandTag:"SendEditExternalAddressScopeTask"});if(!N0(Z))return Z;let{hmacRest:Y}=Z.data;return Y?zQ({data:{hmacRest:Y}}):zQ({error:new C0("EditScope final-chunk response did not carry hmac_rest")})}buildPayload(Q){let Z=l$[Q.blockchainFamily.toLowerCase()];if(Z===void 0)throw Error(`Unsupported blockchain family: ${Q.blockchainFamily}`);let Y=new WQ;return MY(Y,kQ.STRUCT_TYPE,j5),MY(Y,kQ.STRUCT_VERSION,W1),q$(Y,kQ.CONTACT_NAME,Q.contactName),q$(Y,kQ.SCOPE,Q.newScope),wZ(Y,kQ.ACCOUNT_IDENTIFIER,Q.identifier),q$(Y,kQ.PREVIOUS_SCOPE,Q.previousScope),wZ(Y,kQ.GROUP_HANDLE,Q.groupHandle),Q.chainId!==void 0&&FG(Y,kQ.CHAIN_ID,Q.chainId),wZ(Y,kQ.HMAC_PROOF,Q.hmacProof),wZ(Y,kQ.HMAC_REST,Q.hmacRest),MY(Y,kQ.BLOCKCHAIN_FAMILY,Z),Y.build()}}var kg=w(()=>{I0();Bg();m$();$8();eV()});function Cg(Q){try{XJ(Q.contactName,{field:"contactName",bufferLength:J8}),XJ(Q.previousScope,{field:"previousScope",bufferLength:CX}),XJ(Q.newScope,{field:"newScope",bufferLength:CX});let Z=Q.blockchainFamily.toLowerCase();if(!(Z in l$))throw new PZ(`Unsupported blockchain family: ${Q.blockchainFamily}`);if(Z==="ethereum"){if(yY(Q.identifier,{field:"identifier",expectedBytes:SX}),Q.chainId===void 0)throw new PZ("chainId is required for the Ethereum blockchain family.")}else if(Q.identifier.length===0)throw new PZ("identifier must not be empty.");return Q.chainId!==void 0&&Qq(Q.chainId),yY(Q.groupHandle,{field:"groupHandle",expectedBytes:zG}),yY(Q.hmacProof,{field:"hmacProof",expectedBytes:U1}),yY(Q.hmacRest,{field:"hmacRest",expectedBytes:s80}),null}catch(Z){if(Z instanceof PZ)return Z;throw Z}}var s80;var Sg=w(()=>{m$();B4();s80=U1});var wL;var wg=w(()=>{I0();R0();KZ();N4();z1();kg();Sg();wL=class wL extends AQ{makeStateMachine(Q){let{isSupported:Z,editScope:Y}=this.extractDependencies(Q),$=this.input.appName;return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:$}}).makeStateMachine(Q),waitForAppAndVersionStateMachine:new kJ({input:{}}).makeStateMachine(Q),editScope:VQ(({input:J})=>Y(J))},guards:{skipOpenApp:({context:J})=>J.input.skipOpenApp===!0,noInternalError:({context:J})=>J._internalState.error===null,contactsSupported:({context:J})=>{let{appAndVersion:X}=J._internalState;return X!==null&&Z(X)}},actions:{assignValidationError:r({_internalState:({context:J})=>{let X=Cg(J.input);return X?{...J._internalState,error:X}:J._internalState}}),assignVersionError:r({_internalState:({context:J})=>({...J._internalState,error:new Y8})}),assignErrorFromEvent:r({_internalState:({context:J,event:X})=>({...J._internalState,error:new xQ(X.error instanceof Error?X.error.message:String(X.error))})})}}).createMachine({id:"EditExternalAddressScopeDeviceAction",initial:"InitialState",context:({input:J})=>({input:J,intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,appAndVersion:null,hmacRest:null}}),states:{InitialState:{always:[{target:"ValidateInput",guard:"skipOpenApp"},{target:"OpenAppDeviceAction"}]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",src:"openAppStateMachine",input:()=>({appName:$}),onSnapshot:{actions:r({intermediateValue:({event:J})=>J.snapshot.context.intermediateValue})},onDone:{target:"CheckOpenAppResult",actions:r({_internalState:({event:J,context:X})=>J.output.caseOf({Right:()=>X._internalState,Left:(G)=>({...X._internalState,error:G})})})}}},CheckOpenAppResult:{always:[{target:"ValidateInput",guard:"noInternalError"},{target:"Error"}]},ValidateInput:{entry:"assignValidationError",always:[{target:"WaitForAppAndVersion",guard:"noInternalError"},{target:"Error"}]},WaitForAppAndVersion:{entry:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"waitForAppAndVersion",src:"waitForAppAndVersionStateMachine",input:()=>({}),onSnapshot:{actions:r({intermediateValue:({event:J})=>J.snapshot.context.intermediateValue})},onDone:{target:"CheckAppAndVersion",actions:r({_internalState:({event:J,context:X})=>J.output.caseOf({Right:(G)=>({...X._internalState,appAndVersion:{name:G.name,version:G.version}}),Left:(G)=>({...X._internalState,error:G})})})}}},CheckAppAndVersion:{always:[{target:"VersionGuard",guard:"noInternalError"},{target:"Error"}]},VersionGuard:{always:[{target:"EditScope",guard:"contactsSupported"},{target:"Error",actions:"assignVersionError"}]},EditScope:{entry:r({intermediateValue:{requiredUserInteraction:k0.RegisterWallet}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"editScope",src:"editScope",input:({context:J})=>J.input,onDone:{target:"EditScopeResultCheck",actions:r({_internalState:({event:J,context:X})=>N0(J.output)?{...X._internalState,hmacRest:J.output.data.hmacRest}:{...X._internalState,error:J.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},EditScopeResultCheck:{always:[{target:"Success",guard:"noInternalError"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:J})=>{let{hmacRest:X,error:G}=J._internalState;if(X){let{input:W}=J;return U0({contactName:W.contactName,previousScope:W.previousScope,scope:W.newScope,identifier:W.identifier,blockchainFamily:W.blockchainFamily,chainId:W.chainId,groupHandle:W.groupHandle,hmacProof:W.hmacProof,hmacRest:X})}return a(G??new xQ("No error in final state"))}})}extractDependencies(Q){return{isSupported:(Z)=>rV(Q,Z),editScope:(Z)=>new SL(Q,{contactName:Z.contactName,previousScope:Z.previousScope,newScope:Z.newScope,identifier:Z.identifier,blockchainFamily:Z.blockchainFamily,chainId:Z.chainId,groupHandle:Z.groupHandle,hmacProof:Z.hmacProof,hmacRest:Z.hmacRest}).run()}}}});function _L(Q,Z){let Y=Q.extractFieldByLength(Z);if(!(!Y||Y.length!==Z))return Uint8Array.from(Y)}class vL{name="registerIdentity";args;errorHelper=new uJ;constructor(Q){this.args=Q}getApdu(){return new w0({cla:VG,ins:qG,p1:H5,p2:this.args.p2}).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{if(Q.data.length===0)return o({data:{}});let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y!==_g)return o({error:new C0(`Expected struct_type 0x${_g.toString(16)}, got ${Y===void 0?"undefined":`0x${Y.toString(16)}`}`)});let $=_L(Z,zg);if(!$)return o({error:new C0("group_handle missing or truncated")});let J=_L(Z,Wg);if(!J)return o({error:new C0("hmac_name missing or truncated")});let X=_L(Z,tV);return X?o({data:{groupHandle:$,hmacProof:J,hmacRest:X}}):o({error:new C0("hmac_rest missing or truncated")})})}}var _g=45;var vg=w(()=>{I0();R0();m$();z1()});class xL{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=this.buildPayload(this.args),Z=await K1(this.api,{payload:Q,p1:H5,makeCommand:(X,G)=>new vL({data:X,p2:G}),logger:this.args.logger,commandTag:"SendRegisterIdentityTask"});if(!N0(Z))return Z;let{groupHandle:Y,hmacProof:$,hmacRest:J}=Z.data;return!Y||!$||!J?zQ({error:new C0("RegisterIdentity final-chunk response was incomplete")}):zQ({data:{groupHandle:Y,hmacProof:$,hmacRest:J}})}buildPayload(Q){let Z=l$[Q.blockchainFamily.toLowerCase()];if(Z===void 0)throw Error(`Unsupported blockchain family: ${Q.blockchainFamily}`);let Y=new WQ;return MY(Y,kQ.STRUCT_TYPE,Ug),MY(Y,kQ.STRUCT_VERSION,W1),q$(Y,kQ.CONTACT_NAME,Q.contactName),q$(Y,kQ.SCOPE,Q.scope),wZ(Y,kQ.ACCOUNT_IDENTIFIER,Q.identifier),Q.chainId!==void 0&&FG(Y,kQ.CHAIN_ID,Q.chainId),MY(Y,kQ.BLOCKCHAIN_FAMILY,Z),Q.existingContactGroup&&(wZ(Y,kQ.GROUP_HANDLE,Q.existingContactGroup.groupHandle),wZ(Y,kQ.HMAC_PROOF,Q.existingContactGroup.hmacProof)),Y.build()}}var xg=w(()=>{I0();vg();m$();$8();eV()});function fg(Q){try{XJ(Q.contactName,{field:"contactName",bufferLength:J8}),XJ(Q.scope,{field:"scope",bufferLength:CX});let Z=Q.blockchainFamily.toLowerCase();if(!(Z in l$))throw new PZ(`Unsupported blockchain family: ${Q.blockchainFamily}`);if(Z==="ethereum"){if(yY(Q.identifier,{field:"identifier",expectedBytes:SX}),Q.chainId===void 0)throw new PZ("chainId is required for the Ethereum blockchain family.")}else if(Q.identifier.length===0)throw new PZ("identifier must not be empty.");return Q.chainId!==void 0&&Qq(Q.chainId),Q.existingContactGroup&&(yY(Q.existingContactGroup.groupHandle,{field:"existingContactGroup.groupHandle",expectedBytes:zG}),yY(Q.existingContactGroup.hmacProof,{field:"existingContactGroup.hmacProof",expectedBytes:U1})),null}catch(Z){if(Z instanceof PZ)return Z;throw Z}}var yg=w(()=>{m$();B4()});var fL;var gg=w(()=>{I0();R0();KZ();N4();z1();xg();yg();fL=class fL extends AQ{makeStateMachine(Q){let{isSupported:Z,registerIdentity:Y}=this.extractDependencies(Q),$=this.input.appName;return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:$}}).makeStateMachine(Q),waitForAppAndVersionStateMachine:new kJ({input:{}}).makeStateMachine(Q),registerIdentity:VQ(({input:J})=>Y(J))},guards:{skipOpenApp:({context:J})=>J.input.skipOpenApp===!0,noInternalError:({context:J})=>J._internalState.error===null,contactsSupported:({context:J})=>{let{appAndVersion:X}=J._internalState;return X!==null&&Z(X)}},actions:{assignValidationError:r({_internalState:({context:J})=>{let X=fg(J.input);return X?{...J._internalState,error:X}:J._internalState}}),assignVersionError:r({_internalState:({context:J})=>({...J._internalState,error:new Y8})}),assignErrorFromEvent:r({_internalState:({context:J,event:X})=>({...J._internalState,error:new xQ(X.error instanceof Error?X.error.message:String(X.error))})})}}).createMachine({id:"RegisterExternalAddressDeviceAction",initial:"InitialState",context:({input:J})=>({input:J,intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,appAndVersion:null,proofs:null}}),states:{InitialState:{always:[{target:"ValidateInput",guard:"skipOpenApp"},{target:"OpenAppDeviceAction"}]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",src:"openAppStateMachine",input:()=>({appName:$}),onSnapshot:{actions:r({intermediateValue:({event:J})=>J.snapshot.context.intermediateValue})},onDone:{target:"CheckOpenAppResult",actions:r({_internalState:({event:J,context:X})=>J.output.caseOf({Right:()=>X._internalState,Left:(G)=>({...X._internalState,error:G})})})}}},CheckOpenAppResult:{always:[{target:"ValidateInput",guard:"noInternalError"},{target:"Error"}]},ValidateInput:{entry:"assignValidationError",always:[{target:"WaitForAppAndVersion",guard:"noInternalError"},{target:"Error"}]},WaitForAppAndVersion:{entry:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"waitForAppAndVersion",src:"waitForAppAndVersionStateMachine",input:()=>({}),onSnapshot:{actions:r({intermediateValue:({event:J})=>J.snapshot.context.intermediateValue})},onDone:{target:"CheckAppAndVersion",actions:r({_internalState:({event:J,context:X})=>J.output.caseOf({Right:(G)=>({...X._internalState,appAndVersion:{name:G.name,version:G.version}}),Left:(G)=>({...X._internalState,error:G})})})}}},CheckAppAndVersion:{always:[{target:"VersionGuard",guard:"noInternalError"},{target:"Error"}]},VersionGuard:{always:[{target:"RegisterIdentity",guard:"contactsSupported"},{target:"Error",actions:"assignVersionError"}]},RegisterIdentity:{entry:r({intermediateValue:{requiredUserInteraction:k0.RegisterWallet}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"registerIdentity",src:"registerIdentity",input:({context:J})=>J.input,onDone:{target:"RegisterIdentityResultCheck",actions:r({_internalState:({event:J,context:X})=>N0(J.output)?{...X._internalState,proofs:J.output.data}:{...X._internalState,error:J.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},RegisterIdentityResultCheck:{always:[{target:"Success",guard:"noInternalError"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:J})=>{let{proofs:X,error:G}=J._internalState;if(X){let{input:W}=J;return U0({mode:W.existingContactGroup?"existingContactGroup":"newContactGroup",contactName:W.contactName,scope:W.scope,identifier:W.identifier,blockchainFamily:W.blockchainFamily,chainId:W.chainId,groupHandle:X.groupHandle,hmacProof:X.hmacProof,hmacRest:X.hmacRest})}return a(G??new xQ("No error in final state"))}})}extractDependencies(Q){return{isSupported:(Z)=>rV(Q,Z),registerIdentity:(Z)=>new xL(Q,{contactName:Z.contactName,scope:Z.scope,identifier:Z.identifier,blockchainFamily:Z.blockchainFamily,chainId:Z.chainId,existingContactGroup:Z.existingContactGroup}).run()}}}});function i80(Q,Z){let Y=Q.extractFieldByLength(Z);if(!(!Y||Y.length!==Z))return Uint8Array.from(Y)}class yL{name="renameContact";args;errorHelper=new uJ;constructor(Q){this.args=Q}getApdu(){return new w0({cla:qg,ins:Fg,p1:L5,p2:this.args.p2}).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{if(Q.data.length===0)return o({data:{}});let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y!==hg)return o({error:new C0(`Expected struct_type 0x${hg.toString(16)}, got ${Y===void 0?"undefined":`0x${Y.toString(16)}`}`)});let $=i80(Z,Kg);return $?o({data:{hmacProof:$}}):o({error:new C0("hmac_name missing or truncated")})})}}var hg;var bg=w(()=>{I0();R0();m$();z1();$8();hg=E5});class gL{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=this.buildPayload(this.args),Z=await K1(this.api,{payload:Q,p1:L5,makeCommand:($,J)=>new yL({data:$,p2:J}),logger:this.args.logger,commandTag:"SendRenameContactTask"});if(!N0(Z))return Z;let{hmacProof:Y}=Z.data;return Y?zQ({data:{hmacProof:Y}}):zQ({error:new C0("RenameContact final-chunk response did not carry hmac_name")})}buildPayload(Q){let Z=new WQ;return MY(Z,kQ.STRUCT_TYPE,E5),MY(Z,kQ.STRUCT_VERSION,W1),q$(Z,kQ.CONTACT_NAME,Q.newContactName),q$(Z,kQ.PREVIOUS_CONTACT_NAME,Q.previousContactName),wZ(Z,kQ.GROUP_HANDLE,Q.groupHandle),Q.includeDerivationPath&&wZ(Z,kQ.DERIVATION_PATH,Dg([2147483692,2147483708,2147483648,0,0])),wZ(Z,kQ.HMAC_PROOF,Q.hmacProof),Z.build()}}var cg=w(()=>{I0();bg();m$();$8();eV()});function ug(Q){try{return XJ(Q.newContactName,{field:"newContactName",bufferLength:J8}),XJ(Q.previousContactName,{field:"previousContactName",bufferLength:J8}),yY(Q.groupHandle,{field:"groupHandle",expectedBytes:zG}),yY(Q.hmacProof,{field:"hmacProof",expectedBytes:U1}),null}catch(Z){if(Z instanceof PZ)return Z;throw Z}}var pg=w(()=>{B4()});var hL;var lg=w(()=>{I0();R0();KZ();O5();N4();z1();cg();pg();hL=class hL extends AQ{makeStateMachine(Q){let{getOsVersion:Z,isOsVersionSupported:Y,renameContact:$}=this.extractDependencies(Q),{deviceModelId:J}=Q.getDeviceSessionState();return NQ({types:{input:{},context:{},output:{}},actors:{goToDashboardStateMachine:new RY({input:{}}).makeStateMachine(Q),getOsVersion:VQ(Z),renameContact:VQ(({input:X})=>$(X.args,X.includeDerivationPath))},guards:{noInternalError:({context:X})=>X._internalState.error===null,contactsOsSupported:({context:X})=>{let{osVersion:G}=X._internalState;return G!==null&&Y(G)}},actions:{assignValidationError:r({_internalState:({context:X})=>{let G=ug(X.input);return G?{...X._internalState,error:G}:X._internalState}}),assignVersionError:r({_internalState:({context:X})=>({...X._internalState,error:new Y8})}),assignErrorFromEvent:r({_internalState:({context:X,event:G})=>({...X._internalState,error:new xQ(G.error instanceof Error?G.error.message:String(G.error))})})}}).createMachine({id:"RenameContactDeviceAction",initial:"InitialState",context:({input:X})=>({input:X,intermediateValue:{requiredUserInteraction:k0.None},_internalState:{error:null,osVersion:null,proof:null}}),states:{InitialState:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboardStateMachine",input:()=>({}),onSnapshot:{actions:r({intermediateValue:({event:X})=>({requiredUserInteraction:X.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:r({_internalState:({event:X,context:G})=>X.output.caseOf({Right:()=>G._internalState,Left:(W)=>({...G._internalState,error:W})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"ValidateInput",guard:"noInternalError"},{target:"Error"}]},ValidateInput:{entry:"assignValidationError",always:[{target:"GetOsVersion",guard:"noInternalError"},{target:"Error"}]},GetOsVersion:{entry:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"getOsVersion",src:"getOsVersion",onDone:{target:"GetOsVersionResultCheck",actions:r({_internalState:({event:X,context:G})=>N0(X.output)?{...G._internalState,osVersion:X.output.data.seVersion}:{...G._internalState,error:X.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetOsVersionResultCheck:{always:[{target:"VersionGuard",guard:"noInternalError"},{target:"Error"}]},VersionGuard:{always:[{target:"RenameContact",guard:"contactsOsSupported"},{target:"Error",actions:"assignVersionError"}]},RenameContact:{entry:r({intermediateValue:{requiredUserInteraction:k0.RegisterWallet}}),exit:r({intermediateValue:{requiredUserInteraction:k0.None}}),invoke:{id:"renameContact",src:"renameContact",input:({context:X})=>({args:X.input,includeDerivationPath:Yg(J,X._internalState.osVersion??"")}),onDone:{target:"RenameContactResultCheck",actions:r({_internalState:({event:X,context:G})=>N0(X.output)?{...G._internalState,proof:X.output.data}:{...G._internalState,error:X.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},RenameContactResultCheck:{always:[{target:"Success",guard:"noInternalError"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:X})=>{let{proof:G,error:W}=X._internalState;if(G){let{input:U}=X;return U0({previousContactName:U.previousContactName,contactName:U.newContactName,groupHandle:U.groupHandle,hmacProof:G.hmacProof})}return a(W??new xQ("No error in final state"))}})}extractDependencies(Q){return{getOsVersion:()=>Q.sendCommand(new IY),isOsVersionSupported:(Z)=>Xg(Q,Z),renameContact:(Z,Y)=>new gL(Q,{previousContactName:Z.previousContactName,newContactName:Z.newContactName,groupHandle:Z.groupHandle,hmacProof:Z.hmacProof,includeDerivationPath:Y}).run()}}}});var k4;var bL=w(()=>{k4={Dmk:Symbol.for("Dmk"),SessionId:Symbol.for("SessionId"),AppName:Symbol.for("AppName")}});var a80,r80,t80=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?r80(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&a80(Z,Y,J),J},cL=(Q,Z)=>(Y,$)=>Z(Y,$,Q),uL=class{constructor(Q,Z,Y){this.dmk=Q,this.sessionId=Z,this.appName=Y}registerExternalAddress(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new fL({input:{...Q,appName:this.appName}})})}renameContact(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new hL({input:Q})})}editExternalAddressIdentifier(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new kL({input:{...Q,appName:this.appName}})})}editExternalAddressScope(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new wL({input:{...Q,appName:this.appName}})})}};var mg=w(()=>{W0();Tg();wg();gg();lg();bL();a80=Object.defineProperty,r80=Object.getOwnPropertyDescriptor;uL=t80([e(),cL(0,g(k4.Dmk)),cL(1,g(k4.SessionId)),cL(2,g(k4.AppName))],uL)});var G8;var Zq=w(()=>{G8={AppBinder:Symbol.for("AppBinder")}});var dg=w(()=>{mg();Zq()});var e80,QG0,ZG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?QG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&e80(Z,Y,J),J},YG0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),pL=class{constructor(Q){this.appBinder=Q}execute(Q){return this.appBinder.editExternalAddressIdentifier(Q)}};var ng=w(()=>{W0();Zq();e80=Object.defineProperty,QG0=Object.getOwnPropertyDescriptor;pL=ZG0([e(),YG0(0,g(G8.AppBinder))],pL)});var $G0,JG0,GG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?JG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&$G0(Z,Y,J),J},XG0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),lL=class{constructor(Q){this.appBinder=Q}execute(Q){return this.appBinder.editExternalAddressScope(Q)}};var og=w(()=>{W0();Zq();$G0=Object.defineProperty,JG0=Object.getOwnPropertyDescriptor;lL=GG0([e(),XG0(0,g(G8.AppBinder))],lL)});var VG0,qG0,FG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?qG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&VG0(Z,Y,J),J},zG0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),mL=class{constructor(Q){this.appBinder=Q}execute(Q){return this.appBinder.registerExternalAddress(Q)}};var sg=w(()=>{W0();Zq();VG0=Object.defineProperty,qG0=Object.getOwnPropertyDescriptor;mL=FG0([e(),zG0(0,g(G8.AppBinder))],mL)});var WG0,KG0,UG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?KG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&WG0(Z,Y,J),J},OG0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),dL=class{constructor(Q){this.appBinder=Q}execute(Q){return this.appBinder.renameContact(Q)}};var ig=w(()=>{W0();Zq();WG0=Object.defineProperty,KG0=Object.getOwnPropertyDescriptor;dL=UG0([e(),OG0(0,g(G8.AppBinder))],dL)});var nL=()=>{};var ag=w(()=>{ng();og();sg();ig();nL()});var rg=w(()=>{dg();bL();ag()});var tg=w(()=>{rg();nL()});var eg=w(()=>{tg()});class oL{name="provideContact";args;errorHelper=new uJ;constructor(Q){this.args=Q}getApdu(){return new w0({cla:VG,ins:qG,p1:D5,p2:this.args.p2}).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>o({data:void 0}))}}var Qh=w(()=>{I0();R0();m$();z1()});function sL(Q){let Z=l$[Q.blockchainFamily.toLowerCase()];if(Z===void 0)throw Error(`Unsupported blockchain family: ${Q.blockchainFamily}`);let Y=new WQ;return MY(Y,kQ.STRUCT_TYPE,Og),MY(Y,kQ.STRUCT_VERSION,W1),q$(Y,kQ.CONTACT_NAME,Q.contactName),q$(Y,kQ.SCOPE,Q.scope),wZ(Y,kQ.ACCOUNT_IDENTIFIER,Q.identifier),wZ(Y,kQ.GROUP_HANDLE,Q.groupHandle),Q.chainId!==void 0&&FG(Y,kQ.CHAIN_ID,Q.chainId),MY(Y,kQ.BLOCKCHAIN_FAMILY,Z),wZ(Y,kQ.HMAC_PROOF,Q.hmacProof),wZ(Y,kQ.HMAC_REST,Q.hmacRest),Y.build()}function iL(Q,{payload:Z,logger:Y}){return K1(Q,{payload:Z,p1:D5,makeCommand:($,J)=>new oL({data:$,p2:J}),logger:Y,commandTag:"provideContact"})}var Zh=w(()=>{I0();Qh();m$();$8();eV()});var Yh=w(()=>{eg();O5();Zh()});var xQQ;var aL=w(()=>{xQQ=JZ(mJ(),1);Yh()});class rL{constructor(Q){this.args=Q}name="storeTransaction";errorHelper=new s0(_Q,vQ);getApdu(){let{serializedTransaction:Q,isFirstChunk:Z}=this.args;return new w0({cla:224,ins:4,p1:Z?0:128,p2:1}).addBufferToData(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var $h=w(()=>{I0();IQ();R0();EZ()});function Jh({addressBook:Q,subset:Z,deviceState:Y,appConfig:$}){if(!IG0(Y,$))return;let J=Z.to?.toLowerCase();if(J!==void 0)for(let X of Q.contactGroups){let G=X.externalAddresses.find((U)=>U.address.toLowerCase()===J&&U.chainId===BigInt(Z.chainId));if(G===void 0)continue;let W=mQ(G.address);if(W!==null)return sL({contactName:X.contactName,scope:G.scope,identifier:W,groupHandle:X.groupHandle,hmacProof:X.hmacProof,hmacRest:G.hmacRest,blockchainFamily:DG0,chainId:G.chainId})}}function IG0(Q,Z){let Y=aV(Q.deviceModelId);if(!Y.supported)return!1;let $=Y.minAppVersion[U5];return $===void 0?!1:new YY(Q,Z,new p$).withMinVersionInclusiveAcceptingPrerelease($).check()}var DG0="ethereum";var Gh=w(()=>{aL();I0();oV()});class C4{constructor(Q,Z,Y=(J,X)=>new kX(J,X),$=(J,X)=>new Z8(J,X)){this._api=Q,this._args=Z,this._provideContextTaskFactory=Y,this._sendCommandInChunksTaskFactory=$,this._logger=Z.loggerFactory("ProvideTransactionContextsTask")}_logger;async run(){this._logger.debug("[run] Starting ProvideTransactionContextsTask",{data:{derivationPath:this._args.derivationPath,contextTypes:this._args.contexts.map((Y)=>Y.context.type),subcontextCounts:this._args.contexts.map((Y)=>Y.subcontextCallbacks.length),transactionLength:this._args.serializedTransaction?.length}});let Q=!1,Z=await this._provideExternalContact();for(let{context:Y,subcontextCallbacks:$}of this._args.contexts){if(Z&&Y.type===u.ETHEREUM_TRUSTED_NAME)continue;for(let X of $){let G=await X();G.type!==u.ERROR&&hJ(G)&&await this._provideContextTaskFactory(this._api,{context:G,loggerFactory:this._args.loggerFactory}).run()}if(Y.type===u.ETHEREUM_PROXY_INFO||Y.type===u.ETHEREUM_TRUSTED_NAME)continue;if(!Q&&this._args.serializedTransaction!==void 0&&Y.type===u.ETHEREUM_TRANSACTION_INFO){Q=!0;let X=QZ.splitPath(this._args.derivationPath),G=new WQ;G.add8BitUIntToData(X.length),X.forEach((W)=>{G.add32BitUIntToData(W)}),G.addBufferToData(this._args.serializedTransaction),await this._sendCommandInChunksTaskFactory(this._api,{data:G.build(),commandFactory:(W)=>new rL({serializedTransaction:W.chunkedData,isFirstChunk:W.isFirstChunk})}).run()}let J=await this._provideContextTaskFactory(this._api,{context:Y,loggerFactory:this._args.loggerFactory}).run();if(!N0(J))return this._logger.error("[run] Failed to provide context",{data:{contextType:Y.type,error:J.error}}),a(J)}return this._logger.debug("[run] ProvideTransactionContextsTask completed successfully"),U0(void 0)}async _provideExternalContact(){if(this._args.externalContact===void 0)return!1;let Q=Jh({...this._args.externalContact,deviceState:this._api.getDeviceSessionState()});if(Q===void 0)return!1;let Z=await iL(this._api,{payload:Q,logger:this._logger});return N0(Z)?!0:(this._logger.warn("[provideExternalContact] Contact rejected, signing without it",{data:{error:Z.error}}),!1)}}var tL=w(()=>{X$();aL();I0();IQ();R0();$h();Gh();F5();D4()});var S4;var eL=w(()=>{S4=((Q)=>(Q[Q.LEGACY=0]="LEGACY",Q[Q.EIP2930=1]="EIP2930",Q[Q.EIP1559=2]="EIP1559",Q[Q.EIP4844=3]="EIP4844",Q))(S4||{})});class QE{name="signTransaction";errorHelper=new s0(_Q,vQ);args;constructor(Q){this.args=Q}getApdu(){let{serializedTransaction:Q,isFirstChunk:Z}=this.args;return new w0({cla:224,ins:4,p1:Z?0:128,p2:0}).addBufferToData(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({data:YQ});let $=Z.encodeToHexaString(Z.extractFieldByLength(RG0),!0);if(!$)return o({error:new C0("R is missing")});let J=Z.encodeToHexaString(Z.extractFieldByLength(LG0),!0);return J?o({data:HQ({v:Y,r:$,s:J})}):o({error:new C0("S is missing")})})}}var RG0=32,LG0=32;var Xh=w(()=>{I0();IQ();R0();EZ()});class ZE{name="startTransaction";errorHelper=new s0(_Q,vQ);getApdu(){return new w0({cla:224,ins:4,p1:0,p2:2}).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({error:new C0("V is missing")});let $=Z.encodeToHexaString(Z.extractFieldByLength(EG0),!0);if(!$)return o({error:new C0("R is missing")});let J=Z.encodeToHexaString(Z.extractFieldByLength(PG0),!0);return J?o({data:HQ({v:Y,r:$,s:J})}):o({error:new C0("S is missing")})})}}var EG0=32,PG0=32;var Vh=w(()=>{I0();IQ();R0();EZ()});class YE{constructor(Q,Z){this.api=Q,this.args=Z,this._logger=Z.loggerFactory("SendSignTransactionTask")}_logger;async run(){if(this._logger.debug("[run] Starting SendSignTransactionTask",{data:{derivationPath:this.args.derivationPath,chainId:this.args.chainId,transactionType:this.args.transactionType,clearSigningType:this.args.clearSigningType,transactionLength:this.args.serializedTransaction.length}}),this.args.clearSigningType===JJ.EIP7730){this._logger.debug("[run] Using EIP7730 clear signing, starting transaction");let W=await this.api.sendCommand(new ZE);return N0(W)?(this._logger.debug("[run] Transaction signed successfully (EIP7730)"),this.recoverSignature(W.data).mapOrDefault((U)=>o({data:U}),o({error:new C0("no signature returned")}))):(this._logger.error("[run] Failed to start transaction",{data:{error:W.error}}),W)}let{derivationPath:Q,serializedTransaction:Z}=this.args,Y=QZ.splitPath(Q),$=new WQ(Z.length+1+Y.length*jG0);$.add8BitUIntToData(Y.length),Y.forEach((W)=>{$.add32BitUIntToData(W)});let J=$.build(),X=this.getChunks(J,Z);this._logger.debug("[run] Sending transaction in chunks",{data:{chunksCount:X.length}});let G=YQ;for(let W=0;W<X.length;W++){let U=await this.api.sendCommand(new QE({serializedTransaction:X[W],isFirstChunk:W===0}));if(!N0(U))return this._logger.error("[run] Failed to send transaction chunk",{data:{chunkIndex:W,error:U.error}}),U;G=U.data}return this._logger.debug("[run] Transaction signed successfully"),this.recoverSignature(G).mapOrDefault((W)=>o({data:W}),o({error:new C0("no signature returned")}))}getChunks(Q,Z){let Y=Uint8Array.from([...Q,...Z]),$=YZ;if(Y.length<=$)return[Y];if(this.args.transactionType===S4.LEGACY)try{let G=A5.decodeRlp(Z);if(Array.isArray(G)){let W=G.slice(-3),U=A5.encodeRlp(W),K=mQ(U).subarray(1);for($=YZ;$>Q.length;$--){let O=Y.length%$;if(O===0||O>K.length)break}}}catch{$=YZ}let J=0,X=[];for(;J<Y.length;)X.push(Y.slice(J,J+$)),J+=$;return X}recoverSignature(Q){return Q.map(({v:Z,r:Y,s:$})=>{if(this.args.transactionType!==S4.LEGACY)return{v:Z,r:Y,s:$};let J=4294967295,X=this.args.chainId;for(;X>J;)X=X>>8;let G=X*2+35&255;return{v:(Z==G?0:1)+this.args.chainId*2+35,r:Y,s:$}})}}var A5,jG0=4;var qh=w(()=>{I0();IQ();R0();L4();eL();Xh();Vh();A5=require("ethers")});var w4;var $E=w(()=>{I0();R0();KZ();KL();L4();z5();X5();UL();OL();XG();oV();DL();EL();iy();tL();qh();M4();w4=class w4 extends AQ{makeStateMachine(Q){let{getAddress:Z,getAppConfig:Y,web3CheckOptIn:$,parseTransaction:J,buildContexts:X,signTransaction:G,provideContexts:W,detectBlindSigning:U}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:AY}}).makeStateMachine(Q),getAddress:VQ(Z),getAppConfig:VQ(Y),web3CheckOptIn:VQ($),parseTransaction:VQ(J),buildContexts:VQ(X),provideContexts:VQ(W),signTransaction:VQ(G),detectBlindSigning:VQ(U)},guards:{noInternalError:({context:K})=>K._internalState.error===null,notRefusedByUser:({context:K})=>K._internalState.error!==null&&(!("errorCode"in K._internalState.error)||K._internalState.error.errorCode!=="6985"),isWeb3ChecksSupported:({context:K})=>new YY(Q.getDeviceSessionState(),K._internalState.appConfig,new p$).withMinVersionExclusive(K5).excludeDeviceModel(JQ.NANO_S).excludeDeviceModel(JQ.NANO_SP).excludeDeviceModel(JQ.NANO_X).check(),shouldOptIn:({context:K})=>!K._internalState.appConfig.web3ChecksEnabled&&!K._internalState.appConfig.web3ChecksOptIn,skipOpenApp:({context:K})=>!!K.input.options.skipOpenApp,hasSignature:({context:K})=>K._internalState.signature!==null},actions:{assignErrorFromEvent:r({_internalState:(K)=>({...K.context._internalState,error:K.event.error})})}}).createMachine({id:"SignTransactionDeviceAction",initial:"InitialState",context:({input:K})=>({input:K,intermediateValue:{requiredUserInteraction:k0.None,step:V$.OPEN_APP},_internalState:{error:null,appConfig:null,subset:null,contexts:[],clearSigningType:null,contextErrorCount:0,transactionType:null,signature:null,isBlindSign:null,usedFallback:!1}}),states:{InitialState:{always:[{target:"GetAppConfig",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:AY},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:(K)=>({...K.event.snapshot.context.intermediateValue,step:V$.OPEN_APP})})},onDone:{actions:r({_internalState:(K)=>K.event.output.caseOf({Right:()=>K.context._internalState,Left:(O)=>({...K.context._internalState,error:O})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"GetAppConfig",guard:"noInternalError"},"Error"]},GetAppConfig:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.GET_APP_CONFIG}}),invoke:{id:"getAppConfig",src:"getAppConfig",onDone:{target:"GetAppConfigResultCheck",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,appConfig:K.output.data}:{...O._internalState,error:K.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetAppConfigResultCheck:{always:[{target:"Web3ChecksOptIn",guard:yq(["noInternalError","isWeb3ChecksSupported","shouldOptIn"])},{target:"ParseTransaction",guard:"noInternalError"},{target:"Error"}]},Web3ChecksOptIn:{entry:r({intermediateValue:{requiredUserInteraction:k0.Web3ChecksOptIn,step:V$.WEB3_CHECKS_OPT_IN}}),invoke:{id:"web3CheckOptIn",src:"web3CheckOptIn",onDone:{target:"Web3ChecksOptInResult",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,appConfig:{...O._internalState.appConfig,web3ChecksEnabled:K.output.data.enabled}}:O._internalState})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Web3ChecksOptInResult:{entry:r(({context:K})=>({intermediateValue:{requiredUserInteraction:k0.None,step:V$.WEB3_CHECKS_OPT_IN_RESULT,result:K._internalState.appConfig.web3ChecksEnabled}})),after:{0:{target:"ParseTransaction"}}},ParseTransaction:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.PARSE_TRANSACTION}}),invoke:{id:"parseTransaction",src:"parseTransaction",input:({context:K})=>({mapper:K.input.mapper,transaction:K.input.transaction}),onDone:{target:"GetAddress",actions:r({_internalState:({event:K,context:O})=>({...O._internalState,subset:K.output.subset,transactionType:K.output.type})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetAddress:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.GET_ADDRESS}}),invoke:{id:"getAddress",src:"getAddress",input:({context:K})=>({derivationPath:K.input.derivationPath,checkOnDevice:!1,returnChainCode:!1}),onDone:{target:"BuildContexts",actions:r({_internalState:({event:K,context:O})=>{if(N0(K.output)){let I={...O._internalState.subset,from:K.output.data.address};return{...O._internalState,subset:I}}return{...O._internalState}}})},onError:{target:"Error"}}},BuildContexts:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.BUILD_CONTEXTS}}),invoke:{id:"buildContexts",src:"buildContexts",input:({context:K})=>({contextModule:K.input.contextModule,mapper:K.input.mapper,parser:K.input.parser,options:K.input.options,appConfig:K._internalState.appConfig,derivationPath:K.input.derivationPath,subset:K._internalState.subset,transaction:K.input.transaction,deviceModelId:Q.getDeviceModel().id,loggerFactory:this.getLoggerFactory(Q)}),onDone:{target:"ProvideContexts",actions:[r({_internalState:({event:K,context:O})=>({...O._internalState,contexts:K.output.clearSignContexts,clearSigningType:K.output.clearSigningType,contextErrorCount:K.output.contextErrorCount})})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ProvideContexts:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.PROVIDE_CONTEXTS}}),invoke:{id:"provideContexts",src:"provideContexts",input:({context:K})=>({contexts:K._internalState.contexts,derivationPath:K.input.derivationPath,serializedTransaction:K.input.transaction,externalContact:{addressBook:K.input.addressBook??E4,subset:K._internalState.subset,appConfig:K._internalState.appConfig},loggerFactory:this.getLoggerFactory(Q)}),onDone:{target:"SignTransaction"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},SignTransaction:{entry:r({intermediateValue:{requiredUserInteraction:k0.SignTransaction,step:V$.SIGN_TRANSACTION}}),invoke:{id:"signTransaction",src:"signTransaction",input:({context:K})=>({derivationPath:K.input.derivationPath,serializedTransaction:K.input.transaction,chainId:K._internalState.subset.chainId,transactionType:K._internalState.transactionType,clearSigningType:K._internalState.clearSigningType}),onDone:{target:"SignTransactionResultCheck",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,signature:K.output.data}:{...O._internalState,error:K.output.error}})]},onError:{target:"SignTransactionResultCheck",actions:"assignErrorFromEvent"}}},SignTransactionResultCheck:{always:[{guard:"noInternalError",target:"DetectBlindSigning"},{guard:"notRefusedByUser",target:"BlindSignTransactionFallback"},{target:"DetectBlindSigning"}]},BlindSignTransactionFallback:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.BLIND_SIGN_TRANSACTION_FALLBACK},_internalState:({context:K})=>({...K._internalState,usedFallback:!0})}),invoke:{id:"blindSignTransactionFallback",src:"signTransaction",input:({context:K})=>({derivationPath:K.input.derivationPath,serializedTransaction:K.input.transaction,chainId:K._internalState.subset.chainId,transactionType:K._internalState.transactionType,clearSigningType:JJ.BASIC}),onDone:{target:"BlindSignTransactionFallbackResultCheck",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,signature:K.output.data}:{...O._internalState,error:K.output.error}})]},onError:{target:"DetectBlindSigning",actions:"assignErrorFromEvent"}}},BlindSignTransactionFallbackResultCheck:{always:"DetectBlindSigning"},DetectBlindSigning:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:V$.DETECT_BLIND_SIGNING}}),invoke:{id:"detectBlindSigning",src:"detectBlindSigning",input:({context:K})=>{let O=Q.getDeviceSessionState(),I=O.sessionStateType!==CQ.Connected?O.firmwareVersion?.os??null:null,{subset:L,contexts:A,usedFallback:M,clearSigningType:k,contextErrorCount:B}=K._internalState;return{input:{type:"transaction",hasContext:!(!!L?.data&&L.data.length>2)||A.length>0,contextTypes:A.map((C)=>C.context.type),usedFallback:M,chainId:L?.chainId??null,targetAddress:L?.to??null,selectorId:L?.selector&&L.selector.length===By?L.selector:null,deviceModelId:Q.getDeviceModel().id,signerAppVersion:K._internalState.appConfig?.version??"",deviceVersion:I,clearSigningType:k,partialContextErrors:B},contextModule:K.input.contextModule,loggerFactory:this.getLoggerFactory(Q)}},onDone:[{guard:"hasSignature",target:"Success",actions:r({_internalState:({event:K,context:O})=>({...O._internalState,isBlindSign:K.output.isBlindSign})})},{target:"Error",actions:r({_internalState:({event:K,context:O})=>({...O._internalState,isBlindSign:K.output.isBlindSign})})}],onError:[{guard:"hasSignature",target:"Success"},{target:"Error"}]}},Success:{type:"final"},Error:{type:"final"}},output:({context:K})=>K._internalState.signature?U0(K._internalState.signature):a(K._internalState.error||new xQ("No error in final state"))})}extractDependencies(Q){return{getAddress:async(Z)=>Q.sendCommand(new TX(Z.input)),getAppConfig:async()=>Q.sendCommand(new P4),web3CheckOptIn:async()=>Q.sendCommand(new j4),parseTransaction:async(Z)=>Promise.resolve(new PL({mapper:Z.input.mapper,transaction:Z.input.transaction}).run()),buildContexts:async(Z)=>new iV(Q,Z.input).run(),provideContexts:async(Z)=>new C4(Q,Z.input).run(),signTransaction:async(Z)=>new YE(Q,{...Z.input,loggerFactory:this.getLoggerFactory(Q)}).run(),detectBlindSigning:async(Z)=>new A4(Z.input).run()}}}});var M5,AG0,MG0,TG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?MG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&AG0(Z,Y,J),J},Fh=10,WG=class{constructor(){}mapTransactionToSubset(Q){try{let Z=M5.ethers.Transaction.from(DQ(Q)),Y=Number(Z.chainId.toString());return Y<=0?a(Error("Pre-EIP-155 transactions are not supported")):U0({subset:{chainId:Y,to:Z.to??void 0,data:Z.data,selector:Z.data.length>=Fh?Z.data.slice(0,Fh):Z.data,value:Z.value},serializedTransaction:M5.getBytes(Z.unsignedSerialized),type:Z.type||0})}catch{return a(Error("Invalid transaction"))}}};var T5=w(()=>{I0();W0();R0();M5=require("ethers"),AG0=Object.defineProperty,MG0=Object.getOwnPropertyDescriptor;WG=TG0([e()],WG)});var NG0,BG0,kG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?BG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&NG0(Z,Y,J),J},CG0=4,_4=32,KG=class{extractValue(Q,Z){let{to:Y,data:$,value:J}=Q;return Z===nV.FROM?a(Error("Cannot get 'FROM' field of an unsigned transaction")):Z===nV.TO?q0.fromNullable(Y).map((X)=>mQ(X)).filter((X)=>X!==null).map((X)=>[X]).toEither(Error("Failed to extract TO field of transaction")):Z===nV.VALUE?q0.fromNullable(J).map((X)=>new WQ().add256BitUIntToData(X).build()).map((X)=>[X]).toEither(Error("Failed to extract VALUE field of transaction")):q0.fromNullable($).toEither(Error("Transaction calldata is empty")).chain((X)=>q0.fromNullable(mQ(X)).toEither(Error(`Invalid hex string calldata: ${X}`))).chain((X)=>this.extractCalldataValue(X,Z))}extractCalldataValue(Q,Z){return Q=Q.slice(CG0),Z.length===0?a(Error("Path is empty")):this.extractCalldataValueAt(Q,Z,0,0)}extractCalldataValueAt(Q,Z,Y,$){let J=Z[Z.length-1],X=J.type===Q8.SLICE?J:null;for(;Z.length>0;){let G=Z[0];switch(Z=Z.slice(1),G.type){case Q8.TUPLE:$=Y,Y+=G.offset*_4;break;case Q8.ARRAY:return this.getU256(Q.slice(Y)).toEither(Error(`Invalid array length at offset ${Y}`)).chain((W)=>{Y+=_4,$=Y;let U=G.start===void 0?0:G.start<0?W+G.start:G.start,K=G.end===void 0?W:G.end<0?W+G.end:G.end;return U<0||U>=W||K>W||U>=K?a(Error(`Array slice out of bounds, start=${G.start}, end=${G.end}`)):Array.from({length:K-U},(O,I)=>I).map((O)=>Y+(O+U)*G.itemSize*_4).reduce((O,I)=>O.chain((L)=>this.extractCalldataValueAt(Q,Z,I,$).map((A)=>[...L,...A])),U0([]))});case Q8.REF:if(this.getU256(Q.slice(Y)).ifJust((W)=>Y=$+W).isNothing())return a(Error(`Invalid ref at offset ${Y}`));break;case Q8.LEAF:switch(G.leafType){case MX.ARRAY_LEAF:return a(Error("Array leaf is not supported in v1 of protocol"));case MX.TUPLE_LEAF:return a(Error("Tuple leaf is not supported in v1 of protocol"));case MX.STATIC_LEAF:return this.getSlice(Q,Y,_4).chain((W)=>X===null?U0([W]):this.sliceLeaf(W,X));case MX.DYNAMIC_LEAF:return this.getU256(Q.slice(Y)).toEither(Error(`Invalid leaf length at offset ${Y}`)).chain((W)=>(Y+=_4,this.getSlice(Q,Y,W).chain((U)=>X===null?U0([U]):this.sliceLeaf(U,X))))}break;case Q8.SLICE:return a(Error("Slice can only be used as last element of the path"))}}return a(Error("Path did not resolve to a leaf element"))}sliceLeaf(Q,Z){let Y=Q.length,$=Z.start===void 0?0:Z.start<0?Y+Z.start:Z.start,J=Z.end===void 0?Y:Z.end<0?Y+Z.end:Z.end;return $>=J?a(Error(`invalid leaf slice: start ${$}, end ${J}`)):this.getSlice(Q,$,J-$).map((X)=>[X])}getSlice(Q,Z,Y){return Z<0||Q.length<Z+Y?a(Error(`calldata too small to slice at offset ${Z} of length ${Y}`)):U0(Q.slice(Z,Z+Y))}getU256(Q){return q0.fromNullable(new BY(Q).extract256BitUInt(!0)).filter((Z)=>Z<=Number.MAX_SAFE_INTEGER).map((Z)=>Number(Z))}};var N5=w(()=>{X$();I0();W0();R0();NG0=Object.defineProperty,BG0=Object.getOwnPropertyDescriptor;KG=kG0([e()],KG)});var zh=(Q)=>new w4({input:{derivationPath:Q.derivationPath,transaction:Q.transaction,contextModule:Q.contextModule,addressBook:Q.addressBook,options:Q.options??{},mapper:new WG,parser:new KG},inspect:Q.inspect,loggerFactory:Q.loggerFactory});var Wh=w(()=>{$E();T5();N5()});var R$;var JE=w(()=>{R$=((Q)=>(Q.OPEN_APP="signer.eth.steps.openApp",Q.GET_APP_CONFIG="signer.eth.steps.getAppConfig",Q.GET_ADDRESS="signer.eth.steps.getAddress",Q.WEB3_CHECKS_OPT_IN="signer.eth.steps.web3ChecksOptIn",Q.WEB3_CHECKS_OPT_IN_RESULT="signer.eth.steps.web3ChecksOptInResult",Q.BUILD_CONTEXT="signer.eth.steps.buildContext",Q.PROVIDE_CONTEXT="signer.eth.steps.provideContext",Q.PROVIDE_GENERIC_CONTEXT="signer.eth.steps.provideGenericContext",Q.SIGN_TYPED_DATA="signer.eth.steps.signTypedData",Q.SIGN_TYPED_DATA_LEGACY="signer.eth.steps.signTypedDataLegacy",Q.DETECT_BLIND_SIGNING="signer.eth.steps.detectBlindSigning",Q))(R$||{})});class v4{constructor(Q){this.args=Q}name="signEIP712";errorHelper=new s0(_Q,vQ);getApdu(){let{derivationPath:Q,legacyArgs:Z}=this.args,Y={cla:224,ins:12,p1:0,p2:Z.isJust()?0:1},$=QZ.splitPath(Q),J=new w0(Y);J.add8BitUIntToData($.length);for(let X of $)J.add32BitUIntToData(X);return Z.ifJust(({domainHash:X,messageHash:G})=>{J.addHexaStringToData(X),J.addHexaStringToData(G)}),J.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({error:new C0("V is missing")});let $=Z.encodeToHexaString(Z.extractFieldByLength(SG0),!0);if(!$)return o({error:new C0("R is missing")});let J=Z.encodeToHexaString(Z.extractFieldByLength(wG0),!0);return J?o({data:{r:$,s:J,v:Y}}):o({error:new C0("S is missing")})})}}var SG0=32,wG0=32;var GE=w(()=>{I0();IQ();R0();EZ()});class wX{constructor(Q,Z,Y){this.typeName=Q,this.name=Z,this.size=Y}}class X8{constructor(Q,Z,Y,$,J){this.typeName=Q,this.rootType=Z,this.rowType=Y,this.count=$,this.levels=J}}class _X{constructor(Q){this.typeName=Q}}class x4{constructor(Q){this.root=Q}}class Yq{constructor(Q){this.length=Q}}class vX{constructor(Q){this.data=Q}}var $q=()=>{};class XE{constructor(Q,Z,Y,$,J,X,G,W,U,K,O=(I,L)=>new iV(I,L)){this.api=Q,this.contextModule=Z,this.parser=Y,this.transactionParser=$,this.transactionMapper=J,this.data=X,this.derivationPath=G,this.appConfig=W,this.from=U,this.loggerFactory=K,this.buildFullContextFactory=O}async run(){let Q=this.parser.parse(this.data);if(Q.isLeft())throw Q.extract();let{types:Z,domain:Y,message:$}=Q.unsafeCoerce(),J=this.api.getDeviceSessionState(),X,G=await this.api.sendCommand(new GJ);N0(G)&&(X=G.data.challenge);let{contexts:W,contextErrorCount:U}=await this.getAdditionalContexts(J,X),K=YQ,O={},I={},L=this.getClearSignVersion(J);if(L.isJust()){let A=this.data.domain.verifyingContract?.toLowerCase()||_G0,M=this.data.domain.chainId||0,k=$.filter((C)=>C.value instanceof vX).map((C)=>({path:C.path,value:C.value.data})),B=await this.contextModule.getTypedDataFilters({verifyingContract:A,chainId:M,version:L.extract(),schema:this.data.types,challenge:X,deviceModelId:J.deviceModelId,fieldsValues:k});B.type==="success"&&(K=HQ(B),{calldatasPreContexts:O,calldatasPostContexts:I}=await this.getCalldatasContexts(J,B))}return{...{derivationPath:this.derivationPath,additionalContexts:W,types:Z,domain:Y,message:$,clearSignContext:K,calldatasPreContexts:O,calldatasPostContexts:I,deviceModelId:J.deviceModelId,loggerFactory:this.loggerFactory},clearSigningType:K.isJust()?JJ.EIP7730:JJ.BASIC,contextErrorCount:U}}async getAdditionalContexts(Q,Z){let Y=new YY(Q,this.appConfig,new p$).withMinVersionInclusive(W5).excludeDeviceModel(JQ.NANO_S).check(),$=[];Y&&($.push(u.ETHEREUM_GATED_SIGNING),Z!==void 0&&$.push(u.ETHEREUM_PROXY_INFO)),this.appConfig.web3ChecksEnabled&&$.push(u.ETHEREUM_TRANSACTION_CHECK),this.data.domain.chainId!==void 0&&$.push(u.ETHEREUM_DYNAMIC_NETWORK,u.ETHEREUM_DYNAMIC_NETWORK_ICON);let J=await this.contextModule.getContexts({deviceModelId:Q.deviceModelId,data:this.data,from:this.from,chainId:this.data.domain.chainId||0,challenge:Z},$),X=J.filter((G)=>G.type===u.ERROR).length;return{contexts:J.filter(hJ).filter((G)=>$.includes(G.type)),contextErrorCount:X}}getClearSignVersion(Q){return new YY(Q,this.appConfig,new p$).withMinVersionInclusive("1.10.0").excludeDeviceModel(JQ.NANO_S).check()?new YY(Q,this.appConfig,new p$).withMinVersionInclusive("1.12.0").check()?HQ("v2"):HQ("v1"):YQ}async getCalldatasContexts(Q,Z){let Y={},$={};for(let J in Z.calldatas){let{subset:X}=Z.calldatas[J],G=await this.buildFullContextFactory(this.api,{contextModule:this.contextModule,mapper:this.transactionMapper,parser:this.transactionParser,options:{},appConfig:this.appConfig,derivationPath:this.derivationPath,subset:X,deviceModelId:Q.deviceModelId,loggerFactory:this.loggerFactory}).run();if(G.clearSigningType===JJ.EIP7730||G.clearSigningType===JJ.BASIC&&G.clearSignContexts.every(({context:W})=>W.type===u.ETHEREUM_TRUSTED_NAME)){let W=G.clearSignContexts;Y[J]=W.filter((U)=>U.context.type===u.ETHEREUM_TRUSTED_NAME),$[J]=W.filter((U)=>U.context.type!==u.ETHEREUM_TRUSTED_NAME)}}return{calldatasPreContexts:Y,calldatasPostContexts:$}}}var _G0="0x0000000000000000000000000000000000000000";var Kh=w(()=>{X$();I0();R0();L4();sV();oV();EL();M4();$q()});class nY{constructor(Q){this.args=Q}name="sendEIP712Filtering";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:30,p1:"discarded"in this.args&&this.args.discarded?1:0,p2:vG0[this.args.type]},Z=new w0(Q);switch(this.args.type){case"message_info":Z.encodeInLVFromAscii(this.args.displayName).add8BitUIntToData(this.args.filtersCount).encodeInLVFromHexa(this.args.signature);break;case"discarded_path":Z.encodeInLVFromAscii(this.args.path);break;case"datetime":case"raw":Z.encodeInLVFromAscii(this.args.displayName).encodeInLVFromHexa(this.args.signature);break;case"trusted-name":Z.encodeInLVFromAscii(this.args.displayName).addHexaStringToData(this.args.typesAndSourcesPayload).encodeInLVFromHexa(this.args.signature);break;case"token":case"amount":this.args.type==="amount"&&Z.encodeInLVFromAscii(this.args.displayName),Z.add8BitUIntToData(this.args.tokenIndex).encodeInLVFromHexa(this.args.signature);break;case"calldata-info":Z.add8BitUIntToData(this.args.calldataIndex).add8BitUIntToData(this.args.valueFlag?1:0).add8BitUIntToData(this.args.calleeFlag).add8BitUIntToData(this.args.chainIdFlag?1:0).add8BitUIntToData(this.args.selectorFlag?1:0).add8BitUIntToData(this.args.amountFlag?1:0).add8BitUIntToData(this.args.spenderFlag).encodeInLVFromHexa(this.args.signature);break;case"calldata-value":case"calldata-callee":case"calldata-chain-id":case"calldata-selector":case"calldata-amount":case"calldata-spender":Z.add8BitUIntToData(this.args.calldataIndex).encodeInLVFromHexa(this.args.signature);break}return Z.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var dY,f4,vG0;var Uh=w(()=>{I0();IQ();R0();EZ();dY=((Q)=>(Q.Activation="activation",Q.DiscardedPath="discarded_path",Q.MessageInfo="message_info",Q.Datetime="datetime",Q.Raw="raw",Q.Amount="amount",Q.Token="token",Q.TrustedName="trusted-name",Q.CalldataInfo="calldata-info",Q.CalldataValue="calldata-value",Q.CalldataCallee="calldata-callee",Q.CalldataChainId="calldata-chain-id",Q.CalldataSelector="calldata-selector",Q.CalldataAmount="calldata-amount",Q.CalldataSpender="calldata-spender",Q))(dY||{}),f4=((Q)=>(Q[Q.None=0]="None",Q[Q.Present=1]="Present",Q[Q.VerifyingContract=2]="VerifyingContract",Q))(f4||{}),vG0={activation:0,discarded_path:1,message_info:15,"calldata-spender":244,"calldata-amount":245,"calldata-selector":246,"calldata-chain-id":247,"calldata-callee":248,"calldata-value":249,"calldata-info":250,"trusted-name":251,datetime:252,token:253,amount:254,raw:255}});class k5{constructor(Q){this.args=Q}name="sendEIP712StructDefinition";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:26,p1:0,p2:this.args.command};if(this.args.command===0)return new w0(Q).addAsciiStringToData(this.args.name).build();let Z=new w0(Q),Y=this.constructTypeDescByte(this.args.type);if(Z.add8BitUIntToData(Y),this.getTypeCustomName(this.args.type).ifJust(($)=>{Z.encodeInLVFromAscii($)}),this.getTypeSize(this.args.type).ifJust(($)=>{Z.add8BitUIntToData($)}),this.args.type instanceof X8){Z.add8BitUIntToData(this.args.type.levels.length);for(let $ of this.args.type.levels)$.caseOf({Just:(J)=>{Z.add8BitUIntToData(1).add8BitUIntToData(J)},Nothing:()=>{Z.add8BitUIntToData(0)}})}return Z.encodeInLVFromAscii(this.args.name).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}constructTypeDescByte(Q){let Z=Q instanceof X8?1:0,Y=this.getTypeSize(Q).isJust()?1:0,$=this.getType(Q);return Z<<7|Y<<6|$}getTypeSize(Q){return Q instanceof X8?this.getTypeSize(Q.rootType):Q instanceof wX?Q.size:YQ}getTypeCustomName(Q){return Q instanceof X8?this.getTypeCustomName(Q.rootType):Q instanceof _X?HQ(Q.typeName):YQ}getType(Q){if(Q instanceof X8)return this.getType(Q.rootType);if(Q instanceof _X)return 0;switch(Q.name){case"int":return 1;case"uint":return 2;case"address":return 3;case"bool":return 4;case"string":return 5;case"bytes":return Q.size.isJust()?6:7}}}var B5;var Oh=w(()=>{I0();IQ();R0();$q();EZ();B5=((Q)=>(Q[Q.Name=0]="Name",Q[Q.Field=255]="Field",Q))(B5||{})});class C5{constructor(Q){this.args=Q}name="sendEIP712StructImplem";errorHelper=new s0(_Q,vQ);getApdu(){let Q={cla:224,ins:28,p1:this.args.type!=255||this.args.value.isLastChunk?0:1,p2:this.args.type};switch(this.args.type){case 0:return new w0(Q).addAsciiStringToData(this.args.value).build();case 15:return new w0(Q).add8BitUIntToData(this.args.value).build();case 255:return new w0(Q).addBufferToData(this.args.value.data).build()}}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var UG;var VE=w(()=>{I0();IQ();R0();EZ();UG=((Q)=>(Q[Q.ROOT=0]="ROOT",Q[Q.ARRAY=15]="ARRAY",Q[Q.FIELD=255]="FIELD",Q))(UG||{})});class y4{constructor(Q,Z){this.api=Q,this.args=Z}async run(){if(this.args.type!==UG.FIELD)return await this.api.sendCommand(new C5(this.args));let Q=o({data:void 0}),Z=new WQ(this.args.value.length+2).add16BitUIntToData(this.args.value.length).addBufferToData(this.args.value).build();for(let Y=0;Y<Z.length;Y+=YZ)if(Q=await this.api.sendCommand(new C5({type:UG.FIELD,value:{data:Z.slice(Y,Y+YZ),isLastChunk:Y>=Z.length-YZ}})),!N0(Q))return Q;return Q}}var Hh=w(()=>{I0();VE()});class qE{constructor(Q,Z,Y,$=(J)=>new C4(this.api,J)){this.api=Q,this.contextModule=Z,this.args=Y,this.provideContextFactory=$;for(let J of this.args.domain)if(J.path==="chainId"&&J.value instanceof vX){let X=BigInt(DQ(J.value.data));X<=Number.MAX_SAFE_INTEGER&&(this.chainId=HQ(Number(X)));break}}chainId=YQ;calldataMetadatas={};async run(){for(let G of this.args.additionalContexts)await this.provideContext(G);let Q=this.args.additionalContexts.some((G)=>G.type===u.ETHEREUM_PROXY_INFO),Z=this.args.clearSignContext.extract()?.proxy;Z!==void 0&&!Q&&await this.provideContext(Z);let Y=this.args.clearSignContext.extract()?.certificate;Y!==void 0&&await this.api.sendCommand(new L1({keyUsage:Y.keyUsageNumber,certificate:Y.payload}));let $=o({data:void 0}),J=Object.entries(this.args.types).sort(([G],[W])=>G.localeCompare(W));for(let[G,W]of J){let U=await this.api.sendCommand(new k5({command:B5.Name,name:G}));if(!N0(U))return U;for(let[K,O]of Object.entries(W)){let I=await this.api.sendCommand(new k5({command:B5.Field,name:K,type:O}));if(!N0(I))return I}}if(this.args.clearSignContext.isJust()){let G=await this.api.sendCommand(new nY({type:dY.Activation}));if(!N0(G))return G}for(let G of this.args.domain){let W=await this.getImplementationTask(G).run();if(!N0(W))return W}if(this.args.clearSignContext.isJust()){let G=this.args.clearSignContext.extract(),W=await this.api.sendCommand(new nY({type:dY.MessageInfo,displayName:G.messageInfo.displayName,filtersCount:G.messageInfo.filtersCount,signature:G.messageInfo.signature}));if(!N0(W))return W}let X={indexes:{},nextIndex:0};for(let G of this.args.message){let W=await this.provideTokenInformation(G,X);if(W.isJust())return W.extract();let U=await this.provideTrustedName(G);if(U.isJust())return U.extract();let K=await this.filterValue(G,X);if(K.isJust()&&!N0(K.extract()))return K.extract();let O=await this.getImplementationTask(G).run();if(!N0(O))return O;if(await this.tryProvideTransactionContext(),this.args.clearSignContext.isJust()&&G.value instanceof Yq&&G.value.length===0){let I=Object.entries(this.args.clearSignContext.extract().filters).filter(([L])=>L.startsWith(`${G.path}.[]`)).map(([,L])=>L);for(let L of I){let A=await this.api.sendCommand(new nY({type:dY.DiscardedPath,path:L.path}));if(!N0(A))return A;let M=await this.provideFiltering(L,X,!0);if(!N0(M))return M}}}return $}async provideContext({type:Q,payload:Z,certificate:Y}){switch(Y&&await this.api.sendCommand(new L1({keyUsage:Y.keyUsageNumber,certificate:Y.payload})),Q){case u.ETHEREUM_TRANSACTION_CHECK:await new F1(this.api,{payload:Z,commandFactory:($)=>new H4({payload:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();break;case u.ETHEREUM_DYNAMIC_NETWORK:await new F1(this.api,{payload:Z,commandFactory:($)=>new BX({data:$.chunkedData,isFirstChunk:$.isFirstChunk,configurationType:NX.CONFIGURATION})}).run();break;case u.ETHEREUM_DYNAMIC_NETWORK_ICON:await new F1(this.api,{payload:Z,commandFactory:($)=>new BX({data:$.chunkedData,isFirstChunk:$.isFirstChunk,configurationType:NX.ICON}),withPayloadLength:!1}).run();break;case u.ETHEREUM_PROXY_INFO:await new F1(this.api,{payload:Z,commandFactory:($)=>new K4({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();break;case u.ETHEREUM_GATED_SIGNING:await new F1(this.api,{payload:Z,commandFactory:($)=>new W4({data:$.chunkedData,isFirstChunk:$.isFirstChunk})}).run();break;case u.ETHEREUM_TOKEN:case u.ETHEREUM_NFT:case u.ETHEREUM_TRUSTED_NAME:case u.ETHEREUM_PLUGIN:case u.ETHEREUM_EXTERNAL_PLUGIN:case u.ETHEREUM_ENUM:case u.ETHEREUM_TRANSACTION_INFO:case u.ETHEREUM_TRANSACTION_FIELD_DESCRIPTION:case u.ETHEREUM_SAFE:case u.ETHEREUM_SIGNER:throw Error(`Context type ${Q} not supported in EIP712 messages`);default:throw Error(`Unhandled context type ${Q}`)}}getImplementationTask(Q){return Q.value instanceof x4?new y4(this.api,{type:UG.ROOT,value:Q.value.root}):Q.value instanceof Yq?new y4(this.api,{type:UG.ARRAY,value:Q.value.length}):new y4(this.api,{type:UG.FIELD,value:Q.value.data})}async provideTokenInformation(Q,Z){if(this.args.clearSignContext.isJust()){let Y=this.args.clearSignContext.extract().filters[Q.path];if(Y!==void 0&&(Y.type==="amount"||Y.type==="token")&&Z.indexes[Y.tokenIndex]===void 0){let $=Y.tokenIndex,J=this.args.clearSignContext.extract().tokens[$];if(J===void 0)return YQ;let X=await this.api.sendCommand(new U4({payload:J}));if(!N0(X))return q0.of(X);let{tokenIndex:G}=X.data;Z.nextIndex=(G+1)%Dh,Number($)===pV&&(G=pV),Z.indexes[Number($)]=G}}return YQ}async provideTrustedName(Q){if(this.args.clearSignContext.isJust()&&this.chainId.isJust()){let Z=this.args.clearSignContext.extract(),Y=Z.filters[Q.path],$=Z.trustedNamesAddresses[Q.path];if(Y!==void 0&&Y.type==="trusted-name"&&$!==void 0){let J=await this.api.sendCommand(new GJ);if(!N0(J))return HQ(J);let X=await this.contextModule.getFieldContext({chainId:this.chainId.extract(),address:$,challenge:J.data.challenge,types:Y.types,sources:Y.sources,deviceModelId:this.args.deviceModelId},u.ETHEREUM_TRUSTED_NAME);if(X.type===u.ETHEREUM_TRUSTED_NAME){X.certificate&&await this.api.sendCommand(new L1({keyUsage:X.certificate.keyUsageNumber,certificate:X.certificate.payload}));let G=await new F1(this.api,{payload:X.payload,commandFactory:(W)=>new O4({data:W.chunkedData,isFirstChunk:W.isFirstChunk})}).run();if(!N0(G))return HQ(G)}}}return YQ}async filterValue(Q,Z){if(this.args.clearSignContext.isJust()){let Y=this.args.clearSignContext.extract().filters[Q.path];if(Y===void 0)return YQ;let $=await this.provideFiltering(Y,Z,!1);return q0.of($)}return YQ}async provideFiltering(Q,Z,Y){switch(Q.type){case"trusted-name":return await this.api.sendCommand(new nY({type:dY.TrustedName,discarded:Y,displayName:Q.displayName,typesAndSourcesPayload:Q.typesAndSourcesPayload,signature:Q.signature}));case"datetime":return await this.api.sendCommand(new nY({type:dY.Datetime,discarded:Y,displayName:Q.displayName,signature:Q.signature}));case"raw":return await this.api.sendCommand(new nY({type:dY.Raw,discarded:Y,displayName:Q.displayName,signature:Q.signature}));case"token":return this.sanitizeDeviceIndex(Q.tokenIndex,Z),await this.api.sendCommand(new nY({type:dY.Token,discarded:Y,tokenIndex:Z.indexes[Q.tokenIndex],signature:Q.signature}));case"amount":return this.sanitizeDeviceIndex(Q.tokenIndex,Z),await this.api.sendCommand(new nY({type:dY.Amount,discarded:Y,displayName:Q.displayName,tokenIndex:Z.indexes[Q.tokenIndex],signature:Q.signature}));case"calldata-value":return await this.provideCalldataInfos(Q.calldataIndex),await this.api.sendCommand(new nY({type:dY.CalldataValue,discarded:Y,calldataIndex:Q.calldataIndex,signature:Q.signature}));case"calldata-callee":return await this.provideCalldataInfos(Q.calldataIndex),await this.api.sendCommand(new nY({type:dY.CalldataCallee,discarded:Y,calldataIndex:Q.calldataIndex,signature:Q.signature}));case"calldata-spender":return await this.provideCalldataInfos(Q.calldataIndex),await this.api.sendCommand(new nY({type:dY.CalldataSpender,discarded:Y,calldataIndex:Q.calldataIndex,signature:Q.signature}));case"calldata-chain-id":return await this.provideCalldataInfos(Q.calldataIndex),await this.api.sendCommand(new nY({type:dY.CalldataChainId,discarded:Y,calldataIndex:Q.calldataIndex,signature:Q.signature}));case"calldata-selector":return await this.provideCalldataInfos(Q.calldataIndex),await this.api.sendCommand(new nY({type:dY.CalldataSelector,discarded:Y,calldataIndex:Q.calldataIndex,signature:Q.signature}));case"calldata-amount":return await this.provideCalldataInfos(Q.calldataIndex),await this.api.sendCommand(new nY({type:dY.CalldataAmount,discarded:Y,calldataIndex:Q.calldataIndex,signature:Q.signature}));default:throw Error(`ProvideEIP712ContextTask/provideFiltering - Unhandled filter ${Q}`)}}async provideCalldataInfos(Q){if(this.args.clearSignContext.isJust()){if(this.calldataMetadatas[Q]!==void 0)return this.calldataMetadatas[Q].remainingFilters--,YQ;let Z=this.args.clearSignContext.extract().calldatas[Q];if(Z===void 0)return YQ;let Y=[Z.filter.valueFlag,Z.filter.calleeFlag===b$.Present,Z.filter.chainIdFlag,Z.filter.selectorFlag,Z.filter.amountFlag,Z.filter.spenderFlag===b$.Present].filter((J)=>J).length,$=this.args.calldatasPreContexts[Q];return $?.length&&await this.provideContextFactory({contexts:$,derivationPath:this.args.derivationPath,loggerFactory:this.args.loggerFactory}).run(),this.calldataMetadatas[Q]={remainingFilters:Y-1,postContexts:this.args.calldatasPostContexts[Q]},q0.of(await this.api.sendCommand(new nY({type:dY.CalldataInfo,discarded:!1,calldataIndex:Q,valueFlag:Z.filter.valueFlag,calleeFlag:this.mapCalldataPresence(Z.filter.calleeFlag),chainIdFlag:Z.filter.chainIdFlag,selectorFlag:Z.filter.selectorFlag,amountFlag:Z.filter.amountFlag,spenderFlag:this.mapCalldataPresence(Z.filter.spenderFlag),signature:Z.filter.signature})))}return YQ}async tryProvideTransactionContext(){for(let Q in this.calldataMetadatas){let Z=this.calldataMetadatas[Q];Z.remainingFilters===0&&(Z.postContexts?.length&&await this.provideContextFactory({contexts:Z.postContexts,derivationPath:this.args.derivationPath,loggerFactory:this.args.loggerFactory}).run(),delete this.calldataMetadatas[Q])}}mapCalldataPresence(Q){switch(Q){case b$.None:return f4.None;case b$.Present:return f4.Present;case b$.VerifyingContract:return f4.VerifyingContract;default:throw Error(`Unhandled presence ${Q}`)}}sanitizeDeviceIndex(Q,Z){Z.indexes[Q]===void 0&&(Z.indexes[Q]=Z.nextIndex,Z.nextIndex=(Z.nextIndex+1)%Dh)}}var Dh=5;var Ih=w(()=>{X$();X$();I0();R0();sV();aR();rR();eR();QL();$L();JL();Uh();Oh();VE();Hh();$q();$q();tL();qL()});class zE{constructor(Q,Z,Y,$){this.api=Q,this.data=Z,this.derivationPath=Y,this._logger=$("SignTypedDataLegacyTask")}_logger;async run(){this._logger.debug("[run] Starting SignTypedDataLegacyTask",{data:{derivationPath:this.derivationPath,primaryType:this.data.primaryType}});let Q=FE.TypedDataEncoder.hashDomain(this.data.domain);if(!this.data.types[this.data.primaryType])throw this._logger.error("[run] Primary type not defined in types",{data:{primaryType:this.data.primaryType}}),Error(`Primary type "${this.data.primaryType}" is not defined in the types.`);let Z=this.data.types,{EIP712Domain:Y,...$}=Z,J=FE.TypedDataEncoder.hashStruct(this.data.primaryType,$,this.data.message);return this._logger.debug("[run] Computed hashes, sending blind sign command"),await this.api.sendCommand(new v4({derivationPath:this.derivationPath,legacyArgs:HQ({domainHash:Q,messageHash:J})}))}}var FE;var Rh=w(()=>{R0();GE();FE=require("ethers")});function Lh(Q){if(Q==null)return null;if(typeof Q=="number")return Number.isSafeInteger(Q)?Q:null;if(typeof Q=="string"){if(Q.trim()==="")return null;let Z=Number(Q);return Number.isSafeInteger(Z)?Z:null}return null}var Eh=()=>{};var g4;var WE=w(()=>{I0();R0();KZ();JE();X5();UL();GE();OL();XG();oV();DL();Kh();Ih();Rh();M4();Eh();g4=class g4 extends AQ{makeStateMachine(Q){let{getAddress:Z,getAppConfig:Y,web3CheckOptIn:$,buildContext:J,provideContext:X,signTypedData:G,signTypedDataLegacy:W,detectBlindSigning:U}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:AY}}).makeStateMachine(Q),getAddress:VQ(Z),getAppConfig:VQ(Y),web3CheckOptIn:VQ($),buildContext:VQ(J),provideContext:VQ(X),signTypedData:VQ(G),signTypedDataLegacy:VQ(W),detectBlindSigning:VQ(U)},guards:{noInternalError:({context:K})=>K._internalState.error===null,notRefusedByUser:({context:K})=>K._internalState.error!==null&&(!("errorCode"in K._internalState.error)||K._internalState.error.errorCode!=="6985"),isWeb3ChecksSupported:({context:K})=>new YY(Q.getDeviceSessionState(),K._internalState.appConfig,new p$).withMinVersionExclusive(K5).excludeDeviceModel(JQ.NANO_S).excludeDeviceModel(JQ.NANO_SP).excludeDeviceModel(JQ.NANO_X).check(),shouldOptIn:({context:K})=>!K._internalState.appConfig.web3ChecksEnabled&&!K._internalState.appConfig.web3ChecksOptIn,skipOpenApp:({context:K})=>K.input.skipOpenApp,hasSignature:({context:K})=>K._internalState.signature!==null},actions:{assignErrorFromEvent:r({_internalState:(K)=>({...K.context._internalState,error:K.event.error})})}}).createMachine({id:"SignTypedDataDeviceAction",initial:"InitialState",context:({input:K})=>({input:K,intermediateValue:{requiredUserInteraction:k0.None,step:R$.OPEN_APP},_internalState:{error:null,appConfig:null,from:null,typedDataContext:null,signature:null,isBlindSign:null,usedFallback:!1}}),states:{InitialState:{always:[{target:"GetAppConfig",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:AY},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:(K)=>({...K.event.snapshot.context.intermediateValue,step:R$.OPEN_APP})})},onDone:{actions:r({_internalState:(K)=>K.event.output.caseOf({Right:()=>K.context._internalState,Left:(O)=>({...K.context._internalState,error:O})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"GetAppConfig",guard:"noInternalError"},"Error"]},GetAppConfig:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:R$.GET_APP_CONFIG}}),invoke:{id:"getAppConfig",src:"getAppConfig",onDone:{target:"GetAppConfigResultCheck",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,appConfig:K.output.data}:{...O._internalState,error:K.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetAppConfigResultCheck:{always:[{target:"Web3ChecksOptIn",guard:yq(["noInternalError","isWeb3ChecksSupported","shouldOptIn"])},{target:"GetAddress",guard:"noInternalError"},{target:"Error"}]},Web3ChecksOptIn:{entry:r({intermediateValue:{requiredUserInteraction:k0.Web3ChecksOptIn,step:R$.WEB3_CHECKS_OPT_IN}}),invoke:{id:"web3CheckOptIn",src:"web3CheckOptIn",onDone:{target:"Web3ChecksOptInResult",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,appConfig:{...O._internalState.appConfig,web3ChecksEnabled:K.output.data.enabled}}:O._internalState})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Web3ChecksOptInResult:{entry:r(({context:K})=>({intermediateValue:{requiredUserInteraction:k0.None,step:R$.WEB3_CHECKS_OPT_IN_RESULT,result:K._internalState.appConfig.web3ChecksEnabled}})),after:{0:{target:"GetAddress"}}},GetAddress:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:R$.GET_ADDRESS}}),invoke:{id:"getAddress",src:"getAddress",input:({context:K})=>({derivationPath:K.input.derivationPath}),onDone:{target:"BuildContext",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,from:K.output.data.address}:{...O._internalState,error:K.output.error}})]},onError:{target:"Error"}}},BuildContext:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:R$.BUILD_CONTEXT}}),invoke:{id:"buildContext",src:"buildContext",input:({context:K})=>({contextModule:K.input.contextModule,parser:K.input.parser,transactionParser:K.input.transactionParser,transactionMapper:K.input.transactionMapper,data:K.input.data,appConfig:K._internalState.appConfig,derivationPath:K.input.derivationPath,from:K._internalState.from}),onDone:{target:"ProvideContext",actions:[r({_internalState:({event:K,context:O})=>({...O._internalState,typedDataContext:K.output})})]},onError:{target:"SignTypedDataLegacy"}}},ProvideContext:{entry:r({intermediateValue:{requiredUserInteraction:k0.SignTypedData,step:R$.PROVIDE_CONTEXT}}),invoke:{id:"provideContext",src:"provideContext",input:({context:K})=>({contextModule:K.input.contextModule,taskArgs:K._internalState.typedDataContext}),onDone:{actions:r({_internalState:(K)=>N0(K.event.output)?K.context._internalState:{...K.context._internalState,error:K.event.output.error}}),target:"ProvideContextResultCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ProvideContextResultCheck:{always:[{guard:"noInternalError",target:"SignTypedData"},{guard:"notRefusedByUser",target:"SignTypedDataLegacy"},{target:"Error"}]},SignTypedData:{entry:r({intermediateValue:{requiredUserInteraction:k0.SignTypedData,step:R$.SIGN_TYPED_DATA}}),invoke:{id:"signTypedData",src:"signTypedData",input:({context:K})=>({derivationPath:K.input.derivationPath}),onDone:{target:"SignTypedDataResultCheck",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,signature:K.output.data}:{...O._internalState,error:K.output.error}})]},onError:{target:"DetectBlindSigning",actions:"assignErrorFromEvent"}}},SignTypedDataResultCheck:{always:[{guard:"noInternalError",target:"DetectBlindSigning"},{guard:"notRefusedByUser",target:"SignTypedDataLegacy"},{target:"DetectBlindSigning"}]},SignTypedDataLegacy:{entry:r({intermediateValue:{requiredUserInteraction:k0.SignTypedData,step:R$.SIGN_TYPED_DATA_LEGACY},_internalState:({context:K})=>({...K._internalState,usedFallback:!0})}),invoke:{id:"signTypedDataLegacy",src:"signTypedDataLegacy",input:({context:K})=>({derivationPath:K.input.derivationPath,data:K.input.data}),onDone:{target:"SignTypedDataLegacyResultCheck",actions:[r({_internalState:({event:K,context:O})=>N0(K.output)?{...O._internalState,signature:K.output.data}:{...O._internalState,error:K.output.error}})]},onError:{target:"DetectBlindSigning",actions:"assignErrorFromEvent"}}},SignTypedDataLegacyResultCheck:{always:"DetectBlindSigning"},DetectBlindSigning:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:R$.DETECT_BLIND_SIGNING}}),invoke:{id:"detectBlindSigning",src:"detectBlindSigning",input:({context:K})=>{let O=Q.getDeviceSessionState(),I=O.sessionStateType!==CQ.Connected?O.firmwareVersion?.os??null:null;return{input:{type:"typedData",hasContext:K._internalState.typedDataContext?.clearSignContext.isJust()??!1,usedFallback:K._internalState.usedFallback,chainId:Lh(K.input.data.domain.chainId),targetAddress:K.input.data.domain.verifyingContract??null,deviceModelId:Q.getDeviceModel().id,signerAppVersion:K._internalState.appConfig?.version??"",deviceVersion:I,clearSigningType:K._internalState.typedDataContext?.clearSigningType??null,partialContextErrors:K._internalState.typedDataContext?.contextErrorCount??0},contextModule:K.input.contextModule,loggerFactory:this.getLoggerFactory(Q)}},onDone:[{guard:"hasSignature",target:"Success",actions:r({_internalState:({event:K,context:O})=>({...O._internalState,isBlindSign:K.output.isBlindSign})})},{target:"Error",actions:r({_internalState:({event:K,context:O})=>({...O._internalState,isBlindSign:K.output.isBlindSign})})}],onError:[{guard:"hasSignature",target:"Success"},{target:"Error"}]}},Success:{type:"final"},Error:{type:"final"}},output:({context:K})=>K._internalState.signature?U0(K._internalState.signature):a(K._internalState.error||new xQ("No error in final state"))})}extractDependencies(Q){return{getAddress:async(Z)=>Q.sendCommand(new TX(Z.input)),getAppConfig:async()=>Q.sendCommand(new P4),web3CheckOptIn:async()=>Q.sendCommand(new j4),buildContext:async(Z)=>new XE(Q,Z.input.contextModule,Z.input.parser,Z.input.transactionParser,Z.input.transactionMapper,Z.input.data,Z.input.derivationPath,Z.input.appConfig,Z.input.from,this.getLoggerFactory(Q)).run(),provideContext:async(Z)=>new qE(Q,Z.input.contextModule,Z.input.taskArgs).run(),signTypedData:async(Z)=>Q.sendCommand(new v4({derivationPath:Z.input.derivationPath,legacyArgs:YQ})),signTypedDataLegacy:async(Z)=>new zE(Q,Z.input.data,Z.input.derivationPath,this.getLoggerFactory(Q)).run(),detectBlindSigning:async(Z)=>new A4(Z.input).run()}}}});function Ph(Q,Z){switch(Q.name){case"string":return typeof Z!="string"?YQ:HQ(new TextEncoder().encode(Z));case"bytes":case"address":return typeof Z!="string"?YQ:xG0(Q,Z);case"bool":case"uint":case"int":return Q.name==="bool"&&typeof Z=="boolean"&&(Z=Number(Z)),typeof Z!="string"&&typeof Z!="number"&&typeof Z!="bigint"?YQ:fG0(Q.name,Q.size.mapOrDefault((Y)=>Y*8,1),Z)}}function xG0(Q,Z){let Y=Q.name==="address"?HQ(20):Q.size;return q0.fromNullable(mQ(Z)).filter(($)=>Y.mapOrDefault((J)=>$.length<=J,!0))}function fG0(Q,Z,Y){let $;switch(typeof Y){case"bigint":$=Y;break;case"number":if(!Number.isInteger(Y))return YQ;$=BigInt(Y);break;case"string":if(Y.length===0)return YQ;try{$=BigInt(Y)}catch{return YQ}break}let J=Q==="int";return yG0($,BigInt(Z),J).chain((X)=>q0.fromNullable(mQ(X.toString(16))))}function yG0(Q,Z,Y){if(!Y)return Q>=0n&&Q<1n<<Z?HQ(Q):YQ;let $=1n<<Z-1n;if(Q>=$||Q<-$)return YQ;if(Q<0n){let J=(1n<<Z)-1n;Q=-Q,Q=(~Q&J)+1n}return HQ(Q)}var jh=w(()=>{I0();R0()});class KE{domainTypeName="EIP712Domain";domainDefaultTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"};structs;constructor(Q,Z){if(!(this.domainTypeName in Q)){let $=[];Object.entries(this.domainDefaultTypes).forEach(([J,X])=>{J in Z&&$.push({name:J,type:X})}),$.length>0&&(Q[this.domainTypeName]=$)}let Y={};for(let[$,J]of Object.entries(Q)){let X={};for(let G of J)X[G.name]=this.parseType(G.type);Y[$]=X}this.structs=Y}getStructDefinitions(){return this.structs}parse(Q,Z){if(!this.isRecord(Z))return a(Error("Message is not a record"));let Y=[{path:"",type:"",value:new x4(Q)}];return this.visitValue(Q,Z,"",($)=>Y.push($))?U0(Y):a(Error("Failed to parse"))}isRecord(Q){return typeof Q=="object"&&Q!==null}parseType(Q){return this.tryParsePrimitiveType(Q).mapOrDefault((Z)=>Z,this.tryParseArrayType(Q).mapOrDefault((Z)=>Z,new _X(Q)))}tryParsePrimitiveType(Q){{let Z=Q.match(/^(((u?)int)(\d+))$/);if(Z){let Y=parseInt(Z[4]);return Y%8!==0||Y===0||Y>256?YQ:HQ(new wX(Z[1],Z[3]?"uint":"int",HQ(Y/8)))}}{let Z=Q.match(/^((bytes)(\d*))$/);if(Z){let Y=Z[3]?parseInt(Z[3]):null;return Y!==null&&(Y===0||Y>32)?YQ:HQ(new wX(Z[1],"bytes",q0.fromNullable(Y)))}}return Q==="address"||Q==="bool"||Q==="string"?HQ(new wX(Q,Q,YQ)):YQ}tryParseArrayType(Q){let Z=Q.match(/^([^[[]*)(((\[\d*\])*)\[\d*\])$/);if(Z){let Y=[...Z[2].matchAll(/\[(\d*)\]/g)];if(Y&&Y.length>0){let $=Y.map(([,X])=>X?HQ(parseInt(X)):YQ),J=this.tryParsePrimitiveType(Z[1]).mapOrDefault((X)=>X,new _X(Z[1]));return HQ(new X8(Q,J,Z[1]+Z[3],$[$.length-1],$))}}return YQ}visitValue(Q,Z,Y,$){return this.tryVisitStructValue(Q,Z,Y,$)||this.tryVisitPrimitiveValue(Q,Z,Y,$)||this.tryVisitArrayValue(Q,Z,Y,$)}tryVisitPrimitiveValue(Q,Z,Y,$){return!this.isRecord(Z)&&!Array.isArray(Z)&&this.tryParsePrimitiveType(Q).chain((J)=>Ph(J,Z).ifJust((X)=>{$({path:Y,type:Q,value:new vX(X)})})).isJust()}tryVisitStructValue(Q,Z,Y,$){let J=this.structs[Q];if(J===void 0||!this.isRecord(Z))return!1;for(let[X,G]of Object.entries(J)){let W=Z[X];if(W===void 0)return!1;let U=Y.length?`${Y}.${X}`:X;if(!this.visitValue(G.typeName,W,`${U}`,$))return!1}return!0}tryVisitArrayValue(Q,Z,Y,$){return Array.isArray(Z)&&this.tryParseArrayType(Q).filter((J)=>J.count.mapOrDefault((X)=>Z.length==X,!0)).mapOrDefault((J)=>{$({path:Y,type:Q,value:new Yq(Z.length)});for(let X of Z){let G=Y.length?`${Y}.[]`:"[]";if(!this.visitValue(J.rowType,X,`${G}`,$))return!1}return!0},!1)}}var Ah=w(()=>{R0();$q();jh()});var gG0,hG0,bG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?hG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&gG0(Z,Y,J),J},Jq=class{parse(Q){let Z=new KE(Q.types,Q.domain),Y=Z.getStructDefinitions(),$=Z.parse("EIP712Domain",Q.domain),J=Z.parse(Q.primaryType,Q.message);return $.chain((X)=>J.map((G)=>({types:Y,domain:X,message:G})))}};var UE=w(()=>{W0();Ah();gG0=Object.defineProperty,hG0=Object.getOwnPropertyDescriptor;Jq=bG0([e()],Jq)});var Mh=(Q)=>new g4({input:{derivationPath:Q.derivationPath,data:Q.data,contextModule:Q.contextModule,skipOpenApp:Q.skipOpenApp,parser:new Jq,transactionMapper:new WG,transactionParser:new KG},inspect:Q.inspect,loggerFactory:Q.loggerFactory});var Th=w(()=>{WE();T5();N5();UE()});var S5;var OE=w(()=>{S5={GetAddressUseCase:Symbol.for("GetAddressUseCase")}});var d$;var OG=w(()=>{d$={AppBinding:Symbol.for("AppBinder")}});var cG0,uG0,pG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?uG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&cG0(Z,Y,J),J},lG0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),w5=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.getAddress({derivationPath:Q,checkOnDevice:Z?.checkOnDevice??!1,returnChainCode:Z?.returnChainCode??!1,skipOpenApp:Z?.skipOpenApp??!1,chainId:Z?.chainId})}};var Nh=w(()=>{W0();OG();cG0=Object.defineProperty,uG0=Object.getOwnPropertyDescriptor;w5=pG0([e(),lG0(0,g(d$.AppBinding))],w5)});var Bh=()=>new b0(({bind:Q})=>{Q(S5.GetAddressUseCase).to(w5)});var kh=w(()=>{W0();OE();Nh()});var jJ;var HE=w(()=>{jJ={Dmk:Symbol.for("Dmk"),SessionId:Symbol.for("SessionId"),ContextModule:Symbol.for("ContextModule"),DmkLoggerFactory:Symbol.for("DmkLoggerFactory"),AddressBook:Symbol.for("AddressBook")}});var V8;var _5=w(()=>{V8={SignTransactionUseCase:Symbol.for("SignTransactionUseCase"),TransactionParserService:Symbol.for("TransactionParserService"),TransactionMapperService:Symbol.for("TransactionMapperService"),TransactionMappers:Symbol.for("TransactionMappers")}});var Gq;var Ch=w(()=>{Gq=((Q)=>(Q.OPEN_APP="signer.eth.steps.openApp",Q.BUILD_CONTEXTS="signer.eth.steps.buildContexts",Q.PROVIDE_CONTEXTS="signer.eth.steps.provideContexts",Q.VERIFY_SAFE_ADDRESS="signer.eth.steps.verifySafeAddress",Q))(Gq||{})});class DE{constructor(Q,Z){this._api=Q,this._args=Z,this._logger=Z.loggerFactory("BuildSafeAddressContextTask")}_logger;async run(){this._logger.debug("[run] Starting BuildSafeAddressContextTask",{data:{safeContractAddress:this._args.safeContractAddress,chainId:this._args.options.chainId}});let Q=await this._api.sendCommand(new GJ);if(!N0(Q))throw this._logger.error("[run] Failed to get challenge"),Error("Failed to get challenge");let Z=Q.data.challenge,Y=await this._args.contextModule.getContexts({safeContractAddress:this._args.safeContractAddress,chainId:this._args.options.chainId,deviceModelId:this._args.deviceModelId,challenge:Z},[u.ETHEREUM_SAFE,u.ETHEREUM_SIGNER]);if(Y.forEach(($)=>{if($.type===u.ERROR)throw Error($.error.message)}),Y.length!==2||Y.find(($)=>$.type===u.ETHEREUM_SAFE)===void 0||Y.find(($)=>$.type===u.ETHEREUM_SIGNER)===void 0)throw this._logger.error("[run] Invalid safe address contexts",{data:{receivedTypes:Y.map(($)=>$.type),expectedTypes:[u.ETHEREUM_SAFE,u.ETHEREUM_SIGNER]}}),Error("Invalid safe address contexts");return this._logger.debug("[run] BuildSafeAddressContextTask completed successfully"),{clearSignContexts:Y.filter(hJ)}}}var Sh=w(()=>{X$();I0();sV()});var IE;var wh=w(()=>{I0();R0();KZ();Ch();XG();Sh();F5();IE=class IE extends AQ{makeStateMachine(Q){let{buildSafeAddressContexts:Z,provideContexts:Y}=this.extractDependencies(Q);return NQ({types:{input:{},context:{},output:{}},actors:{openAppStateMachine:new kZ({input:{appName:AY}}).makeStateMachine(Q),buildSafeAddressContexts:VQ(Z),provideContexts:VQ(Y)},guards:{noInternalError:({context:$})=>$._internalState.error===null,skipOpenApp:({context:$})=>!!$.input.options.skipOpenApp},actions:{assignErrorFromEvent:r({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"VerifySafeAddressDeviceAction",initial:"InitialState",context:({input:$})=>({input:$,intermediateValue:{requiredUserInteraction:k0.None,step:Gq.OPEN_APP},_internalState:{error:null,contexts:[]}}),states:{InitialState:{always:[{target:"BuildSafeAddressContexts",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:AY},src:"openAppStateMachine",onSnapshot:{actions:r({intermediateValue:($)=>({...$.event.snapshot.context.intermediateValue,step:Gq.OPEN_APP})})},onDone:{actions:r({_internalState:($)=>$.event.output.caseOf({Right:()=>$.context._internalState,Left:(J)=>({...$.context._internalState,error:J})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"BuildSafeAddressContexts",guard:"noInternalError"},"Error"]},BuildSafeAddressContexts:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:Gq.BUILD_CONTEXTS}}),invoke:{id:"buildSafeAddressContexts",src:"buildSafeAddressContexts",input:({context:$})=>({contextModule:$.input.contextModule,safeContractAddress:$.input.safeContractAddress,options:$.input.options,deviceModelId:Q.getDeviceModel().id,loggerFactory:this.getLoggerFactory(Q)}),onDone:{target:"ProvideContexts",actions:[r({_internalState:({event:$,context:J})=>({...J._internalState,contexts:$.output.clearSignContexts})})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ProvideContexts:{entry:r({intermediateValue:{requiredUserInteraction:k0.None,step:Gq.VERIFY_SAFE_ADDRESS}}),invoke:{id:"provideContexts",src:"provideContexts",input:({context:$})=>({contexts:$._internalState.contexts}),onDone:{target:"ProvideContextsResultCheck",actions:[r({_internalState:({event:$,context:J})=>$.output.isLeft()?{...J._internalState,error:$.output.extract()}:{...J._internalState,error:null}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ProvideContextsResultCheck:{always:[{guard:"noInternalError",target:"Success"},{target:"Error"}]},Success:{type:"final"},Error:{type:"final"}},output:({context:$})=>$._internalState.error?a($._internalState.error):U0(void 0)})}extractDependencies(Q){return{provideContexts:async(Z)=>{for(let Y of Z.input.contexts){let $=await new kX(Q,{context:Y,loggerFactory:this.getLoggerFactory(Q)}).run();if(!N0($))return a($.error)}return U0(void 0)},buildSafeAddressContexts:async(Z)=>new DE(Q,Z.input).run()}}}});class RE{name="signEIP7702Authorization";args;errorHelper=new s0(_Q,vQ);constructor(Q){this.args=Q}getApdu(){let{data:Q,isFirstChunk:Z}=this.args;return new w0({cla:224,ins:52,p1:Z?1:0,p2:0}).addBufferToData(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({data:YQ});let $=Z.encodeToHexaString(Z.extractFieldByLength(mG0),!0);if(!$)return o({error:new C0("R is missing")});let J=Z.encodeToHexaString(Z.extractFieldByLength(dG0),!0);return J?o({data:HQ({r:$,s:J,v:Y})}):o({error:new C0("S is missing")})})}}var mG0=32,dG0=32;var _h=w(()=>{I0();IQ();R0();EZ()});class LE{constructor(Q,Z){this.api=Q,this.args=Z,this._logger=Z.logger}_logger;async run(){let{derivationPath:Q,chainId:Z,address:Y,nonce:$}=this.args;this._logger.debug("[run] Starting SendSignAuthorizationDelegationTask",{data:{derivationPath:Q,chainId:Z,address:Y,nonce:$}});let J=QZ.splitPath(Q),X=this.buildData(J,Z,Y,$);this._logger.debug("[run] Sending authorization delegation in chunks",{data:{bufferLength:X.length}});let G=await new Z8(this.api,{data:X,commandFactory:(W)=>new RE({data:W.chunkedData,isFirstChunk:W.isFirstChunk})}).run();return N0(G)?(this._logger.debug("[run] Authorization delegation signed successfully"),G.data.mapOrDefault((W)=>o({data:W}),o({error:new C0("no signature returned")}))):(this._logger.error("[run] Failed to sign authorization delegation",{data:{error:G.error}}),G)}buildData(Q,Z,Y,$){let J=new WQ;J.add8BitUIntToData(Q.length),Q.forEach((W)=>{J.add32BitUIntToData(W)});let X=new WQ;X.encodeInTLVFromBuffer(nG0,Uint8Array.from([1])),X.encodeInTLVFromHexa(oG0,Y),X.encodeInTLVFromUInt64(sG0,Z),X.encodeInTLVFromUInt64(iG0,$);let G=X.build();return J.add16BitUIntToData(G.length).addBufferToData(G).build()}}var nG0=0,oG0=1,sG0=2,iG0=3;var vh=w(()=>{I0();IQ();_h();D4()});var aG0,rG0,tG0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?rG0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&aG0(Z,Y,J),J},xX=(Q,Z)=>(Y,$)=>Z(Y,$,Q),v5=class{constructor(Q,Z,Y,$,J,X,G){this.dmk=Q,this.contextModule=Z,this.mapper=Y,this.parser=$,this.sessionId=J,this.dmkLoggerFactory=X,this.addressBook=G}getAddress(Q){let Z=this.dmkLoggerFactory("SendGetAddressTask");return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Y)=>new I4(Y,{contextModule:this.contextModule,derivationPath:Q.derivationPath,checkOnDevice:Q.checkOnDevice,returnChainCode:Q.returnChainCode,chainId:Q.chainId,loggerFactory:this.dmkLoggerFactory}).run(),appName:AY,requiredUserInteraction:Q.checkOnDevice?k0.VerifyAddress:k0.None,skipOpenApp:Q.skipOpenApp},logger:Z})})}verifySafeAddress(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new IE({input:{safeContractAddress:Q.safeContractAddress,contextModule:this.contextModule,options:Q.options??{chainId:1}},loggerFactory:this.dmkLoggerFactory})})}signPersonalMessage(Q){let Z=this.dmkLoggerFactory("SendSignPersonalMessageTask");return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Y)=>new R4(Y,{...Q,logger:Z}).run(),appName:AY,requiredUserInteraction:k0.SignPersonalMessage,skipOpenApp:Q.skipOpenApp},logger:this.dmkLoggerFactory("SendSignPersonalMessageTask")})})}signTransaction(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new w4({input:{derivationPath:Q.derivationPath,transaction:Q.transaction,mapper:this.mapper,parser:this.parser,contextModule:this.contextModule,addressBook:this.addressBook,options:Q.options??{}},loggerFactory:this.dmkLoggerFactory})})}signTypedData(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new g4({input:{derivationPath:Q.derivationPath,data:Q.data,parser:Q.parser,transactionMapper:this.mapper,transactionParser:this.parser,contextModule:this.contextModule,skipOpenApp:Q.skipOpenApp},loggerFactory:this.dmkLoggerFactory})})}signDelegationAuthorization(Q){let Z=this.dmkLoggerFactory("SendSignAuthorizationDelegationTask");return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Y)=>new LE(Y,{...Q,logger:Z}).run(),appName:AY,requiredUserInteraction:k0.SignDelegationAuthorization,skipOpenApp:!1},logger:this.dmkLoggerFactory("SendSignAuthorizationDelegationTask")})})}};var xh=w(()=>{I0();I0();W0();WE();WL();HE();_5();$E();wh();FL();vh();XG();aG0=Object.defineProperty,rG0=Object.getOwnPropertyDescriptor;v5=tG0([e(),xX(0,g(jJ.Dmk)),xX(1,g(jJ.ContextModule)),xX(2,g(V8.TransactionMapperService)),xX(3,g(V8.TransactionParserService)),xX(4,g(jJ.SessionId)),xX(5,g(jJ.DmkLoggerFactory)),xX(6,g(jJ.AddressBook))],v5)});var fh=()=>new b0(({bind:Q})=>{Q(d$.AppBinding).to(v5)});var yh=w(()=>{W0();OG();xh()});var x5;var EE=w(()=>{x5={SignDelegationAuthorizationUseCase:Symbol.for("SignDelegationAuthorizationUseCase")}});var eG0,QX0,ZX0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?QX0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&eG0(Z,Y,J),J},YX0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),f5=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y,$){return this._appBinder.signDelegationAuthorization({derivationPath:Q,nonce:Z,address:Y,chainId:$})}};var gh=w(()=>{W0();OG();eG0=Object.defineProperty,QX0=Object.getOwnPropertyDescriptor;f5=ZX0([e(),YX0(0,g(d$.AppBinding))],f5)});var hh=()=>new b0(({bind:Q})=>{Q(x5.SignDelegationAuthorizationUseCase).to(f5)});var bh=w(()=>{W0();EE();gh()});var y5;var PE=w(()=>{y5={SignMessageUseCase:Symbol.for("SignMessageUseCase")}});var $X0,JX0,GX0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?JX0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&$X0(Z,Y,J),J},XX0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),g5=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z,Y){return this._appBinder.signPersonalMessage({derivationPath:Q,message:Z,skipOpenApp:Y?.skipOpenApp??!1})}};var ch=w(()=>{W0();OG();$X0=Object.defineProperty,JX0=Object.getOwnPropertyDescriptor;g5=GX0([e(),XX0(0,g(d$.AppBinding))],g5)});var uh=()=>new b0(({bind:Q})=>{Q(y5.SignMessageUseCase).to(g5)});var ph=w(()=>{W0();PE();ch()});var VX0,qX0,FX0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?qX0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&VX0(Z,Y,J),J},zX0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),h5=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.verifySafeAddress({safeContractAddress:Q,options:Z})}};var lh=w(()=>{W0();OG();VX0=Object.defineProperty,qX0=Object.getOwnPropertyDescriptor;h5=FX0([e(),zX0(0,g(d$.AppBinding))],h5)});var b5;var jE=w(()=>{b5={VerifySafeAddressUseCase:Symbol.for("VerifySafeAddressUseCase")}});var mh=()=>new b0(({bind:Q})=>{Q(b5.VerifySafeAddressUseCase).to(h5)});var dh=w(()=>{W0();lh();jE()});var WX0,KX0,UX0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?KX0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&WX0(Z,Y,J),J},OX0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),c5=class{_appBinding;constructor(Q){this._appBinding=Q}execute(Q,Z,Y){return this._appBinding.signTransaction({derivationPath:Q,transaction:Z,options:Y})}};var nh=w(()=>{W0();OG();WX0=Object.defineProperty,KX0=Object.getOwnPropertyDescriptor;c5=UX0([e(),OX0(0,g(d$.AppBinding))],c5)});var oh=()=>new b0(({bind:Q})=>{Q(V8.SignTransactionUseCase).to(c5),Q(V8.TransactionMapperService).to(WG),Q(V8.TransactionParserService).to(KG)});var sh=w(()=>{W0();_5();T5();N5();nh()});var fX;var u5=w(()=>{fX={SignTypedDataUseCase:Symbol.for("SignTypedDataUseCase"),TypedDataParserService:Symbol.for("TypedDataParserService")}});var HX0,DX0,IX0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?DX0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&HX0(Z,Y,J),J},ih=(Q,Z)=>(Y,$)=>Z(Y,$,Q),p5=class{_appBinding;_parser;constructor(Q,Z){this._appBinding=Q,this._parser=Z}execute(Q,Z,Y){return this._appBinding.signTypedData({derivationPath:Q,parser:this._parser,data:Z,skipOpenApp:Y?.skipOpenApp??!1})}};var ah=w(()=>{W0();OG();u5();HX0=Object.defineProperty,DX0=Object.getOwnPropertyDescriptor;p5=IX0([e(),ih(0,g(d$.AppBinding)),ih(1,g(fX.TypedDataParserService))],p5)});var rh=()=>new b0(({bind:Q})=>{Q(fX.SignTypedDataUseCase).to(p5),Q(fX.TypedDataParserService).to(Jq)});var th=w(()=>{W0();u5();UE();ah()});var eh=({dmk:Q,sessionId:Z,contextModule:Y,addressBook:$})=>{let J=new T$;return J.bind(jJ.Dmk).toConstantValue(Q),J.bind(jJ.ContextModule).toConstantValue(Y),J.bind(jJ.SessionId).toConstantValue(Z),J.bind(jJ.AddressBook).toConstantValue($??E4),J.bind(jJ.DmkLoggerFactory).toConstantValue((X)=>Q.getLoggerFactory()(["SignerEth",X])),J.loadSync(Bh(),fh(),hh(),uh(),oh(),rh(),mh()),J};var Qb=w(()=>{W0();z5();kh();yh();bh();HE();ph();dh();sh();th()});class AE{_container;constructor({dmk:Q,sessionId:Z,contextModule:Y,addressBook:$}){this._container=eh({dmk:Q,sessionId:Z,contextModule:Y,addressBook:$})}signTransaction(Q,Z,Y){return this._container.get(V8.SignTransactionUseCase).execute(Q,Z,Y)}signMessage(Q,Z,Y){return this._container.get(y5.SignMessageUseCase).execute(Q,Z,Y)}signTypedData(Q,Z,Y){return this._container.get(fX.SignTypedDataUseCase).execute(Q,Z,Y)}getAddress(Q,Z){return this._container.get(S5.GetAddressUseCase).execute(Q,Z)}verifySafeAddress(Q,Z){return this._container.get(b5.VerifySafeAddressUseCase).execute(Q,Z)}signDelegationAuthorization(Q,Z,Y,$){return this._container.get(x5.SignDelegationAuthorizationUseCase).execute(Q,$,Y,Z)}}var Zb=w(()=>{OE();Qb();PE();jE();_5();u5();EE()});class Yb{_dmk;_sessionId;_customContextModule;_originToken;_addressBook;constructor({dmk:Q,sessionId:Z,originToken:Y}){this._dmk=Q,this._sessionId=Z,this._originToken=Y}withContextModule(Q){return this._customContextModule=Q,this}withAddressBook(Q){return this._addressBook=Q,this}build(){let Q=this._customContextModule??new Z5({originToken:this._originToken,loggerFactory:(Z)=>this._dmk.getLoggerFactory()(["ContextModule",Z])}).setChain(G$.Ethereum).build();return new AE({dmk:this._dmk,sessionId:this._sessionId,contextModule:Q,addressBook:this._addressBook})}}var $b=w(()=>{X$();Zb()});var Jb=w(()=>{by();py();Wh();KL();Th();JE();z5();eL();$b()});var Gb={};j$(Gb,{TransactionType:()=>S4,SignerEthBuilder:()=>Yb,SignTypedDataDeviceActionFactory:()=>Mh,SignTypedDataDAStateStep:()=>R$,SignTransactionDeviceActionFactory:()=>zh,SignTransactionDAStep:()=>V$,SignPersonalMessageDeviceActionFactory:()=>uy,GetAddressDeviceActionFactory:()=>hy,EMPTY_EVM_ADDRESS_BOOK:()=>E4});var D8Q;var Xb=w(()=>{D8Q=JZ(mJ(),1);Jb()});var gY;var D1=w(()=>{gY={AppBinding:Symbol.for("AppBinding")}});var pJ="Zcash";var kE=()=>{};var Vq;var CE=w(()=>{Vq={Dmk:Symbol.for("Dmk"),SessionId:Symbol.for("SessionId")}});var aQ=224,o$,E$,AJ,HG,l5=255;var tZ=w(()=>{o$={FIRST:0,NEXT:128,CHANGE_PATH:255},E$={DEFAULT:0,SAPLING:5,HASH_INPUT_CONTINUE:128},AJ={FIRST:0,NEXT:128,LAST:1},HG={CONTINUE:0,FINISHED:1}});var rQ,gb,tQ=(Q)=>new gb(Q);var TY=w(()=>{I0();rQ={6300:{message:"GPAuthFailedError"},"63c0":{message:"PinRemainingAttemptsError"},6400:{message:"ExecutionError"},6700:{message:"IncorrectLengthError"},6981:{message:"CommandIncompatibleFileStructureError"},6982:{message:"SecurityStatusNotSatisfiedError"},6985:{message:"UserRejectedError"},6986:{message:"ConditionsOfUseNotSatisfiedError"},"6a80":{message:"IncorrectDataError"},"6a84":{message:"NotEnoughMemorySpaceError"},"6a88":{message:"ReferencedDataNotFoundError"},"6a89":{message:"FileAlreadyExistsError"},"6a8a":{message:"SwapWithoutTrustedInputsError"},"6b00":{message:"IncorrectP1P2Error"},"6d00":{message:"InsNotSupportedError"},"6e00":{message:"ClaNotSupportedError"},"6f00":{message:"TechnicalProblemError"},"6f01":{message:"VersionParsingFailError"},"6f03":{message:"RngFailureError"},"6f42":{message:"LicensingError"},"6faa":{message:"HaltedError"},9240:{message:"MemoryProblemError"},9400:{message:"NoEFSelectedError"},9402:{message:"InvalidOffsetError"},9404:{message:"FileNotFoundError"},9408:{message:"InconsistentFileError"},9484:{message:"AlgorithmNotSupportedError"},9485:{message:"InvalidKCVError"},9802:{message:"CodeNotInitializedError"},9804:{message:"AccessConditionNotFullfilledError"},9808:{message:"ContradictionSecretCodeStatusError"},9810:{message:"ContradictionInvalidationError"},9840:{message:"CodeBlockedError"},9850:{message:"MaxValueReachedError"},b007:{message:"BadStateError"},unsupported_v6_transaction:{message:"UnsupportedV6TransactionError"}};gb=class gb extends DZ{constructor(Q){super({tag:"ZcashAppCommandError",...Q})}}});class qq{name="GetAddress";args;errorHelper=new s0(rQ,tQ);constructor(Q){this.args=Q}getApdu(){let Q={cla:aQ,ins:_X0,p1:this.args.checkOnDevice?1:0,p2:0},Z=new w0(Q),Y=QZ.splitPath(this.args.derivationPath);return Z.add8BitUIntToData(Y.length),Y.forEach(($)=>{Z.add32BitUIntToData($)}),Z.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q),Y=Z.extract8BitUInt();if(Y===void 0)return o({error:new C0("Public key length is missing")});if(Z.testMinimalLength(Y)===!1)return o({error:new C0("Public key is missing")});let $=Z.extractFieldByLength(Y);if($===void 0)return o({error:new C0("Unable to extract public key")});let J=Z.extract8BitUInt();if(J===void 0)return o({error:new C0("Address length is missing")});if(Z.testMinimalLength(J)===!1)return o({error:new C0("Address is missing")});let X=Z.extractFieldByLength(J);if(X===void 0)return o({error:new C0("Unable to extract address")});let G=Z.encodeToString(X);if(Z.testMinimalLength(hb)===!1)return o({error:new C0("Chain code is missing")});let W=Z.extractFieldByLength(hb);return W===void 0?o({error:new C0("Unable to extract chain code")}):o({data:{publicKey:$,address:G,chainCode:W}})})}}var hb=32,_X0=64;var SE=w(()=>{I0();IQ();R0();tZ();TY()});class wE{name="getAppConfig";errorHelper=new s0(rQ,tQ);getApdu(){return new w0({cla:aQ,ins:vX0,p1:0,p2:E$.DEFAULT}).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new FQ(Q);Z.extract8BitUInt(),Z.extract8BitUInt();let Y=Z.extract8BitUInt(),$=Z.extract8BitUInt(),J=Z.extract8BitUInt();return Y===void 0||$===void 0||J===void 0?o({error:new C0("Cannot extract version")}):o({data:{version:`${Y}.${$}.${J}`}})})}}var vX0=196;var bb=w(()=>{I0();IQ();R0();tZ();TY()});class _E{name="SignMessage";args;constructor(Q){this.args=Q}getApdu(){throw console.log(this.args),Error("SignMessageCommand.getApdu() not implemented")}parseResponse(Q){throw Error("SignMessageCommand.parseResponse() not implemented")}}var cb=()=>{};class m5{name="GetFullViewingKey";errorHelper=new s0(rQ,tQ);args;constructor(Q){this.args=Q}getApdu(){let Q=this.args.isContinue?o$.NEXT:o$.FIRST,Z={cla:aQ,ins:xX0,p1:Q,p2:this.args.p2},Y=new w0(Z);if(!this.args.isContinue){let $=QZ.splitPath(this.args.derivationPath);if(Y.add8BitUIntToData($.length),$.forEach((J)=>{Y.add32BitUIntToData(J)}),this.args.p2===Fq.UFVK){if(!this.args.transparentDerivationPath)throw Error("GetFullViewingKeyCommand: UFVK export requires a transparent derivation path (app-zcash >= v3.8.0)");let J=QZ.splitPath(this.args.transparentDerivationPath);Y.add8BitUIntToData(J.length),J.forEach((X)=>{Y.add32BitUIntToData(X)})}}return Y.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>o({data:{data:new Uint8Array(Q.data)}}))}}function ub(Q){return Q==="orchardFvk"?Fq.ORCHARD_FVK:Fq.UFVK}var Fq,xX0=80;var pb=w(()=>{I0();IQ();R0();tZ();TY();Fq={UFVK:0,ORCHARD_FVK:1}});function ZZ(...Q){let Z=Q.reduce((J,X)=>J+X.length,0),Y=new Uint8Array(Z),$=0;return Q.forEach((J)=>{Y.set(J,$),$+=J.length}),Y}var hX=()=>{};function d5(Q,Z){return`32'/${Q}/${Z}`}var vE=()=>{};function fX0(Q){let Z=`Orchard FVK must be ${lb} bytes (got ${Q.length})`;if(Q.length<2)return Z;let Y=new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint16(0,!1);return 2+Y===Q.length?`${Z}. Payload matches UFVK framing (u16 BE length + ${Y} bytes). Use mode "ufvk" for this response, or use a Zcash app build that exports raw Orchard FVK for GET_VK P2=0x01.`:Z}function yX0(Q){return Q.length!==lb?zQ({error:new C0(fX0(Q))}):zQ({data:{mode:"orchardFvk",fullViewingKey:Q}})}function gX0(Q){if(Q.length<2)return!1;let Z=new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint16(0,!1);return Q.length>=2+Z}function hX0(Q){if(Q.length<2)return zQ({error:new C0("UFVK string length is missing")});let Z=new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint16(0,!1);if(2+Z>Q.length)return zQ({error:new C0("UFVK string is truncated")});let Y=Q.slice(2,2+Z),$;try{$=new TextDecoder("utf-8",{fatal:!0}).decode(Y)}catch{return zQ({error:new C0("UFVK is not valid UTF-8")})}return 2+Z<Q.length?zQ({error:new C0("UFVK response has extra trailing bytes")}):zQ({data:{mode:"ufvk",fullViewingKey:$}})}function bX0(Q){let Z=Q.split("/");if(Z.length<3)return{error:new C0(`Zcash UFVK derivation path must have at least purpose/coin/account levels (got "${Q}")`)};let[,Y,$]=Z;return!Y||!$?{error:new C0(`Zcash UFVK derivation path components are malformed (got "${Q}")`)}:{orchardDerivationPath:d5(Y,$),transparentDerivationPath:`44'/${Y}/${$}`}}class xE{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=ub(this.args.mode),Z;if(this.args.mode==="ufvk"){let X=bX0(this.args.derivationPath);if("error"in X)return zQ({error:X.error});Z={isContinue:!1,p2:Fq.UFVK,derivationPath:X.orchardDerivationPath,transparentDerivationPath:X.transparentDerivationPath}}else Z={isContinue:!1,p2:Fq.ORCHARD_FVK,derivationPath:this.args.derivationPath};let Y=await this.api.sendCommand(new m5(Z));if(!N0(Y))return zQ({error:Y.error});let $=new Uint8Array(Y.data.data),J=$;for(;$.length===YZ&&!(this.args.mode==="ufvk"&&gX0(J));){let X=await this.api.sendCommand(new m5({isContinue:!0,p2:Q}));if(!N0(X))return zQ({error:X.error});$=new Uint8Array(X.data.data),J=ZZ(J,$)}return this.args.mode==="ufvk"?hX0(J):yX0(J)}}var lb=96;var mb=w(()=>{I0();I0();pb();hX();vE()});class fE{name="GetShieldedAddress";args;errorHelper=new s0(rQ,tQ);constructor(Q){this.args=Q}getApdu(){let Q={cla:aQ,ins:cX0,p1:this.args.checkOnDevice?1:0,p2:0},Z=new w0(Q),Y=QZ.splitPath(this.args.orchardDerivationPath),$=QZ.splitPath(this.args.transparentDerivationPath);return[Y,$].forEach((J)=>{Z.add8BitUIntToData(J.length),J.forEach((X)=>{Z.add32BitUIntToData(X)})}),Z.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{if(Q.data.length===YZ)return o({error:new C0("Response requires continuation which is not supported")});let Z=new FQ(Q),Y=Z.extract16BitUInt();if(Y===void 0)return o({error:new C0("Address length is missing")});if(Z.testMinimalLength(Y)===!1)return o({error:new C0("Address is missing")});let $=Z.extractFieldByLength(Y);if($===void 0)return o({error:new C0("Unable to extract address")});if(Z.testMinimalLength(1))return o({error:new C0("Unexpected trailing bytes in response")});let J;try{J=new TextDecoder("utf-8",{fatal:!0}).decode($)}catch{return o({error:new C0("Address is not valid UTF-8")})}return o({data:{address:J}})})}}var cX0=81;var db=w(()=>{I0();IQ();R0();tZ();TY()});function uX0(Q){let Z=Q.startsWith("m/")?Q.slice(2):Q,Y=Z.split("/");if(Y.length!==5)return{error:new C0(`Shielded address derivation path must have exactly 5 levels purpose/coin/account/change/index (got "${Q}")`)};let $=(U)=>/^\d+'?$/.test(U);if(!Y.every($))return{error:new C0(`Shielded address derivation path contains non-numeric components (got "${Q}")`)};let[J,X,G,W]=Y;return J!=="44'"?{error:new C0(`Shielded address derivation path purpose must be 44' (got "${J}")`)}:X?.endsWith("'")?G?.endsWith("'")?W!=="0"?{error:new C0(`Shielded address derivation path change must be 0 (got "${W}")`)}:{orchardDerivationPath:d5(X,G),transparentDerivationPath:Z}:{error:new C0(`Shielded address derivation path account must be hardened (got "${G}")`)}:{error:new C0(`Shielded address derivation path coin type must be hardened (got "${X}")`)}}class yE{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=uX0(this.args.derivationPath);if("error"in Q)return zQ({error:Q.error});let Z=await this.api.sendCommand(new fE({orchardDerivationPath:Q.orchardDerivationPath,transparentDerivationPath:Q.transparentDerivationPath,checkOnDevice:this.args.checkOnDevice}));return N0(Z)?zQ({data:{address:Z.data.address}}):zQ({error:Z.error})}}var nb=w(()=>{I0();db();vE()});class n5{name="GetTrustedInput";errorHelper=new s0(rQ,tQ);args;constructor(Q){this.args=Q}getApdu(){let{transaction:Q,indexLookup:Z}=this.args,Y,$=!1;if(typeof Z=="number"&&Z>=0){$=!0;let X=new Uint8Array(gE);new DataView(X.buffer,X.byteOffset,X.byteLength).setUint32(0,Z,!1),Y=new Uint8Array(Q.length+gE),Y.set(X,0),Y.set(Q,gE)}else Y=Q;let J={cla:aQ,ins:pX0,p1:$?o$.FIRST:o$.NEXT,p2:E$.DEFAULT};return new w0(J).addBufferToData(Y).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:Q}))}}var gE=4,pX0=66;var ob=w(()=>{I0();IQ();R0();tZ();TY()});var hE;var sb=w(()=>{I0();hE=class hE extends DZ{appVersion;constructor(Q){super({tag:"UnsupportedV6TransactionError",message:`The Zcash app version ${Q} installed on the device does not support V6 (Ironwood) source transactions, so a UTXO received from one cannot be signed. Support is expected in a future Zcash app update.`,errorCode:"unsupported_v6_transaction"}),this.appVersion=Q}}});function lX0(Q,Z,Y,$){if(typeof Q.setBigUint64==="function")return Q.setBigUint64(Z,Y,$);let J=BigInt(32),X=BigInt(4294967295),G=Number(Y>>J&X),W=Number(Y&X),U=$?4:0,K=$?0:4;Q.setUint32(Z+U,G,$),Q.setUint32(Z+K,W,$)}function bE(Q,Z,Y){return Q&Z^~Q&Y}function cE(Q,Z,Y){return Q&Z^Q&Y^Z&Y}var b4,F8;var uE=w(()=>{eq();b4=class b4 extends tq{constructor(Q,Z,Y,$){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=Q,this.outputLen=Z,this.padOffset=Y,this.isLE=$,this.buffer=new Uint8Array(Q),this.view=m9(this.buffer)}update(Q){JV(this),Q=rq(Q),gG(Q);let{view:Z,buffer:Y,blockLen:$}=this,J=Q.length;for(let X=0;X<J;){let G=Math.min($-this.pos,J-X);if(G===$){let W=m9(Q);for(;$<=J-X;X+=$)this.process(W,X);continue}if(Y.set(Q.subarray(X,X+G),this.pos),this.pos+=G,X+=G,this.pos===$)this.process(Z,0),this.pos=0}return this.length+=Q.length,this.roundClean(),this}digestInto(Q){JV(this),l9(Q,this),this.finished=!0;let{buffer:Z,view:Y,blockLen:$,isLE:J}=this,{pos:X}=this;if(Z[X++]=128,CJ(this.buffer.subarray(X)),this.padOffset>$-X)this.process(Y,0),X=0;for(let O=X;O<$;O++)Z[O]=0;lX0(Y,$-8,BigInt(this.length*8),J),this.process(Y,0);let G=m9(Q),W=this.outputLen;if(W%4)throw Error("_sha2: outputLen should be aligned to 32bit");let U=W/4,K=this.get();if(U>K.length)throw Error("_sha2: outputLen bigger than state");for(let O=0;O<U;O++)G.setUint32(4*O,K[O],J)}digest(){let{buffer:Q,outputLen:Z}=this;this.digestInto(Q);let Y=Q.slice(0,Z);return this.destroy(),Y}_cloneInto(Q){Q||(Q=new this.constructor),Q.set(...this.get());let{blockLen:Z,buffer:Y,length:$,finished:J,destroyed:X,pos:G}=this;if(Q.destroyed=X,Q.finished=J,Q.length=$,Q.pos=G,$%Z)Q.buffer.set(Y);return Q}clone(){return this._cloneInto()}};F8=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});function ib(Q,Z,Y,$){if(Q===0)return Z^Y^$;if(Q===1)return Z&Y|~Z&$;if(Q===2)return(Z|~Y)^$;if(Q===3)return Z&$|Y&~$;return Z^(Y|~$)}var mX0,ab,dX0,rb,tb,eb,Qc,nX0,oX0,sX0,iX0,o5,pE,Zc;var Yc=w(()=>{uE();eq();mX0=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ab=(()=>Uint8Array.from(Array(16).fill(0).map((Q,Z)=>Z)))(),dX0=(()=>ab.map((Q)=>(9*Q+5)%16))(),rb=(()=>{let Y=[[ab],[dX0]];for(let $=0;$<4;$++)for(let J of Y)J.push(J[$].map((X)=>mX0[X]));return Y})(),tb=(()=>rb[0])(),eb=(()=>rb[1])(),Qc=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((Q)=>Uint8Array.from(Q)),nX0=tb.map((Q,Z)=>Q.map((Y)=>Qc[Z][Y])),oX0=eb.map((Q,Z)=>Q.map((Y)=>Qc[Z][Y])),sX0=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),iX0=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);o5=new Uint32Array(16);pE=class pE extends b4{constructor(){super(64,20,8,!0);this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:Q,h1:Z,h2:Y,h3:$,h4:J}=this;return[Q,Z,Y,$,J]}set(Q,Z,Y,$,J){this.h0=Q|0,this.h1=Z|0,this.h2=Y|0,this.h3=$|0,this.h4=J|0}process(Q,Z){for(let L=0;L<16;L++,Z+=4)o5[L]=Q.getUint32(Z,!0);let Y=this.h0|0,$=Y,J=this.h1|0,X=J,G=this.h2|0,W=G,U=this.h3|0,K=U,O=this.h4|0,I=O;for(let L=0;L<5;L++){let A=4-L,M=sX0[L],k=iX0[L],B=tb[L],C=eb[L],S=nX0[L],_=oX0[L];for(let x=0;x<16;x++){let f=aq(Y+ib(L,J,G,U)+o5[B[x]]+M,S[x])+O|0;Y=O,O=U,U=aq(G,10)|0,G=J,J=f}for(let x=0;x<16;x++){let f=aq($+ib(A,X,W,K)+o5[C[x]]+k,_[x])+I|0;$=I,I=K,K=aq(W,10)|0,W=X,X=f}}this.set(this.h1+G+K|0,this.h2+U+I|0,this.h3+O+$|0,this.h4+Y+X|0,this.h0+J+W|0)}roundClean(){CJ(o5)}destroy(){this.destroyed=!0,CJ(this.buffer),this.set(0,0,0,0,0)}};Zc=GV(()=>new pE)});var $c;var Jc=w(()=>{Yc();$c=Zc});var aX0,DG,lE,Gc;var Xc=w(()=>{uE();eq();aX0=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),DG=new Uint32Array(64);lE=class lE extends b4{constructor(Q=32){super(64,Q,8,!1);this.A=F8[0]|0,this.B=F8[1]|0,this.C=F8[2]|0,this.D=F8[3]|0,this.E=F8[4]|0,this.F=F8[5]|0,this.G=F8[6]|0,this.H=F8[7]|0}get(){let{A:Q,B:Z,C:Y,D:$,E:J,F:X,G,H:W}=this;return[Q,Z,Y,$,J,X,G,W]}set(Q,Z,Y,$,J,X,G,W){this.A=Q|0,this.B=Z|0,this.C=Y|0,this.D=$|0,this.E=J|0,this.F=X|0,this.G=G|0,this.H=W|0}process(Q,Z){for(let O=0;O<16;O++,Z+=4)DG[O]=Q.getUint32(Z,!1);for(let O=16;O<64;O++){let I=DG[O-15],L=DG[O-2],A=SJ(I,7)^SJ(I,18)^I>>>3,M=SJ(L,17)^SJ(L,19)^L>>>10;DG[O]=M+DG[O-7]+A+DG[O-16]|0}let{A:Y,B:$,C:J,D:X,E:G,F:W,G:U,H:K}=this;for(let O=0;O<64;O++){let I=SJ(G,6)^SJ(G,11)^SJ(G,25),L=K+I+bE(G,W,U)+aX0[O]+DG[O]|0,M=(SJ(Y,2)^SJ(Y,13)^SJ(Y,22))+cE(Y,$,J)|0;K=U,U=W,W=G,G=X+L|0,X=J,J=$,$=Y,Y=L+M|0}Y=Y+this.A|0,$=$+this.B|0,J=J+this.C|0,X=X+this.D|0,G=G+this.E|0,W=W+this.F|0,U=U+this.G|0,K=K+this.H|0,this.set(Y,$,J,X,G,W,U,K)}roundClean(){CJ(DG)}destroy(){this.set(0,0,0,0,0,0,0,0),CJ(this.buffer)}};Gc=GV(()=>new lE)});var Vc;var qc=w(()=>{Xc();Vc=Gc});function Fc(Q){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,Q>>>0,!1),Z}function hY(Q){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,Q>>>0,!0),Z}var c4=()=>{};function i5(Q){if(Q===void 0||Q.byteLength===0)return new Uint8Array(mE);if(Q.byteLength!==mE)throw Error(`expiryHeight must be ${mE} bytes (got ${Q.byteLength})`);return s$(Q)}var a5=50,Kc=0,dE=4294967295,r5=1,rX0=118,tX0=169,eX0=20,QV0=136,ZV0=172,z8,s$=(Q)=>Uint8Array.from(Q),YV0=(Q,Z)=>new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint16(Z,!0),s5=(Q,Z)=>new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint32(Z,!0),$V0=(Q)=>({prevout:s$(Q.prevout),script:s$(Q.script),sequence:s$(Q.sequence),tree:Q.tree?s$(Q.tree):void 0}),JV0=(Q)=>({amount:s$(Q.amount),script:s$(Q.script)}),Uc=(Q)=>({version:s$(Q.version),inputs:Q.inputs.map($V0),outputs:Q.outputs?.map(JV0),locktime:Q.locktime?s$(Q.locktime):void 0,timestamp:Q.timestamp?s$(Q.timestamp):void 0,nVersionGroupId:Q.nVersionGroupId?s$(Q.nVersionGroupId):void 0,nExpiryHeight:Q.nExpiryHeight?s$(Q.nExpiryHeight):void 0,extraData:Q.extraData?s$(Q.extraData):void 0,consensusBranchId:Q.consensusBranchId?s$(Q.consensusBranchId):void 0}),eZ=(Q)=>Q<253?Uint8Array.of(Q):Q<=65535?Uint8Array.of(253,Q&255,Q>>8&255):Uint8Array.of(254,Q&255,Q>>8&255,Q>>16&255,Q>>24&255),zc=(Q,Z)=>{if(Z>=Q.length)return null;let Y=Q[Z];if(Y<253)return[Y,Z+1];if(Y===253)return Z+3>Q.length?null:[YV0(Q,Z+1),Z+3];if(Y===254)return Z+5>Q.length?null:[s5(Q,Z+1)>>>0,Z+5];if(Y===255){if(Z+9>Q.length)return null;let $=s5(Q,Z+1);return s5(Q,Z+5)!==0?null:[$,Z+9]}return null},Oc=(Q)=>{if(Q.length===0)return null;let Z=zc(Q,0);if(Z===null||Z[0]<0)return null;let Y=Z[0],$=Z[1],J=[];for(let X=0;X<Y;X+=1){if($+8>Q.length)return null;$+=8;let G=zc(Q,$);if(G===null)return null;let[W,U]=G;if(W<0||U+W>Q.length)return null;J.push(Q.subarray(U,U+W)),$=U+W}return $!==Q.length?null:J},Wc=({outputs:Q})=>{let Z=new Uint8Array(0);return Q&&(Z=ZZ(Z,eZ(Q.length)),Q.forEach((Y)=>{Z=ZZ(Z,Y.amount,eZ(Y.script.length),Y.script)})),Z},nE=(Q,Z)=>{let Y=new Uint8Array(0);if(Q.inputs.forEach((G)=>{Y=ZZ(Y,G.prevout,eZ(G.script.length),G.script,G.sequence)}),Q.version.length>=4&&(s5(Q.version,0)&2147483647)===4){let G=Q.locktime&&Q.locktime.byteLength>0?Q.locktime:new Uint8Array(4),W=i5(Q.nExpiryHeight),U=Q.extraData||new Uint8Array(0);return ZZ(Q.version,Q.nVersionGroupId||new Uint8Array(0),Q.consensusBranchId||new Uint8Array(0),eZ(Q.inputs.length),Y,Wc(Q),new Uint8Array(3),G,eZ(W.length+U.length),W,U)}let $=Wc(Q);Q.outputs&&Q.locktime&&($=ZZ($,new Uint8Array(3),Q.extraData||new Uint8Array(0)));let J=Q.locktime&&Q.locktime.byteLength>0?Q.locktime:new Uint8Array(4),X=i5(Q.nExpiryHeight);return ZZ(Q.version,Z??Q.timestamp??new Uint8Array(0),Q.nVersionGroupId||new Uint8Array(0),Q.consensusBranchId||new Uint8Array(0),J,X,eZ(Q.inputs.length),Y,$)},oE=(Q)=>{let Z=((Q.at(64)??0)&1)===0?2:3;return ZZ(Uint8Array.of(Z),Q.subarray(1,33))},GV0=(Q)=>$c(Vc(Q)),Hc=(Q)=>{let Z;if(Q.length===65?Z=oE(Q):Q.length===33?Z=Q:Z=null,Z?.length!==33)throw Error("Expected 65-byte uncompressed or 33-byte compressed secp256k1 public key");let Y=GV0(Z);return ZZ(Uint8Array.of(rX0,tX0,eX0),Y,Uint8Array.of(QV0,ZV0))},t5=(Q)=>Q==null||Q>=z8.NU6_3?hY(933566043):Q>=z8.NU6_2?hY(1412952880):Q>=z8.NU6_1?hY(1307332080):Q>=z8.NU6?hY(3370586197):Q>=z8.NU5?hY(3268858036):Q>=z8.CANOPY?hY(3925833126):Q>=z8.HEARTWOOD?hY(4122551051):Q>=z8.BLOSSOM?hY(733220448):Q>=z8.SAPLING?hY(1991772603):hY(1537743641),Dc=()=>hY(2147483653),mE=4;var u4=w(()=>{Jc();qc();hX();c4();z8={NU6_3:3428143,NU6_2:3364600,NU6_1:3146400,NU6:2726400,NU5:1687104,CANOPY:1046400,HEARTWOOD:903000,BLOSSOM:653600,SAPLING:419200}});class Lc{resolve(Q,Z){if(Q.sessionStateType===CQ.Connected)return{isCompatible:!1,version:Ic};let Y=Q.currentApp;return Y?.name!==pJ?{isCompatible:!1,version:Ic}:{isCompatible:!0,version:Y.version}}}function Ec(Q){try{let Z=Q.getDeviceSessionState(),Y=new Lc,{isCompatible:$,version:J}=Y.resolve(Z,Rc);return $?new YY(Z,Rc,Y).withMinVersionInclusive(XV0).check()?void 0:J:void 0}catch{return}}var Ic="0.0.0",Rc,XV0="3.8.0";var Pc=w(()=>{I0();kE();Rc={version:""}});class d4{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q=this.args.indexLookup??0,Z=vV0(this.args.transaction);if(_V0(this.args.transaction)){let G=Ec(this.api);if(G!==void 0)return zQ({error:new hE(G)})}let Y=Z[0];if(!Y)throw Error("Unable to prepare first trusted input APDU chunk");let $=await this.api.sendCommand(new n5({transaction:Y,indexLookup:Q}));if(!N0($))return zQ({error:$.error});let J=$.data,X=1;for(;X<Z.length;){let G=Z[X];if(!G)throw Error("Unable to prepare trusted input APDU chunk");let W=await this.api.sendCommand(new n5({transaction:G}));if(!N0(W))return zQ({error:W.error});J=W.data,X+=1}return zQ({data:J})}}var wc=255,VV0=4,qV0,FV0,eE=4,zV0,IG,P$=32,_c=8,WV0=1,e5=64,jc=192,W8=52,KV0=16,m4=512,zq,vc=80,UV0,OV0,HV0,iE,DV0,p4,IV0,aE,rE,tE,RV0,l4,LV0,xc,EV0,Ac=128,Mc=50,PV0=2147483647,jV0=4,AV0=5,fc=6,Tc=3632576152,sE=(Q,Z)=>(lJ(Q,Z,Z+1),Q[Z]??0),QP=(Q,Z)=>(lJ(Q,Z,Z+4),new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint32(Z,!0)),MV0=(Q,Z)=>{lJ(Q,Z,Z+8);let Y=new DataView(Q.buffer,Q.byteOffset,Q.byteLength),$=Y.getUint32(Z,!0);return Y.getUint32(Z+4,!0)*4294967296+$},Nc=(Q)=>`0x${Q.toString(16).padStart(8,"0")}`,lJ=(Q,Z,Y)=>{if(Z<0||Y<Z||Y>Q.length)throw Error("Malformed transaction while splitting trusted input chunks")},RG=(Q,Z)=>{let Y=sE(Q,Z);if(Y<253)return{value:Y,byteLength:1,nextOffset:Z+1};if(Y===253)return{value:sE(Q,Z+1)+(sE(Q,Z+2)<<8),byteLength:3,nextOffset:Z+3};if(Y===254)return{value:QP(Q,Z+1),byteLength:5,nextOffset:Z+5};lJ(Q,Z+1,Z+9);let $=MV0(Q,Z+1);if(!Number.isSafeInteger($))throw Error("CompactSize value exceeds JavaScript safe integer range");return{value:$,byteLength:9,nextOffset:Z+9}},Bc=(Q)=>{let Z=Q.filter((J)=>J.length>0);if(Z.length===0)throw Error("Cannot send trusted input for an empty transaction");let Y=[],$=!0;return Z.forEach((J)=>{let X=0;for(;X<J.length;){let G=Math.min(X+($?qV0:FV0),J.length);Y.push(J.slice(X,G)),X=G,$=!1}}),Y},TV0=(Q,Z)=>ZZ(Q,new Uint8Array([4]),Z),NV0,BV0=(Q,Z)=>{let Y=Z;return{take:($)=>{lJ(Q,Y,Y+$);let J=Q.slice(Y,Y+$);return Y+=$,J},skip:($)=>{lJ(Q,Y,Y+$),Y+=$},takeCount:()=>{let{value:$,nextOffset:J}=RG(Q,Y);return Y=J,$},consumed:()=>Y}},kc=(Q,Z)=>{let Y=Q.takeCount();if(Y===0)return NV0;let $=Array.from({length:Y},()=>Q.take(LV0)),J=Q.take(Z?EV0:xc);return Z||Q.skip(P$),{actions:$,digestData:J}},Cc=(Q,Z)=>{if(Z===0)return;let Y=Q.takeCount();Q.skip(Y+Z*e5+e5)},kV0=(Q,Z,Y)=>{let $=BV0(Q,Z),J=$.takeCount(),X=Array.from({length:J},()=>$.take(HV0)),G=$.takeCount(),W=Array.from({length:G},()=>$.take(IV0)),U=new Uint8Array,K=new Uint8Array;(J>0||G>0)&&(U=$.take(_c),J>0&&(Y?$.skip(P$):K=$.take(P$)),$.skip(J*(jc+e5)+G*jc+e5));let O=kc($,!Y);Cc($,O.actions.length);let I;if(Y&&(I=kc($,!1),Cc($,I.actions.length)),$.consumed()!==Q.length)throw Error("Malformed transaction while splitting trusted input chunks");return{saplingSpends:X,saplingOutputs:W,saplingValueBalance:U,saplingAnchor:K,orchard:O,ironwood:I}},CV0=(Q)=>{let Z=Q.subarray(0,iE),Y=Q.subarray(iE,p4),$=Q.subarray(p4,p4+zq),J=Q.subarray(p4+zq);return{compact:ZZ(Y,$.subarray(0,W8)),memo:$.subarray(W8,W8+m4),nonCompact:ZZ(Z,$.subarray(W8+m4),J)}},SV0=(Q)=>{let Z=Q.subarray(0,aE),Y=Q.subarray(aE,rE),$=Q.subarray(rE,tE),J=Q.subarray(tE,l4),X=Q.subarray(l4,l4+zq),G=Q.subarray(l4+zq);return{compact:ZZ(Y,J,X.subarray(0,W8)),memo:X.subarray(W8,W8+m4),nonCompact:ZZ(Z,$,X.subarray(W8+m4),G)}},Sc=(Q,Z)=>{Z.forEach((Y)=>{for(let $=0;$<Y.length;$+=Ac)Q.push(Y.subarray($,$+Ac))})},wV0=(Q,Z)=>{if(Q.push(ZZ(eZ(Z.saplingSpends.length),eZ(Z.saplingOutputs.length),eZ(Z.orchard.actions.length),...Z.ironwood!==void 0?[eZ(Z.ironwood.actions.length)]:[])),Z.saplingSpends.length>0||Z.saplingOutputs.length>0){Q.push(ZZ(Z.saplingValueBalance,Z.saplingAnchor)),Z.saplingSpends.forEach(($)=>Q.push($));let Y=Z.saplingOutputs.map(CV0);Y.forEach(({compact:$})=>Q.push($)),Sc(Q,Y.map(({memo:$})=>$)),Y.forEach(({nonCompact:$})=>Q.push($))}(Z.ironwood!==void 0?[Z.orchard,Z.ironwood]:[Z.orchard]).forEach((Y)=>{if(Y.actions.length===0)return;let $=Y.actions.map(SV0);$.forEach(({compact:J})=>Q.push(J)),Sc(Q,$.map(({memo:J})=>J)),$.forEach(({nonCompact:J})=>Q.push(J)),Q.push(Y.digestData)})},yc=(Q)=>QP(Q,0)&PV0,_V0=(Q)=>yc(Q)===fc,vV0=(Q)=>{let Z=yc(Q),Y=Z===jV0,$=Z===fc;if(!Y&&!$&&Z!==AV0)throw Error(`Unsupported transaction version ${Z} while splitting trusted input chunks`);if($){let O=QP(Q,eE);if(O!==Tc)throw Error(`Unexpected version group id for a v6 transaction while splitting trusted input chunks: expected ${Nc(Tc)}, got ${Nc(O)}`)}let J=0,X=new Uint8Array,G=new Uint8Array,W=[];Y?J+=IG:(lJ(Q,IG,IG+8),X=Q.slice(IG,IG+4),G=Q.slice(IG+4,IG+8),J+=zV0);let U=RG(Q,J);J=U.nextOffset,W.push(ZZ(Q.slice(0,IG),Q.slice(J-U.byteLength,J)));for(let O=0;O<U.value;O+=1){let I=J;lJ(Q,J,J+36),J+=36;let L=RG(Q,J);J=L.nextOffset,W.push(Q.slice(I,J));let A=J;lJ(Q,J,J+L.value+4),J+=L.value+4;let M=Q.slice(A,J);for(let k=0;k<M.length;k+=Mc)W.push(M.slice(k,k+Mc))}let K=RG(Q,J);J=K.nextOffset,W.push(Q.slice(J-K.byteLength,J));for(let O=0;O<K.value;O+=1){let I=J;lJ(Q,J,J+8),J+=8;let L=RG(Q,J);J=L.nextOffset,lJ(Q,J,J+L.value),J+=L.value,W.push(Q.slice(I,J))}if(Y){let O=RG(Q,J),I=RG(Q,O.nextOffset),L=RG(Q,I.nextOffset);return W.push(Q.slice(J,L.nextOffset)),W.push(Q.slice(L.nextOffset)),Bc(W)}return wV0(W,kV0(Q,J,$)),W.push(TV0(X,G)),Bc(W)};var ZP=w(()=>{I0();ob();sb();u4();Pc();hX();qV0=wc-VV0,FV0=wc,zV0=5*eE,IG=3*eE,zq=W8+m4+KV0,UV0=P$,OV0=UV0+P$,HV0=OV0+P$,iE=P$,DV0=iE+P$,p4=DV0+P$,IV0=p4+zq+vc,aE=P$,rE=aE+P$,tE=rE+P$,RV0=tE+P$,l4=RV0+P$,LV0=l4+zq+vc,xc=WV0+_c,EV0=xc+P$,NV0={actions:[],digestData:new Uint8Array}});class YP{constructor(Q){this.args=Q}name="PcztHeader";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:xV0,p1:AJ.FIRST,p2:HG.CONTINUE};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var xV0=82;var gc=w(()=>{I0();IQ();R0();tZ();TY()});class $P{constructor(Q){this.args=Q}name="PcztIronwoodAction";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:fV0,p1:this.args.p1,p2:this.args.p2};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var fV0=88;var hc=w(()=>{I0();IQ();R0();tZ();TY()});class JP{constructor(Q){this.args=Q}name="PcztOrchardAction";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:yV0,p1:this.args.p1,p2:this.args.p2};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var yV0=86;var bc=w(()=>{I0();IQ();R0();tZ();TY()});class GP{constructor(Q){this.args=Q}name="PcztTransparentInput";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:gV0,p1:this.args.p1,p2:this.args.p2};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var gV0=83;var cc=w(()=>{I0();IQ();R0();tZ();TY()});class XP{constructor(Q){this.args=Q}name="PcztTransparentOutput";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:hV0,p1:this.args.p1,p2:this.args.p2};return new w0(Q).addBufferToData(this.args.data).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:void 0}))}}var hV0=84;var uc=w(()=>{I0();IQ();R0();tZ();TY()});class VP{constructor(Q){this.args=Q}name="SignPcztIronwood";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:bV0,p1:AJ.FIRST,p2:this.args.actionIndex};return new w0(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new Uint8Array(Q.data);return Z.length!==pc?o({error:new C0(`Expected ${pc}-byte Ironwood spendAuthSig, got ${Z.length}`)}):o({data:{spendAuthSig:Z}})})}}var bV0=89,pc=64;var lc=w(()=>{I0();IQ();R0();tZ();TY()});class qP{constructor(Q){this.args=Q}name="SignPcztOrchard";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:cV0,p1:AJ.FIRST,p2:this.args.actionIndex};return new w0(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new Uint8Array(Q.data);return Z.length!==mc?o({error:new C0(`Expected ${mc}-byte Orchard spendAuthSig, got ${Z.length}`)}):o({data:{spendAuthSig:Z}})})}}var cV0=87,mc=64;var dc=w(()=>{I0();IQ();R0();tZ();TY()});class FP{constructor(Q){this.args=Q}name="SignPcztTransparent";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:uV0,p1:AJ.FIRST,p2:this.args.inputIndex};return new w0(Q).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new Uint8Array(Q.data);return Z.length<2?o({error:new C0(`Expected a transparent signature with a trailing sighash byte, got ${Z.length} bytes`)}):Z[Z.length-1]!==r5?o({error:new C0(`Expected sighash_type SIGHASH_ALL (0x01), got 0x${Z[Z.length-1].toString(16)}`)}):o({data:{signature:Z}})})}}var uV0=85;var nc=w(()=>{I0();IQ();R0();tZ();TY();u4()});var oc,sc=(Q)=>{let Z=QZ.splitPath(Q),Y=new WQ;return Y.add8BitUIntToData(Z.length),Z.forEach(($)=>Y.add32BitUIntToData($)),Y.build()},ic=(Q)=>{if(Q===null)return Uint8Array.of(0);let Z=new WQ;return Z.add8BitUIntToData(1),Z.add32BitUIntToData(Q,!1),Z.build()},ac=(Q)=>Q?ZZ(eZ(1),Q.pubkey,Q.seedFingerprint??oc,sc(Q.signingPath)):eZ(0),pV0=(Q,Z)=>ZZ(Z??oc,sc(Q)),QO=(Q)=>lV0(ZZ(eZ(Q.length),Q)),lV0=(Q)=>{if(Q.length<=l5)return[Q];let Z=[];for(let Y=0;Y<Q.length;Y+=l5)Z.push(Q.subarray(Y,Y+l5));return Z},rc=(Q)=>{let Z=new WQ;return Z.addBufferToData(Uint8Array.of(80,67,90,84)),Z.add32BitUIntToData(Q.txVersion>=6?2:1,!1),Z.add32BitUIntToData(Q.txVersion,!1),Z.add32BitUIntToData(Q.versionGroupId,!1),Z.add32BitUIntToData(Q.consensusBranchId,!1),Z.addBufferToData(ic(Q.fallbackLockTime)),Z.add32BitUIntToData(Q.expiryHeight,!1),Z.add32BitUIntToData(Q.coinType,!1),Z.add8BitUIntToData(Q.txModifiable),Z.build()},tc=(Q)=>{let Z=[eZ(Q.length)];for(let Y of Q){let $=new WQ;$.addBufferToData(Y.prevoutTxid),$.add32BitUIntToData(Y.prevoutIndex,!1),$.addBufferToData(ic(Y.sequence)),$.add64BitUIntToData(Y.value,!1),Z.push($.build()),Z.push(...QO(Y.scriptPubKey)),Z.push(ZZ(Uint8Array.of(Y.sighashType),ac(Y.derivation)))}return Z},ec=(Q)=>{let Z=[eZ(Q.length)];for(let Y of Q){let $=new WQ;$.add64BitUIntToData(Y.value,!1),Z.push($.build()),Z.push(...QO(Y.scriptPubKey)),Z.push(ac(Y.derivation))}return Z},Qu=(Q)=>{let Z=[eZ(Q.actions.length)];if(Q.actions.length===0)return Z;for(let J of Q.actions){let X=new WQ;X.addBufferToData(J.cvNet),X.addBufferToData(J.nullifier),X.addBufferToData(J.rk),X.addBufferToData(J.spendRecipient),X.add64BitUIntToData(J.spendValue,!1),X.addBufferToData(J.spendRho),X.addBufferToData(J.spendRseed),X.addBufferToData(J.alpha),Z.push(X.build()),Z.push(pV0(J.signingPath,J.seedFingerprint)),Z.push(ZZ(J.cmx,J.ephemeralKey)),Z.push(...QO(J.encCiphertext)),Z.push(...QO(J.outCiphertext));let G=new WQ;G.addBufferToData(J.recipient),G.add64BitUIntToData(J.value,!1),G.addBufferToData(J.rseed),G.addBufferToData(J.rcv),"notePlaintextVersion"in J&&G.add8BitUIntToData(J.notePlaintextVersion),Z.push(G.build())}let Y=new WQ,$=Q.valueBalance;return Y.add8BitUIntToData(Q.flags),Y.add64BitUIntToData($<0n?-$:$,!1),Y.add8BitUIntToData($<0n?1:0),Y.addBufferToData(Q.anchor),Z.push(Y.build()),Z},Zu=(Q)=>Qu(Q),Yu=(Q)=>Qu(Q),n4=(Q,Z)=>Q===0?AJ.FIRST:Q===Z-1?AJ.LAST:AJ.NEXT,zP=(Q,Z,Y)=>Y&&Q===Z-1?HG.FINISHED:HG.CONTINUE;var $u=w(()=>{I0();IQ();tZ();u4();hX();oc=new Uint8Array(32)});class WP{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let{global:Q,transparentInputs:Z,transparentOutputs:Y,orchardBundle:$,ironwoodBundle:J}=this.args.transaction,X=$??mV0,G=J??null,W=Q.txVersion===dV0;if(W&&G===null)return zQ({error:new Dq("V6 transaction requires a non-null Ironwood bundle")});if(!W&&G!==null)return zQ({error:new Dq("V5 transaction does not support an Ironwood bundle")});let U=W&&G!==null,K=await this.api.sendCommand(new YP({data:rc(Q)}));if(!N0(K))return zQ({error:K.error});let O=tc(Z);for(let B=0;B<O.length;B+=1){let C=await this.api.sendCommand(new GP({data:O[B],p1:n4(B,O.length),p2:HG.CONTINUE}));if(!N0(C))return zQ({error:C.error})}let I=ec(Y);for(let B=0;B<I.length;B+=1){let C=await this.api.sendCommand(new XP({data:I[B],p1:n4(B,I.length),p2:HG.CONTINUE}));if(!N0(C))return zQ({error:C.error})}let L=Zu(X);for(let B=0;B<L.length;B+=1){let C=await this.api.sendCommand(new JP({data:L[B],p1:n4(B,L.length),p2:zP(B,L.length,!W)}));if(!N0(C))return zQ({error:C.error})}if(U){let B=Yu(G);for(let C=0;C<B.length;C+=1){let S=await this.api.sendCommand(new $P({data:B[C],p1:n4(C,B.length),p2:zP(C,B.length,!0)}));if(!N0(S))return zQ({error:S.error})}}let A=[];for(let B=0;B<X.actions.length;B+=1){if(X.actions[B].spendValue===0n)continue;let C=await this.api.sendCommand(new qP({actionIndex:B}));if(!N0(C))return zQ({error:C.error});A.push(C.data)}let M=[];if(U)for(let B=0;B<G.actions.length;B+=1){if(G.actions[B].spendValue===0n)continue;let C=await this.api.sendCommand(new VP({actionIndex:B}));if(!N0(C))return zQ({error:C.error});M.push(C.data)}let k=[];for(let B=0;B<Z.length;B+=1){let C=await this.api.sendCommand(new FP({inputIndex:B}));if(!N0(C))return zQ({error:C.error});k.push(C.data.signature)}return zQ({data:{orchard:A,transparentInputSigs:k,ironwood:M}})}}var mV0,dV0=6;var Ju=w(()=>{I0();gc();hc();bc();cc();uc();lc();dc();nc();tZ();$u();mV0={actions:[],flags:0,valueBalance:0n,anchor:new Uint8Array(32)}});class KP{constructor(Q){this.args=Q}name="HashOutputFull";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:nV0,p1:this.args.isLastChunk?o$.NEXT:o$.FIRST,p2:E$.DEFAULT};return new w0(Q).addBufferToData(this.args.outputChunk).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:Q}))}}var nV0=74;var Gu=w(()=>{I0();IQ();R0();tZ();TY()});class UP{constructor(Q){this.args=Q}name="ProvideOutputFullChangePath";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:oV0,p1:o$.CHANGE_PATH,p2:E$.DEFAULT},Z=new w0(Q),Y=QZ.splitPath(this.args.derivationPath);return Z.add8BitUIntToData(Y.length),Y.forEach(($)=>{Z.add32BitUIntToData($)}),Z.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:Q}))}}var oV0=74;var Xu=w(()=>{I0();IQ();R0();tZ();TY()});class OP{constructor(Q){this.args=Q}name="SignTransaction";errorHelper=new s0(rQ,tQ);getApdu(){let{derivationPath:Q,expiryHeight:Z,lockTime:Y,sigHashType:$}=this.args,J=QZ.splitPath(Q),X=Fc(Y),G={cla:aQ,ins:72,p2:E$.DEFAULT,p1:0},W=new w0(G);return W.add8BitUIntToData(J.length),J.forEach((U)=>{W.add32BitUIntToData(U)}),W.add8BitUIntToData(0).addBufferToData(X).add8BitUIntToData($),W.addBufferToData(Z),W.build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefaultLazy(()=>{let Z=new Uint8Array(Q.data);return Z.length>0&&(Z[0]=48),o({data:{signature:Z}})})}}var Vu=w(()=>{I0();IQ();R0();tZ();c4();TY()});class o4{constructor(Q){this.args=Q}name="StartUntrustedHashTransactionInput";errorHelper=new s0(rQ,tQ);getApdu(){let Q={cla:aQ,ins:sV0,p1:this.args.firstRound?o$.FIRST:o$.NEXT,p2:this.args.newTransaction?E$.SAPLING:E$.HASH_INPUT_CONTINUE};return new w0(Q).addBufferToData(this.args.transactionData).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:Q}))}}var sV0=68;var qu=w(()=>{I0();IQ();R0();tZ();TY()});class HP{constructor(Q){this.args=Q}name="ZcashSaplingOutputCommit";errorHelper=new s0(rQ,tQ);getApdu(){let{lockTime:Q,sigHashType:Z,expiryHeight:Y}=this.args,$=ZZ(hY(Q),Uint8Array.of(0,0),Uint8Array.of(Z&255),Y);if($.length!==11)throw Error("ZcashSaplingOutputCommit: internal payload length");let J={cla:aQ,ins:iV0,p1:0,p2:E$.DEFAULT};return new w0(J).addBufferToData($).build()}parseResponse(Q){return q0.fromNullable(this.errorHelper.getError(Q)).orDefault(o({data:{committed:!0}}))}}var iV0=72;var Fu=w(()=>{I0();IQ();R0();tZ();hX();c4();TY()});function zu(Q,Z){if(Q.length!==Z.length)return!1;for(let Y=0;Y<Q.length;Y+=1)if(Q[Y]!==Z[Y])return!1;return!0}var Wu=()=>{};class DP{constructor(Q,Z){this.api=Q,this.args=Z}async run(){let Q={...{lockTime:Kc,sigHashType:r5,additionals:[]},...this.args.transactionArg},{inputs:Z,associatedKeysets:Y,blockHeight:$,changePath:J,outputScriptHex:X,lockTime:G,sigHashType:W,additionals:U,expiryHeight:K}=Q,O=new Set(U.map((V)=>V.trim().toLowerCase()));if(!O.has("zcash"))return zQ({error:new C0('signTransaction requires additionals to include "zcash" (Zcash transparent signing only).')});let I=O.has("sapling");if(Z.length!==Y.length)return zQ({error:new C0("Inputs and associatedKeysets lengths mismatch")});let L=hY(G),A=Dc(),M;try{M=i5(K)}catch(V){return zQ({error:new C0(V instanceof Error?V.message:"Invalid expiryHeight")})}let k=mQ(X)??new Uint8Array,B=new Uint8Array(0),C={inputs:[],version:A,timestamp:new Uint8Array(0)};C.nVersionGroupId=Uint8Array.of(10,39,167,38),C.nExpiryHeight=M,C.extraData=I?new Uint8Array(11):Uint8Array.of(0);let S=await this.collectTrustedInputsAndOutputs(Z);if(!("trustedInputs"in S))return S;let{trustedInputs:_,regularOutputs:x}=S;C.inputs=Z.map((V,z)=>{let H=hY(V.length>=4&&typeof V[3]=="number"?V[3]:dE);return{script:x[z].script,prevout:B,sequence:H}});let f=await this.collectPublicKeys(Y);if(!Array.isArray(f))return f;let h=f,i=await this.shouldProvideChangePath(J,Y,h,k);if(typeof i!="boolean")return i;C.consensusBranchId=t5($);let Z0=await this.executeHashSequence(C,_,J,i,k,I,G,W,M);if(Z0)return Z0;let t=await this.signEachInput(Z,Y,x,C,_,G,W,M);if(!Array.isArray(t))return t;let c=t;C.version=A,C.consensusBranchId=t5($);for(let V=0;V<Z.length;V+=1){C.inputs[V].script=ZZ(Uint8Array.of(c[V].length),c[V],Uint8Array.of(h[V].length),h[V]);let z=4;C.inputs[V].prevout=_[V].value.subarray(z,z+36)}C.locktime=L;let l=ZZ(nE(C,C.timestamp),k,Uint8Array.of(0,0,0));return zQ({data:DQ(l,!0)})}async collectTrustedInputsAndOutputs(Q){let Z=[],Y=[];for(let $ of Q){let J=$[0],X=Uc(J);X.consensusBranchId=t5($[4]);let G=await this.getTrustedInput($[1],X,J.serializedPreviousTransactionOverride);if(typeof G!="string")return G;let W=hY($.length>=4&&typeof $[3]=="number"?$[3]:dE);if(Z.push({trustedInput:!0,value:mQ(G)??new Uint8Array,sequence:W}),X.outputs&&$[1]<=X.outputs.length-1){let U=X.outputs[$[1]];if(!U)return zQ({error:new C0("Invalid output index in previous transaction")});Y.push(U)}else return zQ({error:new C0("Invalid output index in previous transaction")})}return{trustedInputs:Z,regularOutputs:Y}}async collectPublicKeys(Q){let Z=[];for(let Y of Q){let $=await this.api.sendCommand(new qq({derivationPath:Y,checkOnDevice:!1}));if(!N0($))return zQ({error:$.error});Z.push(oE($.data.publicKey))}return Z}async shouldProvideChangePath(Q,Z,Y,$){let J=typeof Q=="string"?Q.trim():"";if(J==="")return!1;let X=Z.indexOf(J),G;if(X>=0)G=Y[X];else{let W=await this.api.sendCommand(new qq({derivationPath:J,checkOnDevice:!1}));if(!N0(W))return zQ({error:W.error});G=W.data.publicKey}try{let W=Hc(G),U=Oc($);return U!==null&&U.length>=2&&U.some((K)=>zu(K,W))}catch{return!1}}async executeHashSequence(Q,Z,Y,$,J,X,G,W,U){let K=await this.startUntrustedHashTransactionInput(!0,Q,Z);if(K)return K;if($&&Y){let I=await this.api.sendCommand(new UP({derivationPath:Y}));if(!N0(I))return zQ({error:I.error})}let O=await this.hashOutputFull(J);if(O)return O;if(X){let I=await this.api.sendCommand(new HP({lockTime:G,sigHashType:W,expiryHeight:U}));if(!N0(I))return zQ({error:I.error})}return null}async signEachInput(Q,Z,Y,$,J,X,G,W){let U=[];for(let K=0;K<Q.length;K+=1){let O=Q[K],I=O.length>=3&&typeof O[2]=="string"?mQ(O[2])??new Uint8Array:Y[K].script,L={...$,inputs:[{...$.inputs[K],script:I}]},A=await this.startUntrustedHashTransactionInput(!1,L,[J[K]]);if(A)return A;let M=await this.api.sendCommand(new OP({derivationPath:Z[K],lockTime:X,sigHashType:G,expiryHeight:W}));if(!N0(M))return zQ({error:M.error});U.push(M.data.signature)}return U}async getTrustedInput(Q,Z,Y){let $=Y&&Y.length>0?Y:nE(Z,Z.timestamp),J=await new d4(this.api,{transaction:$,indexLookup:Q}).run();return t$(J)?DQ(J.data.data,!1):zQ({error:J.error})}async hashOutputFull(Q){let Z=0;for(;Z<Q.length;){let Y=Z+a5>=Q.length?Q.length-Z:a5,$=Q.subarray(Z,Z+Y),J=await this.api.sendCommand(new KP({outputChunk:$,isLastChunk:Z+Y===Q.length}));if(!N0(J))return zQ({error:J.error});Z+=Y}return null}buildScriptBlocks(Q){if(Q.script.length===0)return[Q.sequence];let Z=[],Y=0;for(;Y!==Q.script.length;){let $=Math.min(a5,Q.script.length-Y),J=Q.script.subarray(Y,Y+$);Z.push(Y+$===Q.script.length?ZZ(J,Q.sequence):Uint8Array.from(J)),Y+=$}return Z}async sendInputBlocks(Q,Z){for(let Y of Q){let $=await this.api.sendCommand(new o4({newTransaction:Z,firstRound:!1,transactionData:Y}));if(!N0($))return zQ({error:$.error})}return null}async startUntrustedHashTransactionInput(Q,Z,Y){let $=Z.consensusBranchId||new Uint8Array(0),J=ZZ(Z.version,Z.timestamp||new Uint8Array(0),Z.nVersionGroupId||new Uint8Array(0),$,eZ(Z.inputs.length)),X=await this.api.sendCommand(new o4({newTransaction:Q,firstRound:!0,transactionData:J}));if(!N0(X))return zQ({error:X.error});for(let G=0;G<Z.inputs.length;G+=1){let W=Z.inputs[G],U=Y[G].value,K=Y[G].trustedInput?Uint8Array.of(1,U.length):Uint8Array.of(0),O=ZZ(K,U,eZ(W.script.length)),I=await this.api.sendCommand(new o4({newTransaction:Q,firstRound:!1,transactionData:O}));if(!N0(I))return zQ({error:I.error});let L=await this.sendInputBlocks(this.buildScriptBlocks(W),Q);if(L)return L}return null}}var Ku=w(()=>{I0();SE();Gu();Xu();Vu();qu();Fu();ZP();u4();Wu();hX();c4()});var aV0,rV0,tV0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?rV0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&aV0(Z,Y,J),J},Uu=(Q,Z)=>(Y,$)=>Z(Y,$,Q),ZO=class{constructor(Q,Z){this.dmk=Q,this.sessionId=Z}getAppConfig(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new QJ({input:{command:new wE,appName:pJ,requiredUserInteraction:k0.None,skipOpenApp:Q.skipOpenApp}})})}getAddress(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new QJ({input:{command:new qq(Q),appName:pJ,requiredUserInteraction:Q.checkOnDevice?k0.VerifyAddress:k0.None,skipOpenApp:Q.skipOpenApp}})})}getShieldedAddress(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Z)=>new yE(Z,{derivationPath:Q.derivationPath,checkOnDevice:Q.checkOnDevice}).run(),appName:pJ,requiredUserInteraction:Q.checkOnDevice?k0.VerifyAddress:k0.None,skipOpenApp:Q.skipOpenApp}})})}getFullViewingKey(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Z)=>new xE(Z,{derivationPath:Q.derivationPath,mode:Q.mode}).run(),appName:pJ,requiredUserInteraction:k0.None,skipOpenApp:Q.skipOpenApp}})})}signTransaction(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Z)=>new DP(Z,Q).run(),appName:pJ,requiredUserInteraction:k0.SignTransaction,skipOpenApp:Q.skipOpenApp??!1}})})}signPcztTransaction(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Z)=>new WP(Z,{transaction:Q.transaction}).run(),appName:pJ,requiredUserInteraction:k0.SignTransaction,skipOpenApp:Q.skipOpenApp??!1}})})}signMessage(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new QJ({input:{command:new _E(Q),appName:pJ,requiredUserInteraction:k0.SignPersonalMessage,skipOpenApp:Q.skipOpenApp}})})}getTrustedInput(Q){return this.dmk.executeDeviceAction({sessionId:this.sessionId,deviceAction:new nZ({input:{task:async(Z)=>new d4(Z,Q).run(),appName:pJ,requiredUserInteraction:k0.None,skipOpenApp:Q.skipOpenApp??!1}})})}};var Ou=w(()=>{I0();W0();kE();CE();SE();bb();cb();mb();nb();ZP();Ju();Ku();aV0=Object.defineProperty,rV0=Object.getOwnPropertyDescriptor;ZO=tV0([e(),Uu(0,g(Vq.Dmk)),Uu(1,g(Vq.SessionId))],ZO)});var Hu=()=>new b0(({bind:Q})=>{Q(gY.AppBinding).to(ZO)});var Du=w(()=>{W0();D1();Ou()});var LG;var IP=w(()=>{LG={GetAddressUseCase:Symbol.for("GetAddressUseCase"),GetFullViewingKeyUseCase:Symbol.for("GetFullViewingKeyUseCase"),GetShieldedAddressUseCase:Symbol.for("GetShieldedAddressUseCase")}});var eV0,Qq0,Zq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Qq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&eV0(Z,Y,J),J},Yq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),YO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.getAddress({derivationPath:Q,checkOnDevice:Z?.checkOnDevice??!1,skipOpenApp:Z?.skipOpenApp??!1})}};var Iu=w(()=>{W0();D1();eV0=Object.defineProperty,Qq0=Object.getOwnPropertyDescriptor;YO=Zq0([e(),Yq0(0,g(gY.AppBinding))],YO)});var $q0,Jq0,Gq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Jq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&$q0(Z,Y,J),J},Xq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),$O=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.getFullViewingKey({derivationPath:Q,mode:Z?.mode??"ufvk",skipOpenApp:Z?.skipOpenApp??!1})}};var Ru=w(()=>{W0();D1();$q0=Object.defineProperty,Jq0=Object.getOwnPropertyDescriptor;$O=Gq0([e(),Xq0(0,g(gY.AppBinding))],$O)});var Vq0,qq0,Fq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?qq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Vq0(Z,Y,J),J},zq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),JO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.getShieldedAddress({derivationPath:Q,checkOnDevice:Z?.checkOnDevice??!1,skipOpenApp:Z?.skipOpenApp??!1})}};var Lu=w(()=>{W0();D1();Vq0=Object.defineProperty,qq0=Object.getOwnPropertyDescriptor;JO=Fq0([e(),zq0(0,g(gY.AppBinding))],JO)});var Eu=()=>new b0(({bind:Q})=>{Q(LG.GetAddressUseCase).to(YO),Q(LG.GetFullViewingKeyUseCase).to($O),Q(LG.GetShieldedAddressUseCase).to(JO)});var Pu=w(()=>{W0();IP();Iu();Ru();Lu()});var GO;var RP=w(()=>{GO={GetAppConfigUseCase:Symbol.for("GetAppConfigUseCase")}});var Wq0,Kq0,Uq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Kq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Wq0(Z,Y,J),J},Oq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),XO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(){return this._appBinder.getAppConfig({skipOpenApp:!1})}};var ju=w(()=>{W0();D1();Wq0=Object.defineProperty,Kq0=Object.getOwnPropertyDescriptor;XO=Uq0([e(),Oq0(0,g(gY.AppBinding))],XO)});var Au=()=>new b0(({bind:Q})=>{Q(GO.GetAppConfigUseCase).to(XO)});var Mu=w(()=>{W0();RP();ju()});var VO;var LP=w(()=>{VO={SignMessageUseCase:Symbol.for("SignMessageUseCase")}});var Hq0,Dq0,Iq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Dq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Hq0(Z,Y,J),J},Rq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),qO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.signMessage({derivationPath:Q,message:Z,skipOpenApp:!1})}};var Tu=w(()=>{W0();D1();Hq0=Object.defineProperty,Dq0=Object.getOwnPropertyDescriptor;qO=Iq0([e(),Rq0(0,g(gY.AppBinding))],qO)});var Nu=()=>new b0(({bind:Q})=>{Q(VO.SignMessageUseCase).to(qO)});var Bu=w(()=>{W0();LP();Tu()});var EG;var EP=w(()=>{EG={GetTrustedInputUseCase:Symbol.for("GetTrustedInputUseCase"),SignTransactionUseCase:Symbol.for("SignTransactionUseCase"),SignPcztTransactionUseCase:Symbol.for("SignPcztTransactionUseCase")}});var Lq0,Eq0,Pq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Eq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Lq0(Z,Y,J),J},jq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),FO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.getTrustedInput({transaction:Q,indexLookup:Z?.indexLookup,skipOpenApp:Z?.skipOpenApp??!1})}};var ku=w(()=>{W0();D1();Lq0=Object.defineProperty,Eq0=Object.getOwnPropertyDescriptor;FO=Pq0([e(),jq0(0,g(gY.AppBinding))],FO)});var Aq0,Mq0,Tq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?Mq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Aq0(Z,Y,J),J},Nq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),zO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.signPcztTransaction({transaction:Q,skipOpenApp:Z?.skipOpenApp})}};var Cu=w(()=>{W0();D1();Aq0=Object.defineProperty,Mq0=Object.getOwnPropertyDescriptor;zO=Tq0([e(),Nq0(0,g(gY.AppBinding))],zO)});var Bq0,kq0,Cq0=(Q,Z,Y,$)=>{for(var J=$>1?void 0:$?kq0(Z,Y):Z,X=Q.length-1,G;X>=0;X--)(G=Q[X])&&(J=($?G(Z,Y,J):G(J))||J);return $&&J&&Bq0(Z,Y,J),J},Sq0=(Q,Z)=>(Y,$)=>Z(Y,$,Q),WO=class{_appBinder;constructor(Q){this._appBinder=Q}execute(Q,Z){return this._appBinder.signTransaction({transactionArg:Q,skipOpenApp:Z?.skipOpenApp})}};var Su=w(()=>{W0();D1();Bq0=Object.defineProperty,kq0=Object.getOwnPropertyDescriptor;WO=Cq0([e(),Sq0(0,g(gY.AppBinding))],WO)});var wu=()=>new b0(({bind:Q})=>{Q(EG.GetTrustedInputUseCase).to(FO),Q(EG.SignTransactionUseCase).to(WO),Q(EG.SignPcztTransactionUseCase).to(zO)});var _u=w(()=>{W0();EP();ku();Cu();Su()});var vu=({dmk:Q,sessionId:Z})=>{let Y=new T$;return Y.bind(Vq.Dmk).toConstantValue(Q),Y.bind(Vq.SessionId).toConstantValue(Z),Y.loadSync(Hu(),Au(),Eu(),wu(),Nu()),Y};var xu=w(()=>{W0();Du();CE();Pu();Mu();Bu();_u()});class PP{_container;constructor({dmk:Q,sessionId:Z}){this._container=vu({dmk:Q,sessionId:Z})}getAppConfig(){return this._container.get(GO.GetAppConfigUseCase).execute()}getAddress(Q,Z){return this._container.get(LG.GetAddressUseCase).execute(Q,Z)}getFullViewingKey(Q,Z){return this._container.get(LG.GetFullViewingKeyUseCase).execute(Q,Z)}getShieldedAddress(Q,Z){return this._container.get(LG.GetShieldedAddressUseCase).execute(Q,Z)}signTransaction(Q,Z){return this._container.get(EG.SignTransactionUseCase).execute(Q,Z)}signPcztTransaction(Q,Z){return this._container.get(EG.SignPcztTransactionUseCase).execute(Q,Z)}signMessage(Q,Z){return this._container.get(VO.SignMessageUseCase).execute(Q,Z)}getTrustedInput(Q,Z){return this._container.get(EG.GetTrustedInputUseCase).execute(Q,Z)}}var fu=w(()=>{xu();IP();RP();LP();EP()});class yu{_dmk;_sessionId;constructor({dmk:Q,sessionId:Z}){this._dmk=Q,this._sessionId=Z}build(){return new PP({dmk:this._dmk,sessionId:this._sessionId})}}var gu=w(()=>{fu()});var hu=w(()=>{gu()});var bu={};j$(bu,{SignerZcashBuilder:()=>yu});var YFQ;var cu=w(()=>{YFQ=JZ(mJ(),1);hu()});var Y60={};j$(Y60,{preloadLedgerDMK:()=>vH,ledgerWallet:()=>du,getLedgerExtendedPublicKey:()=>ou,getLedgerDMKSession:()=>$1,disconnectLedgerDMKSession:()=>xH,LEDGER_SUPPORTED_CHAINS:()=>dq0});module.exports=oQ(Y60);var jP=require("@scure/base"),_0=require("@swapkit/helpers"),jZ=require("@swapkit/toolboxes/utxo"),UO=require("@swapkit/wallet-core"),K8=require("ts-pattern");var _8=require("@swapkit/helpers"),h1=require("rxjs");var Uq=require("@swapkit/helpers"),RO=require("ts-pattern"),IO={Completed:"completed",Error:"error",Stopped:"stopped"},NY={None:"none",SignTransaction:"sign-transaction",VerifyAddress:"verify-address"},Zp=new Set(["6985","5501"]),U8=["6986"],Yp=new Set(["5515"]),$p=new Set(["6511","6807","6d00","6e00"]),Jp=new Set(["DeviceDisconnectedBeforeSendingApdu","DeviceDisconnectedWhileSendingError","DeviceNotRecognizedError","DeviceSessionNotFound","NoAccessibleDeviceError","ReconnectionFailedError"]),Gp=new Set(["DisconnectedDevice","DisconnectedDeviceDuringOperation"]),Xp=new Set(["UserRefusedOnDevice"]),Vp=4,qp=/^(?:0x)?([0-9a-f]{4})$/i;function Fp(Q){let Z=[],Y=Q;while(Z.length<Vp&&typeof Y==="object"&&Y!==null){let $=Y;Z.push($),Y=$.originalError}return Z}function zp({errorCode:Q,statusCode:Z}){let Y=typeof Q==="string"?qp.exec(Q)?.[1]:void 0;if(Y)return Y.toLowerCase();return typeof Z==="number"?Z.toString(16).padStart(4,"0"):void 0}function NJ(Q,{userRefusedStatusWords:Z=[]}={}){let Y=Fp(Q),$=Y.find((O)=>O instanceof Uq.SwapKitError);if($)return $;let J=Y.flatMap(({_tag:O})=>typeof O==="string"?[O]:[]),X=Y.flatMap(({name:O})=>typeof O==="string"?[O]:[]),G=Y.map(zp).find((O)=>O!==void 0),W=Y.map((O)=>O.message).filter((O)=>typeof O==="string"&&O.length>0).at(-1),U=new Set([...Zp,...Z]),K=RO.match({errorNames:X,errorTags:J,statusWord:G}).when(({errorNames:O,errorTags:I,statusWord:L})=>I.includes("RefusedByUserDAError")||O.some((A)=>Xp.has(A))||!!L&&U.has(L),()=>"wallet_connection_rejected_by_user").when(({errorTags:O,statusWord:I})=>O.includes("DeviceLockedError")||!!I&&Yp.has(I),()=>"wallet_ledger_device_locked").when(({errorTags:O,statusWord:I})=>O.includes("UnsupportedApplicationDAError")||!!I&&$p.has(I),()=>"wallet_ledger_app_not_open").when(({errorNames:O,errorTags:I})=>I.some((L)=>Jp.has(L))||O.some((L)=>Gp.has(L)),()=>"wallet_ledger_connection_error").otherwise(()=>"wallet_ledger_transport_error");return new Uq.SwapKitError({errorKey:K,info:{errorTag:J[0],message:W,statusWord:G}},Q)}function MZ({action:Q,onDeviceActionState:Z,userRefusedStatusWords:Y}){return new Promise(($,J)=>{let X;try{X=Q().observable}catch(K){J(NJ(K,{userRefusedStatusWords:Y}));return}let G=!1,W;function U(K){if(G)return;G=!0,W?.unsubscribe(),K()}if(W=X.subscribe({complete:()=>{U(()=>J(new Uq.SwapKitError("wallet_ledger_invalid_response")))},error:(K)=>{U(()=>J(NJ(K,{userRefusedStatusWords:Y})))},next:(K)=>{try{Z?.(K)}catch(O){}RO.match(K).with({status:IO.Completed},({output:O})=>U(()=>$(O))).with({status:IO.Error},({error:O})=>U(()=>J(NJ(O,{userRefusedStatusWords:Y})))).with({status:IO.Stopped},()=>U(()=>J(new Uq.SwapKitError("wallet_ledger_connection_error")))).otherwise(()=>{return})}}),G)W.unsubscribe()})}var Qa=1000,wH,O$;function Za(){if(typeof navigator>"u"||!("hid"in navigator))return Promise.reject(new _8.SwapKitError("wallet_ledger_webhid_not_supported"));return Promise.all([Promise.resolve().then(() => (I0(),NV)),Promise.resolve().then(() => (Hk(),Ok))]).then(([{DeviceManagementKitBuilder:Q},{webHidTransportFactory:Z}])=>new Q().addTransport(Z).build()).catch((Q)=>{if(wH=void 0,Q instanceof _8.SwapKitError)throw Q;throw new _8.SwapKitError("wallet_ledger_connection_error",Q)})}function Dk(){return wH??=Za(),wH}function _H(){return Dk().then((Q)=>Ik({dmk:Q}))}function Ya(Q){return typeof Q==="object"&&Q!==null&&"_tag"in Q&&Q._tag==="DeviceSessionNotFound"}function $a({dmk:Q,sessionId:Z}){try{return Q.getConnectedDevice({sessionId:Z}),!0}catch(Y){return!1}}async function Ja({sessionPromise:Q}){let Z=Q;try{let Y=await Z;if($a(Y))return Y;if(O$===Z)O$=_H();return O$??=_H(),Z=O$,await Z}catch(Y){if(O$===Z)O$=void 0;if(Y instanceof _8.SwapKitError)throw Y;throw new _8.SwapKitError("wallet_ledger_connection_error",Y)}}async function Ga(){let Q=typeof navigator>"u"?void 0:navigator.hid;if(typeof Q?.getDevices!=="function")return!1;try{let[Z,{LEDGER_VENDOR_ID:Y}]=await Promise.all([Q.getDevices(),Promise.resolve().then(() => (I0(),NV))]);return Z.some(({vendorId:$})=>$===Y)}catch(Z){return!1}}async function Xa({dmk:Q}){if(!await Ga())return;try{return await h1.firstValueFrom(Q.listenToAvailableDevices({}).pipe(h1.map(([Z])=>Z),h1.filter((Z)=>Z!==void 0),h1.timeout({first:Qa})))}catch(Z){return}}async function Ik({dmk:Q}){let Z=!1;try{let Y=await Xa({dmk:Q});if(Y)return{dmk:Q,sessionId:await Q.connect({device:Y})};let $=Q.startDiscovering({});Z=!0;let J=await h1.firstValueFrom($),X=await Q.connect({device:J});return{dmk:Q,sessionId:X}}catch(Y){if(Y instanceof _8.SwapKitError)throw Y;throw new _8.SwapKitError("wallet_ledger_connection_error",Y)}finally{if(Z)try{await Q.stopDiscovering()}catch(Y){}}}function $1({dmk:Q}={}){if(Q)return Ik({dmk:Q});return O$??=_H(),Ja({sessionPromise:O$})}function v8({build:Q,dmkSession:Z}){let Y;return async function(){let J=Z??await $1();if(Y?.session.dmk!==J.dmk||Y.session.sessionId!==J.sessionId){let X=Promise.resolve().then(()=>Q(J));Y={session:J,signer:X};let G=Y;X.catch(()=>{if(Y===G)Y=void 0})}return Y.signer}}function vH(){let Q=Dk();return Q.catch(()=>{return}),Q}async function xH({dmkSession:Q}={}){let Z=O$,Y=Q;if(!Y){if(!Z)return;if(O$===Z)O$=void 0;try{Y=await Z}catch{return}}if(Z)try{let $=await Z;if(O$===Z&&$.dmk===Y.dmk&&$.sessionId===Y.sessionId)O$=void 0}catch($){if(O$===Z)O$=void 0}try{await Y.dmk.disconnect({sessionId:Y.sessionId})}catch($){if(Ya($))return;throw NJ($)}}var VZ=require("@swapkit/helpers"),b1=async({chain:Q,ledgerClient:Z})=>{if(!Z)return"";switch(Q){case VZ.Chain.Cosmos:case VZ.Chain.THORChain:return Z.connect();case VZ.Chain.Ethereum:case VZ.Chain.BinanceSmartChain:case VZ.Chain.Avalanche:case VZ.Chain.Polygon:case VZ.Chain.Arbitrum:case VZ.Chain.Arc:case VZ.Chain.Berachain:case VZ.Chain.Optimism:case VZ.Chain.Base:case VZ.Chain.Aurora:case VZ.Chain.Gnosis:case VZ.Chain.Monad:case VZ.Chain.XLayer:return Z.getAddress();case VZ.Chain.Bitcoin:case VZ.Chain.BitcoinCash:case VZ.Chain.Dash:case VZ.Chain.Dogecoin:case VZ.Chain.Litecoin:case VZ.Chain.Zcash:{let Y=Z;await Y.connect();let $=await Y.getAddress();return Q===VZ.Chain.BitcoinCash?$.replace("bitcoincash:",""):$}case VZ.Chain.Near:return await Z.getAddress();case VZ.Chain.Ripple:return Z.getAddress();case VZ.Chain.Tron:return Z.getAddress();case VZ.Chain.Sui:return Z.connect();default:throw new VZ.SwapKitError("wallet_chain_not_supported",{chain:Q,wallet:VZ.WalletOption.LEDGER})}};var yQ=require("@swapkit/helpers");var RJ=require("@scure/base"),hV=require("@scure/bip32"),hZ=require("@swapkit/helpers"),UI=require("ts-pattern");async function Rk({chain:Q,indexes:Z,publicKey:Y,tx:$}){let{getMissingSpendingMetadata:J,getNetworkForChain:X}=await import("@swapkit/toolboxes/utxo");for(let{index:G,...W}of J({chain:Q,indexes:Z,network:X(Q),publicKey:Y,tx:$}))$.updateInput(G,W)}var Sk=require("@scure/base"),c1=require("@swapkit/helpers");var Ak=require("@swapkit/helpers");function za(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function J1({paramsOrPath:Q,transport:Z}){if(za(Q))return Q;return{derivationPath:Q,transport:Z}}async function OJ({appName:Q,connection:Z,createApp:Y,operation:$,requiredUserInteraction:J=NY.None}){let{dmkSession:X,onDeviceActionState:G,transport:W}=Z;if(X&&W)throw new Ak.SwapKitError("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});if(W)try{return await $(Y(W))}catch(k){throw NJ(k)}let U=X??await $1(),[{CallTaskInAppDeviceAction:K,DmkResultFactory:O,UnknownDeviceExchangeError:I},{LedgerJsDmkTransport:L}]=await Promise.all([Promise.resolve().then(() => (I0(),NV)),Promise.resolve().then(() => (jk(),Pk))]),A=new K({input:{appName:Q,requiredUserInteraction:J,skipOpenApp:!1,task:async(k)=>{try{let B=await $(Y(new L(k)));return O({data:{output:B}})}catch(B){return O({error:new I(B)})}}}});return(await MZ({action:()=>U.dmk.executeDeviceAction({deviceAction:A,sessionId:U.sessionId}),onDeviceActionState:G})).output}var kk=require("@swapkit/helpers"),Mk=100,Tk={cla:224,ins:74},fH=0,Nk=128,Wa=[0,144,0];function Bk(Q,Z){let Y=Q[Z];if(Y===void 0||Y===255)return;if(Y<253)return{size:1,value:Y};let $=Y===253?2:4;if(Z+1+$>Q.length)return;let J=new DataView(Q.buffer,Q.byteOffset+Z+1,$);return{size:1+$,value:$===2?J.getUint16(0,!0):J.getUint32(0,!0)}}function yH(Q,Z){let Y=(G,W={})=>new kk.SwapKitError({errorKey:"wallet_ledger_invalid_params",info:{chain:Z,maxLength:Mk,operation:"splitOutputsForLegacyApp",outputsLength:Q.length,reason:G,...W}}),$=Bk(Q,0);if(!$?.value)throw Y("Transaction outputs do not start with a readable non-zero output count");let J=[],X=$.size;for(let G=0;G<$.value;G+=1){let W=G===0?0:X,U=Bk(Q,X+8),K=U?X+8+U.size+U.value:void 0;if(!K||K>Q.length)throw Y("Transaction output is truncated",{outputIndex:G});let O=K-W;if(O>Mk)throw Y("Output is longer than the Ledger app can check; shorten the memo",{outputIndex:G,pieceLength:O});J.push(Q.subarray(W,K)),X=K}if(X!==Q.length)throw Y("Transaction outputs are followed by trailing bytes",{trailingBytes:Q.length-X});return J}function Ck(Q,Z){let Y=[],$=async(J,X,G,W,U=Buffer.alloc(0),...K)=>{if(!(J===Tk.cla&&X===Tk.ins&&(G===fH||G===Nk)))return Q.send(J,X,G,W,U,...K);if(Y.push(U),G===fH)return Buffer.from(Wa);let I=Buffer.concat(Y);Y=[];let L=yH(I,Z),A=Buffer.alloc(0);for(let[M,k]of L.entries()){let B=M===L.length-1?Nk:fH;A=await Q.send(J,X,B,W,Buffer.from(k),...K)}return A};return new Proxy(Q,{get:(J,X,G)=>X==="send"?$:Reflect.get(J,X,G)})}var wk=["bitcoin-cash","dash","dogecoin","zcash"],Ka=["bitcoin-cash","dash","dogecoin","litecoin"],Ua={bitcoin:"Bitcoin","bitcoin-cash":"Bitcoin Cash",dash:"Dash",dogecoin:"Dogecoin",litecoin:"Litecoin",zcash:"Zcash"},Oa=({outputScriptHex:Q,inputUtxos:Z,btcApp:Y,derivationPath:$,chain:J},X)=>{let G=Z.map((O)=>{return[Y.splitTransaction(O.txHex||"",!wk.includes(J),J==="zcash"),O.index,void 0,void 0]}),W=c1.getWalletFormatFor($),U=W!=="legacy",K={additionals:W==="bech32"?["bech32"]:[],associatedKeysets:G.map(()=>$),inputs:G,outputScriptHex:Q,segwit:U,useTrustedInputForSegwit:U};return Y.createPaymentTransaction({...K,...X})},Ha=({outputScriptHex:Q,inputUtxos:Z,btcApp:Y,derivationPaths:$,chain:J},X)=>{if($.length!==Z.length)throw new c1.SwapKitError("wallet_ledger_invalid_params",{message:`Derivation paths count (${$.length}) must match inputs count (${Z.length})`});let G=Z.map((O)=>{return[Y.splitTransaction(O.txHex||"",!wk.includes(J),J==="zcash"),O.index,void 0,void 0]}),W=c1.getWalletFormatFor($[0]??""),U=W!=="legacy",K={additionals:W==="bech32"?["bech32"]:[],associatedKeysets:$,inputs:G,outputScriptHex:Q,segwit:U,useTrustedInputForSegwit:U};return Y.createPaymentTransaction({...K,...X})},wV=({chain:Q,additionalSignParams:Z})=>{let Y=Ka.includes(Q);return($,J)=>{let{derivationPath:X,...G}=J1({paramsOrPath:$,transport:J}),W=typeof X==="string"?X:c1.derivationPathToString(X),U=c1.getWalletFormatFor(W);async function K({operation:I,requiredUserInteraction:L}){let A=(await import("@ledgerhq/hw-app-btc")).default;return OJ({appName:Ua[Q],connection:G,createApp:(M)=>new A({currency:Q,transport:Y?Ck(M,Q):M}),operation:I,requiredUserInteraction:L})}async function O(I){let[{splitTransaction:L},{serializeTransactionOutputs:A}]=await Promise.all([import("@ledgerhq/hw-app-btc/splitTransaction"),import("@ledgerhq/hw-app-btc/serializeTransaction")]),M=A(L(Sk.hex.encode(I.unsignedTx),!0));if(Y)yH(M,Q);return M.toString("hex")}return{connect:async()=>{await K({operation:async()=>!0})},disconnect:async()=>{},getAddress:async()=>{let{toCashAddress:I}=await import("@swapkit/toolboxes/utxo"),{bitcoinAddress:L}=await K({operation:(A)=>A.getWalletPublicKey(W,{format:U})});if(!L)throw new c1.SwapKitError("wallet_ledger_get_address_error",{message:`Cannot get ${Q} address from ledger derivation path: ${W}`});return Q==="bitcoin-cash"&&U==="legacy"?I(L).replace(/(bchtest:|bitcoincash:)/,""):L},getExtendedPublicKey:async(I="84'/0'/0'",L=76067358)=>{return await K({operation:(A)=>A.getWalletXpub({path:I,xpubVersion:L})})},signTransaction:async(I,L)=>{let A=await O(I);return await K({operation:(M)=>Oa({btcApp:M,chain:Q,derivationPath:W,inputUtxos:L,outputScriptHex:A},Z),requiredUserInteraction:NY.SignTransaction})},signTransactionWithMultiplePaths:async(I,L,A)=>{let M=await O(I);return await K({operation:(k)=>Ha({btcApp:k,chain:Q,derivationPaths:A,inputUtxos:L,outputScriptHex:M},Z),requiredUserInteraction:NY.SignTransaction})}}}},_k=wV({chain:"bitcoin"}),vk=wV({chain:"litecoin"}),xk=wV({additionalSignParams:{additionals:["abc","cashaddr"],segwit:!1,sigHashType:65,useTrustedInputForSegwit:!0},chain:"bitcoin-cash"}),fk=wV({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dogecoin"}),yk=wV({additionalSignParams:{additionals:[],segwit:!1,useTrustedInputForSegwit:!1},chain:"dash"}),gk=wV({additionalSignParams:{additionals:["zcash","sapling"],expiryHeight:(()=>{let Q=Buffer.alloc(4);return Q.writeUInt32LE(0),Q})(),lockTime:0,segwit:!1,useTrustedInputForSegwit:!1},chain:"zcash"});gH();function e_(Q){return(typeof Q==="string"?Q:hZ.derivationPathToString(Q)).replace(/^m\//,"").replace(/^\/+/,"")}function t_({path:Q,reason:Z}){return new hZ.SwapKitError("wallet_ledger_invalid_params",{path:Q,reason:Z})}function Qv(Q){let Z=e_(Q),Y=/^(44|49|84|86)'\/0'\/(\d+)'(?:\/(0|1)\/(\d+))?$/.exec(Z);if(!Y)throw t_({path:Z,reason:"Expected a Bitcoin path with purpose 44, 49, 84, or 86 and coin type 0"});let $=Number(Y[1]),J=Number(Y[2]),X=Number(Y[3]??0),G=Number(Y[4]??0);if(J>=hV.HARDENED_OFFSET||G>=hV.HARDENED_OFFSET)throw t_({path:Z,reason:"Account and address index must be below 2^31"});let W=`${$}'/0'/${J}'`;return{accountPath:W,addressIndex:G,change:X,fullPath:`${W}/${X}/${G}`,purpose:$}}function cQ0(Q){if(Q.length!==4)throw new hZ.SwapKitError("wallet_ledger_invalid_response",{reason:`Expected a 4-byte master fingerprint, received ${Q.length}`});return new DataView(Q.buffer,Q.byteOffset,Q.byteLength).getUint32(0,!1)}function KI({count:Q,tx:Z}){if(Q!==Z.inputsLength)throw new hZ.SwapKitError("wallet_ledger_invalid_params",{reason:`Input metadata count (${Q}) must match transaction inputs count (${Z.inputsLength})`})}function uQ0({accountPath:Q,derivationPaths:Z,tx:Y}){KI({count:Z.length,tx:Y});let $=Z.map(Qv),J=$.find((X)=>X.accountPath!==Q);if(J)throw new hZ.SwapKitError("wallet_ledger_invalid_params",{accountPath:Q,path:J.fullPath,reason:"All input derivation paths must belong to the configured Bitcoin account"});return $}function pQ0(Q){return Promise.resolve().then(() => (lK(),pK)).then(({DefaultDescriptorTemplate:Z})=>UI.match(Q).with(44,()=>Z.LEGACY).with(49,()=>Z.NESTED_SEGWIT).with(84,()=>Z.NATIVE_SEGWIT).with(86,()=>Z.TAPROOT).exhaustive())}function lQ0(Q){return"signature"in Q&&"pubkey"in Q}function s8({inputIndex:Q,reason:Z}){return new hZ.SwapKitError("wallet_ledger_invalid_response",{inputIndex:Q,reason:Z})}async function mQ0({input:Q,inputIndex:Z,previousTransaction:Y}){if(!(Y&&Q.txid&&Q.index!==void 0))throw s8({inputIndex:Z,reason:"PSBT input is missing its previous output"});let{RawTx:$,utils:J}=await import("@swapkit/utxo-signer"),X=$.encode({...Y,segwitFlag:!1,witnesses:void 0}),G=J.sha256x2(X).reverse();if(RJ.hex.encode(G)!==RJ.hex.encode(Q.txid))throw new hZ.SwapKitError("wallet_ledger_invalid_params",{inputIndex:Z,reason:"Previous transaction does not match the input txid"});let W=Y.outputs[Q.index];if(!W)throw s8({inputIndex:Z,reason:"Previous transaction has no spent output"});let{witnessUtxo:U}=Q;if(U&&(U.amount!==W.amount||RJ.hex.encode(U.script)!==RJ.hex.encode(W.script)))throw new hZ.SwapKitError("wallet_ledger_invalid_params",{inputIndex:Z,reason:"Input witnessUtxo does not match the previous transaction output"});return W}async function dQ0({inputIndex:Q,path:Z,publicKey:Y,spentOutput:$}){let{p2pkh:J,p2sh:X,p2tr:G,p2wpkh:W}=await import("@swapkit/utxo-signer"),U=UI.match(Z.purpose).with(44,()=>J(Y).script).with(49,()=>X(W(Y)).script).with(84,()=>W(Y).script).with(86,()=>G(Y.slice(1)).script).exhaustive();if(RJ.hex.encode(U)===RJ.hex.encode($.script))return;throw new hZ.SwapKitError("wallet_ledger_invalid_params",{inputIndex:Q,path:Z.fullPath,reason:"Input does not spend the script derived from its derivation path"})}function Zv({derivationPath:Q=hZ.NetworkDerivationPath.BTC,dmkSession:Z,onDeviceActionState:Y,transport:$}={}){let J=Qv(Q),X=$?_k(Q,$):void 0,G=v8({build:async(_)=>{let{SignerBtcBuilder:x}=await Promise.resolve().then(() => (lK(),pK));return new x(_).build()},dmkSession:Z}),W,U;function K(){if(X)throw new hZ.SwapKitError("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return G()}function O(){if(!W){W=K().then(async(x)=>{let{extendedPublicKey:f}=await MZ({action:()=>x.getExtendedPublicKey(J.accountPath),onDeviceActionState:Y});return f});let _=W;_.catch(()=>{if(W===_)W=void 0})}return W}function I(){if(!U){U=K().then(async(x)=>{let{masterFingerprint:f}=await MZ({action:()=>x.getMasterFingerprint(),onDeviceActionState:Y});return cQ0(f)});let _=U;_.catch(()=>{if(U===_)U=void 0})}return U}async function L(){let _=X?await X.getExtendedPublicKey(J.accountPath):await O(),{publicKey:x}=hV.HDKey.fromExtendedKey(_).derive(`m/${J.change}/${J.addressIndex}`);if(!x)throw new hZ.SwapKitError("wallet_ledger_invalid_response",{path:J.fullPath,reason:"Could not derive a public key from the Ledger account xpub"});return x}async function A(){let[{DefaultWallet:_},x]=await Promise.all([Promise.resolve().then(() => (lK(),pK)),pQ0(J.purpose)]);return new _(J.accountPath,x)}async function M({inputUtxos:_,tx:x}){let{RawTx:f}=await import("@swapkit/utxo-signer"),i=Array.from({length:x.inputsLength},(Z0,t)=>t).some((Z0)=>!(x.getInput(Z0).nonWitnessUtxo||_?.[Z0]?.txHex))?await import("@swapkit/toolboxes/utxo").then(({getUtxoApi:Z0})=>{let t=Z0(hZ.Chain.Bitcoin);return SV((c)=>t.getRawTx(c))}):void 0;return Promise.all(Array.from({length:x.inputsLength},async(Z0,t)=>{let c=x.getInput(t);if(c.nonWitnessUtxo)return c.nonWitnessUtxo;if(!c.txid)throw s8({inputIndex:t,reason:"PSBT input is missing its previous txid"});let l=_?.[t]?.txHex??await i?.(RJ.hex.encode(c.txid));if(!l)throw new hZ.SwapKitError("wallet_ledger_invalid_params",{inputIndex:t,reason:"Unable to resolve the previous transaction for Ledger signing"});return f.decode(RJ.hex.decode(l))}))}async function k({inputUtxos:_,paths:x,tx:f}){let[h,i,Z0]=await Promise.all([O(),I(),M({inputUtxos:_,tx:f})]),{bip32Path:t}=await import("@swapkit/utxo-signer"),c=hV.HDKey.fromExtendedKey(h),l=f.clone(),V=[];for(let[z,H]of x.entries()){let F=c.derive(`m/${H.change}/${H.addressIndex}`).publicKey;if(!F)throw new hZ.SwapKitError("wallet_ledger_invalid_response",{inputIndex:z,reason:"Could not derive a public key from the Ledger account xpub"});V[z]=F;let D=l.getInput(z),P=Z0[z],j=await mQ0({input:D,inputIndex:z,previousTransaction:P});await dQ0({inputIndex:z,path:H,publicKey:F,spentOutput:j});let R={fingerprint:i,path:t(`m/${H.fullPath}`)};if(H.purpose===86){let q=F.slice(1);l.updateInput(z,{tapBip32Derivation:[[q,{der:R,hashes:[]}]],tapInternalKey:q,witnessUtxo:j})}else l.updateInput(z,{bip32Derivation:[[F,R]],nonWitnessUtxo:P,witnessUtxo:H.purpose===44?void 0:j});await Rk({chain:hZ.Chain.Bitcoin,indexes:[z],publicKey:F,tx:l})}return{psbt:l,publicKeys:V}}async function B({inputUtxos:_,paths:x,tx:f}){let[h,i,{psbt:Z0,publicKeys:t}]=await Promise.all([K(),A(),k({inputUtxos:_,paths:x,tx:f})]),c=Z0.toPSBT(0),l=await MZ({action:()=>h.signPsbt(i,c),onDeviceActionState:Y}),V=new Set;for(let z of l){if(!lQ0(z))throw s8({reason:"Unexpected MuSig2 signature"});let{inputIndex:H,pubkey:F}=z,D=x[H],P=t[H];if(!(D&&P)||V.has(H))throw s8({inputIndex:H,reason:"Unexpected or duplicate input signature"});if(V.add(H),D.purpose===86){if(z.tapleafHash)throw s8({inputIndex:H,reason:"Unexpected taproot script signature"});Z0.updateInput(H,{tapKeySig:z.signature});continue}if(RJ.hex.encode(F)!==RJ.hex.encode(P))throw s8({inputIndex:H,reason:"Signature public key does not match the input derivation"});Z0.updateInput(H,{partialSig:[[P,z.signature]]})}if(V.size!==Z0.inputsLength)throw s8({reason:`Ledger signed ${V.size} of ${Z0.inputsLength} inputs`});return Z0}function C(_){return _.finalize(),_.hex}function S({tx:_,inputUtxos:x}){if(x)KI({count:x.length,tx:_});if(X)return x?X.signTransaction(_,x):y6({chain:hZ.Chain.Bitcoin,legacyClient:X,tx:_});let f=Array.from({length:_.inputsLength},()=>J);return B({inputUtxos:x,paths:f,tx:_}).then(C)}return{connect:async()=>{if(X)return X.connect();await K()},disconnect:async()=>X?.disconnect(),getAddress:async()=>{if(X)return X.getAddress();let _=await K(),x=await A(),{address:f}=await MZ({action:()=>_.getWalletAddress(x,J.addressIndex,{change:J.change===1}),onDeviceActionState:Y});if(!f)throw new hZ.SwapKitError("wallet_ledger_get_address_error",{path:J.fullPath});return f},getExtendedPublicKey:async({checkOnDevice:_=!1,path:x=J.accountPath}={})=>{if(X)return X.getExtendedPublicKey(x);let f=await K(),h=e_(x),{extendedPublicKey:i}=await MZ({action:()=>f.getExtendedPublicKey(h,{checkOnDevice:_}),onDeviceActionState:Y});return i},getPublicKey:L,showAddressAndPubKey:async()=>{if(X)return{address:await X.getAddress()};let _=await K(),x=await A();return MZ({action:()=>_.getWalletAddress(x,J.addressIndex,{change:J.change===1,checkOnDevice:!0}),onDeviceActionState:Y})},signTransaction:async(_)=>{if(X){let f=await y6({chain:hZ.Chain.Bitcoin,legacyClient:X,tx:_}),{Transaction:h}=await import("@swapkit/utxo-signer");return h.fromRaw(RJ.hex.decode(f),{allowUnknownOutputs:!0})}let x=Array.from({length:_.inputsLength},()=>J);return await B({paths:x,tx:_})},signTransactionHex:S,signTransactionWithMultiplePaths:async({derivationPaths:_,inputUtxos:x,tx:f})=>{if(x)KI({count:x.length,tx:f});let h=uQ0({accountPath:J.accountPath,derivationPaths:_,tx:f});if(X){let i=x??await HW(f,hZ.Chain.Bitcoin);return X.signTransactionWithMultiplePaths(f,i,h.map((Z0)=>`m/${Z0.fullPath}`))}return B({inputUtxos:x,paths:h,tx:f}).then(C)}}}var YU=require("@scure/base"),gJ=require("@swapkit/helpers");var Yv=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,nQ0=Yv>>1n;function oQ0(Q){return Q.reduce((Z,Y)=>Z<<8n|BigInt(Y),0n)}function sQ0(Q){let Z=new Uint8Array(32),Y=Q;for(let $=31;$>=0;$-=1)Z[$]=Number(Y&0xffn),Y>>=8n;return Z}function mK(Q){let Z=oQ0(Q.subarray(32,64));if(Z<=nQ0)return Q;let Y=new Uint8Array(64);return Y.set(Q.subarray(0,32),0),Y.set(sQ0(Yv-Z),32),Y}function PZ0(Q){let Z=(typeof Q==="string"?Q:gJ.derivationPathToString(Q)).replace(/^m\//,"").replace(/^\/+/,"");if(!/^44'\/118'\/\d+'\/(0|1)\/\d+$/.test(Z))throw new gJ.SwapKitError("wallet_ledger_invalid_params",{path:Z,reason:"Expected a five-level Cosmos derivation path with coin type 118"});return Z}async function kv(Q){let{Secp256k1Signature:Z}=await import("@cosmjs/crypto");try{return mK(Q.length===64?Z.fromFixedLength(Q).toFixedLength():Z.fromDer(Q).toFixedLength())}catch(Y){throw new gJ.SwapKitError("wallet_ledger_invalid_response",Y)}}class TI{chain="cosmos";derivationPath;onDeviceActionState;transport;legacyAppPromise;pubKey=null;getSessionSigner;constructor({derivationPath:Q=gJ.NetworkDerivationPath.GAIA,dmkSession:Z,onDeviceActionState:Y,transport:$}={}){this.derivationPath=PZ0(Q),this.getSessionSigner=v8({build:async(J)=>{let{SignerCosmosBuilder:X}=await Promise.resolve().then(() => (Bv(),Nv));return new X(J).build()},dmkSession:Z}),this.onDeviceActionState=Y,this.transport=$}getSigner(){if(this.transport)throw new gJ.SwapKitError("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return this.getSessionSigner()}getLegacyApp(){if(!this.transport)throw new gJ.SwapKitError("wallet_ledger_invalid_params",{reason:"Legacy Cosmos transport is unavailable"});return this.legacyAppPromise??=import("@ledgerhq/hw-app-cosmos").then(({default:Q})=>new Q(this.transport)),this.legacyAppPromise}async runLegacyOperation(Q){let Z=await this.getLegacyApp();try{return await Q(Z)}catch(Y){throw NJ(Y,{userRefusedStatusWords:U8})}}async signBytes(Q){if(this.transport){let $=await this.runLegacyOperation((J)=>J.sign(this.derivationPath,new TextDecoder().decode(Q)));if($.return_code!==36864||!$.signature)throw new gJ.SwapKitError("wallet_ledger_invalid_response",{returnCode:$.return_code});return kv($.signature)}let Z=await this.getSigner(),Y=await MZ({action:()=>Z.signTransaction(this.derivationPath,this.chain,Q),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:U8});return kv(Y)}async connect(){if(this.transport)await this.getLegacyApp();else await this.getSigner();let{address:Q,publicKey:Z}=await this.getAddressAndPubKey();return this.pubKey=Buffer.from(Z,"hex").toString("base64"),Q}async disconnect(){}async getAddressAndPubKey(){if(this.transport)return this.runLegacyOperation(($)=>$.getAddress(this.derivationPath,this.chain));let Q=await this.getSigner(),{address:Z,publicKey:Y}=await MZ({action:()=>Q.getAddress(this.derivationPath,this.chain),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:U8});return{address:Z,publicKey:YU.hex.encode(Y)}}async showAddressAndPubKey(){if(this.transport)return this.runLegacyOperation(($)=>$.getAddress(this.derivationPath,this.chain,!0));let Q=await this.getSigner(),{address:Z,publicKey:Y}=await MZ({action:()=>Q.getAddress(this.derivationPath,this.chain,{checkOnDevice:!0}),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:U8});return{address:Z,publicKey:YU.hex.encode(Y)}}async signTransaction(Q,Z="0"){let Y=await this.signBytes(typeof Q==="string"?new TextEncoder().encode(Q):Q);if(!this.pubKey){let{publicKey:$}=await this.getAddressAndPubKey();this.pubKey=Buffer.from($,"hex").toString("base64")}return[{pub_key:{type:"tendermint/PubKeySecp256k1",value:this.pubKey},sequence:Z,signature:Y}]}async signAmino(Q,Z){let $=(await this.getAccounts()).find(({address:W})=>W===Q);if(!$)throw new gJ.SwapKitError("wallet_ledger_address_not_found",{address:Q});let{encodeSecp256k1Signature:J,serializeSignDoc:X}=await import("@cosmjs/amino"),G=await this.signBytes(X(Z));return{signature:J($.pubkey,G),signed:Z}}async getAccounts(){let{address:Q,publicKey:Z}=await this.getAddressAndPubKey();return[{address:Q,algo:"secp256k1",pubkey:YU.hex.decode(Z)}]}}var HZ=require("@swapkit/helpers"),Vb=require("ethers");function RX0({primaryType:Q,types:Z}){let Y={};function $(J){if(Object.hasOwn(Y,J)||!Object.hasOwn(Z,J))return;let X=Z[J];if(!X)return;Y[J]=X;for(let G of X)$(G.type.replace(/\[[0-9]*\]/g,""))}if($(Q),!Object.hasOwn(Y,Q))throw new HZ.SwapKitError("wallet_ledger_invalid_params",{primaryType:Q,reason:"The EIP-712 primary type is not defined"});return Y}var LX0={report:()=>Promise.resolve(void 0)};class L$ extends Vb.AbstractSigner{chainId=HZ.ChainId.Ethereum;derivationPath="";dmkSession;getLedgerSigner;onDeviceActionState;originToken;constructor({provider:Q,dmkSession:Z,derivationPath:Y=HZ.NetworkDerivationPath.OP,chainId:$=HZ.ChainId.Optimism,onDeviceActionState:J,originToken:X}){super(Q);this.chainId=$||HZ.ChainId.Ethereum,this.derivationPath=(typeof Y==="string"?Y:HZ.derivationPathToString(Y)).replace(/^m\//,""),this.dmkSession=Z,this.onDeviceActionState=J,this.originToken=X,this.getLedgerSigner=v8({build:async(G)=>{let[{ContextModuleBuilder:W,ContextModuleChainID:U},{SignerEthBuilder:K}]=await Promise.all([Promise.resolve().then(() => (X$(),Ny)),Promise.resolve().then(() => (Xb(),Gb))]),O=new W({loggerFactory:(I)=>G.dmk.getLoggerFactory()(["ContextModule",I]),originToken:X}).setChain(U.Ethereum).setBlindSigningReporter(LX0).build();return O.signReport=()=>Promise.resolve(),new K({...G,originToken:X}).withContextModule(O).build()},dmkSession:Z}),Object.defineProperty(this,"provider",{enumerable:!0,value:Q||null,writable:!1})}connect=(Q)=>new L$({chainId:this.chainId,derivationPath:this.derivationPath,dmkSession:this.dmkSession,onDeviceActionState:this.onDeviceActionState,originToken:this.originToken,provider:Q});getAddress=async()=>{let{address:Q}=await this.getAddressAndPubKey();if(!Q)throw new HZ.SwapKitError("wallet_ledger_failed_to_get_address");return Q};getAddressAndPubKey=async()=>{let Q=await this.getLedgerSigner();return MZ({action:()=>Q.getAddress(this.derivationPath,{chainId:Number(this.chainId)}),onDeviceActionState:this.onDeviceActionState})};showAddressAndPubKey=async()=>{let Q=await this.getLedgerSigner();return MZ({action:()=>Q.getAddress(this.derivationPath,{chainId:Number(this.chainId),checkOnDevice:!0}),onDeviceActionState:this.onDeviceActionState})};signMessage=async(Q)=>{let{Signature:Z,toUtf8Bytes:Y}=await import("ethers"),$=typeof Q==="string"?Y(Q):Q,J=await this.getLedgerSigner(),X=await MZ({action:()=>J.signMessage(this.derivationPath,$),onDeviceActionState:this.onDeviceActionState});return Z.from(X).serialized};signTypedData=async(Q,Z,Y,$)=>{let{buildEIP712DomainType:J}=await import("@swapkit/toolboxes/evm"),{hexlify:X,Signature:G,TypedDataEncoder:W}=await import("ethers"),{EIP712Domain:U,...K}=Z,O=$??W.from(K).primaryType,I=RX0({primaryType:O,types:K}),L=await W.resolveNames(Q,I,Y,async(S)=>{let _=await this.resolveName(S);if(!_)throw new HZ.SwapKitError("wallet_ledger_invalid_params",{name:S});return _}),A=L.domain.chainId==null?void 0:Number(L.domain.chainId);if(A!==void 0&&!Number.isSafeInteger(A))throw new HZ.SwapKitError("wallet_ledger_invalid_params",{chainId:L.domain.chainId});let k={domain:{...L.domain.chainId!=null&&{chainId:A},...L.domain.name!=null&&{name:L.domain.name},...L.domain.salt!=null&&{salt:X(L.domain.salt)},...L.domain.verifyingContract!=null&&{verifyingContract:L.domain.verifyingContract},...L.domain.version!=null&&{version:L.domain.version}},message:L.value,primaryType:O,types:{EIP712Domain:J(L.domain),...I}},B=await this.getLedgerSigner(),C=await MZ({action:()=>B.signTypedData(this.derivationPath,k),onDeviceActionState:this.onDeviceActionState});return G.from(C).serialized};signTransaction=async(Q)=>{let{copyRequest:Z,getAddress:Y,getBytes:$,resolveAddress:J,resolveProperties:X,Transaction:G}=await import("ethers"),W=Z(Q);if(W.type===4||W.authorizationList?.length)throw new HZ.SwapKitError("wallet_ledger_invalid_params",{message:"Ledger Ethereum DSK does not support EIP-7702 transactions"});let U=BigInt(this.chainId);if(W.chainId!=null&&W.chainId!==U)throw new HZ.SwapKitError("wallet_ledger_invalid_params",{chainId:W.chainId,expectedChainId:U,message:"Transaction chainId does not match the Ledger client chain"});let{from:K,to:O}=await X({from:W.from?J(W.from,this):void 0,to:W.to?J(W.to,this):void 0}),I=K||W.nonce==null?await this.getAddress():void 0;if(K&&I&&Y(K)!==Y(I))throw new HZ.SwapKitError("wallet_ledger_invalid_params",{message:"Transaction from address does not match the Ledger account"});if(O)W.to=O;if(delete W.from,delete W.authorizationList,W.chainId=U,W.type==null&&W.gasPrice!=null&&W.accessList==null&&W.maxFeePerGas==null&&W.maxPriorityFeePerGas==null)W.type=0;W.nonce??=await this.provider?.getTransactionCount(I??await this.getAddress());let A=G.from(W),M=$(A.unsignedSerialized),k=await this.getLedgerSigner(),B=await MZ({action:()=>k.signTransaction(this.derivationPath,M),onDeviceActionState:this.onDeviceActionState});return A.signature=B,A.serialized}}function qb(Q){return new L$({...Q,chainId:HZ.ChainId.Arbitrum})}function Fb(Q){return new L$({...Q,chainId:HZ.ChainId.Arc})}function zb(Q){return new L$({...Q,chainId:HZ.ChainId.Aurora})}function Wb(Q){return new L$({...Q,chainId:HZ.ChainId.Avalanche})}function Kb(Q){return new L$({...Q,chainId:HZ.ChainId.Base})}function Ub(Q){return new L$({...Q,chainId:HZ.ChainId.Ethereum})}function Ob(Q){return new L$({...Q,chainId:HZ.ChainId.Gnosis})}function Hb(Q){return new L$({...Q,chainId:HZ.ChainId.Optimism})}function Db(Q){return new L$({...Q,chainId:HZ.ChainId.Polygon})}function Ib(Q){return new L$({...Q,chainId:HZ.ChainId.BinanceSmartChain})}function Rb(Q){return new L$({...Q,chainId:HZ.ChainId.Monad})}function Lb(Q){return new L$({...Q,chainId:HZ.ChainId.XLayer})}function Eb(Q){return new L$({...Q,chainId:HZ.ChainId.Berachain})}var O1=require("@swapkit/helpers");async function Pb(Q,Z){let{derivationPath:Y,...$}=J1({paramsOrPath:Q,transport:Z}),J=(Y||O1.NetworkDerivationPath[O1.Chain.Near]).join("'/").concat("'");async function X({operation:K,requiredUserInteraction:O}){let I=(await import("@ledgerhq/hw-app-near")).default;return OJ({appName:"NEAR",connection:$,createApp:(L)=>new I(L),operation:K,requiredUserInteraction:O})}let{address:G,publicKey:W}=await X({operation:(K)=>K.getAddress(J)});return{getAddress(){return Promise.resolve(G)},async getPublicKey(){let{PublicKey:K}=await import("@near-js/crypto"),O=W.startsWith("ed25519:")?W:`ed25519:${W}`;return K.fromString(O)},signDelegateAction(K){return Promise.reject(new O1.SwapKitError("wallet_ledger_method_not_supported",{method:"signDelegateAction",wallet:"Ledger"}))},signNep413Message(K,O,I,L,A){return Promise.reject(new O1.SwapKitError("wallet_ledger_method_not_supported",{method:"signNep413Message",wallet:"Ledger"}))},async signTransaction(K){let{Signature:O,SignedTransaction:I}=await import("@near-js/transactions");try{let L=await X({operation:(k)=>k.signTransaction(K.encode(),J),requiredUserInteraction:NY.SignTransaction});if(!L)throw new O1.SwapKitError("wallet_ledger_signing_error",{reason:"Ledger returned no NEAR signature"});let A=new O({data:L,keyType:0}),M=new I({signature:A,transaction:K});return[L,M]}catch(L){if(L instanceof O1.SwapKitError)throw L;throw new O1.SwapKitError("wallet_ledger_signing_error",{error:L})}}}}var n$=require("@swapkit/helpers");class jb{derivationPath;address=null;publicKey=null;connection;constructor(Q,Z){let{derivationPath:Y,...$}=J1({paramsOrPath:Q,transport:Z});this.derivationPath=typeof Y==="string"?Y:n$.derivationPathToString(Y||n$.NetworkDerivationPath[n$.Chain.Sui]),this.connection=$}getLedgerPath(){return this.derivationPath.replace(/^m\//,"").replace(/\/(\d+)\/(\d+)$/,"/$1'/$2'")}async runSuiOperation({operation:Q,requiredUserInteraction:Z}){let Y=(await import("@ledgerhq/hw-app-sui")).default;return OJ({appName:"Sui",connection:this.connection,createApp:($)=>new Y($),operation:Q,requiredUserInteraction:Z})}async connect(){let Q=this.getLedgerPath(),Z=await this.runSuiOperation({operation:(Y)=>Y.getPublicKey(Q)});if(!Z?.publicKey)throw new n$.SwapKitError("wallet_ledger_failed_to_get_address");return this.publicKey=Z.publicKey,this.address=`0x${Buffer.from(Z.address).toString("hex")}`,this.address}toSuiAddress(){if(!this.address)throw new n$.SwapKitError("wallet_ledger_failed_to_get_address");return this.address}async getAddress(){if(this.address)return this.address;return await this.connect()}async signTransaction(Q){let Z=Q instanceof Uint8Array?Q:Q.transaction;if(!this.publicKey)throw new n$.SwapKitError("wallet_ledger_failed_to_get_address");try{let Y=this.getLedgerPath(),$=new Uint8Array(3+Z.length);$.set(Z,3);let J=await this.runSuiOperation({operation:(W)=>W.signTransaction(Y,$),requiredUserInteraction:NY.SignTransaction});if(!J?.signature)throw new n$.SwapKitError("wallet_ledger_signing_error");let X=this.publicKey.length===33?this.publicKey.slice(1):this.publicKey;if(X.length!==32)throw new n$.SwapKitError("wallet_ledger_signing_error",{error:"Invalid public key length"});let G=new Uint8Array(97);return G.set(J.signature,1),G.set(X,65),{bytes:Buffer.from(Z).toString("base64"),signature:Buffer.from(G).toString("base64")}}catch(Y){if(Y instanceof n$.SwapKitError)throw Y;throw new n$.SwapKitError("wallet_ledger_signing_error",{error:Y})}}}function Ab(Q,Z){return new jb(Q,Z)}var yX=require("@scure/base"),gX=require("@swapkit/helpers");var q8=require("@swapkit/helpers"),Nb=85,EX0=4,PX0=0,ME=2,jX0=0,AX0=1,Mb=2,TE=36864,Tb=250;class h4{name="THORChainCommand";params;constructor(Q){this.params=Q}getApdu(){let{data:Q=new Uint8Array,ins:Z,p1:Y=0,p2:$=0}=this.params;return{cla:Nb,data:Q,ins:Z,p1:Y,p2:$}}parseResponse(Q){let Z=(Q.statusCode[0]??0)*256+(Q.statusCode[1]??0);if(Z!==TE)throw Error(`THORChain app returned status 0x${Z.toString(16).padStart(4,"0")}`);return Q.data}}function Bb({path:Q}){if(Q.length!==5)throw new q8.SwapKitError("wallet_ledger_invalid_params",{reason:"THORChain path must contain five elements"});let Z=new Uint8Array(20),Y=new DataView(Z.buffer);return Q.forEach(($,J)=>{if(typeof $!=="number"||!Number.isInteger($)||$<0||$>4294967295)throw new q8.SwapKitError("wallet_ledger_invalid_params",{reason:`Invalid THORChain path segment ${J}`});if(J>=3&&$>=2147483648)throw new q8.SwapKitError("wallet_ledger_invalid_params",{reason:`THORChain path segment ${J} must not be hardened`});let X=$&2147483647,G=J<3?(X|2147483648)>>>0:X;Y.setUint32(J*4,G,!0)}),Z}function MX0({hrp:Q,path:Z}){let Y=new TextEncoder().encode(Q);if(Y.length<1||Y.length>83)throw new q8.SwapKitError("wallet_ledger_invalid_params",{reason:"Invalid THORChain address prefix"});let $=Bb({path:Z});return Uint8Array.from([Y.length,...Y,...$])}function kb({checkOnDevice:Q,hrp:Z,path:Y}){return new h4({data:MX0({hrp:Z,path:Y}),ins:EX0,p1:Q?1:0})}function Cb({message:Q,path:Z}){let Y=[new h4({data:Bb({path:Z}),ins:ME,p1:jX0})];if(Q.length===0)return Y.push(new h4({data:new Uint8Array,ins:ME,p1:Mb})),Y;for(let $=0;$<Q.length;$+=Tb){let J=Math.min($+Tb,Q.length);Y.push(new h4({data:Q.slice($,J),ins:ME,p1:J===Q.length?Mb:AX0}))}return Y}function Sb({response:Q}){if(Q.length<2)throw new q8.SwapKitError("wallet_ledger_invalid_response",{reason:"THORChain response is missing status bytes"});return Q.slice(0,-2)}async function wb({transport:Q}){let Z=await Q.send(Nb,PX0,0,0,Buffer.alloc(0),[TE]),Y=Sb({response:Z});if(Y.length<4)throw new q8.SwapKitError("wallet_ledger_invalid_response",{reason:"Invalid THORChain version response"});return`${Y[1]}.${Y[2]}.${Y[3]}`}async function _b({command:Q,transport:Z}){let Y=Q.getApdu(),$=await Z.send(Y.cla,Y.ins,Y.p1,Y.p2,Buffer.from(Y.data),[TE]);return Sb({response:$})}function vb({response:Q}){if(Q.length<34)throw new q8.SwapKitError("wallet_ledger_invalid_response",{reason:"Invalid THORChain address response"});let Z=Q.slice(0,33),Y=new TextDecoder().decode(Q.slice(33));if(!Y)throw new q8.SwapKitError("wallet_ledger_invalid_response",{reason:"THORChain address is empty"});return{address:Y,publicKey:Z}}function NE({version:Q}){return`THORChain Ledger app major 2 is required, received ${Q||"unknown"}`}var TX0="THORChain";function NX0(Q){if(typeof Q==="string")return Q;let Z=Q.chain?.toUpperCase(),Y=(Q.symbol||Q.ticker||"").toUpperCase();if(!(Z&&Y))return Y||Z||"";return`${Z}${Q.synth?"/":"."}${Y}`}function BX0(Q){return{...Q,msgs:Q.msgs.map((Z)=>{if(!Z.type.includes("MsgDeposit"))return Z;let Y=Z.value.coins;if(!Array.isArray(Y))return Z;return{...Z,value:{...Z.value,coins:Y.map(($)=>({...$,asset:NX0($.asset)}))}}})}}async function kX0({signature:Q}){let{Secp256k1Signature:Z}=await import("@cosmjs/crypto");try{return mK(Z.fromDer(Q).toFixedLength())}catch(Y){throw new gX.SwapKitError("wallet_ledger_invalid_signature",Y)}}async function CX0({commands:Q,transport:Z}){let Y=await wb({transport:Z});if(!Y.startsWith("2.")){let{InvalidResponseFormatError:J}=await Promise.resolve().then(() => (I0(),NV));throw new J(NE({version:Y}))}let $=new Uint8Array;for(let J of Q)$=await _b({command:J,transport:Z});return $}class BE{derivationPath;dmkSession;onDeviceActionState;pubKey;transport;constructor({derivationPath:Q=gX.NetworkDerivationPath.THOR,dmkSession:Z,onDeviceActionState:Y,transport:$}={}){if(Z&&$)throw new gX.SwapKitError("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});this.derivationPath=Q,this.dmkSession=Z,this.onDeviceActionState=Y,this.transport=$}get pubkey(){return this.pubKey?yX.base64.encode(this.pubKey):null}executeCommands=async({commands:Q,requiredUserInteraction:Z})=>{if(this.transport)try{return await CX0({commands:Q,transport:this.transport})}catch(M){throw NJ(M,{userRefusedStatusWords:U8})}let Y=this.dmkSession??await $1(),{Apdu:$,CallTaskInAppDeviceAction:J,CommandResultFactory:X,DmkResultFactory:G,InvalidResponseFormatError:W,InvalidStatusWordError:U,isSuccessCommandResult:K,UnknownDeviceExchangeError:O}=await Promise.resolve().then(() => (I0(),NV)),I=(M)=>{let k=M.getApdu();return{getApdu:()=>new $(k.cla,k.ins,k.p1,k.p2,k.data),name:M.name,parseResponse:(B)=>{try{return X({data:M.parseResponse(B)})}catch(C){let S=yX.hex.encode(B.statusCode);return X({error:Object.assign(new U(C instanceof Error?C.message:String(C)),{errorCode:S})})}}}},L=new J({input:{appName:TX0,requiredUserInteraction:Z,skipOpenApp:!1,task:async(M)=>{try{let k=M.getDeviceSessionState(),B="currentApp"in k?k.currentApp.version:void 0;if(!B?.startsWith("2."))return G({error:new W(NE({version:B}))});let C=new Uint8Array;for(let S of Q){let _=await M.sendCommand(I(S));if(!K(_))return G({error:_.error});C=_.data}return G({data:{response:C}})}catch(k){return G({error:new O(k)})}}}});return(await MZ({action:()=>Y.dmk.executeDeviceAction({deviceAction:L,sessionId:Y.sessionId}),onDeviceActionState:this.onDeviceActionState,userRefusedStatusWords:U8})).response};getAddressData=async({checkOnDevice:Q})=>{let Z=await this.executeCommands({commands:[kb({checkOnDevice:Q,hrp:"thor",path:this.derivationPath})],requiredUserInteraction:Q?NY.VerifyAddress:NY.None});return vb({response:Z})};signBytes=async({message:Q})=>{let Z=await this.executeCommands({commands:Cb({message:Q,path:this.derivationPath}),requiredUserInteraction:NY.SignTransaction});return kX0({signature:Z})};connect=async()=>{let{address:Q,publicKey:Z}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Z,Q};getAddressAndPubKey=async()=>{let{address:Q,publicKey:Z}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Z,{bech32_address:Q,compressed_pk:Z,error_message:"No errors",return_code:36864}};showAddressAndPubKey=async()=>{let{address:Q,publicKey:Z}=await this.getAddressData({checkOnDevice:!0});return this.pubKey=Z,{bech32_address:Q,compressed_pk:Z,error_message:"No errors",return_code:36864}};signTransaction=async({rawTx:Q,sequence:Z="0"})=>{if(!this.pubKey)await this.connect();let Y=this.pubKey;if(!Y)throw new gX.SwapKitError("wallet_ledger_pubkey_not_found");let $=await this.signBytes({message:new TextEncoder().encode(Q)});return[{pub_key:{type:"tendermint/PubKeySecp256k1",value:yX.base64.encode(Y)},sequence:Z,signature:yX.base64.encode($)}]};signAmino=async(Q,Z)=>{let Y=(await this.getAccounts()).find(({address:G})=>G===Q);if(!Y)throw new gX.SwapKitError("wallet_ledger_address_not_found",{address:Q});let{encodeSecp256k1Signature:$,serializeSignDoc:J}=await import("@cosmjs/amino"),X=await this.signBytes({message:J(BX0(Z))});return{signature:$(Y.pubkey,X),signed:Z}};getAccounts=async()=>{let{address:Q,publicKey:Z}=await this.getAddressData({checkOnDevice:!1});return this.pubKey=Z,[{address:Q,algo:"secp256k1",pubkey:Z}]};sign=async(Q)=>yX.base64.encode(await this.signBytes({message:new TextEncoder().encode(Q)}))}var H1=require("@swapkit/helpers");class xb{derivationPath;ledgerTimeout=50000;connection;constructor(Q,Z){let{derivationPath:Y,...$}=J1({paramsOrPath:Q,transport:Z});this.derivationPath=typeof Y==="string"?Y:H1.derivationPathToString(Y||H1.NetworkDerivationPath.TRON),this.connection=$}async runTronOperation({operation:Q,requiredUserInteraction:Z}){let Y=(await import("@ledgerhq/hw-app-trx")).default;return OJ({appName:"Tron",connection:this.connection,createApp:($)=>new Y($),operation:Q,requiredUserInteraction:Z})}checkOrCreateTransportAndLedger=async()=>{await this.runTronOperation({operation:async()=>!0})};createTransportAndLedger=async()=>{await this.runTronOperation({operation:async()=>!0})};getAddress=async()=>{let Q=await this.getAddressAndPubKey();if(!Q)throw new H1.SwapKitError("wallet_ledger_failed_to_get_address");return Q.address};getAddressAndPubKey=async()=>{let Q=await this.runTronOperation({operation:(Z)=>Z.getAddress(this.derivationPath)});if(!Q)throw new H1.SwapKitError("wallet_ledger_failed_to_get_address");return{address:Q.address,publicKey:Q.publicKey}};showAddressAndPubKey=async()=>{return await this.runTronOperation({operation:(Q)=>Q.getAddress(this.derivationPath,!0),requiredUserInteraction:NY.VerifyAddress})};signTransaction=async(Q)=>{try{let Z=await this.runTronOperation({operation:(Y)=>Y.signTransaction(this.derivationPath,Q.raw_data_hex,[]),requiredUserInteraction:NY.SignTransaction});if(!Z)throw new H1.SwapKitError("wallet_ledger_signing_error");return{...Q,signature:[Z]}}catch(Z){if(Z instanceof H1.SwapKitError)throw Z;throw new H1.SwapKitError("wallet_ledger_signing_error",{error:Z})}}}function fb(Q,Z){return new xb(Q,Z)}var Xq=require("@swapkit/helpers");var SX0=2147483648;function wX0(Q){return Object.fromEntries(Object.entries(Q).filter(([,Z])=>Z!==null&&Z!==void 0))}async function yb(Q,Z){let{derivationPath:Y,...$}=J1({paramsOrPath:Q,transport:Z}),J=Xq.derivationPathToString(Y||Xq.NetworkDerivationPath[Xq.Chain.Ripple]);async function X({operation:K,requiredUserInteraction:O}){let I=(await import("@ledgerhq/hw-app-xrp")).default;return OJ({appName:"XRP",connection:$,createApp:(L)=>new I(L),operation:K,requiredUserInteraction:O})}let{address:G,publicKey:W}=await X({operation:(K)=>K.getAddress(J)});async function U(K){let[{encode:O},{hashes:I}]=await Promise.all([import("ripple-binary-codec"),import("xrpl")]),L={...wX0(K),Flags:K.Flags||SX0,SigningPubKey:W.toUpperCase()},A=O(L),M=await X({operation:(C)=>C.signTransaction(J,A),requiredUserInteraction:NY.SignTransaction}),k=O({...L,TxnSignature:M});return{hash:I.hashSignedTx(k),tx_blob:k}}return{getAddress:()=>G,signTransaction:U}}var MJ=require("@scure/base"),i$=require("@swapkit/helpers");var wq0=3364600;function uu(Q){return(typeof Q==="string"?Q:i$.derivationPathToString(Q)).replace(/^m\//,"").replace(/^\/+/,"")}function KO(Q){let Z=uu(Q),Y=/^44'\/133'\/(\d+)'(?:\/(0|1)\/(\d+))?$/.exec(Z);if(!Y)throw new i$.SwapKitError("wallet_ledger_invalid_params",{path:Z,reason:"Expected a Zcash BIP44 path with coin type 133"});let $=Number(Y[1]),J=`44'/133'/${$}'`;return{account:$,accountPath:J,fullPath:`${J}/${Y[2]??0}/${Y[3]??0}`}}function _q0(Q){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,Q>>>0,!0),Z}function vq0(Q){let Z=new Uint8Array(8);return new DataView(Z.buffer).setBigUint64(0,Q,!0),Z}function Wq(Q,Z){return new i$.SwapKitError({errorKey:"wallet_ledger_invalid_params",info:Q},Z)}function xq0({bytes:Q,offset:Z}){if(Z+4>Q.length)throw Error("Unexpected end of previous transaction");return new DataView(Q.buffer,Q.byteOffset+Z,4).getUint32(0,!0)}function fq0(Q){let Z=0;function Y(J){if(Z+J>Q.length)throw Error(`Previous transaction ends before byte ${Z+J}`);return Z+=J,Q.slice(Z-J,Z)}function $(){let J=Y(1)[0]??0;if(J<253)return J;let X=new DataView(Y(J===253?2:J===254?4:8).buffer),G=X.byteLength===2?X.getUint16(0,!0):X.byteLength===4?X.getUint32(0,!0):Number(X.getBigUint64(0,!0));if(!Number.isSafeInteger(G))throw Error("Previous transaction compact-size value exceeds safe range");return G}return{compactSize:$,rest:()=>Y(Q.length-Z),take:Y,varBytes:()=>Y($())}}function yq0({bytes:Q,version:Z}){let Y=fq0(Q),$=Y.take(Z===4?8:20),J=[];for(let K=Y.compactSize();J.length<K;){let O=Y.take(36),I=Y.varBytes(),L=Y.take(4);J.push({prevout:O,script:I,sequence:L})}let X=[];for(let K=Y.compactSize();X.length<K;){let O=Y.take(8),I=Y.varBytes();X.push({amount:O,script:I})}let G={inputs:J,nVersionGroupId:$.slice(4,8),outputs:X,version:$.slice(0,4)};if(Z>=5)return{...G,consensusBranchId:$.slice(8,12),locktime:$.slice(12,16),nExpiryHeight:$.slice(16,20)};let W=Y.take(4),U=Y.take(4);return{...G,extraData:Y.rest(),locktime:W,nExpiryHeight:U}}function pu({hash:Q,txid:Z}){let Y=Q.toLowerCase();return Y===MJ.hex.encode(Z)||Y===MJ.hex.encode(Z.slice().reverse())}async function gq0(Q){let{CompactSize:Z,utils:Y}=await import("@swapkit/utxo-signer"),$=Array.from({length:Q.outputsLength},(J,X)=>Q.getOutput(X));return Y.concatBytes(Z.encode(BigInt($.length)),...$.flatMap(({amount:J,script:X})=>[vq0(J),Z.encode(BigInt(X.length)),X]))}async function hq0(Q){let{ZCASH_IRONWOOD_ACTIVATION_HEIGHT:Z,ZcashConsensusBranchId:Y}=await import("@swapkit/utxo-signer");switch(Q){case Y.NU6_2:return wq0;case Y.IRONWOOD:return Z;default:throw new i$.SwapKitError("wallet_ledger_invalid_params",{consensusBranchId:Q,reason:"Ledger Zcash DSK signing supports NU6.2 and Ironwood target branches"})}}async function bq0({inputIndex:Q,utxo:Z}){let{hash:Y,index:$,txHex:J}=Z,X={inputIndex:Q,outputIndex:$,txid:Y};if(!J)throw Wq({...X,reason:"Zcash Ledger signing requires the full previous transaction txHex for every input"});function G(A){try{return A()}catch(M){throw Wq({...X,reason:M instanceof Error?M.message:String(M)},M)}}let W=G(()=>MJ.hex.decode(J.replace(/^0x/i,""))),U=G(()=>xq0({bytes:W,offset:0})),K=U&2147483647;if((U&2147483648)===0||K<4||K>6)throw Wq({...X,reason:"Ledger Zcash signing supports only overwintered v4, v5 and v6 previous transactions",version:K});let O=G(()=>yq0({bytes:W,version:K}));if($<0||$>=O.outputs.length)throw Wq({...X,outputCount:O.outputs.length,reason:"Zcash input references an output outside its previous transaction"});if(K>=5)return{...O,serializedPreviousTransactionOverride:W};let{utils:I}=await import("@swapkit/utxo-signer"),L=I.sha256x2(W);if(!pu({hash:Y,txid:L}))throw Wq({...X,previousTxid:MJ.hex.encode(L.reverse()),reason:"Previous transaction does not hash to the input txid"});return O}function cq0({accountPath:Q,derivationPaths:Z,inputUtxos:Y,tx:$}){if(Y.length!==$.inputsLength||Z.length!==$.inputsLength)throw new i$.SwapKitError("wallet_ledger_invalid_params",{derivationPathCount:Z.length,inputCount:$.inputsLength,inputUtxoCount:Y.length,reason:"Zcash input UTXOs and derivation paths must match the transaction input count"});return Y.forEach((J,X)=>{let G=$.getInput(X);if(!pu({hash:J.hash,txid:G.txid})||J.index!==G.index)throw Wq({inputIndex:X,reason:"Zcash input UTXO does not match the transaction input",transactionInput:{index:G.index,txid:MJ.hex.encode(G.txid)},utxo:{hash:J.hash,index:J.index}})}),Z.map((J)=>{let X=KO(J);if(X.accountPath!==Q)throw new i$.SwapKitError("wallet_ledger_invalid_params",{accountPath:Q,path:X.fullPath,reason:"All Zcash input derivation paths must belong to the configured account"});return X.fullPath})}function uq0(Q){let Z=Q.replace(/^0x/i,""),Y=MJ.hex.decode(Z);if(Y.length<4||(new DataView(Y.buffer,Y.byteOffset,4).getUint32(0,!0)&2147483647)!==5)throw new i$.SwapKitError("wallet_ledger_invalid_response",{reason:"Ledger Zcash signer did not return a version 5 transaction"});return Z}function lu({derivationPath:Q=i$.NetworkDerivationPath.ZEC,dmkSession:Z,onDeviceActionState:Y,transport:$}={}){let J=KO(Q),X=$?gk(Q,$):void 0,G=v8({build:async(I)=>{let{SignerZcashBuilder:L}=await Promise.resolve().then(() => (cu(),bu));return new L(I).build()},dmkSession:Z});function W(){if(X)throw new i$.SwapKitError("wallet_ledger_invalid_params",{reason:"A Device Signer Kit operation is unavailable when a legacy transport is supplied"});return G()}async function U({checkOnDevice:I=!1,path:L=J.fullPath}={}){let A=await W();return MZ({action:()=>A.getAddress(L,{checkOnDevice:I}),onDeviceActionState:Y})}async function K({path:I=J.accountPath,xpubVersion:L=76067358}={}){let A=KO(I);if(A.fullPath!==`${A.accountPath}/0/0`||uu(I).split("/").length!==3)throw new i$.SwapKitError("wallet_ledger_invalid_params",{path:I,reason:"Zcash extended public keys are exported at account level"});let M={dmkSession:$?void 0:Z??await $1(),onDeviceActionState:Y,transport:$},{default:k}=await import("@ledgerhq/hw-app-btc");return OJ({appName:"Zcash",connection:M,createApp:(B)=>new k({currency:"zcash",transport:B}),operation:(B)=>B.getWalletXpub({path:A.accountPath,xpubVersion:L})})}async function O({changePath:I,derivationPaths:L,inputUtxos:A,tx:M}){let k=cq0({accountPath:J.accountPath,derivationPaths:L??Array.from({length:M.inputsLength},()=>J.fullPath),inputUtxos:A,tx:M});if(X)throw new i$.SwapKitError("wallet_ledger_invalid_params",{reason:"Zcash signing requires a Ledger DMK session instead of a legacy transport"});let B=await hq0(M.consensusBranchId),C=await Promise.all(A.map(async(f,h)=>[await bq0({inputIndex:h,utxo:f}),f.index,null,M.getInput(h).sequence??4294967295])),S={additionals:["zcash","sapling"],associatedKeysets:k,blockHeight:B,changePath:I?KO(I).fullPath:J.fullPath,expiryHeight:_q0(M.expiryHeight),inputs:C,lockTime:M.lockTime,outputScriptHex:MJ.hex.encode(await gq0(M))},_=await W(),x=await MZ({action:()=>_.signTransaction(S),onDeviceActionState:Y});return uq0(x)}return{connect:async()=>{if(X)return X.connect();await W()},disconnect:async()=>X?.disconnect(),getAddress:async()=>{if(X)return X.getAddress();return(await U()).address},getAddressAndPubKey:async()=>{if(X)return{address:await X.getAddress()};let{address:I,chainCode:L,publicKey:A}=await U();return{address:I,chainCode:MJ.hex.encode(L),publicKey:MJ.hex.encode(A)}},getExtendedPublicKey:K,showAddressAndPubKey:async()=>{if(X)return{address:await X.getAddress()};let{address:I,chainCode:L,publicKey:A}=await U({checkOnDevice:!0});return{address:I,chainCode:MJ.hex.encode(L),publicKey:MJ.hex.encode(A)}},signTransaction:O,signTransactionWithMultiplePaths:async(I)=>O(I)}}async function TJ({chain:Q,dmkSession:Z,derivationPath:Y,onDeviceActionState:$,originToken:J,transport:X}){let G=yQ.EVMChains.includes(Q);if(Z&&X)throw new yQ.SwapKitError("wallet_ledger_invalid_params",{message:"Provide either a Ledger DMK session or a LedgerJS transport, not both"});if(G&&X)throw new yQ.SwapKitError("wallet_ledger_invalid_params",{message:"Ledger EVM clients require a DMK session instead of a LedgerJS transport"});let W={derivationPath:Y??yQ.NetworkDerivationPath[Q],dmkSession:Z,onDeviceActionState:$,transport:X},{match:U}=await import("ts-pattern");return U(Q).returnType().with(yQ.Chain.THORChain,()=>Promise.resolve(new BE(W))).with(yQ.Chain.Cosmos,()=>Promise.resolve(new TI(W))).with(yQ.Chain.Bitcoin,()=>Promise.resolve(Zv(W))).with(yQ.Chain.BitcoinCash,()=>Promise.resolve(xk(W))).with(yQ.Chain.Dash,()=>Promise.resolve(yk(W))).with(yQ.Chain.Dogecoin,()=>Promise.resolve(fk(W))).with(yQ.Chain.Litecoin,()=>Promise.resolve(vk(W))).with(yQ.Chain.Zcash,()=>Promise.resolve(lu(W))).with(yQ.Chain.Ripple,()=>Promise.resolve(yb(W))).with(yQ.Chain.Tron,()=>Promise.resolve(fb(W))).with(yQ.Chain.Sui,()=>Promise.resolve(Ab(W))).with(yQ.Chain.Near,()=>Promise.resolve(Pb(W))).with(yQ.Chain.Arbitrum,yQ.Chain.Arc,yQ.Chain.Aurora,yQ.Chain.Avalanche,yQ.Chain.Berachain,yQ.Chain.BinanceSmartChain,yQ.Chain.Ethereum,yQ.Chain.Gnosis,yQ.Chain.Monad,yQ.Chain.Optimism,yQ.Chain.Polygon,yQ.Chain.Base,yQ.Chain.XLayer,async()=>{let{getProvider:K}=await import("@swapkit/toolboxes/evm"),O={derivationPath:Y,dmkSession:Z,onDeviceActionState:$,originToken:J,provider:await K(Q)};return U(Q).with(yQ.Chain.BinanceSmartChain,()=>Ib(O)).with(yQ.Chain.Avalanche,()=>Wb(O)).with(yQ.Chain.Arbitrum,()=>qb(O)).with(yQ.Chain.Arc,()=>Fb(O)).with(yQ.Chain.Berachain,()=>Eb(O)).with(yQ.Chain.Optimism,()=>Hb(O)).with(yQ.Chain.Polygon,()=>Db(O)).with(yQ.Chain.Base,()=>Kb(O)).with(yQ.Chain.Aurora,()=>zb(O)).with(yQ.Chain.Gnosis,()=>Ob(O)).with(yQ.Chain.Monad,()=>Rb(O)).with(yQ.Chain.XLayer,()=>Lb(O)).otherwise(()=>Ub(O))}).otherwise(()=>{throw new yQ.SwapKitError("wallet_chain_not_supported",{chain:Q,wallet:yQ.WalletOption.LEDGER})})}var mu=[_0.Chain.Arbitrum,_0.Chain.Arc,_0.Chain.Aurora,_0.Chain.Avalanche,_0.Chain.Base,_0.Chain.Berachain,_0.Chain.BinanceSmartChain,_0.Chain.Bitcoin,_0.Chain.BitcoinCash,_0.Chain.Cosmos,_0.Chain.Dash,_0.Chain.Dogecoin,_0.Chain.Ethereum,_0.Chain.Gnosis,_0.Chain.Litecoin,_0.Chain.Monad,_0.Chain.Near,_0.Chain.Optimism,_0.Chain.Polygon,_0.Chain.Ripple,_0.Chain.Sui,_0.Chain.THORChain,_0.Chain.XLayer,_0.Chain.Tron,_0.Chain.Zcash],pq0=[_0.Chain.BitcoinCash,_0.Chain.Bitcoin,_0.Chain.Dash,_0.Chain.Dogecoin,_0.Chain.Litecoin,_0.Chain.Zcash],lq0=[_0.Chain.Ethereum,_0.Chain.Avalanche,_0.Chain.Arbitrum,_0.Chain.Arc,_0.Chain.Berachain,_0.Chain.Optimism,_0.Chain.Polygon,_0.Chain.BinanceSmartChain,_0.Chain.Base,_0.Chain.Aurora,_0.Chain.Gnosis,_0.Chain.Monad,_0.Chain.XLayer];function mq0(Q){return mu.includes(Q)}var du=UO.createWallet({connect:({addChain:Q,supportedChains:Z,walletType:Y})=>async function(J,X,{address:G,dmkSession:W,onDeviceActionState:U,originToken:K,transport:O}={}){let[I]=_0.filterSupportedChains({chains:J,supportedChains:Z,walletType:Y});if(!I)return!1;let L=X??_0.NetworkDerivationPath[I],A=await Z60({address:G,chain:I,derivationPath:L,dmkSession:W,onDeviceActionState:U,originToken:K,transport:O});return Q({...A,chain:I,walletType:_0.WalletOption.LEDGER}),!0},directSigningSupport:{[_0.Chain.Arbitrum]:!0,[_0.Chain.Arc]:!0,[_0.Chain.Aurora]:!0,[_0.Chain.Avalanche]:!0,[_0.Chain.Base]:!0,[_0.Chain.Berachain]:!0,[_0.Chain.BinanceSmartChain]:!0,[_0.Chain.Ethereum]:!0,[_0.Chain.Gnosis]:!0,[_0.Chain.Monad]:!0,[_0.Chain.Bitcoin]:!0,[_0.Chain.BitcoinCash]:!0,[_0.Chain.Cosmos]:!0,[_0.Chain.Dash]:!0,[_0.Chain.Dogecoin]:!0,[_0.Chain.Litecoin]:!0,[_0.Chain.Near]:!0,[_0.Chain.Optimism]:!0,[_0.Chain.Polygon]:!0,[_0.Chain.Ripple]:!0,[_0.Chain.Sui]:!0,[_0.Chain.THORChain]:!0,[_0.Chain.Tron]:!0,[_0.Chain.XLayer]:!0},getExtendedPublicKey:ou,name:"connectLedger",supportedChains:[...mu],walletType:_0.WalletOption.LEDGER}),dq0=UO.getWalletSupportedChains(du);function nu({chain:Q,path:Z,signer:Y,xpubVersion:$}){let J=K8.match(Q).with(_0.Chain.Bitcoin,_0.Chain.Litecoin,()=>Z).with(_0.Chain.BitcoinCash,_0.Chain.Dash,_0.Chain.Dogecoin,_0.Chain.Zcash,()=>Z.replace(/^m\//,"")).exhaustive();return K8.match(Q).with(_0.Chain.Bitcoin,()=>Y.getExtendedPublicKey({path:J})).with(_0.Chain.Zcash,()=>Y.getExtendedPublicKey({path:J,xpubVersion:$})).with(_0.Chain.BitcoinCash,_0.Chain.Dash,_0.Chain.Dogecoin,_0.Chain.Litecoin,()=>Y.getExtendedPublicKey(J,$)).exhaustive()}function nq0(Q){let Z=jZ.getUtxoApi(_0.Chain.Zcash),Y=SV(($)=>Z.getRawTx($));return Promise.all(Array.from({length:Q.inputsLength},async($,J)=>{let X=Q.getInput(J),G=jP.hex.encode(X.txid),W=jP.hex.encode(X.txid.slice().reverse()),U=await Y(G),[K,O]=U?[G,U]:[W,await Y(W)];if(!O)throw new _0.SwapKitError("wallet_ledger_invalid_params",{inputIndex:J,outputIndex:X.index,reason:"Unable to resolve previous transaction hex for Ledger signing in either txid byte order",reversedTxid:W,txid:G});return{hash:K,index:X.index,txHex:O,value:Number(X.value)}}))}async function ou(Q,Z,{accountIndex:Y,dmkSession:$,onDeviceActionState:J,transport:X}={}){if(![_0.Chain.BitcoinCash,_0.Chain.Bitcoin,_0.Chain.Dash,_0.Chain.Dogecoin,_0.Chain.Litecoin,_0.Chain.Zcash].includes(Q))throw new _0.SwapKitError("wallet_chain_not_supported",{chain:Q,wallet:_0.WalletOption.LEDGER});let G=Q,W=await TJ({chain:G,derivationPath:Z,dmkSession:$,onDeviceActionState:J,transport:X});if(!W.getExtendedPublicKey)return;let U=jZ.getUTXOAccountPath({accountIndex:Y,chain:G,derivationPath:Z}),K=_0.derivationPathToString(U),O=jZ.getNetworkForChain(G).bip32.public;try{let I=await nu({chain:G,path:K,signer:W,xpubVersion:O});return{accountIndex:jZ.getUTXOAccountIndexFromPath(U),path:K,xpub:I}}finally{await W.disconnect?.()}}async function oq0({address:Q,chain:Z,dmkSession:Y,derivationPath:$,onDeviceActionState:J,transport:X}){let{getUtxoToolbox:G}=await import("@swapkit/toolboxes/utxo"),W=Z,U=await TJ({chain:Z,derivationPath:$,dmkSession:Y,onDeviceActionState:J,transport:X}),K=Q??await b1({chain:Z,ledgerClient:U}),O=(Z===_0.Chain.Bitcoin?_0.getUTXOScriptTypeForPath($):void 0)??jZ.getScriptTypeForAddress(K,W),{publicKey:I,signLedgerTransaction:L,toolboxSigner:A}=await K8.match(Z).with(_0.Chain.Bitcoin,async()=>{let i=U,t=O===_0.UTXOScriptType.P2SH_P2WPKH||O===_0.UTXOScriptType.P2TR?await i.getPublicKey():void 0;return{publicKey:t,signLedgerTransaction:({inputUtxos:c,transaction:l})=>i.signTransactionHex({inputUtxos:c,tx:l}),toolboxSigner:{getAddress:i.getAddress,publicKey:t,signTransaction:i.signTransaction}}}).with(_0.Chain.BitcoinCash,_0.Chain.Dogecoin,_0.Chain.Dash,_0.Chain.Litecoin,async()=>{let{createLegacyPsbtSigner:i,signLegacyPsbtTransaction:Z0}=await Promise.resolve().then(() => (gH(),bk)),t=U;return{publicKey:void 0,signLedgerTransaction:({inputUtxos:c,transaction:l})=>Z0({chain:W,inputUtxos:c,legacyClient:t,tx:l}),toolboxSigner:i({address:K,chain:W,legacyClient:t})}}).with(_0.Chain.Zcash,()=>{let i=U;return{publicKey:void 0,signLedgerTransaction:async({inputUtxos:Z0,transaction:t})=>{if(!("consensusBranchId"in t))throw new _0.SwapKitError("wallet_ledger_method_not_supported",{method:"signPCZT",wallet:_0.WalletOption.LEDGER});let c=Z0??await nq0(t);return i.signTransaction({inputUtxos:c,tx:t})},toolboxSigner:void 0}}).exhaustive(),M=A?await G(W,{scriptType:O,signer:A}):G(W,{scriptType:O}),k=async(i)=>M.broadcastTx(await L({transaction:i})),B=async(i)=>{let Z0=i.feeRate||(await M.getFeeRates())[i.feeOptionKey||_0.FeeOption.Fast],{tx:t,inputs:c}=await M.createTransaction({...i,feeRate:Z0,fetchTxHex:!0,publicKey:i.publicKey??I,sender:K}),l=await L({inputUtxos:c,transaction:t});return await M.broadcastTx(l)};async function C({accountIndex:i}={}){if(!U.getExtendedPublicKey)return;let Z0=jZ.getUTXOAccountPath({accountIndex:i,chain:W,derivationPath:$}),t=_0.derivationPathToString(Z0),c=jZ.getNetworkForChain(W).bip32.public,l=await nu({chain:Z,path:t,signer:U,xpubVersion:c});return{accountIndex:jZ.getUTXOAccountIndexFromPath(Z0),path:t,xpub:l}}function S(i={}){return C(i)}async function _({accountIndex:i,index:Z0,change:t=!1}){try{let c=jZ.getUTXOAddressPath({accountIndex:i,chain:W,change:t,derivationPath:$,index:Z0}),l=await TJ({chain:W,derivationPath:c,dmkSession:Y,onDeviceActionState:J,transport:X}),V=await b1({chain:W,ledgerClient:l});return{accountIndex:jZ.getUTXOAccountIndexFromPath(c),address:V,change:t,index:Z0,path:_0.derivationPathToString(c),pubkey:""}}catch{return}}async function x({accountIndex:i,count:Z0,startIndex:t=0,change:c=!1}){return jZ.assertDerivationIndex("count",Z0),jZ.assertDerivationIndex("startIndex",t),(await Promise.all(Array.from({length:Z0},(V,z)=>_({accountIndex:i,change:c,index:t+z})))).filter((V)=>!!V)}let f=jZ.createHDWalletHelpers({chain:W,deriveAddress:_,getBalance:M.getBalance,getUtxos:(i)=>jZ.getUtxoApi(W).getUtxos({address:i,fetchTxHex:!0})});async function h({utxos:i,recipient:Z0,assetValue:t,memo:c,feeRate:l,feeOptionKey:V,changeAddress:z}){if(Z===_0.Chain.Zcash)throw new _0.SwapKitError("wallet_ledger_method_not_supported",{method:"transferFromMultipleAddresses",wallet:_0.WalletOption.LEDGER});if(!i.length)throw new _0.SwapKitError("wallet_ledger_invalid_params",{message:"No UTXOs provided for multi-address transfer"});let H=l||(await M.getFeeRates())[V||_0.FeeOption.Fast],F=c?jZ.compileMemo(c):null,D=[{address:Z0,value:t.getBaseValue("number")}];if(F)D.push({script:F,value:0});let P=i.map(({hash:y,index:p,value:J0,txHex:x0,witnessUtxo:K0})=>({hash:y,index:p,txHex:x0,value:J0,witnessUtxo:K0})),{inputs:j,outputs:R}=M.accumulative({chain:W,feeRate:H,inputs:P,outputs:D});if(!(j&&R))throw new _0.SwapKitError("wallet_ledger_connection_error",{message:"Insufficient balance for multi-address transfer"});let{Transaction:q}=await import("@swapkit/utxo-signer"),E=new q({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!F,version:1}),N=z||i[0]?.address||Z0;jZ.addInputsAndOutputs({chain:W,compiledMemo:F,inputs:j,outputs:R,sender:N,tx:E});let T=j.map((y)=>{let p=i.find((x0)=>x0.hash===y.hash&&x0.index===y.index),J0=jZ.getUTXOAddressPath({chain:W,change:p?.isChange??!1,derivationPath:$,index:p?.derivationIndex??0});return _0.derivationPathToString(J0)});if(!U.signTransactionWithMultiplePaths)throw new _0.SwapKitError("wallet_ledger_method_not_supported",{method:"signTransactionWithMultiplePaths"});let v=await K8.match(Z).with(_0.Chain.Bitcoin,()=>U.signTransactionWithMultiplePaths({derivationPaths:T,inputUtxos:j,tx:E})).with(_0.Chain.BitcoinCash,_0.Chain.Dash,_0.Chain.Dogecoin,_0.Chain.Litecoin,()=>U.signTransactionWithMultiplePaths(E,j,T)).exhaustive();return M.broadcastTx(v)}return{...M,...f,address:K,deriveAddressAtIndex:_,deriveAddresses:x,getExtendedPublicKey:S,getExtendedPublicKeyInfo:C,signAndBroadcastTransaction:k,transfer:B,transferFromMultipleAddresses:h}}async function sq0({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,originToken:J,transport:X}){let G=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,originToken:J,transport:X}),{getEvmToolboxAsync:W}=await import("@swapkit/toolboxes/evm"),U=await b1({chain:Q,ledgerClient:G});return{...await W(Q,{signer:G}),address:U}}async function iq0({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}){let X=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}),{getCosmosToolbox:G}=await import("@swapkit/toolboxes/cosmos"),W=G(Q,{signer:X}),U=await b1({chain:Q,ledgerClient:X});return{...W,address:U}}async function aq0({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}){let X=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}),{getCosmosToolbox:G}=await import("@swapkit/toolboxes/cosmos"),W=G(Q,{signer:X}),U=await b1({chain:Q,ledgerClient:X}),{sign:K}=X;return{...W,address:U,signMessage:K}}async function rq0({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}){let{getNearToolbox:X}=await import("@swapkit/toolboxes/near"),G=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}),W=await G.getAddress();return{...X({signer:G}),address:W}}async function tq0({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}){let{getRippleToolbox:X}=await import("@swapkit/toolboxes/ripple"),G=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}),W=G.getAddress();return{...X({signer:G}),address:W}}async function eq0({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}){let{getTronToolbox:X}=await import("@swapkit/toolboxes/tron"),G=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}),W=await b1({chain:Q,ledgerClient:G});return{...X({signer:G}),address:W}}async function Q60({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}){let{getSuiToolbox:X}=await import("@swapkit/toolboxes/sui"),G=await TJ({chain:Q,derivationPath:Z,dmkSession:Y,onDeviceActionState:$,transport:J}),W=await b1({chain:Q,ledgerClient:G});return{...X({signer:G}),address:W}}function Z60(Q){if(!mq0(Q.chain))throw new _0.SwapKitError("wallet_ledger_chain_not_supported",{chain:Q.chain});return K8.match(Q.chain).with(K8.P.union(...pq0),(Z)=>oq0({...Q,chain:Z})).with(K8.P.union(...lq0),(Z)=>sq0({...Q,chain:Z})).with(_0.Chain.Cosmos,(Z)=>iq0({...Q,chain:Z})).with(_0.Chain.THORChain,(Z)=>aq0({...Q,chain:Z})).with(_0.Chain.Near,(Z)=>rq0({...Q,chain:Z})).with(_0.Chain.Ripple,(Z)=>tq0({...Q,chain:Z})).with(_0.Chain.Tron,(Z)=>eq0({...Q,chain:Z})).with(_0.Chain.Sui,(Z)=>Q60({...Q,chain:Z})).exhaustive()}
|
|
90
|
+
|
|
91
|
+
//# debugId=2326BC1892B379F864756E2164756E21
|
|
4
92
|
//# sourceMappingURL=index.cjs.map
|