coinley-test 0.40.103 โ 0.42.104
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/coinley-vanilla.min.js +143 -34
- package/dist/coinley-vanilla.min.js.map +1 -1
- package/dist/index.esm.js +43393 -3712
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +132 -2
- package/dist/index.umd.js.map +1 -1
- package/dist/style.css +1 -1
- package/package.json +14 -7
package/dist/index.umd.js
CHANGED
|
@@ -1,3 +1,133 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react"),require("wagmi"),require("@tanstack/react-query"),require("@wagmi/core"),require("@wagmi/core/chains"),require("@wagmi/connectors"),require("viem"),require("react-dom"),require("qrcode"),require("axios"),require("react-dom/client")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react","wagmi","@tanstack/react-query","@wagmi/core","@wagmi/core/chains","@wagmi/connectors","viem","react-dom","qrcode","axios","react-dom/client"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.React,e.Wagmi,e.ReactQuery,e.WagmiCore,e.chains,e.connectors,e.Viem,e.ReactDOM,e.QRCode,e.axios,e.ReactDOM)}(this,function(e,t,n,s,a,r,i,o,c,l,d,m,u){"use strict";const h="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABxCAYAAAAj+QZ8AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAzrSURBVHgB7V3dcRs5Em4MtXWPq41gZ1+v7mwrgh3rArAUgagITNcFYDmAK9ERSBuBfQGsxY3Aku26V/MiOO7j1nqAQwMgRQ4xQONnhqOfr8q2TA4H1HzoRqO70c1g4JhUH/dhNKqgrhfT2cEMOoQaqxidyx+P5J8F8PpYjnkNPYLBgPGq+vxSFOJM/rhvXpp39ZAkGaUk40r+WK69jKT8JMdbQE8oYKDAByTJmMItGQj10OR7zyA3itFr2CQD1NhFMYYeMVhCHA8C1co7pV4yYXL4aSz/GVvfFFBBjxguIcCeOt4szYxOhiG2/V7M+T2yY7iEMOaTgIl8mBWkoth7Cduqah2u97JjuIQIUXqvYWlSohZyUEaDE/88/M+P0BMGrLIIYFAZ/R+HTGovJ+42IRqvYxZ485kKBob7QEgZZZoWoyMgrg//+vDX/0JPuA+ESLCXEApG/kxvm0LEkK2secDVZYjFpRZzIWibSyHm0COGSwjnYWoiyOIqjujXskcJUWCBqgItLuriPipOgAombqBH7EEGTKovUvz/xIdxnc8Rx8IdiHpxn7ouCVJXGnPIBD1h9p5BIU6kS6ZkBXt//uvf365fk0SIcvJJv5LUL6Wcdvq1w09z+c9MeknfSHLmEAteX8t7B30EBHsBHkLkPSsI+h482bOs3froERAT+UdLMcPlSch91M0P0w9Pz5bXpqksRcaW6Yj/H8v3vkpyLvRuOBzGxd6F2voZwpBEyKT6XMln8dF4BCzfjW2oz2hCjAu89FxmiPkctyNmMWprdOS5J11dSQsrVgXjxJAT8lyqp2aMpTnGxv1TJCRgdyzO5Jf7Giwtgv8GwWhfH5T0hK0fUQu6UeUf8UfvxY1Jl0LIHMJQBksL5zMIhXCqpLDAFpNrYSAwymnIKEkf4PUv6/+NJsQs2BHirKTlHUVaTAw9cB1xqaQijJDACYGTzUQ5adAqcbb+UuI+RPwCcTgyodjSe6UQ/4ZAtLrLi4DYhn5Y5DVscvjlguLK3xyDvWm+lEYI5+8hHiWJFMEvIRA1/3ZgfYMV9OgfYzPKZWrxfv5JLtx8DCFQhD+5bL6cRIgSN+IXb4GXlCi1VbQEt0IWdA40yRztXaG5DaEQ/Nj2crrrpP72BtJAkJRg1bhlAZr9Cc0y1LPXK/1KTYVZbcsB3rapw2RC1AwW0WvJEktS7A8sWDWyH61jkD/ul3q1xwhVUwj0HnN+1vZ2Huei4Ghvp/qwSumxfWd7I4NqRND3TdLt43rbmO7+PYYNgj93bTazEKIG4PUppELHyM+t76WrRhoEzFw+uMk/Ph0FW1O3N3/l8+9lc7/Lgd6jboR0TF5VNyeW++eQEj8EtKpf7SmGC4i78VvpRPTuUfLGQ1A3CpHkjEOIgk2ti3zXUtJiiq6gc38DXEar+15LMkgqLishSnWhOZce9tyX68mF5f4pUjL3XmHZqC1hVGkJocBnIdcN6uXZI4ZKR2obO22Rx/VE6esG6m+n/nsLW/jX/Rnp5GuTDpP7Fb6IGzJCPMadhHCVjc1rnBVppAg4b5rCinBeHzs/x7fd9uqhuNz59TfrPY3qDA8f3JIxD/lYZzH1TKRgztXEcu8ZWiztH6vtD17wlt23w/qxH1NwI5IMNRx0iDyk2POntMUiLDpftIeOOZ9ufxd5fYv1Y6RjDCFIIAPRywkq9YuxQvp8WAkxkKS2HWdT+VgFpvWw7zG24Dv2Jq8/kv6nl3rH7L4eQ9AQQojcw4BQJ7yiJ2AvhCAMKe+CQqgrKBs+bmecAIxyAlldKUk7g0R4s070ovpdadJ8DL6TM+DPoHizEeGDyeHNmZwHYYukiDA3E0HMGUAsD4fOIAP2LF/EnKtjGAqtQG2EOCzTfDT0/+UM0jFhte8QN+rnur526U+cRXIMuZ8oLgJUWG/nM9bg3wBqFXWalO7UwEplbeYORexGN+6qSLp26Wijws7ktf4sQvQvXT0hb65ywOw92twk0oSG0+mvfhd9KBQhLUeCc2EOjsQ5EjFc/vIul0YHUBOUFR8bUrxQ/jpprXV1VFoTcvgJ3d5H0D0uncRgEvSoeCGlqzIvL1xmaddYfScFft114QIEM9LxFfrFZXKq6T0FbgzT1os4YEbjR2lx9W7KDh3M1Pf4H+wKHVgqdxmFdpknx8TjgRkb1BytBwDtyxIq6N6J1UBEKd0Z7+ARmhDj0k53l6dAiGd6F/+wsfL2rjyzPR9y3ARhk3jPseF+V6RguHF3a0rZZxmLIaLV26uca9o7W0Kf4PUP0x4Lhg0NXve78ukI8boXYnbgsxoayPEQRQz6m27dGnmRGGm7LwgOUK38OwxO4oJNFjxuDldIihiazdwzGT+p1NkLnQlOdcUsVFY75+/7cNrdFWQP4Zq0nRI0MeiW2SSIq4yQxaM0POJOoCsJ0VJSjMqtC3g9x5j8dPa35Bzg+4hkQnSlAv7MxOCpiQGIOeQowXHPEEWIJkFgXZEx5ImnPAasDOj7kJxJEHagg/PgIe/SEbS8rGYlm26Aaw5meRzDA4ZTQizF8LvHA/dlWSVEp+aMLgTryE3iwKj4y/ew22DZTmHJXFQLNkbvdpH8ADX/43d4wNiIh7yqvpyY+k47IUPi8qEv6itCMP4hivC6IlnhOR/+EKAIMalAO04y8J/hfgjQEhJQdrsb7C5ddGjQi7oOPMFuICXjkYwVstTtjYKOEGJQarY6FKR8YsvSSgx37rOHpsZM9vvNNKqgfRxWKf2mqDCOW0G7ZTedfnjyCnYAU8zyRE6Mt31NDL2GpFWGo0IdLcA2dMCLmar8o01sXL9cZvaktSBN1xjt4bgTU4P4nFATOBnLzMWZ/YhxFqwRIc1q9FchEWFV2CZ9PIwtbJapnaiM/Rx9rxy4zVzUJ0hPM2UuGrVUP5fqRpXSZrB3Ysqnxh0M6rmfoML2uXZdaC22MDQBVueiOV+H8Y4K/Lv2hfkjg03YSYDPmuXrjMqZQBouJbnpNbkCoc612/Zo6oDrt+Pca4s/UW4zaWEdc/zLWexL9bHdu4qrS7gFJyE4VojbBR2o1IfpMHqyt4LtrHBABwdJrYTcdmhQ43iDXJbrvQ+05QDoGvLtpTqpddLNqV7xe8s46x0arMVqNrB1vf+w0KoOWGtYgJ3nWleyE2LUlK2NRRpsprmNdKHWvrbvZkvCsBZLa0JLkcsSxRLq6aTklxAsZ5RnzbiFpUa6+eXLrWtdSeGjkf29tmJpDZgKRI66kumkZCUkqXyqC42yfqZlats47VahcL5H2vipIjjOMoOq2UBkocyMhFD7ykahGSfRRcVaH177oR9nf13/+rMEVp9zF/scx5KST0K0Ps+PRh3dqKJiZLCXJCmhFfscx6ivLIS06vMcEFbp6Ar7VCkxxT49ZzLD15RkQjz6PA1aOmabY/mlo713LaV7KE1KEF2Qki4hHn2eBNEoX95Pu+39EL8ZlRRbtW4bkggxMzbOWeiFtZhl5f+YY7FVmfeUodkLCACFFFOt27sdSO1jWEEX0oH7jkb9QrNPKP0fdvaunQMFuh9iBQEgkLJP8QqkEcI6OOjfVprbsQPfgLt3Ldn5qI7pBSKAlNZJnEZI7h25uidvO/xJU428fdNmnI5zICEupL1GSpvqbO2Tgkjt9JlXXalSftsHQI36II7lXSeorvL92OjgihSA99YLVJ8Uu+XVU6dPAlx1FQty//OFNzbBxW9ARYTaWgKlUYYLjtsdkuLMRng8IUWLoy4UusL0gbPIJSt+Btq9CA87oPuzYLRxHdDGSUudep1EsYF4QqgmpAuqYICq3tD6kIL619JapdIJoXWf9kJ5iTHJo7nYW0pSpaislLDlQkXZrp74S2mMlGlNA6FVqmlb4b1uDVkMl7XFvlFpadMzkNILN/QX0xDq5O0BOeRJlY6QVqkhXaiLIgshCCRlevV0DJvZPUjGaow0sxe73VDThjQRz0lSsQ7q+hEyOYKaDjN6u1Yi5GJ/KScFtoc9bVqWGc6pOytTL1Lrmci4AlZM9etxDseU7pzB98WGXldPD6AnJCdbm9k+lsScgSpEY2qb6JomQR0Umghqlwr1DEKAXagpnoY+6oStIVv2uyFmDnlB1d/hR+GwCzUbUVw/+6E5XynotOVROogLKrWz8yZQgkkP2ZwM7gXDJoTSkJ7Y2bkJPeNpxT5r/sdP0BMGLiHMX6FUQHy7V+oxjFxeCcpQMGQwRljQ48+29NZfNwADlxAvLpOzz/vqQk3E3SYkw7n2oUnJsAkRwmEFiXzn/gYkJQOXEGFP51Eue07zhREwJCkZupVldxYWLH/VB1cXat5fdaJhE8JriwUl3nTRrk4T3Bbdq1NCDUEYNCFm87Z8SAtzUukMOoK94bHo7Yw6orMjbTmxDOD05U/SBz2l2wab3ncgjS78H0eagrHjdQciAAAAAElFTkSuQmCC",p="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",y="qtIcCe_-8t4rIWktnWJm0",g=r.createConfig({chains:[i.mainnet,i.bsc,i.polygon,i.arbitrum,i.optimism,i.avalanche,i.celo,i.base],connectors:[o.injected(),o.metaMask({dappMetadata:{name:"Coinley Payment",icon:h}}),o.coinbaseWallet({appName:"Coinley Payment",appLogoUrl:h})],transports:{[i.mainnet.id]:r.fallback([r.http(`https://eth-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://eth-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://cloudflare-eth.com",{timeout:1e4,retryCount:1}),r.http("https://eth.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://ethereum.publicnode.com",{timeout:1e4,retryCount:1})]),[i.bsc.id]:r.fallback([r.http(`https://bnb-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://bnb-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://bsc-dataseed.bnbchain.org",{timeout:1e4,retryCount:1}),r.http("https://bsc-dataseed-public.bnbchain.org",{timeout:1e4,retryCount:1}),r.http("https://bsc.nodereal.io",{timeout:1e4,retryCount:1})]),[i.polygon.id]:r.fallback([r.http(`https://polygon-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://polygon-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://polygon.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://polygon-rpc.com",{timeout:1e4,retryCount:1}),r.http("https://polygon.drpc.org",{timeout:1e4,retryCount:1})]),[i.arbitrum.id]:r.fallback([r.http(`https://arb-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://arb-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://arb1.arbitrum.io/rpc",{timeout:1e4,retryCount:1}),r.http("https://arbitrum.llamarpc.com",{timeout:1e4,retryCount:1})]),[i.optimism.id]:r.fallback([r.http(`https://opt-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://opt-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://mainnet.optimism.io",{timeout:1e4,retryCount:1}),r.http("https://optimism.llamarpc.com",{timeout:1e4,retryCount:1})]),[i.avalanche.id]:r.fallback([r.http(`https://avax-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://avax-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://api.avax.network/ext/bc/C/rpc",{timeout:1e4,retryCount:1}),r.http("https://avalanche.public-rpc.com",{timeout:1e4,retryCount:1})]),[i.celo.id]:r.fallback([r.http(`https://celo-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://celo-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://forno.celo.org",{timeout:1e4,retryCount:1}),r.http("https://celo.drpc.org",{timeout:1e4,retryCount:1})]),[i.base.id]:r.fallback([r.http(`https://base-mainnet.g.alchemy.com/v2/${p}`,{timeout:1e4,retryCount:1}),r.http(`https://base-mainnet.g.alchemy.com/v2/${y}`,{timeout:1e4,retryCount:1}),r.http("https://mainnet.base.org",{timeout:1e4,retryCount:1}),r.http("https://base.llamarpc.com",{timeout:1e4,retryCount:1}),r.http("https://base.meowrpc.com",{timeout:1e4,retryCount:1})])}});let f=class{constructor(e,t,n=null){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=n)}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json",...t.headers};this.publicKey?s["X-Public-Key"]=this.publicKey:(s["X-API-Key"]=this.apiKey,s["X-API-Secret"]=this.apiSecret);const a=t.timeout||6e4,r=new AbortController,i=setTimeout(()=>r.abort(),a);try{const e=await fetch(n,{...t,headers:s,signal:r.signal});if(clearTimeout(i),!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`HTTP ${e.status}`)}return e.json()}catch(o){if(clearTimeout(i),"AbortError"===o.name)throw new Error(`Request timeout after ${a/1e3}s: ${e}`);throw o}}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Tether USD",symbol:"USDT",contractAddress:"0x55d398326f99059fF775485246999027B3197955",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87c6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"USD Coin",symbol:"USDC",contractAddress:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async verifyQRPayment(e){return await this.request("/api/payments/verify-qr",{method:"POST",body:JSON.stringify({paymentId:e})})}async checkPaymentStatus(e){return await this.request(`/api/payments/status/${e}`)}async getContractInfo(e){try{const t=await this.request(`/api/payments/contract/${e}`);if(!t.success)throw new Error("Contract not supported on this network");return t.contractInfo}catch(t){throw new Error(t.message||"Failed to get contract information")}}async processPayment(e,t,n,s){try{return await this.request("/api/payments/process",{method:"POST",body:JSON.stringify({paymentId:e,transactionHash:t,network:n,senderAddress:s}),timeout:9e4})}catch(a){throw a}}async failPayment(e,t="Payment cancelled by user"){return await this.request("/api/payments/fail",{method:"POST",body:JSON.stringify({paymentId:e,reason:t,status:"failed"})})}};const b={ethereum:1,bsc:56,polygon:137,arbitrum:42161,optimism:10,avalanche:43114,celo:42220,base:8453},x=e=>"number"==typeof e?e:"string"==typeof e?e.startsWith("0x")?parseInt(e,16):parseInt(e,10):1,w=e=>b[e]||1;function v(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const k="2.39.0";let N={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,version:`viem@${k}`};class C extends Error{constructor(e,t={}){var n;const s=t.cause instanceof C?t.cause.details:(null==(a=t.cause)?void 0:a.message)?t.cause.message:t.details;var a;const r=t.cause instanceof C&&t.cause.docsPath||t.docsPath,i=null==(n=N.getDocsUrl)?void 0:n.call(N,{...t,docsPath:r});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...s?[`Details: ${s}`]:[],...N.version?[`Version: ${N.version}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=s,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=k}walk(e){return P(this,e)}}function P(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?P(e.cause,t):t?null:e}class j extends C{constructor({max:e,min:t,signed:n,size:s,value:a}){super(`Number "${a}" is not in safe ${s?`${8*s}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class I extends C{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function S(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function A(e){return S(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function E(e,{dir:t="left"}={}){let n="string"==typeof e?e.replace("0x",""):e,s=0;for(let a=0;a<n.length-1&&"0"===n["left"===t?a:n.length-a-1].toString();a++)s++;return n="left"===t?n.slice(s):n.slice(0,n.length-s),"string"==typeof e?(1===n.length&&"right"===t&&(n=`${n}0`),`0x${n.length%2==1?`0${n}`:n}`):n}class F extends C{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class U extends C{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function D(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const s=e.replace("0x","");if(s.length>2*n)throw new U({size:Math.ceil(s.length/2),targetSize:n,type:"hex"});return`0x${s["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new U({size:e.length,targetSize:n,type:"bytes"});const s=new Uint8Array(n);for(let a=0;a<n;a++){const r="right"===t;s[r?a:n-a-1]=e[r?a:e.length-a-1]}return s}(e,{dir:t,size:n})}const T=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function B(e,t={}){return"number"==typeof e||"bigint"==typeof e?M(e,t):"string"==typeof e?function(e,t={}){const n=R.encode(e);return L(n,t)}(e,t):"boolean"==typeof e?function(e,t={}){const n=`0x${Number(e)}`;if("number"==typeof t.size)return q(n,{size:t.size}),D(n,{size:t.size});return n}(e,t):L(e,t)}function L(e,t={}){let n="";for(let a=0;a<e.length;a++)n+=T[e[a]];const s=`0x${n}`;return"number"==typeof t.size?(q(s,{size:t.size}),D(s,{dir:"right",size:t.size})):s}function M(e,t={}){const{signed:n,size:s}=t,a=BigInt(e);let r;s?r=n?(1n<<8n*BigInt(s)-1n)-1n:2n**(8n*BigInt(s))-1n:"number"==typeof e&&(r=BigInt(Number.MAX_SAFE_INTEGER));const i="bigint"==typeof r&&n?-r-1n:0;if(r&&a>r||a<i){const t="bigint"==typeof e?"n":"";throw new j({max:r?`${r}${t}`:void 0,min:`${i}${t}`,signed:n,size:s,value:`${e}${t}`})}const o=`0x${(n&&a<0?(1n<<BigInt(8*s))+BigInt(a):a).toString(16)}`;return s?D(o,{size:s}):o}const R=new TextEncoder;const $=new TextEncoder;function G(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){const n=M(e,t);return W(n)}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);if(n[0]=Number(e),"number"==typeof t.size)return q(n,{size:t.size}),D(n,{size:t.size});return n}(e,t):S(e)?W(e,t):H(e,t)}const O={zero:48,nine:57,A:65,F:70,a:97,f:102};function z(e){return e>=O.zero&&e<=O.nine?e-O.zero:e>=O.A&&e<=O.F?e-(O.A-10):e>=O.a&&e<=O.f?e-(O.a-10):void 0}function W(e,t={}){let n=e;t.size&&(q(n,{size:t.size}),n=D(n,{dir:"right",size:t.size}));let s=n.slice(2);s.length%2&&(s=`0${s}`);const a=s.length/2,r=new Uint8Array(a);for(let i=0,o=0;i<a;i++){const e=z(s.charCodeAt(o++)),t=z(s.charCodeAt(o++));if(void 0===e||void 0===t)throw new C(`Invalid byte sequence ("${s[o-2]}${s[o-1]}" in "${s}").`);r[i]=16*e+t}return r}function H(e,t={}){const n=$.encode(e);return"number"==typeof t.size?(q(n,{size:t.size}),D(n,{dir:"right",size:t.size})):n}function q(e,{size:t}){if(A(e)>t)throw new I({givenSize:A(e),maxSize:t})}function V(e,t={}){const{signed:n}=t;t.size&&q(e,{size:t.size});const s=BigInt(e);if(!n)return s;const a=(e.length-2)/2;return s<=(1n<<8n*BigInt(a)-1n)-1n?s:s-BigInt(`0x${"f".padStart(2*a,"f")}`)-1n}function Q(e,t={}){return Number(V(e,t))}function K(e,t){return({exclude:n,format:s})=>({exclude:n,format:(e,a)=>{const r=t(e,a);if(n)for(const t of n)delete r[t];return{...r,...s(e,a)}},type:e})}const Z={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Y(e,t){const n={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?Q(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?Q(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Z[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))),n.yParity=(()=>{if(e.yParity)return Number(e.yParity);if("bigint"==typeof n.v){if(0n===n.v||27n===n.v)return 0;if(1n===n.v||28n===n.v)return 1;if(n.v>=35n)return n.v%2n==0n?1:0}})(),"legacy"===n.type&&(delete n.accessList,delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas,delete n.yParity),"eip2930"===n.type&&(delete n.maxFeePerBlobGas,delete n.maxFeePerGas,delete n.maxPriorityFeePerGas),"eip1559"===n.type&&delete n.maxFeePerBlobGas,n}const _=K("transaction",Y);function J(e,t){const n=(e.transactions??[]).map(e=>"string"==typeof e?e:Y(e));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:n,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const X=K("block",J);const ee={"0x0":"reverted","0x1":"success"};function te(e,t){const n={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(e=>function(e,{args:t,eventName:n}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...n?{args:t,eventName:n}:{}}}(e)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Q(e.transactionIndex):null,status:e.status?ee[e.status]:null,type:e.type?Z[e.type]||e.type:null};return e.blobGasPrice&&(n.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(n.blobGasUsed=BigInt(e.blobGasUsed)),n}const ne=K("transactionReceipt",te),se={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function ae(e,t){const n={};return void 0!==e.authorizationList&&(n.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?M(BigInt(e.r)):e.r,s:e.s?M(BigInt(e.s)):e.s,chainId:M(e.chainId),nonce:M(e.nonce),...void 0!==e.yParity?{yParity:M(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:M(e.v)}:{}}))),void 0!==e.accessList&&(n.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(n.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?n.blobs=e.blobs.map(e=>L(e)):n.blobs=e.blobs),void 0!==e.data&&(n.data=e.data),e.account&&(n.from=e.account.address),void 0!==e.from&&(n.from=e.from),void 0!==e.gas&&(n.gas=M(e.gas)),void 0!==e.gasPrice&&(n.gasPrice=M(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(n.maxFeePerBlobGas=M(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(n.maxFeePerGas=M(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(n.maxPriorityFeePerGas=M(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(n.nonce=M(e.nonce)),void 0!==e.to&&(n.to=e.to),void 0!==e.type&&(n.type=se[e.type]),void 0!==e.value&&(n.value=M(e.value)),n}const re=K("transactionRequest",ae);const ie=2n**256n-1n;function oe(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}class ce extends C{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class le extends C{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class de extends C{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const me={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new de({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new le({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new ce({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new ce({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const n=this.inspectBytes(e);return this.position+=t??e,n},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function ue(e,{recursiveReadLimit:t=8192}={}){const n=Object.create(me);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}function he(e,t="hex"){const n=pe(e),s=ue(new Uint8Array(n.length));return n.encode(s),"hex"===t?L(s.bytes):s.bytes}function pe(e){return Array.isArray(e)?function(e){const t=e.reduce((e,t)=>e+t.length,0),n=ye(t);return{length:t<=55?1+t:1+n+t,encode(s){t<=55?s.pushByte(192+t):(s.pushByte(247+n),1===n?s.pushUint8(t):2===n?s.pushUint16(t):3===n?s.pushUint24(t):s.pushUint32(t));for(const{encode:t}of e)t(s)}}}(e.map(e=>pe(e))):function(e){const t="string"==typeof e?W(e):e,n=ye(t.length),s=1===t.length&&t[0]<128?1:t.length<=55?1+t.length:1+n+t.length;return{length:s,encode(e){1===t.length&&t[0]<128?e.pushBytes(t):t.length<=55?(e.pushByte(128+t.length),e.pushBytes(t)):(e.pushByte(183+n),1===n?e.pushUint8(t.length):2===n?e.pushUint16(t.length):3===n?e.pushUint24(t.length):e.pushUint32(t.length),e.pushBytes(t))}}}(e)}function ye(e){if(e<256)return 1;if(e<65536)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new C("Length is too large.")}const ge={ether:-9,wei:9};function fe(e,t="wei"){return function(e,t){let n=e.toString();const s=n.startsWith("-");s&&(n=n.slice(1)),n=n.padStart(t,"0");let[a,r]=[n.slice(0,n.length-t),n.slice(n.length-t)];return r=r.replace(/(0+)$/,""),`${s?"-":""}${a||"0"}${r?`.${r}`:""}`}(e,ge[t])}function be(e){const t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),n=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(n+1)} ${t}`).join("\n")}class xe extends C{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class we extends C{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",be(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class ve extends C{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}function ke(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),s="string"==typeof e.blobs[0]?e.blobs.map(e=>W(e)):e.blobs,a=[];for(const r of s)a.push(Uint8Array.from(t.blobToKzgCommitment(r)));return"bytes"===n?a:a.map(e=>L(e))}function Ne(e){const{kzg:t}=e,n=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),s="string"==typeof e.blobs[0]?e.blobs.map(e=>W(e)):e.blobs,a="string"==typeof e.commitments[0]?e.commitments.map(e=>W(e)):e.commitments,r=[];for(let i=0;i<s.length;i++){const e=s[i],n=a[i];r.push(Uint8Array.from(t.computeBlobKzgProof(e,n)))}return"bytes"===n?r:r.map(e=>L(e))}
|
|
2
|
-
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ce(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Pe(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function je(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ie(e,t){Pe(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Se(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ae(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Ee(e,t){return e<<32-t|e>>>t}function Fe(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ue=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Fe(e[t]);return e};function De(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),Pe(e),e}class Te{}function Be(e){const t=t=>e().update(De(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function Le(e,t,n){return e&t^~e&n}function Me(e,t,n){return e&t^e&n^t&n}class Re extends Te{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ae(this.buffer)}update(e){je(this),Pe(e=De(e));const{view:t,buffer:n,blockLen:s}=this,a=e.length;for(let r=0;r<a;){const i=Math.min(s-this.pos,a-r);if(i===s){const t=Ae(e);for(;s<=a-r;r+=s)this.process(t,r);continue}n.set(e.subarray(r,r+i),this.pos),this.pos+=i,r+=i,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){je(this),Ie(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:a}=this;let{pos:r}=this;t[r++]=128,Se(this.buffer.subarray(r)),this.padOffset>s-r&&(this.process(n,0),r=0);for(let d=r;d<s;d++)t[d]=0;!function(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const a=BigInt(32),r=BigInt(4294967295),i=Number(n>>a&r),o=Number(n&r),c=s?4:0,l=s?0:4;e.setUint32(t+c,i,s),e.setUint32(t+l,o,s)}(n,s-8,BigInt(8*this.length),a),this.process(n,0);const i=Ae(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)i.setUint32(4*d,l[d],a)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:a,destroyed:r,pos:i}=this;return e.destroyed=r,e.finished=a,e.length=s,e.pos=i,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const $e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=BigInt(2**32-1),Oe=BigInt(32);function ze(e,t=!1){return t?{h:Number(e&Ge),l:Number(e>>Oe&Ge)}:{h:0|Number(e>>Oe&Ge),l:0|Number(e&Ge)}}const We=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]),He=new Uint32Array(64);class qe extends Re{constructor(e=32){super(64,e,8,!1),this.A=0|$e[0],this.B=0|$e[1],this.C=0|$e[2],this.D=0|$e[3],this.E=0|$e[4],this.F=0|$e[5],this.G=0|$e[6],this.H=0|$e[7]}get(){const{A:e,B:t,C:n,D:s,E:a,F:r,G:i,H:o}=this;return[e,t,n,s,a,r,i,o]}set(e,t,n,s,a,r,i,o){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|a,this.F=0|r,this.G=0|i,this.H=0|o}process(e,t){for(let d=0;d<16;d++,t+=4)He[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){const e=He[d-15],t=He[d-2],n=Ee(e,7)^Ee(e,18)^e>>>3,s=Ee(t,17)^Ee(t,19)^t>>>10;He[d]=s+He[d-7]+n+He[d-16]|0}let{A:n,B:s,C:a,D:r,E:i,F:o,G:c,H:l}=this;for(let d=0;d<64;d++){const e=l+(Ee(i,6)^Ee(i,11)^Ee(i,25))+Le(i,o,c)+We[d]+He[d]|0,t=(Ee(n,2)^Ee(n,13)^Ee(n,22))+Me(n,s,a)|0;l=c,c=o,o=i,i=r+e|0,r=a,a=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,a=a+this.C|0,r=r+this.D|0,i=i+this.E|0,o=o+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,s,a,r,i,o,c,l)}roundClean(){Se(He)}destroy(){this.set(0,0,0,0,0,0,0,0),Se(this.buffer)}}const Ve=Be(()=>new qe);function Qe(e){const{commitment:t,version:n=1}=e,s=e.to??("string"==typeof t?"hex":"bytes"),a=Ve(S(r=t,{strict:!1})?G(r):r);var r;return a.set([n],0),"bytes"===s?a:L(a)}const Ke=4096,Ze=131072,Ye=761855;class _e extends C{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class Je extends C{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class Xe extends C{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class et extends C{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:["Expected: 1",`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}function tt(e){const{data:t,kzg:n,to:s}=e,a=e.blobs??function(e){const t=e.to??("string"==typeof e.data?"hex":"bytes"),n="string"==typeof e.data?W(e.data):e.data,s=A(n);if(!s)throw new Je;if(s>Ye)throw new _e({maxSize:Ye,size:s});const a=[];let r=!0,i=0;for(;r;){const e=ue(new Uint8Array(Ze));let t=0;for(;t<Ke;){const s=n.slice(i,i+31);if(e.pushByte(0),e.pushBytes(s),s.length<31){e.pushByte(128),r=!1;break}t++,i+=31}a.push(e)}return"bytes"===t?a.map(e=>e.bytes):a.map(e=>L(e.bytes))}({data:t,to:s}),r=e.commitments??ke({blobs:a,kzg:n,to:s}),i=e.proofs??Ne({blobs:a,commitments:r,kzg:n,to:s}),o=[];for(let c=0;c<a.length;c++)o.push({blob:a[c],commitment:r[c],proof:i[c]});return o}class nt extends C{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class st extends C{constructor({chainId:e}){super("number"==typeof e?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}class at extends C{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${fe(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(at,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class rt extends C{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${fe(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${fe(n)} gwei`:""}).`].join("\n"),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(rt,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class it extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const ot=BigInt(0),ct=BigInt(1),lt=BigInt(2),dt=BigInt(7),mt=BigInt(256),ut=BigInt(113),ht=[],pt=[],yt=[];for(let Xn=0,es=ct,ts=1,ns=0;Xn<24;Xn++){[ts,ns]=[ns,(2*ts+3*ns)%5],ht.push(2*(5*ns+ts)),pt.push((Xn+1)*(Xn+2)/2%64);let e=ot;for(let t=0;t<7;t++)es=(es<<ct^(es>>dt)*ut)%mt,es<&&(e^=ct<<(ct<<BigInt(t))-ct);yt.push(e)}const gt=function(e,t=!1){const n=e.length;let s=new Uint32Array(n),a=new Uint32Array(n);for(let r=0;r<n;r++){const{h:n,l:i}=ze(e[r],t);[s[r],a[r]]=[n,i]}return[s,a]}(yt,!0),ft=gt[0],bt=gt[1],xt=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),wt=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class vt extends Te{constructor(e,t,n,s=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=a,Ce(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var r;this.state=new Uint8Array(200),this.state32=(r=this.state,new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)))}clone(){return this._cloneInto()}keccak(){Ue(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let s=0;s<10;s++)n[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const t=(s+8)%10,a=(s+2)%10,r=n[a],i=n[a+1],o=xt(r,i,1)^n[t],c=wt(r,i,1)^n[t+1];for(let n=0;n<50;n+=10)e[s+n]^=o,e[s+n+1]^=c}let t=e[2],a=e[3];for(let n=0;n<24;n++){const s=pt[n],r=xt(t,a,s),i=wt(t,a,s),o=ht[n];t=e[o],a=e[o+1],e[o]=r,e[o+1]=i}for(let s=0;s<50;s+=10){for(let t=0;t<10;t++)n[t]=e[s+t];for(let t=0;t<10;t++)e[s+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=ft[s],e[1]^=bt[s]}Se(n)}(this.state32,this.rounds),Ue(this.state32),this.posOut=0,this.pos=0}update(e){je(this),Pe(e=De(e));const{blockLen:t,state:n}=this,s=e.length;for(let a=0;a<s;){const r=Math.min(t-this.pos,s-a);for(let t=0;t<r;t++)n[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,128&t&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){je(this,!1),Pe(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,a=e.length;s<a;){this.posOut>=n&&this.keccak();const r=Math.min(n-this.posOut,a-s);e.set(t.subarray(this.posOut,this.posOut+r),s),this.posOut+=r,s+=r}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ce(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ie(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Se(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:a,enableXOF:r}=this;return e||(e=new vt(t,n,s,r,a)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=a,e.suffix=n,e.outputLen=s,e.enableXOF=r,e.destroyed=this.destroyed,e}}const kt=(()=>{return e=1,t=136,n=32,Be(()=>new vt(t,e,n));var e,t,n})();const Nt=new it(8192);function Ct(e,t){if(Nt.has(`${e}.${t}`))return Nt.get(`${e}.${t}`);const n=e.substring(2).toLowerCase(),s=(a=H(n),kt(S(a,{strict:!1})?G(a):a));var a;const r=n.split("");for(let o=0;o<40;o+=2)s[o>>1]>>4>=8&&r[o]&&(r[o]=r[o].toUpperCase()),(15&s[o>>1])>=8&&r[o+1]&&(r[o+1]=r[o+1].toUpperCase());const i=`0x${r.join("")}`;return Nt.set(`${e}.${t}`,i),i}const Pt=/^0x[a-fA-F0-9]{40}$/,jt=new it(8192);function It(e,t){const{strict:n=!0}=t??{},s=`${e}.${n}`;if(jt.has(s))return jt.get(s);const a=!(!Pt.test(e)||e.toLowerCase()!==e&&n&&Ct(e)!==e);return jt.set(s,a),a}function St(e,t,n,{strict:s}={}){return S(e,{strict:!1})?function(e,t,n,{strict:s}={}){const a=`0x${e.replace("0x","").slice(2*t,2*n)}`;s&&At(a,t,n);return a}(e,t,n,{strict:s}):function(e,t,n,{strict:s}={}){const a=e.slice(t,n);s&&At(a,t,n);return a}(e,t,n,{strict:s})}function At(e,t,n){if(A(e)!==n-t)throw new F({offset:n,position:"end",size:A(e)})}function Et(e){const{chainId:t,maxPriorityFeePerGas:n,maxFeePerGas:s,to:a}=e;if(t<=0)throw new st({chainId:t});if(a&&!It(a))throw new nt({address:a});if(s&&s>ie)throw new at({maxFeePerGas:s});if(n&&s&&n>s)throw new rt({maxFeePerGas:s,maxPriorityFeePerGas:n})}function Ft(e){if(!e||0===e.length)return[];const t=[];for(let n=0;n<e.length;n++){const{address:s,storageKeys:a}=e[n];for(let e=0;e<a.length;e++)if(a[e].length-2!=64)throw new ve({storageKey:a[e]});if(!It(s,{strict:!1}))throw new nt({address:s});t.push([s,a])}return t}function Ut(e,t){const n=function(e){if(e.type)return e.type;if(void 0!==e.authorizationList)return"eip7702";if(void 0!==e.blobs||void 0!==e.blobVersionedHashes||void 0!==e.maxFeePerBlobGas||void 0!==e.sidecars)return"eip4844";if(void 0!==e.maxFeePerGas||void 0!==e.maxPriorityFeePerGas)return"eip1559";if(void 0!==e.gasPrice)return void 0!==e.accessList?"eip2930":"legacy";throw new we({transaction:e})}(e);return"eip1559"===n?function(e,t){const{chainId:n,gas:s,nonce:a,to:r,value:i,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:l,data:d}=e;Et(e);const m=Ft(l),u=[M(n),a?M(a):"0x",c?M(c):"0x",o?M(o):"0x",s?M(s):"0x",r??"0x",i?M(i):"0x",d??"0x",m,...Dt(e,t)];return oe(["0x02",he(u)])}(e,t):"eip2930"===n?function(e,t){const{chainId:n,gas:s,data:a,nonce:r,to:i,value:o,accessList:c,gasPrice:l}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r}=e;if(t<=0)throw new st({chainId:t});if(r&&!It(r))throw new nt({address:r});if(n||a)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(s&&s>ie)throw new at({maxFeePerGas:s})}(e);const d=Ft(c),m=[M(n),r?M(r):"0x",l?M(l):"0x",s?M(s):"0x",i??"0x",o?M(o):"0x",a??"0x",d,...Dt(e,t)];return oe(["0x01",he(m)])}(e,t):"eip4844"===n?function(e,t){const{chainId:n,gas:s,nonce:a,to:r,value:i,maxFeePerBlobGas:o,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:m}=e;!function(e){const{blobVersionedHashes:t}=e;if(t){if(0===t.length)throw new Je;for(const e of t){const t=A(e),n=Q(St(e,0,1));if(32!==t)throw new Xe({hash:e,size:t});if(1!==n)throw new et({hash:e,version:n})}}Et(e)}(e);let u=e.blobVersionedHashes,h=e.sidecars;if(e.blobs&&(void 0===u||void 0===h)){const t="string"==typeof e.blobs[0]?e.blobs:e.blobs.map(e=>L(e)),n=e.kzg,s=ke({blobs:t,kzg:n});if(void 0===u&&(u=function(e){const{commitments:t,version:n}=e,s=e.to??("string"==typeof t[0]?"hex":"bytes"),a=[];for(const r of t)a.push(Qe({commitment:r,to:s,version:n}));return a}({commitments:s})),void 0===h){h=tt({blobs:t,commitments:s,proofs:Ne({blobs:t,commitments:s,kzg:n})})}}const p=Ft(d),y=[M(n),a?M(a):"0x",l?M(l):"0x",c?M(c):"0x",s?M(s):"0x",r??"0x",i?M(i):"0x",m??"0x",p,o?M(o):"0x",u??[],...Dt(e,t)],g=[],f=[],b=[];if(h)for(let x=0;x<h.length;x++){const{blob:e,commitment:t,proof:n}=h[x];g.push(e),f.push(t),b.push(n)}return oe(["0x03",he(h?[y,g,f,b]:y)])}(e,t):"eip7702"===n?function(e,t){const{authorizationList:n,chainId:s,gas:a,nonce:r,to:i,value:o,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:d,data:m}=e;!function(e){const{authorizationList:t}=e;if(t)for(const n of t){const{chainId:e}=n,t=n.address;if(!It(t))throw new nt({address:t});if(e<0)throw new st({chainId:e})}Et(e)}(e);const u=Ft(d),h=function(e){if(!e||0===e.length)return[];const t=[];for(const n of e){const{chainId:e,nonce:s,...a}=n,r=n.address;t.push([e?B(e):"0x",r,s?B(s):"0x",...Dt({},a)])}return t}(n);return oe(["0x04",he([M(s),r?M(r):"0x",l?M(l):"0x",c?M(c):"0x",a?M(a):"0x",i??"0x",o?M(o):"0x",m??"0x",u,h,...Dt(e,t)])])}(e,t):function(e,t){const{chainId:n=0,gas:s,data:a,nonce:r,to:i,value:o,gasPrice:c}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r}=e;if(r&&!It(r))throw new nt({address:r});if(void 0!==t&&t<=0)throw new st({chainId:t});if(n||a)throw new C("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(s&&s>ie)throw new at({maxFeePerGas:s})}(e);let l=[r?M(r):"0x",c?M(c):"0x",s?M(s):"0x",i??"0x",o?M(o):"0x",a??"0x"];if(t){const e=(()=>{if(t.v>=35n){return(t.v-35n)/2n>0?t.v:27n+(35n===t.v?0n:1n)}if(n>0)return BigInt(2*n)+BigInt(35n+t.v-27n);const e=27n+(27n===t.v?0n:1n);if(t.v!==e)throw new xe({v:t.v});return e})(),s=E(t.r),a=E(t.s);l=[...l,M(e),"0x00"===s?"0x":s,"0x00"===a?"0x":a]}else n>0&&(l=[...l,M(n),"0x","0x"]);return he(l)}(e,t)}function Dt(e,t){const n=t??e,{v:s,yParity:a}=n;if(void 0===n.r)return[];if(void 0===n.s)return[];if(void 0===s&&void 0===a)return[];const r=E(n.r),i=E(n.s);return["number"==typeof a?a?M(1):"0x":0n===s?"0x":1n===s?M(1):27n===s?"0x":M(1),"0x00"===r?"0x":r,"0x00"===i?"0x":i]}const Tt={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};function Bt(e,t){return function(e){return"deposit"===e.type||void 0!==e.sourceHash}(e)?function(e){!function(e){const{from:t,to:n}=e;if(t&&!It(t))throw new nt({address:t});if(n&&!It(n))throw new nt({address:n})}(e);const{sourceHash:t,data:n,from:s,gas:a,isSystemTx:r,mint:i,to:o,value:c}=e;return oe(["0x7e",he([t,s,o??"0x",i?B(i):"0x",c?B(c):"0x",a?B(a):"0x",r?"0x1":"0x",n??"0x"])])}(e):Ut(e,t)}const Lt={blockTime:2e3,contracts:Tt,formatters:{block:X({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;const t=Y(e);return"0x7e"===t.typeHex&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?V(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}),stateRoot:e.stateRoot}}}),transaction:_({format(e){const t={};return"0x7e"===e.type&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?V(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:ne({format:e=>({l1GasPrice:e.l1GasPrice?V(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?V(e.l1GasUsed):null,l1Fee:e.l1Fee?V(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null})})},serializers:{transaction:Bt}},Mt=v({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Rt=v({id:43114,name:"Avalanche",blockTime:1700,nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io",apiUrl:"https://api.snowtrace.io"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:11907934}}}),$t=1,Gt=v({...Lt,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...Lt.contracts,disputeGameFactory:{[$t]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[$t]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[$t]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[$t]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:1}),Ot=v({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),zt={estimateFeesPerGas:async e=>{var t;if(!(null==(t=e.request)?void 0:t.feeCurrency))return null;const[n,s]=await Promise.all([Wt(e.client,e.request.feeCurrency),Ht(e.client,e.request.feeCurrency)]);return{maxFeePerGas:e.multiply(n-s)+s,maxPriorityFeePerGas:s}}};async function Wt(e,t){const n=await e.request({method:"eth_gasPrice",params:[t]});return BigInt(n)}async function Ht(e,t){const n=await e.request({method:"eth_maxPriorityFeePerGas",params:[t]});return BigInt(n)}function qt(e){return 0===e||0n===e||null==e||"0"===e||""===e||"string"==typeof e&&("0x"===E(e).toLowerCase()||"0x00"===E(e).toLowerCase())}function Vt(e){return!qt(e)}function Qt(e){return"cip64"===e.type||function(e){return void 0!==e.maxFeePerGas&&void 0!==e.maxPriorityFeePerGas}(e)&&Vt(e.feeCurrency)}const Kt={transaction:function(e,t){return Qt(e)?function(e,t){!function(e){const{chainId:t,maxPriorityFeePerGas:n,gasPrice:s,maxFeePerGas:a,to:r,feeCurrency:i}=e;if(t<=0)throw new st({chainId:t});if(r&&!It(r))throw new nt({address:r});if(s)throw new C("`gasPrice` is not a valid CIP-64 Transaction attribute.");if(Vt(a)&&a>Zt)throw new at({maxFeePerGas:a});if(Vt(n)&&Vt(a)&&n>a)throw new rt({maxFeePerGas:a,maxPriorityFeePerGas:n});if(Vt(i)&&!It(i))throw new C("`feeCurrency` MUST be a token address for CIP-64 transactions.");if(qt(i))throw new C("`feeCurrency` must be provided for CIP-64 transactions.")}(e);const{chainId:n,gas:s,nonce:a,to:r,value:i,maxFeePerGas:o,maxPriorityFeePerGas:c,accessList:l,feeCurrency:d,data:m}=e,u=[B(n),a?B(a):"0x",c?B(c):"0x",o?B(o):"0x",s?B(s):"0x",r??"0x",i?B(i):"0x",m??"0x",Ft(l),d,...Dt(e,t)];return oe(["0x7b",he(u)])}(e,t):Bt(e,t)}};const Zt=ie;const Yt=v({...{blockTime:1e3,contracts:Tt,formatters:{block:X({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;return{...Y(e),...e.gatewayFee?{gatewayFee:V(e.gatewayFee),gatewayFeeRecipient:e.gatewayFeeRecipient}:{},feeCurrency:e.feeCurrency}})}}}),transaction:_({format(e){if("0x7e"===e.type)return{isSystemTx:e.isSystemTx,mint:e.mint?V(e.mint):void 0,sourceHash:e.sourceHash,type:"deposit"};const t={feeCurrency:e.feeCurrency};return"0x7b"===e.type?t.type="cip64":("0x7c"===e.type&&(t.type="cip42"),t.gatewayFee=e.gatewayFee?V(e.gatewayFee):null,t.gatewayFeeRecipient=e.gatewayFeeRecipient),t}}),transactionRequest:re({format(e){const t={};return e.feeCurrency&&(t.feeCurrency=e.feeCurrency),Qt(e)&&(t.type="0x7b"),t}})},serializers:Kt,fees:zt},id:42220,name:"Celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://celoscan.io",apiUrl:"https://api.celoscan.io/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:13112599}},testnet:!1}),_t=v({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Jt=1,Xt=v({...Lt,id:10,name:"OP Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io"]}},blockExplorers:{default:{name:"Optimism Explorer",url:"https://optimistic.etherscan.io",apiUrl:"https://api-optimistic.etherscan.io/api"}},contracts:{...Lt.contracts,disputeGameFactory:{[Jt]:{address:"0xe5965Ab5962eDc7477C8520243A95517CD252fA9"}},l2OutputOracle:{[Jt]:{address:"0xdfe97868233d1aa22e815a266982f2cf17685a27"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:4286263},portal:{[Jt]:{address:"0xbEb5Fc579115071764c7423A4f12eDde41f106Ed"}},l1StandardBridge:{[Jt]:{address:"0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1"}}},sourceId:1}),en=v({id:137,name:"Polygon",blockTime:2e3,nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-rpc.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com",apiUrl:"https://api.polygonscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:25770160}}}),tn=(e,t,n=!1)=>{if(!e||"string"!=typeof e)throw new Error(`Missing ${t} address`);if(!e.startsWith("0x"))throw new Error(`Invalid ${t} address format: must start with 0x`);if(42!==e.length)throw new Error(`Invalid ${t} address length: expected 42 characters, got ${e.length}`);if("0x0000000000000000000000000000000000000000"===e&&!n)throw new Error(`Invalid ${t} address: cannot be zero address`)},nn=e=>{const t=(e=>{tn(e.token,"token"),tn(e.recipient1,"recipient1"),tn(e.recipient2,"recipient2");const t=0n===BigInt(e.recipient3Percentage||0);if(tn(e.recipient3,"recipient3",t),!e.paymentId||"string"!=typeof e.paymentId||0===e.paymentId.length)throw new Error("Invalid payment ID: must be a non-empty string");let n,s,a,r;try{n=BigInt(e.amount||0),s=BigInt(e.recipient1Percentage||0),a=BigInt(e.recipient2Percentage||0),r=BigInt(e.recipient3Percentage||0)}catch(o){throw new Error("Invalid numeric values: cannot convert to BigInt")}if(n<=0n)throw new Error(`Invalid amount: ${e.amount} (must be greater than 0)`);const i=s+a+r;if(10000n!==i)throw new Error(`Invalid percentages: total is ${i} but must equal 10000 basis points (100%). Individual: ${s}, ${a}, ${r}`);return{amount:n,percentage1:s,percentage2:a,percentage3:r}})(e);return{token:e.token,amount:t.amount,paymentId:e.paymentId,recipient1:e.recipient1,recipient2:e.recipient2,recipient3:e.recipient3,recipient1Percentage:t.percentage1,recipient2Percentage:t.percentage2,recipient3Percentage:t.percentage3}},sn=[{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"}],an=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"}],rn=e=>{var t,n;const s=(null==(t=null==e?void 0:e.message)?void 0:t.toLowerCase())||(null==(n=null==e?void 0:e.toString())?void 0:n.toLowerCase())||"",a=(null==e?void 0:e.code)||(null==e?void 0:e.reason)||"";return s.includes("user rejected")||s.includes("user denied")||s.includes("user cancelled")||s.includes("rejected by user")||4001===a||"ACTION_REJECTED"===a?{type:"user_rejected",title:"Transaction Cancelled",message:"You cancelled the transaction. No charges were made.",suggestion:'Click "Pay Now" to try again when you\'re ready.'}:s.includes("insufficient funds")||s.includes("insufficient balance")||s.includes("insufficient eth")||s.includes("insufficient matic")||s.includes("insufficient bnb")||-32e3===a?{type:"insufficient_funds",title:"Insufficient Funds",message:"You don't have enough tokens or gas fees in your wallet.",suggestion:"Add more funds to your wallet and try again."}:s.includes("network error")||s.includes("rpc error")||s.includes("connection failed")||s.includes("timeout")||s.includes("request failed")?{type:"network_error",title:"Network Error",message:"Unable to connect to the blockchain network.",suggestion:"Check your internet connection and try again."}:s.includes("wrong network")||s.includes("unsupported network")||s.includes("chain mismatch")||4902===a?{type:"wrong_network",title:"Wrong Network",message:"Please switch to the correct network in your wallet.",suggestion:"Your wallet should prompt you to switch networks."}:s.includes("wallet not connected")||s.includes("no provider")||s.includes("wallet disconnected")||4900===a?{type:"wallet_disconnected",title:"Wallet Disconnected",message:"Your wallet is not connected.",suggestion:"Please reconnect your wallet and try again."}:s.includes("gas estimation failed")||s.includes("execution reverted")||s.includes("out of gas")?{type:"gas_error",title:"Transaction Failed",message:"The transaction couldn't be processed.",suggestion:"This might be a temporary issue. Please try again."}:s.includes("approve")&&s.includes("failed")?{type:"approval_failed",title:"Token Approval Failed",message:"Failed to approve token spending.",suggestion:"Please try the approval step again."}:s.includes("transaction failed")||s.includes("revert")||s.includes("contract call failed")?{type:"transaction_failed",title:"Transaction Failed",message:"The blockchain transaction was unsuccessful.",suggestion:"Please check your wallet and try again."}:s.includes("popup")||s.includes("blocked")?{type:"popup_blocked",title:"Wallet Popup Blocked",message:"Your browser blocked the wallet popup.",suggestion:"Please allow popups for this site and try again."}:s.includes("rate limit")||s.includes("too many requests")?{type:"rate_limited",title:"Too Many Requests",message:"Please wait a moment before trying again.",suggestion:"Wait 30 seconds and retry your transaction."}:s.includes("payment not yet confirmed")||s.includes("not yet confirmed on-chain")||s.includes("payment not found on-chain")||s.includes("please complete the payment")?{type:"payment_pending",title:"Payment Pending",message:"Your payment is still being confirmed on the blockchain.",suggestion:"Please wait a moment and try again, or check if your transaction completed successfully."}:s.includes("deep link")||s.includes("app not installed")||s.includes("wallet app")?{type:"mobile_wallet_error",title:"Wallet App Issue",message:"Unable to open or connect to your wallet app.",suggestion:"Make sure your wallet app is installed and try again."}:{type:"unknown_error",title:"Something Went Wrong",message:"An unexpected error occurred.",suggestion:"Please try again or contact support if the problem persists."}},on=(e,t="")=>({timestamp:(new Date).toISOString(),context:t,userFriendly:rn(e),technical:{message:(null==e?void 0:e.message)||"Unknown error",code:null==e?void 0:e.code,reason:null==e?void 0:e.reason,stack:null==e?void 0:e.stack,name:null==e?void 0:e.name}}),cn=async(e,t)=>{try{const n=await r.estimateFeesPerGas(e,{chainId:t}),s=120n,a=100n;return{maxFeePerGas:n.maxFeePerGas?n.maxFeePerGas*s/a:void 0,maxPriorityFeePerGas:n.maxPriorityFeePerGas?n.maxPriorityFeePerGas*s/a:void 0}}catch(n){return{}}},ln="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",dn=(e,t,a,i,o,l)=>{const[d,m]=n.useState("idle"),[u,h]=n.useState(""),[p,y]=n.useState(null),{data:f,isPending:b,error:w,sendTransaction:v}=s.useSendTransaction(),{isLoading:k,isSuccess:N}=s.useWaitForTransactionReceipt({hash:f}),C=async()=>{var e,t,n,s,a,i,c;try{m("splitPayment");const u=window.coinleyPendingSplitPayment;if(!u)throw new Error("Missing split payment data");const{contractCall:h,selectedToken:p,paymentData:f,selectedNetwork:b}=u,w=b.chainId||10,v=await o.getContractInfo(w),{abi:k}=v,N=nn(h.params),C=x(w),P=1===C,j=P||43114===C;try{const{request:e}=await r.simulateContract(g,{address:h.contractAddress,abi:k,functionName:"splitPayment",args:[N]})}catch(l){const a=l.data||(null==(e=l.cause)?void 0:e.data);a&&("string"==typeof a&&a.startsWith("0x08c379a0")||"string"==typeof a&&a.startsWith("0x4e487b71"));l.reason||(null==(t=l.cause)?void 0:t.reason)||(null==(n=l.cause)?void 0:n.shortMessage)||(null==(s=l.data)||s.message);if(!j){const{userFriendlyMessage:e}=(e=>{if(!e.message)return{revertReason:"Transaction will revert",userFriendlyMessage:"Transaction simulation failed"};const t=e.message.toLowerCase();return t.includes("abi encoding params/values length mismatch")?{revertReason:"Smart contract parameter mismatch. This is likely a technical issue.",userFriendlyMessage:"Technical error: Contract parameters mismatch. Please try again or contact support."}:t.includes("payment id already used")?{revertReason:"This payment ID has already been used.",userFriendlyMessage:"This payment has already been processed. Please check your transaction history."}:t.includes("percentages must equal 100")?{revertReason:"Payment split percentages are incorrect.",userFriendlyMessage:"Internal error: Payment split configuration is invalid. Please contact support."}:t.includes("token transfer failed")||t.includes("transfer amount exceeds")?{revertReason:"Insufficient token balance or approval.",userFriendlyMessage:"Insufficient balance or token approval. Please check your wallet balance."}:t.includes("amount must be greater than 0")?{revertReason:"Payment amount is invalid.",userFriendlyMessage:"Invalid payment amount. Please try again."}:t.includes("invalid recipient")||t.includes("zero address")?{revertReason:"One of the payment recipients has an invalid address.",userFriendlyMessage:"Payment configuration error: Invalid recipient address. Please contact support."}:t.includes("insufficient gas")||t.includes("out of gas")?{revertReason:"Insufficient gas for transaction.",userFriendlyMessage:"Not enough gas to process transaction. Please increase gas limit or check ETH balance."}:t.includes("nonce")?{revertReason:"Transaction nonce conflict.",userFriendlyMessage:"Transaction ordering conflict. Please try again in a moment."}:{revertReason:e.message,userFriendlyMessage:`Transaction simulation failed: ${e.message.substring(0,100)}${e.message.length>100?"...":""}`}})(l);throw new Error(e)}}const I=await cn(g,w),S="arbitrum"===b.shortName,A=S?2:0;let E;for(let e=0;e<=A;e++)try{if(e>0){const t=2e3*e;await new Promise(e=>setTimeout(e,t))}E=await r.writeContract(g,{address:h.contractAddress,abi:k,functionName:"splitPayment",args:[N],...I});break}catch(d){const t=(null==(a=d.message)?void 0:a.includes("Internal JSON-RPC error"))||(null==(i=d.message)?void 0:i.includes("-32603"))||(null==(c=d.message)?void 0:c.includes("nonce"));if(e===A||!t&&!S)throw d}return y(E),m("processing"),window.coinleyPendingSplitPayment=null,E}catch(u){on(u,"split_payment_transaction");const e=rn(u);throw h(e),m("error"),u}},P=async t=>{try{if(m("processing"),!o||!o.processPayment)throw new Error("API instance not available or missing processPayment method");await new Promise(e=>setTimeout(e,8e3));const n=await o.processPayment(e.id,t,a.shortName,i);return m("success"),n}catch(n){on(n,"final_payment_processing");const e=rn(n);throw h(e),m("error"),n}};return{transactionStep:d,transactionError:u,currentTransactionHash:p,txPending:b,isConfirming:k,isConfirmed:N,executePaymentTransaction:async()=>{var n,s;if(!i||!(null==e?void 0:e.contractCall))throw new Error("Missing wallet connection or payment data");const o=e.contractCall;if(!o.contractAddress)throw new Error("PaymentSplitter contract data missing from payment response");if((null==l?void 0:l.ensureCorrectNetwork)&&a){if(!(await l.ensureCorrectNetwork(a)))throw new Error("Network verification failed. Please ensure you are on the correct network.")}if(!t.contractAddress)throw new Error("Native token transactions not yet supported with PaymentSplitter. Please use ERC-20 tokens.");{const l=t.decimals||6,k=o.approvalAmount||Math.floor(e.totalAmount*Math.pow(10,l));try{let e,n="unknown";try{e=await r.readContract(g,{address:o.tokenAddress,abi:an,functionName:"balanceOf",args:[i]}),n="wallet-rpc"}catch(d){const t=(null==a?void 0:a.chainId)||(null==a?void 0:a.id);if(!t)throw d;{const s=(e=>{const t={1:_t,56:Ot,137:en,42161:Mt,10:Xt,43114:Rt,42220:Yt,8453:Gt}[e],n={1:[`https://eth-mainnet.g.alchemy.com/v2/${ln}`,"https://cloudflare-eth.com","https://eth.llamarpc.com","https://ethereum.publicnode.com"],56:[`https://bnb-mainnet.g.alchemy.com/v2/${ln}`,"https://bsc-dataseed.bnbchain.org","https://bsc-dataseed-public.bnbchain.org","https://bsc.nodereal.io"],137:[`https://polygon-mainnet.g.alchemy.com/v2/${ln}`,"https://polygon.llamarpc.com","https://polygon-rpc.com","https://polygon.drpc.org"],42161:[`https://arb-mainnet.g.alchemy.com/v2/${ln}`,"https://arb1.arbitrum.io/rpc","https://arbitrum.llamarpc.com"],10:[`https://opt-mainnet.g.alchemy.com/v2/${ln}`,"https://mainnet.optimism.io","https://optimism.llamarpc.com"],43114:[`https://avax-mainnet.g.alchemy.com/v2/${ln}`,"https://api.avax.network/ext/bc/C/rpc","https://avalanche.public-rpc.com"],42220:[`https://celo-mainnet.g.alchemy.com/v2/${ln}`,"https://forno.celo.org","https://celo.drpc.org"],8453:[`https://base-mainnet.g.alchemy.com/v2/${ln}`,"https://mainnet.base.org","https://base.llamarpc.com","https://base.meowrpc.com"]}[e];if(!t||!n)return null;const s=n.map(e=>c.http(e,{timeout:1e4,retryCount:1}));return c.createPublicClient({chain:t,transport:c.fallback(s)})})(x(t));if(!s)throw d;try{e=await s.readContract({address:o.tokenAddress,abi:an,functionName:"balanceOf",args:[i]}),n="fallback-rpc"}catch(u){throw d}}}const s=BigInt(k);if(e<s){const n=`Insufficient ${t.symbol} balance. You have ${(Number(e)/Math.pow(10,l)).toFixed(6)} ${t.symbol} but need ${(Number(s)/Math.pow(10,l)).toFixed(6)} ${t.symbol}`;throw new Error(n)}}catch(p){if(p.message.includes("Insufficient"))throw p}m("approve"),window.coinleyPendingSplitPayment={contractCall:o,selectedToken:t,paymentData:e,selectedNetwork:a};try{const e="0xdac17f958d2ee523a2206206994597c13d831ec7"===o.tokenAddress.toLowerCase()||"USDT"===t.symbol.toUpperCase();let n,s=c.erc20Abi;e&&(s=sn);try{n=BigInt(k)}catch(f){throw new Error(`Invalid amount value: ${k}`)}let l=0n,d=0;const u=3;for(;d<u;)try{l=await r.readContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[i,o.contractAddress]});break}catch(b){d++,d<u?await new Promise(e=>setTimeout(e,2e3)):l=0n}if(l>=n){m("splitPayment");const e=await C();return e&&await P(e),e}if(e&&l>0n){const e=await cn(g,a.chainId),t=await r.writeContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[o.contractAddress,0n],...e});await r.waitForTransactionReceipt(g,{hash:t,confirmations:1,timeout:12e4})}const h=await cn(g,a.chainId),p=await r.writeContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[o.contractAddress,n],...h});y(p);await r.waitForTransactionReceipt(g,{hash:p,confirmations:1,timeout:12e4});await new Promise(e=>setTimeout(e,3e3));let x=0;const v=3;let N=!1;for(;x<v&&!N;){try{if(await r.readContract(g,{address:o.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[i,o.contractAddress]})>=n){N=!0;break}x<v-1&&await new Promise(e=>setTimeout(e,2e3))}catch(w){x<v-1&&await new Promise(e=>setTimeout(e,2e3))}x++}const j=await C();return j&&await P(j),j}catch(v){on(v,"approve_transaction");const e=rn(v);if(h(e),m("idle"),(null==(n=v.message)?void 0:n.includes("User rejected"))||(null==(s=v.message)?void 0:s.includes("User denied"))||4001===v.code)throw new Error("Transaction was cancelled by user");throw new Error(`Approve failed: ${v.message}`)}}},executeSplitPayment:C,processFinalPayment:P,resetTransaction:()=>{m("idle"),h(""),y(null),window.coinleyPendingSplitPayment=null},setTransactionError:h,setTransactionStep:m}},mn=({options:e=[],value:s,onChange:a,placeholder:r,renderOption:i,getOptionKey:o,getOptionValue:c,getSearchableText:d,disabled:m=!1})=>{const[u,h]=n.useState(!1),[p,y]=n.useState(""),[g,f]=n.useState({top:0,left:0,width:400,maxHeight:450}),b=n.useRef(null),x=n.useRef(null),w=e.filter(e=>(d?d(e):"").toLowerCase().includes(p.toLowerCase())),v=e.find(e=>c(e)===s),k=()=>{if(x.current){const e=window.innerWidth,t=window.innerHeight,n=Math.min(400,e-40),s=Math.min(450,t-100);f({top:t/2-s/2,left:e/2-n/2,width:n,maxHeight:s})}};n.useEffect(()=>{const e=e=>{b.current&&!b.current.contains(e.target)&&x.current&&!x.current.contains(e.target)&&(h(!1),y(""))},t=()=>{u&&k()};if(u){k();const n=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${n}px`,document.body.style.width="100%",document.addEventListener("mousedown",e),window.addEventListener("resize",t)}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",window.scrollTo(0,-1*parseInt(e||"0"))}document.removeEventListener("mousedown",e),window.removeEventListener("resize",t)}},[u]);const N=u&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-30 transition-opacity",style:{zIndex:999998},onClick:()=>{h(!1),y("")}}),t.jsxs("div",{ref:b,className:"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden",style:{top:g.top,left:g.left,width:g.width,maxHeight:g.maxHeight,zIndex:999999,transform:"translateZ(0)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50",children:[t.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:r||"Select Option"}),t.jsx("button",{onClick:()=>{h(!1),y("")},className:"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsx("div",{className:"p-4 border-b border-gray-200 bg-gray-50",children:t.jsx("input",{type:"text",placeholder:"Search networks and tokens...",value:p,onChange:e=>y(e.target.value),className:"w-full p-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#7042D2]/20 focus:border-[#7042D2] text-sm",style:{fontFamily:"Bricolage Grotesque, sans-serif"},autoFocus:!0})}),t.jsx("div",{className:"overflow-y-auto custom-scrollbar",style:{maxHeight:(g.maxHeight||450)-180+"px",minHeight:"200px"},children:0===w.length?t.jsxs("div",{className:"p-8 text-gray-500 text-center",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"text-4xl mb-3",children:"๐"}),t.jsx("div",{className:"text-lg mb-2",children:"No options found"}),t.jsx("div",{className:"text-sm text-gray-400",children:"Try a different search term"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("span",{className:"font-semibold",children:w.length})," option",1!==w.length?"s":""," available"]}),t.jsx("div",{className:"p-2",children:w.map(e=>t.jsx("button",{type:"button",onClick:()=>{a(c(e)),h(!1),y("")},className:"w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 "+(c(e)===s?"bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30":"text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20"),style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:i(e)},o(e)))})]})}),t.jsx("div",{className:"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center",children:t.jsx("div",{className:"text-xs text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:w.length>5?"โ๏ธ Scroll to see more options":"โจ Select your preferred option"})})]})]});return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"relative",children:t.jsx("button",{ref:x,type:"button",onClick:()=>{m||(u||k(),h(!u))},disabled:m,className:`w-full p-4 border-2 rounded-2xl bg-gradient-to-r from-white to-gray-50 text-left focus:outline-none focus:ring-3 focus:ring-[#7042D2]/20 focus:border-[#7042D2] transition-all duration-300 ease-out shadow-lg hover:shadow-xl ${m?"opacity-50 cursor-not-allowed":"hover:border-[#7042D2]/50 cursor-pointer"} ${u?"border-[#7042D2] ring-3 ring-[#7042D2]/20":"border-gray-200"}`,style:{minHeight:"60px",fontFamily:"Bricolage Grotesque, sans-serif",fontSize:"16px",fontWeight:"500"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center space-x-3",children:v?i(v):t.jsx("span",{className:"text-gray-500",children:r})}),t.jsx("div",{className:"transform transition-transform duration-200 "+(u?"rotate-180":""),children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 text-[#7042D2]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]})})}),"undefined"!=typeof document&&document.body&&l.createPortal(N,document.body),t.jsx("style",{jsx:!0,children:"\n .custom-scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #7042D2 #f1f1f1;\n }\n .custom-scrollbar::-webkit-scrollbar {\n width: 12px;\n }\n .custom-scrollbar::-webkit-scrollbar-track {\n background: #f8f9fa;\n border-radius: 10px;\n margin: 4px;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb {\n background: linear-gradient(180deg, #7042D2 0%, #5b34b1 100%);\n border-radius: 10px;\n border: 2px solid #f8f9fa;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb:hover {\n background: linear-gradient(180deg, #5b34b1 0%, #4c2a93 100%);\n }\n .custom-scrollbar::-webkit-scrollbar-corner {\n background: #f8f9fa;\n }\n "})]})},un=({currentStep:e,targetStep:s,children:a,className:r="",duration:i=300})=>{const[o,c]=n.useState(e===s),[l,d]=n.useState(e===s);return n.useEffect(()=>{e===s?(d(!0),setTimeout(()=>c(!0),10)):(c(!1),setTimeout(()=>d(!1),i))},[e,s,i]),l?t.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${o?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${r}\n `,style:{transitionDuration:`${i}ms`},children:a}):null},hn=({status:e,message:s,theme:a="light",payment:r=null,transactionHash:i=null,selectedPaymentMethod:o=null,selectedNetwork:c=null,merchantName:l="Merchant",onClose:d=null})=>{const[m,u]=n.useState(!1),[h,p]=n.useState(0);n.useEffect(()=>{if("processing"===e){const e=setInterval(()=>{p(e=>e>=90?e:e+15*Math.random())},500);return()=>clearInterval(e)}},[e]);const y=async()=>{if(i)try{await navigator.clipboard.writeText(i),u(!0),setTimeout(()=>u(!1),2e3)}catch(e){}},g=()=>{switch(e){case"processing":return t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20"}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("div",{className:"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse"})})]});case"success":return t.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return t.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"processing"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Processing Payment"}),t.jsx("p",{className:"text-center text-gray-600 mb-6",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Your transaction has been sent to the blockchain and is being processed..."}),t.jsxs("div",{className:"w-full max-w-xs mb-4",children:[t.jsx("div",{className:"bg-gray-200 rounded-full h-3",children:t.jsx("div",{className:"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out",style:{width:`${h}%`}})}),t.jsxs("div",{className:"text-center mt-2 text-sm text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Processing... ",Math.round(h),"%"]})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Transaction submitted"})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Confirming on blockchain..."})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-gray-300 rounded-full"}),t.jsx("span",{className:"text-sm text-gray-400",children:"Finalizing payment..."})]})]}),t.jsx("div",{className:"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-800 text-center",children:"Please don't close this window. This usually takes 10-30 seconds."})})]}):"success"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Payment Successful!"}),r&&o&&t.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Your payment of ",t.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[r.totalAmount||r.amount," ",o.currency]})," has been completed."]}),i&&t.jsxs("div",{className:"w-full mb-6 px-4",children:[t.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Transaction Details"}),t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100 mb-3",onClick:y,children:[t.jsx("span",{className:"font-mono text-sm text-gray-700",children:(f=i,f?f.length<=16?f:`${f.slice(0,8)}...${f.slice(-8)}`:"")}),t.jsxs("div",{className:"flex items-center",children:[m?t.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(()=>{const e=((e,t)=>{if(!e||!t)return null;const n="string"==typeof t?t:t.shortName||t.name;return{ethereum:`https://etherscan.io/tx/${e}`,bsc:`https://bscscan.com/tx/${e}`,polygon:`https://polygonscan.com/tx/${e}`,arbitrum:`https://arbiscan.io/tx/${e}`,optimism:`https://optimistic.etherscan.io/tx/${e}`,avalanche:`https://snowtrace.io/tx/${e}`,celo:`https://celoscan.io/tx/${e}`,base:`https://basescan.org/tx/${e}`}[null==n?void 0:n.toLowerCase()]||null})(i,c),n=(e=>{if(!e)return"Explorer";const t="string"==typeof e?e:e.shortName||e.name;return{ethereum:"Etherscan",bsc:"BscScan",polygon:"PolygonScan",arbitrum:"Arbiscan",optimism:"Optimistic Etherscan",avalanche:"SnowTrace",celo:"CeloScan",base:"BaseScan"}[null==t?void 0:t.toLowerCase()]||"Explorer"})(c);return c&&e&&t.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 w-full p-3 rounded-lg border border-[#7042D2] bg-white hover:bg-purple-50 transition-colors group",children:[t.jsxs("span",{className:"text-sm font-medium text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["View on ",n]}),t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})()]}),d&&t.jsx("button",{onClick:d,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Close"})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[t.jsx("div",{className:"mb-4",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),t.jsx("p",{className:"text-center text-gray-600",children:s})]});var f},pn={bitcoin:1,ethereum:1027,bsc:1839,polygon:3890,cardano:2010,avalanche:5805,fantom:3513,arbitrum:11841,optimism:11840,USDT:825,USDC:3408,BUSD:4687,DAI:4943,FRAX:6952,TUSD:2563,USDP:5992,USDD:5994,FDUSD:26081,PYUSD:28295,WBTC:3717,LINK:1975,UNI:7083,AAVE:7278,COMP:5692,YFI:5864,MKR:1518,SUSHI:6758,CRV:6538,SNX:2586,UMA:5617,BAL:5728,MANA:1966,SAND:6210,APE:18876,LDO:8e3,GRT:6719,ENS:13855,RPL:2943,SHIB:5994,MATIC:3890,BNB:1839,ADA:2010,SOL:5426,DOT:6636,AVAX:5805,TRX:1958,ALGO:4030,FTM:3513,ARB:11841,OP:11840,"1INCH":8104,DYDX:11156,ICP:8916,FIL:2280,CAKE:7186,RUNE:4157,ALPHA:7232,BNT:1727,KNC:1982,ZRX:1896,REN:2539,LRC:1934,WETH:2396,WMATIC:3890,WBNB:1839,UST:7129,USTC:7129,LUSD:8115,MIM:9681,FEI:8642,TRIBE:8741,RAI:8525,SUSD:2927},yn={ethereum:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bsc:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",polygon:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arbitrum:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avalanche:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",celo:"https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png",optimism:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",base:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",eth:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bnb:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",trx:"https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png",algo:"https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png",sol:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png",matic:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arb:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avax:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",op:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png"},gn={metamask:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",coinbase:"https://avatars.githubusercontent.com/u/18060234?s=280&v=4",rabby:"https://rabby.io/logo-128.png",zerion:"https://app.zerion.io/favicon-32x32.png",phantom:"https://phantom.app/favicons/apple-touch-icon.png",trust:"https://trustwallet.com/favicon-196x196.png",okx:"https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png",binance:"https://bin.bnbstatic.com/static/images/common/favicon.ico",cryptocom:"https://crypto.com/favicon.ico",hot:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==",backpack:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiMwMEQ0QUEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMGg4djJoLTJ2NmgtdjhoLTZWMTB6bTIgMnY0aDJWMTJ6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4=","1inch":"https://1inch.io/favicon.svg",default:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=="},fn=e=>(e=>{if(!e)return null;const t=pn[e.toUpperCase()];return t?`https://s2.coinmarketcap.com/static/img/coins/64x64/${t}.png`:null})(e),bn=(e,t)=>{const n=e.toLowerCase(),s=t.toLowerCase();for(const[a,r]of Object.entries(gn))if(n.includes(a)||s.includes(a))return r;return gn.default},xn=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),wn=e=>{switch(e){case"trust":return window.ethereum&&!0===window.ethereum.isTrust;case"metaMask":return window.ethereum&&!0===window.ethereum.isMetaMask;case"injected":return window.ethereum&&!window.ethereum.isMetaMask&&!window.ethereum.isCoinbaseWallet;default:return!1}},vn=(e,t)=>{if(!t)return[];if(!["ethereum","bsc","polygon","arbitrum","optimism","avalanche","celo","base"].includes(t.shortName))return[];return[...(e||[]).map(e=>(e=>({type:e.id,name:e.name,icon:bn(e.name,e.id),description:`Connect using ${e.name}`,isInstalled:!0,connector:e,isWagmi:!0}))(e)),...xn()?[{type:"trust",name:"Trust Wallet",icon:"๐ก๏ธ",description:"Multi-chain wallet with transaction deep links",isInstalled:!1,connector:null,isWagmi:!1,mobileOnly:!0,hasTransactionDeepLinks:!0}]:[]]},kn=(e,t,n,s,a="metamask",r=null)=>{if(!e)return null;try{const t="https://paymentscreen.vercel.app",s=new URLSearchParams,r=(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId);if(!r)return null;s.set("paymentId",r),s.set("preferredWallet",a),s.set("isMobile","true");const i=`${t}?${s.toString()}`;let o;switch(a){case"metamask":o=`https://metamask.app.link/dapp/${i.replace("https://","")}`;break;case"trust":const e=(null==n?void 0:n.chainId)||1;o=`https://link.trustwallet.com/open_url?coin_id=${(e=>{const t="string"==typeof e&&e.startsWith("0x")?parseInt(e,16):parseInt(e);return[1,56,137,42161,10,43114,42220,8453].includes(t)?60:{}[t]||60})(e)}&url=${encodeURIComponent(i)}`;break;case"coinbase":o=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(i)}`;break;default:o=i}return o}catch(i){return null}},Nn=(e,t)=>{if(!t)return null;try{switch(e){case"metamask":return t.includes("metamask.app.link")?t:`https://metamask.app.link/dapp/${t.replace("https://","")}`;case"trust":return t.includes("link.trustwallet.com")?t:`https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(t)}`;case"coinbase":return t.includes("go.cb-w.com")?t:`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t)}`;default:return t}}catch(n){return t}},Cn=Object.freeze(Object.defineProperty({__proto__:null,generateMobilePaymentDeepLink:Nn,generateQRPaymentURI:kn},Symbol.toStringTag,{value:"Module"})),Pn=({walletAddress:e,amount:s,currency:a,network:r,theme:i="light",paymentData:o=null,onPaymentDetected:c=null,config:l=null,selectedToken:m=null,selectedNetwork:u=null,preferredWallet:h="metamask",compact:p=!1})=>{const[y,g]=n.useState(""),[f,b]=n.useState(""),[x,w]=n.useState(!0),[v,k]=n.useState(!1),[N,C]=n.useState(!1),P=n.useRef(null);return n.useEffect(()=>{(async()=>{if(null==o?void 0:o.id){w(!0);try{if(!m||!m.contractAddress)throw new Error("Cannot generate QR code: Token contract address required");if(!u||!u.chainId)throw new Error("Cannot generate QR code: Network chain ID required");const e=kn(o,0,u,0,h);if(e.includes("metamask.app.link")||e.includes("link.trustwallet.com")||e.includes("go.cb-w.com"),!e)throw new Error("Failed to generate Coinley payment URL");g(e);const t=xn(),n=await d.toDataURL(e,{width:p?140:t?350:280,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===i?"#FFFFFF":"#000000",light:"dark"===i?"#000000":"#FFFFFF"}});b(n),w(!1)}catch(e){w(!1)}}else w(!1)})()},[o,s,a,r,i,m,u,l,h]),n.useEffect(()=>()=>{P.current&&clearInterval(P.current)},[]),t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex gap-3 items-start w-full mb-2",children:[t.jsx("div",{className:"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0",children:x?t.jsx("div",{className:"flex items-center justify-center",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1"}),t.jsx("div",{className:"text-xs text-gray-600",children:"Generating..."})]})}):f?t.jsx("img",{src:f,alt:"Payment QR Code",className:"rounded-lg",style:{width:140,height:140}}):t.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center p-2",children:[t.jsx("div",{className:"text-lg mb-1",children:"โ ๏ธ"}),t.jsx("div",{className:"text-xs text-gray-600",children:(null==o?void 0:o.id)?"QR Failed":"Payment not created"})]})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-center",children:[t.jsxs("div",{className:"p-2 bg-gray-50 rounded-lg mb-2",children:[t.jsxs("div",{className:"flex justify-between items-center mb-1",children:[t.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"text-sm font-bold text-[#7042D2]",children:[s," ",a]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),t.jsx("span",{className:"text-xs font-medium text-gray-700",children:r})]})]}),N?t.jsxs("div",{className:"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg",children:[t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Payment Received!"]}):t.jsx("div",{className:"p-1.5 rounded-lg bg-blue-50 border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-700 text-center leading-tight",children:"๐ฑ Scan with phone camera"})})]})]})})},jn=({selectedNetwork:e,onWalletSelect:a,onConnect:r,connectedWallet:i,loading:o,paymentData:c=null,selectedToken:l=null,api:d=null})=>{const[m,u]=n.useState(null),{connectors:h}=s.useConnect(),{isConnected:p,address:y}=s.useAccount(),g=vn(h,e),f=async(t,n)=>{if(xn())if(c)try{const{generateQRPaymentURI:s,generateMobilePaymentDeepLink:a}=await Promise.resolve().then(()=>Cn),r=s(c,l,e,(null==d?void 0:d.config)||{},n);if(!r)throw new Error("Failed to generate payment URL");const i=a(n,r);if(!i)throw new Error(`Failed to generate ${t.name} deep link`);window.location.href=i}catch(s){alert(`Failed to open ${t.name}: ${s.message}`)}else alert("Please create a payment first before selecting a mobile wallet.");else alert(`Please install ${t.name} mobile app or use the browser extension if available.`)};return e?0===g.length?t.jsxs("div",{className:"text-center p-4",children:[t.jsxs("p",{className:"text-gray-500 mb-4",children:["No compatible wallets found for ",e.name]}),t.jsx("div",{className:"p-3 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-sm text-amber-800",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"font-medium mb-2",children:"Install a compatible wallet:"}),t.jsxs("div",{className:"space-y-1 text-xs",children:[t.jsxs("div",{children:["โข ",t.jsx("a",{href:"https://metamask.io/download/",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install MetaMask Wallet"})]}),t.jsxs("div",{children:["โข ",t.jsx("a",{href:"https://www.coinbase.com/wallet",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Coinbase Wallet"})]})]})]})})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Select Wallet for ",e.name]}),t.jsx(mn,{options:g,value:(null==i?void 0:i.walletType)||m||"",onChange:async e=>{u(e);const t=g.find(t=>t.type===e);t&&(a(e),t.isWagmi&&t.connector?await r(t.connector):t.isWagmi||await f(t,e))},placeholder:"Choose your wallet...",renderOption:e=>{var n,s;return t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsxs("div",{className:"w-8 h-8 flex items-center justify-center",children:[e.icon.startsWith("http")||e.icon.startsWith("data:")?t.jsx("img",{src:e.icon,alt:e.name,className:"w-6 h-6 rounded-full object-contain",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="block"}}):t.jsx("div",{className:"text-2xl",children:e.icon}),t.jsx("div",{className:"text-xl",style:{display:"none"},children:"๐"})]}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800 flex items-center",children:[e.name,wn(e.type)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),(null==i?void 0:i.walletType)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"})]}),t.jsx("div",{className:"text-sm text-gray-500",children:(null==i?void 0:i.walletType)===e.type?`Connected โข ${null==(n=i.account)?void 0:n.slice(0,6)}...${null==(s=i.account)?void 0:s.slice(-4)}`:e.description})]}),o&&m===e.type&&t.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]"})]})},getOptionKey:e=>e.type,getOptionValue:e=>e.type,getSearchableText:e=>`${e.name} ${e.description}`,disabled:o})]}):t.jsx("div",{className:"text-center p-4",children:t.jsx("p",{className:"text-gray-500",children:"Please select a network first"})})},In=(()=>{if("undefined"!=typeof process&&process.env)return!1;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.includes("192.168.")}return!1})()||(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search);return"true"===e.get("debug")||"true"===e.get("debugMode")}return!1})(),Sn=({paymentData:e,selectedToken:s,selectedNetwork:a,config:r,onPaymentStarted:i=()=>{},onError:o=()=>{}})=>{var c,l;const[d,m]=n.useState(null),[u,h]=n.useState(!1),[p,y]=n.useState([]),[g,f]=n.useState(!1),[b,x]=n.useState(0);n.useEffect(()=>{var t,n,r;(null==e?void 0:e.id)&&(null==s?void 0:s.contractAddress)&&(null==a?void 0:a.chainId)&&((null==(t=null==e?void 0:e.contractCall)?void 0:t.contractAddress)||(null==e?void 0:e.contractAddress))?w("success","โ
Payment data complete",{paymentId:e.id,tokenContract:s.contractAddress,chainId:a.chainId,paymentContract:(null==(r=null==e?void 0:e.contractCall)?void 0:r.contractAddress)||(null==e?void 0:e.contractAddress)}):(w("debug","โณ Waiting for complete payment data",{hasPaymentId:!!(null==e?void 0:e.id),hasTokenContract:!!(null==s?void 0:s.contractAddress),hasChainId:!!(null==a?void 0:a.chainId),hasPaymentContract:!(!(null==(n=null==e?void 0:e.contractCall)?void 0:n.contractAddress)&&!(null==e?void 0:e.contractAddress)),checkCount:b}),x(e=>e+1))},[e,s,a,b]);const w=(e,t,n=null)=>{const s=(new Date).toLocaleTimeString(),a={id:Date.now()+Math.random(),type:e,message:t,data:n,timestamp:s};In&&(y(e=>[...e,a].slice(-20)),e.toUpperCase())},v=[{id:"metamask",name:"MetaMask",icon:"๐ฆ",description:"Connect with MetaMask mobile"},{id:"trust",name:"Trust Wallet",icon:"๐ก๏ธ",description:"Connect with Trust Wallet"},{id:"coinbase",name:"Coinbase Wallet",icon:"๐",description:"Connect with Coinbase Wallet"}];if(!e)return t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"โ ๏ธ Payment Required"}),t.jsx("div",{className:"text-sm text-amber-700",children:"Please create a payment before selecting a wallet"})]})});const k=(null==e?void 0:e.id)&&(null==s?void 0:s.contractAddress)&&(null==a?void 0:a.chainId)&&((null==(c=null==e?void 0:e.contractCall)?void 0:c.contractAddress)||(null==e?void 0:e.contractAddress));return t.jsx("div",{className:"space-y-4",children:k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Select Mobile Wallet"}),t.jsx(mn,{options:v,value:d||"",onChange:async t=>{const n=v.find(e=>e.id===t);if(n){m(t),h(!0);try{if(w("info",`๐ Mobile wallet selected: ${n.name}`),!e)throw new Error("Payment data not available. Please create payment first.");w("debug","๐ Payment Data Check",{hasPaymentData:!!e,hasSelectedToken:!!s,hasSelectedNetwork:!!a,hasConfig:!!r,paymentId:(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId),tokenAddress:null==s?void 0:s.contractAddress,networkChainId:null==a?void 0:a.chainId,amount:(null==e?void 0:e.totalAmount)||(null==e?void 0:e.amount)||(null==r?void 0:r.amount)});const o=kn(e,0,a,0,t);if(!o)throw new Error("Failed to generate payment URL");w("success","๐ฑ Generated payment URL",{url:o,length:o.length});const c=Nn(t,o);if(!c)throw new Error(`Failed to generate ${n.name} deep link`);w("success",`๐ Deep link generated for ${n.name}`,{deepLink:c}),i({walletType:t,walletName:n.name,paymentUrl:o,deepLink:c}),setTimeout(()=>{w("info",`๐ฑ Opening ${n.name}...`),window.location.href=c},500)}catch(c){w("error","โ Mobile wallet connection failed",{error:c.message,walletId:t,hasPaymentData:!!e,hasSelectedToken:!!s,hasSelectedNetwork:!!a}),o(c.message),h(!1),m(null)}}},placeholder:"Choose your wallet...",renderOption:e=>t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsx("div",{className:"w-8 h-8 flex items-center justify-center",children:t.jsx("div",{className:"text-2xl",children:e.icon})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name,d===e.id&&u&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse",children:"Opening..."})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.description})]})]}),getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.description}`,disabled:u}),t.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"Select a wallet to open it with your payment details"})]}),u&&d&&t.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse",children:t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"}),t.jsxs("div",{className:"text-sm text-blue-700",children:["Opening ",null==(l=v.find(e=>e.id===d))?void 0:l.name,"..."]})]})}),t.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[t.jsxs("div",{className:"flex justify-between items-center text-sm",children:[t.jsx("span",{className:"text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"font-semibold text-gray-800",children:[e.totalAmount," ",(null==s?void 0:s.symbol)||"USDC"]})]}),t.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[t.jsx("span",{className:"text-gray-600",children:"Network:"}),t.jsx("span",{className:"text-gray-800",children:(null==a?void 0:a.name)||"Ethereum"})]})]}),t.jsx("div",{className:"p-3 bg-purple-50 border border-purple-200 rounded-lg",children:t.jsxs("div",{className:"text-xs text-purple-700",children:[t.jsx("div",{className:"font-medium mb-1",children:"๐ฑ Mobile Payment"}),t.jsx("div",{children:"Your selected wallet app will open with payment details pre-filled"})]})}),In&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("button",{onClick:()=>f(!g),className:"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors",children:[g?"๐ฝ Hide Debug Info":"๐ง Show Debug Info"," (",p.length," logs)"]}),g&&t.jsxs("div",{className:"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto",children:[t.jsx("div",{className:"text-white mb-2 font-bold",children:"๐ฑ Mobile Debug Panel"}),0===p.length?t.jsx("div",{className:"text-gray-400",children:"No debug logs yet. Try selecting a wallet..."}):p.map(e=>t.jsxs("div",{className:"mb-3 pb-2 border-b border-gray-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"px-2 py-1 rounded text-xs font-bold "+("error"===e.type?"bg-red-600 text-white":"success"===e.type?"bg-green-600 text-white":"debug"===e.type?"bg-blue-600 text-white":"bg-gray-600 text-white"),children:e.type.toUpperCase()}),t.jsx("span",{className:"text-gray-400",children:e.timestamp})]}),t.jsx("div",{className:"text-yellow-300 mb-1",children:e.message}),e.data&&t.jsx("div",{className:"text-gray-300 text-xs",children:t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer text-blue-300 hover:text-blue-200",children:"๐ Data"}),t.jsx("pre",{className:"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(e.data,null,2)})]})})]},e.id)),t.jsx("button",{onClick:()=>y([]),className:"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700",children:"Clear Logs"})]})]})]}):t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"โณ Preparing Payment..."}),t.jsx("div",{className:"text-sm text-amber-700",children:"Payment is being prepared. Please wait a moment..."}),t.jsx("div",{className:"mt-3",children:t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto"})})]})})})},An=({error:e,onRetry:n,onDismiss:s,context:a="payment",className:r=""})=>{if(!e)return null;const i=rn(e),o=(e=>{switch(e){case"user_rejected":return"info";case"insufficient_funds":case"wrong_network":case"wallet_disconnected":case"payment_pending":return"warning";case"network_error":case"gas_error":case"rate_limited":return"error";default:return"critical"}})(i.type),c=(e=>{switch(e){case"user_rejected":default:return"Try Again";case"insufficient_funds":return"Add Funds & Retry";case"wrong_network":return"Switch Network & Retry";case"wallet_disconnected":return"Reconnect Wallet";case"payment_pending":return"Check Again";case"network_error":case"rate_limited":return"Retry";case"popup_blocked":return"Allow Popups & Retry";case"mobile_wallet_error":return"Open Wallet App"}})(i.type),l={info:{container:"bg-blue-50 border-blue-200",title:"text-blue-800",message:"text-blue-700",icon:"โน๏ธ",button:"bg-blue-600 hover:bg-blue-700"},warning:{container:"bg-amber-50 border-amber-200",title:"text-amber-800",message:"text-amber-700",icon:"โ ๏ธ",button:"bg-amber-600 hover:bg-amber-700"},error:{container:"bg-red-50 border-red-200",title:"text-red-800",message:"text-red-700",icon:"โ",button:"bg-red-600 hover:bg-red-700"},critical:{container:"bg-red-50 border-red-300",title:"text-red-900",message:"text-red-800",icon:"๐จ",button:"bg-red-700 hover:bg-red-800"}},d=l[o]||l.error;return t.jsxs("div",{className:`p-4 border rounded-lg ${d.container} ${r}`,children:[t.jsxs("div",{className:"flex items-start space-x-3",children:[t.jsx("div",{className:"flex-shrink-0 text-xl",children:d.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:`font-semibold ${d.title} mb-1`,children:i.title}),t.jsx("div",{className:`text-sm ${d.message} mb-2`,children:i.message}),i.suggestion&&t.jsxs("div",{className:`text-xs ${d.message} opacity-90`,children:["๐ก ",i.suggestion]})]}),s&&t.jsx("button",{onClick:s,className:"flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Dismiss error",children:t.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:t.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),n&&t.jsxs("div",{className:"mt-3 flex justify-end space-x-2",children:[s&&"info"===o&&t.jsx("button",{onClick:s,className:"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:n,className:`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${d.button}`,children:c})]}),!1]})},En="method",Fn="confirm",Un="processing",Dn="success",Tn="wallet",Bn="qr",Ln="Bricolage Grotesque, sans-serif",Mn=new a.QueryClient,Rn=({publicKey:e,apiKey:a,apiSecret:i,apiUrl:o,config:c,onSuccess:l,onError:d,onClose:m,isOpen:u,theme:p="light"})=>{const y=((e,t,s)=>{const[a,r]=n.useState("method"),[i,o]=n.useState([]),[c,l]=n.useState([]),[d,m]=n.useState(null),[u,h]=n.useState(null),[p,y]=n.useState(null),[g,b]=n.useState(null),[x,w]=n.useState(!1),[v,k]=n.useState(""),[N,C]=n.useState(!1),[P,j]=n.useState("Processing transaction..."),[I,S]=n.useState("wallet"),[A,E]=n.useState(null),F=n.useRef(new f(e,t,s));return{currentStep:a,networks:i,tokens:c,selectedNetwork:d,selectedToken:u,paymentMethod:p,paymentData:g,loading:x,error:v,processing:N,processingMessage:P,paymentType:I,actualTransactionHash:A,setCurrentStep:r,setSelectedNetwork:m,setSelectedToken:h,setPaymentMethod:y,setError:k,setProcessing:C,setProcessingMessage:j,setPaymentType:S,setActualTransactionHash:E,loadData:async()=>{var e,t;try{w(!0),k("");const[n,s]=await Promise.all([F.current.getNetworks(),F.current.getTokens()]),a=(null==(e=n.networks)?void 0:e.reduce((e,t)=>{if("solana"===t.shortName||"tron"===t.shortName||"algorand"===t.shortName)return e;if(!t.chainId||null===t.chainId)return e;const n=`${t.chainId}-${t.shortName}`;return e.some(e=>`${e.chainId}-${e.shortName}`===n)||e.push(t),e},[]))||[],r=(null==(t=s.stablecoins)?void 0:t.reduce((e,t)=>{var n,s,a;if("USDC"!==t.symbol&&"USDT"!==t.symbol)return e;if("solana"===(null==(n=t.Network)?void 0:n.shortName)||"tron"===(null==(s=t.Network)?void 0:s.shortName)||"algorand"===(null==(a=t.Network)?void 0:a.shortName))return e;const r=`${t.symbol}-${t.networkId}`;return e.some(e=>`${e.symbol}-${e.networkId}`===r)||e.push(t),e},[]))||[];o(a),l(r)}catch(n){k("Failed to load payment options. Using fallback data.")}finally{w(!1)}},createPayment:async e=>{try{w(!0),k("");const t={amount:e.amount,currency:u.symbol,network:d.shortName,customerEmail:e.customerEmail,callbackUrl:e.callbackUrl,metadata:{...e.metadata,merchantWalletAddresses:e.merchantWalletAddresses,paymentMethod:p,selectedNetwork:d.shortName,selectedToken:u.symbol,wagmiEnabled:!0}},n=await F.current.createPayment(t);b(n.payment),r("confirm")}catch(t){k(t.message)}finally{w(!1)}},failPayment:async(e="Payment cancelled by user")=>{if(null==g?void 0:g.id)try{await F.current.failPayment(g.id,e)}catch(t){}},resetState:()=>{r("method"),m(null),h(null),y(null),b(null),k(""),C(!1),E(null),S("wallet")},resetTransactionState:()=>{k(""),C(!1),E(null),r("confirm")},api:F.current}})(o,e||a,e?null:i),b=(()=>{const[e,t]=n.useState(null),[a,i]=n.useState(null),[o,c]=n.useState(""),{connect:l,connectors:d}=s.useConnect(),{isConnected:m,address:u,chain:h}=s.useAccount(),{switchChain:p}=s.useSwitchChain();return n.useEffect(()=>{i(m&&u?{account:u,chainId:null==h?void 0:h.id,walletType:e}:null)},[m,u,h,e]),{selectedWalletType:e,connectedWallet:a,connectionError:o,isConnected:m,address:u,chain:h,connectors:d,handleWalletSelection:e=>{t(e),c("")},connectWallet:async(e,t=null)=>{var n,s,a;if(!e)return c("Please select a wallet first"),!1;try{if(c(""),await l({connector:e}),t){const o=w(t.shortName),l=(null==(n=e.name)?void 0:n.toLowerCase())||"",d=l.includes("zerion")||l.includes("trust")||l.includes("rabby")?5e3:500;await new Promise(e=>setTimeout(e,d));const m=r.getAccount(g).chainId;if(o&&m!==o)try{await p({chainId:o}),await new Promise(e=>setTimeout(e,1e3))}catch(i){return 4001===i.code||(null==(s=i.message)?void 0:s.includes("User rejected"))?c("Network switch was cancelled by user"):(null==(a=i.message)?void 0:a.includes("Unrecognized chain ID"))?c(`${t.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${t.name}. Please switch manually in your wallet.`),!1}}return!0}catch(o){return 4001===o.code||o.message.includes("User rejected")||o.message.includes("rejected")?c("User cancelled the connection request"):c(`Failed to connect to ${e.name}. Please try again.`),!1}},disconnectWallet:()=>{i(null),t(null),c("")},switchChain:p,ensureCorrectNetwork:async e=>{var t,n;if(!e)return!0;try{const a=w(e.shortName),i=r.getAccount(g).chainId;if(a&&i!==a)try{return await p({chainId:a}),await new Promise(e=>setTimeout(e,1e3)),!0}catch(s){return 4001===s.code||(null==(t=s.message)?void 0:t.includes("User rejected"))?c("Network switch was cancelled. Please switch to the correct network in your wallet."):(null==(n=s.message)?void 0:n.includes("Unrecognized chain ID"))?c(`${e.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${e.name}. Please switch manually in your wallet.`),!1}return!0}catch(B){return c("Failed to verify network. Please check your wallet connection."),!1}},clearError:()=>{c("")},setSelectedWalletType:t,connect:l}})(),[x,v]=n.useState("metamask"),[k,N]=n.useState(!1),[C,P]=n.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[j,I]=n.useState(!1);n.useEffect(()=>{N(xn())},[]);const{currentStep:S,networks:A,tokens:E,selectedNetwork:F,selectedToken:U,paymentData:D,loading:T,error:B,paymentType:L,loadData:M,createPayment:R,failPayment:$,resetState:G,setSelectedNetwork:O,setSelectedToken:z,setPaymentType:W,setCurrentStep:H,setError:q}=y,{connectedWallet:V,address:Q,connectWallet:K,handleWalletSelection:Z}=b,Y=dn(D,U,F,Q,y.api,b),{executePaymentTransaction:_,processFinalPayment:J,transactionStep:X,transactionError:ee,currentTransactionHash:te}=Y;n.useEffect(()=>{S===Dn&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[S]),n.useEffect(()=>{if(u){M(),G();const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(u){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[u]),n.useEffect(()=>{if("processing"===X||"approve"===X||"splitPayment"===X){const e=setTimeout(()=>{q("Transaction timed out. Please try again."),H(Fn),Y.resetTransaction()},12e4);return()=>clearTimeout(e)}},[X]);const ne=async()=>{await $(),m()};return u?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:ne,"aria-hidden":"true"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"relative pt-4 w-full max-w-md max-h-[90vh] mx-auto shadow-xl bg-gray-100 rounded-3xl flex flex-col overflow-hidden",style:{zIndex:52},children:[t.jsxs("div",{className:"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full",children:[t.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[t.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",children:t.jsx("img",{src:h,alt:"Coinley"})}),t.jsx("span",{className:"text-base font-semibold text-gray-800",style:{fontFamily:Ln},children:"Payment Details"})]}),S!==Dn&&S!==Un&&t.jsx("button",{onClick:ne,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c&&S!==Dn&&t.jsx("div",{className:"flex-shrink-0 mb-3 px-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-xs text-gray-600",children:"Total Amount"}),t.jsxs("div",{className:"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight",style:{fontFamily:Ln},children:["$",(se=c.amount,parseFloat(se).toFixed(2))]}),t.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"No additional fees"}),t.jsx("div",{className:"text-xs text-gray-600 mt-2",children:"Payment to:"}),t.jsxs("div",{className:"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center",style:{fontFamily:Ln},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),c.merchantName||"Merchant"]})]})}),t.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[t.jsx(un,{currentStep:S,targetStep:En,children:t.jsxs("div",{className:"pb-4 pt-3 px-5 bg-white rounded-t-2xl",children:[t.jsx("h3",{className:"font-semibold text-center mb-3 text-sm",style:{fontFamily:Ln},children:"Choose Payment Method"}),t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:Ln},children:"Select Network"}),t.jsx(mn,{options:A,value:(null==F?void 0:F.id)||"",onChange:e=>{const t=A.find(t=>t.id===e);O(t),z(null)},placeholder:"Choose your network...",renderOption:e=>{var n,s;const a="object"==typeof(r=e)&&(null==r?void 0:r.logo)?r.logo:"object"==typeof r&&(null==r?void 0:r.shortName)?yn[r.shortName.toLowerCase()]:"string"==typeof r?yn[r.toLowerCase()]:null;var r;return t.jsxs("div",{className:"flex items-center space-x-3",children:[a?t.jsx("img",{src:a,alt:e.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:a?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.shortName)?void 0:n.slice(0,2).toUpperCase()})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-gray-800",children:e.name}),t.jsx("div",{className:"text-sm text-gray-500",children:null==(s=e.shortName)?void 0:s.toUpperCase()})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.shortName}`,disabled:T})]}),F&&t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:Ln},children:"Select Token"}),t.jsx(mn,{options:E.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==F?void 0:F.shortName)||e.networkId===(null==F?void 0:F.id)}),value:(null==U?void 0:U.id)||"",onChange:e=>{const t=E.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==F?void 0:F.shortName)||e.networkId===(null==F?void 0:F.id)}).find(t=>t.id===e);z(t)},placeholder:"Choose your token...",renderOption:e=>{var n,s;const a=fn(e.symbol);return t.jsxs("div",{className:"flex items-center space-x-3",children:[a?t.jsx("img",{src:a,alt:e.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:a?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(n=e.symbol)?void 0:n.slice(0,2)})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name," (",e.symbol,")"]}),t.jsxs("div",{className:"text-sm text-gray-500",children:[(null==(s=e.Network)?void 0:s.name)||"Unknown Network",e.isStablecoin&&t.jsx("span",{className:"ml-2 text-green-600",children:"โข Stablecoin"})]})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.symbol}`,disabled:T})]}),F&&U&&t.jsx("button",{onClick:()=>R(c),disabled:T,className:"w-full bg-[#7042D2] text-white py-4 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200 shadow-lg hover:shadow-xl",style:{fontFamily:Ln},children:T?"Creating Payment...":"Continue"})]})}),t.jsx(un,{currentStep:S,targetStep:Fn,children:F&&U&&D&&t.jsxs("div",{className:"pb-4 pt-4 px-4 bg-white rounded-t-2xl",children:[!k&&t.jsx("div",{className:"mb-4",children:t.jsxs("div",{className:"flex border-b border-gray-200",children:[t.jsx("button",{onClick:()=>W(Tn),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(L===Tn?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:Ln},children:"Connect Wallet"}),t.jsx("button",{onClick:()=>W(Bn),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(L===Bn?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:Ln},children:"QR Code"})]})}),k?t.jsx(Sn,{paymentData:D,selectedToken:U,selectedNetwork:F,config:c,onPaymentStarted:e=>{P(!0),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.setItem("coinley_mobile_payment_started","true"),e.walletName},onError:e=>{q(e)}}):L===Tn?t.jsx(jn,{selectedNetwork:F,onWalletSelect:Z,onConnect:async e=>{await K(e,F)},connectedWallet:V,loading:T}):null,L===Bn&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-2",children:[t.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1.5 text-center",style:{fontFamily:Ln},children:"Optimize QR for:"}),t.jsx("div",{className:"flex gap-1.5 justify-center flex-wrap",children:[{id:"metamask",name:"MetaMask",icon:"๐ฆ"},{id:"trust",name:"Trust",icon:"๐ก๏ธ"},{id:"coinbase",name:"Coinbase",icon:"๐"}].map(e=>t.jsxs("button",{onClick:()=>v(e.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 "+(x===e.id?"bg-[#7042D2] text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"),style:{fontFamily:Ln},children:[t.jsx("span",{className:"text-sm",children:e.icon}),t.jsx("span",{children:e.name})]},e.id))})]}),t.jsx(Pn,{amount:(null==D?void 0:D.totalAmount)||(null==D?void 0:D.amount)||(null==c?void 0:c.amount),currency:null==U?void 0:U.symbol,network:null==F?void 0:F.shortName,theme:p,paymentData:D,config:c,selectedToken:U,selectedNetwork:F,preferredWallet:x,compact:!0})]}),(B||ee)&&t.jsx("div",{className:"mt-4",children:t.jsx(An,{error:ee||B,onRetry:()=>{q(""),Y.resetTransaction(),"error"===X&&V&&_()},onDismiss:()=>{q(""),Y.resetTransaction()},context:"payment"})}),t.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:()=>H(En),className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:Ln},children:"Back"}),t.jsx("button",{type:"button",onClick:async()=>{var e,t,n,s,a,r,i,o,c,d;if(k&&C){if(!(null==D?void 0:D.id))return void q("Payment ID not found. Please refresh and try again.");try{I(!0),H(Un),q("");const a=await y.api.checkPaymentStatus(D.id);if("completed"===(null==(e=a.payment)?void 0:e.status))H(Dn),l&&l({paymentId:D.id,transactionHash:a.payment.transactionHash,paymentDetails:a.payment});else if("pending"===(null==(t=a.payment)?void 0:t.status)){const e=await y.api.verifyQRPayment(D.id);if(e.success&&e.verified)H(Dn),l&&l({paymentId:D.id,transactionHash:null==(n=e.onChainData)?void 0:n.transactionHash,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";q(`${t}. Please complete the payment in your wallet and try again.`),H(Fn)}}else"failed"===(null==(s=a.payment)?void 0:s.status)?(q("Payment failed. Please try creating a new payment."),H(Fn)):(q("Payment not found. Please verify the payment ID and try again."),H(Fn))}catch(m){q(`Verification failed: ${m.message}. Please ensure payment was completed and try again.`),H(Fn)}finally{I(!1)}}else if(L!==Bn){if(V&&Q)try{H(Un),q("");const e=await _();e&&(q(""),Y.setTransactionError(""),H(Dn),l&&l({paymentId:D.id,transactionHash:e,paymentDetails:D}))}catch(m){H(Fn),(null==(c=m.message)?void 0:c.includes("User rejected"))||(null==(d=m.message)?void 0:d.includes("User denied"))||4001===m.code||"ACTION_REJECTED"===m.code?q("Transaction was cancelled by user. Please try again."):q(m.message||"Transaction failed. Please try again."),Y.resetTransaction()}}else{if(!(null==D?void 0:D.id))return void q("Payment ID not found. Please refresh and try again.");try{H(Un),q("");const e=await y.api.checkPaymentStatus(D.id);if("completed"===(null==(a=e.payment)?void 0:a.status))H(Dn),l&&l({paymentId:D.id,transactionHash:e.payment.transactionHash,paymentDetails:e.payment});else if("pending"===(null==(r=e.payment)?void 0:r.status)){const e=await y.api.verifyQRPayment(D.id);if(e.success&&e.verified)H(Dn),l&&l({paymentId:D.id,transactionHash:null==(i=e.onChainData)?void 0:i.transactionHash,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";q(`${t}. Please complete the payment and try again.`),H(Fn)}}else"failed"===(null==(o=e.payment)?void 0:o.status)?(q("Payment failed. Please try creating a new payment."),H(Fn)):(q("Payment not found. Please verify the payment ID and try again."),H(Fn))}catch(m){q(`Verification failed: ${m.message}. Please ensure payment was completed and try again.`),H(Fn)}}},className:"bg-green-600 text-white w-full py-2.5 px-3 font-semibold rounded-xl hover:bg-green-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 text-sm",disabled:L===Tn&&!V&&!k||k&&!C||"processing"===X||j,style:{fontFamily:Ln},children:j?"Verifying...":"processing"===X?"Processing...":k&&C?"I Have Paid":k?"Select Wallet":L===Bn?"I Have Paid":"Pay Now"})]})]})}),t.jsx(un,{currentStep:S,targetStep:Un,children:t.jsx(hn,{status:"processing",message:"approve"===X?"Approving token spending...":"splitPayment"===X?"Processing payment split...":te?"Confirming transaction on blockchain...":"Processing your payment...",theme:p,transactionHash:te,selectedNetwork:F})}),t.jsx(un,{currentStep:S,targetStep:Dn,children:t.jsx(hn,{status:"success",message:"Payment completed successfully!",theme:p,payment:D,transactionHash:te||(null==D?void 0:D.transactionHash),selectedPaymentMethod:U,selectedNetwork:F,merchantName:(null==c?void 0:c.merchantName)||"Merchant",onClose:m})}),(B||ee)&&t.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4",children:[t.jsx("p",{className:"text-red-800 text-sm",children:B||ee}),t.jsx("button",{onClick:()=>{q(""),Y.setTransactionError("")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]}),S!==Dn&&t.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",style:{fontFamily:Ln},children:[t.jsxs("p",{children:["Powered by ",t.jsx("span",{className:"text-[#7042D2] font-semibold",children:"Coinley"})," - Multi-Wallet Support"]}),t.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})]}):null;var se},$n=e=>t.jsx(s.WagmiProvider,{config:g,children:t.jsx(a.QueryClientProvider,{client:Mn,children:t.jsx(Rn,{...e})})}),Gn=n.createContext(null),On=n.forwardRef(({customerEmail:e="",merchantName:t="",onSuccess:s,onError:a,onClose:r,theme:i="light",autoOpen:o=!1,testMode:c=!1,debug:l=!1,merchantWalletAddresses:d={}},m)=>{const u=n.useContext(Gn);if(!u)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:h,closePayment:p}=u,y=t=>{try{if(!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const n={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};h(n,{onSuccess:s,onError:a,onClose:r})}catch(n){a&&a(n)}},g=()=>{p()};return n.useImperativeHandle(m,()=>({open:y,close:g})),null});On.displayName="CoinleyCheckout";const zn={ethereum:_t,bsc:Ot,polygon:en,arbitrum:Mt,optimism:Xt,avalanche:Rt},Wn=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],type:"function"}];const Hn=new class{constructor(){this.clients=new Map}getClient(e){if(!this.clients.has(e)){const t=zn[e];if(!t)throw new Error(`Unsupported network: ${e}`);const n=c.createPublicClient({chain:t,transport:c.http()});this.clients.set(e,n)}return this.clients.get(e)}async checkNativeBalance(e,t){try{const n=this.getClient(t),s=await n.getBalance({address:e}),a=c.formatUnits(s,18);return{balance:parseFloat(a),balanceWei:s.toString(),symbol:this.getNativeTokenSymbol(t),decimals:18}}catch(n){throw new Error(`Failed to check native balance: ${n.message}`)}}async checkTokenBalance(e,t,n){try{const s=this.getClient(n),a=c.getContract({address:t,abi:Wn,client:s}),[r,i,o]=await Promise.all([a.read.balanceOf([e]),a.read.decimals().catch(()=>18),a.read.symbol().catch(()=>"TOKEN")]);return{balance:parseFloat(c.formatUnits(r,i)),balanceWei:r.toString(),symbol:o,decimals:i,tokenAddress:t}}catch(s){throw new Error(`Failed to check token balance: ${s.message}`)}}async validateBalance(e,t,n,s,a=!0){try{let r,i=null;r=t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,s):await this.checkNativeBalance(e,s),t.contractAddress&&a&&(i=await this.checkNativeBalance(e,s));const o=r.balance>=n,c=o?0:n-r.balance;let l=0,d=!0,m=0;if(a)if(l=this.estimateGasFee(s,!!t.contractAddress),t.contractAddress)d=i.balance>=l,m=d?0:l-i.balance;else{const e=n+l;d=r.balance>=e,m=d?0:e-r.balance}const u={isValid:o&&d,tokenBalance:r,nativeBalance:i,requiredAmount:n,estimatedGasFee:l,hasEnoughTokens:o,hasEnoughForGas:d,tokenShortfall:c,gasShortfall:m,errors:[]};if(o||u.errors.push(`Insufficient ${t.symbol} balance. Need ${n} ${t.symbol}, have ${r.balance.toFixed(6)} ${t.symbol}`),!d){const e=(null==i?void 0:i.symbol)||this.getNativeTokenSymbol(s);t.contractAddress?u.errors.push(`Insufficient ${e} for gas fees. Need ~${l.toFixed(6)} ${e}, have ${i.balance.toFixed(6)} ${e}`):u.errors.push(`Insufficient ${e} for payment + gas. Need ${(n+l).toFixed(6)} ${e} total, have ${r.balance.toFixed(6)} ${e}`)}return u}catch(r){return{isValid:!1,errors:[`Failed to check balance: ${r.message}`],tokenBalance:null,nativeBalance:null}}}estimateGasFee(e,t=!1){return{ethereum:t?.001:5e-4,bsc:t?5e-4:3e-4,polygon:t?.01:.005,arbitrum:t?3e-4:2e-4,optimism:t?3e-4:2e-4,avalanche:t?.001:5e-4}[e]||.001}getNativeTokenSymbol(e){return{ethereum:"ETH",bsc:"BNB",polygon:"MATIC",arbitrum:"ETH",optimism:"ETH",avalanche:"AVAX"}[e]||"ETH"}async getBalance(e,t,n){return t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,n):await this.checkNativeBalance(e,n)}formatBalance(e,t,n=6){return null==e?"Unknown":0===e?`0 ${t}`:e<.001?`${e.toFixed(8)} ${t}`:e<1?`${e.toFixed(6)} ${t}`:`${e.toFixed(4)} ${t}`}async checkMultipleBalances(e,t,n){try{const s=t.map(t=>this.getBalance(e,t,n).catch(e=>({error:e.message,symbol:t.symbol,balance:0})));return await Promise.all(s)}catch(s){throw s}}};class qn{constructor(e,t,n){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=n}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},a=await fetch(n,{...t,headers:s});if(!a.ok){const e=await a.json().catch(()=>({}));throw new Error(e.error||`HTTP ${a.status}`)}return a.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"},{id:"42220",name:"Celo",shortName:"celo",chainId:"0xa4ec",type:"celo"},{id:"8453",name:"Base",shortName:"base",chainId:"0x2105",type:"base"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Binance USD",symbol:"BUSD",contractAddress:"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"USD Coin",symbol:"USDC",contractAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async updatePaymentStatus(e,t,n=null){return await this.request(`/api/payments/${e}/status`,{method:"PUT",body:JSON.stringify({status:t,transactionHash:n})})}}class Vn{constructor(e={}){if(!e.publicKey&&!e.apiKey)throw new Error("CoinleyVanilla: publicKey or apiKey is required");if(!e.publicKey&&!e.apiSecret)throw new Error("CoinleyVanilla: apiSecret is required when using apiKey");if(!e.apiUrl)throw new Error("CoinleyVanilla: apiUrl is required");this.config={publicKey:e.publicKey||null,apiKey:e.apiKey||null,apiSecret:e.apiSecret||null,apiUrl:e.apiUrl.replace(/\/$/,""),theme:e.theme||"light",debug:e.debug||!1,...e},this.isOpen=!1,this.root=null,this.container=null,this.callbacks={},this.currentPayment=null,this.config.debug}open(e,t={}){if(!this.isOpen)try{this._validatePaymentConfig(e),this.callbacks=t,this.currentPayment=e,this._createContainer(),this.root=u.createRoot(this.container),this.isOpen=!0,this.root.render(n.createElement($n,{publicKey:this.config.publicKey,apiKey:this.config.apiKey,apiSecret:this.config.apiSecret,apiUrl:this.config.apiUrl,isOpen:!0,theme:this.config.theme,config:{amount:e.amount,customerEmail:e.customerEmail,merchantName:e.merchantName||"Merchant",callbackUrl:e.callbackUrl||this._getDefaultCallbackUrl(),merchantWalletAddresses:e.merchantWalletAddresses||{},preferredNetwork:e.preferredNetwork,preferredCurrency:e.preferredCurrency,metadata:{...e.metadata,source:"vanilla-sdk",sdkVersion:"2.0.0",timestamp:(new Date).toISOString()}},onSuccess:this._handleSuccess.bind(this),onError:this._handleError.bind(this),onClose:this._handleClose.bind(this)})),this.config.debug}catch(s){t.onError&&t.onError(s.message||"Failed to open payment modal")}}close(){this.isOpen&&(this._cleanup(),this.config.debug)}isPaymentOpen(){return this.isOpen}updateConfig(e){this.config={...this.config,...e},this.config.debug}getConfig(){return{...this.config}}getCurrentPayment(){return this.currentPayment?{...this.currentPayment}:null}_validatePaymentConfig(e){if(!e)throw new Error("Payment configuration is required");if(!e.amount||"number"!=typeof e.amount||e.amount<=0)throw new Error("Valid amount (number > 0) is required");if(!e.customerEmail||"string"!=typeof e.customerEmail)throw new Error("Customer email is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customerEmail))throw new Error("Invalid email format");if(e.merchantWalletAddresses){if("object"!=typeof e.merchantWalletAddresses)throw new Error("merchantWalletAddresses must be an object");Object.keys(e.merchantWalletAddresses).length}}_createContainer(){this.container||(this.container=document.createElement("div"),this.container.id="coinley-payment-container",this.container.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n ",document.body.appendChild(this.container))}_getDefaultCallbackUrl(){return"undefined"!=typeof window?`${window.location.origin}/api/webhooks/coinley`:""}_handleSuccess(e,t,n){this.config.debug,this.callbacks.onSuccess&&this.callbacks.onSuccess(e,t,n)}_handleError(e){this.config.debug,this.callbacks.onError&&this.callbacks.onError(e)}_handleClose(){this._cleanup(),this.callbacks.onClose&&this.callbacks.onClose()}_cleanup(){if(this.isOpen=!1,this.root){try{this.root.unmount()}catch(e){}this.root=null}this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null),this.currentPayment=null}}function Qn(){document.querySelectorAll('script[src*="coinley-vanilla"]').forEach(e=>{const t=e.getAttribute("data-public-key"),n=e.getAttribute("data-api-key"),s=e.getAttribute("data-api-secret"),a=e.getAttribute("data-api-url"),r=e.getAttribute("data-theme")||"light",i=e.hasAttribute("data-debug");if((t||n&&s)&&a)try{window.coinley=new Vn({publicKey:t,apiKey:n,apiSecret:s,apiUrl:a,theme:r,debug:i})}catch(o){}})}"undefined"!=typeof window&&(window.CoinleyVanilla=Vn,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Qn):Qn());class Kn{constructor(e="https://paymentscreen.vercel.app/"){this.basePaymentUrl=e.endsWith("/")?e:e+"/"}generatePaymentURL(e){const{merchant:t,amount:n,productAmount:s,platformFee:a,networkFee:r,token:i="USDC",network:o="Ethereum Mainnet",merchantAddress:c}=e;if(!t)throw new Error("Merchant name is required");if(!n)throw new Error("Amount is required");if(!c)throw new Error("Merchant address (smart contract) is required");const l=s||.95*n,d=a||.03*n,m=r||.02*n,u=new URLSearchParams({merchant:t,amount:n.toString(),productAmount:l.toString(),platformFee:d.toString(),networkFee:m.toString(),token:i,network:o,merchantAddress:c});return this.basePaymentUrl+"?"+u.toString()}async generateQRCode(e,t={}){const{width:n=300,margin:s=2,colorDark:a="#7c3aed",colorLight:r="#ffffff"}=t;try{const t=this.generatePaymentURL(e);return{qrCodeDataURL:await d.toDataURL(t,{width:n,margin:s,color:{dark:a,light:r}}),paymentURL:t,paymentData:{...e,qrCodeUrl:t}}}catch(i){throw new Error(`Failed to generate QR code: ${i.message}`)}}async generateQRCodeToCanvas(e,t,n={}){const{width:s=300,margin:a=2,colorDark:r="#7c3aed",colorLight:i="#ffffff"}=n;try{const n=this.generatePaymentURL(e);return await d.toCanvas(t,n,{width:s,margin:a,color:{dark:r,light:i}}),n}catch(o){throw new Error(`Failed to generate QR code to canvas: ${o.message}`)}}validatePaymentData(e){const t=[],n=[];e.merchant||t.push("Merchant name is required"),(!e.amount||e.amount<=0)&&t.push("Valid amount is required"),e.merchantAddress||t.push("Merchant address (smart contract) is required"),e.merchantAddress&&!/^0x[a-fA-F0-9]{40}$/.test(e.merchantAddress)&&t.push("Invalid Ethereum address format for merchantAddress"),e.amount>1e4&&n.push("Large payment amount detected");return(e.platformFee||0)+(e.networkFee||0)>.1*e.amount&&n.push("High fees detected (>10% of total amount)"),{isValid:0===t.length,errors:t,warnings:n}}async createPaymentQR(e){const{merchantName:t,amount:n,productAmount:s,platformFee:a,networkFee:r,token:i,network:o,merchantWalletAddresses:c,selectedNetwork:l="ethereum",...d}=e,m={merchant:t||"Coinley Merchant",amount:n,productAmount:s,platformFee:a,networkFee:r,token:i||"USDC",network:o||"Ethereum Mainnet",merchantAddress:(null==c?void 0:c[l])||(null==c?void 0:c.ethereum)||(null==c?void 0:c.splitPaymentContract),...d},u=this.validatePaymentData(m);if(!u.isValid)throw new Error(`Payment validation failed: ${u.errors.join(", ")}`);return{...await this.generateQRCode(m),validation:u,instructions:{userAction:"Scan this QR code with your mobile wallet to pay",expectedFlow:"QR Scan โ Payment Screen โ Wallet Connect โ Split Payment โ Confirmation",supportedWallets:["MetaMask","Trust Wallet","Coinbase Wallet","WalletConnect compatible wallets"]}}}}const Zn=new Kn,Yn={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,n=4)=>e?e.length<=t+n?e:`${e.slice(0,t)}...${e.slice(-n)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class _n extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const Jn={react:'\nimport { CoinleyProvider, CoinleyCheckout } from \'coinley-test\';\n\n// New recommended way - using publicKey only\n<CoinleyProvider\n publicKey="pk_your-public-key"\n apiUrl="https://api.coinley.io"\n>\n <CoinleyCheckout\n ref={checkoutRef}\n onSuccess={(paymentId, txHash, details) => console.log(\'Success!\')}\n onError={(error) => console.error(\'Error:\', error)}\n onClose={() => console.log(\'Closed\')}\n />\n</CoinleyProvider>\n\n// Legacy way (still supported) - using apiKey + apiSecret\n<CoinleyProvider\n apiKey="your-api-key"\n apiSecret="your-api-secret"\n apiUrl="https://api.coinley.io"\n>\n ...\n</CoinleyProvider>\n ',vanilla:'\n\x3c!-- Include via CDN --\x3e\n<script src="https://unpkg.com/coinley-test@latest/vanilla"><\/script>\n<link rel="stylesheet" href="https://unpkg.com/coinley-test@latest/vanilla/style.css">\n\n<script>\n// New recommended way - using publicKey only\nconst coinley = new CoinleyVanilla({\n publicKey: "pk_your-public-key",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Legacy way (still supported)\nconst coinleyLegacy = new CoinleyVanilla({\n apiKey: "your-api-key",\n apiSecret: "your-api-secret",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Use in checkout\ncoinley.open({\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n}, {\n onSuccess: (paymentId, txHash, details) => console.log(\'Success!\'),\n onError: (error) => console.error(\'Error:\', error),\n onClose: () => console.log(\'Closed\')\n});\n<\/script>\n '};e.CoinleyCheckout=On,e.CoinleyError=_n,e.CoinleyProvider=({publicKey:e,apiKey:s,apiSecret:a,apiUrl:r,theme:i="light",debug:o=!1,children:c})=>{const[l,d]=n.useState(!1),[m,u]=n.useState(null),[h,p]=n.useState({}),[y,g]=n.useState(""),f=()=>{d(!1),u(null),h.onClose&&h.onClose()},b={openPayment:(e,t)=>{u(e),t&&p(t),d(!0)},closePayment:f};return t.jsxs(Gn.Provider,{value:b,children:[c,l&&m&&t.jsx($n,{publicKey:e,apiKey:s,apiSecret:a,apiUrl:r,isOpen:l,config:m,theme:i,debug:o,merchantName:y,onSuccess:h.onSuccess,onError:h.onError,onClose:f})]})},e.CoinleyVanilla=Vn,e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=$n,e.PaymentAPI=class{constructor(e,t,n=null){t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=n),this.api=m.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{if(this.publicKey)e.headers["x-public-key"]=this.publicKey;else{e.headers["x-api-key"]=this.apiKey,e.headers["x-api-secret"]=this.apiSecret;const t=this.generateMerchantToken();t&&(e.headers.Authorization=`Bearer ${t}`)}return e},e=>Promise.reject(e)),this.api.interceptors.response.use(e=>e,e=>{var t,n,s;if(401===(null==(t=e.response)?void 0:t.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(n=e.response)?void 0:n.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(s=e.response)?void 0:s.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(e){return null}}async request(e,t={}){var n,s;try{return(await this.api({url:e,method:t.method||"GET",data:t.data||t.body?JSON.parse(t.body||"{}"):void 0,...t})).data}catch(a){if(null==(s=null==(n=a.response)?void 0:n.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Request failed")}}async createPayment(e){var t,n;try{return(await this.api.post("/api/payments/create",e)).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to create payment")}}async getPayment(e){var t,n;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(e){return{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:1,type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:56,type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:137,type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(e){return{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,n;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to verify payment")}}async processPayment(e,t,n,s){var a;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:n,senderAddress:s})).data}catch(r){if(null==(a=r.response)?void 0:a.data){const e=r.response.data,t=e.error||e.message||"Payment processing failed",n=new Error(t);throw n.isAlreadyCompleted=e.isAlreadyCompleted||!1,n.verificationAttempts=e.verificationAttempts||0,n.statusCode=r.response.status,n.originalData=e,n}throw new Error(r.message||"Failed to process PaymentSplitter transaction")}}async getContractInfo(e){var t,n;try{return(await this.api.get(`/api/payments/contract/${e}`)).data.contractInfo}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get contract information")}}async getPaymentSplitterStatus(e){var t,n;try{return(await this.api.get(`/api/payments/splitter-status/${e}`)).data.paymentSplitterStatus}catch(s){if(null==(n=null==(t=s.response)?void 0:t.data)?void 0:n.error)throw new Error(s.response.data.error);throw new Error(s.message||"Failed to get PaymentSplitter status")}}async checkPaymentSplitterHealth(){try{return(await this.api.get("/api/payments/health")).data.paymentSplitterHealth}catch(e){return{error:e.message}}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return!1}}},e.PaymentQRGenerator=Kn,e.QRCodePayment=({apiKey:e,apiSecret:s,apiUrl:a,config:r,onSuccess:i,onError:o,onClose:c,isOpen:l,theme:m="light",mode:u="splitpayment",splitPaymentUrl:h="https://paymentscreen.vercel.app/"})=>{var p;const[y,g]=n.useState("network"),[f,b]=n.useState([]),[x,w]=n.useState([]),[v,k]=n.useState(null),[N,C]=n.useState(null),[P,j]=n.useState(null),[I,S]=n.useState(!1),[A,E]=n.useState(""),[F,U]=n.useState(""),[D,T]=n.useState(""),[B,L]=n.useState(""),[M,R]=n.useState(!1),[$,G]=n.useState(""),[O,z]=n.useState(!1),[W,H]=n.useState(null),q=n.useRef(new qn(a,e,s)),V=n.useRef(null);n.useEffect(()=>(l&&(K(),Q()),()=>{V.current&&clearInterval(V.current)}),[l]);const Q=()=>{g("network"),k(null),C(null),j(null),E(""),U(""),T(""),L(""),R(!1),G(""),z(!1),H(null),V.current&&clearInterval(V.current)},K=async()=>{try{S(!0),E("");const[e,t]=await Promise.all([q.current.getNetworks(),q.current.getTokens()]);b(e.networks||[]),w(t.stablecoins||[])}catch(e){E("Failed to load payment options.")}finally{S(!1)}},Z=async e=>{if(!N||!v||!P)return!1;try{const t=await Hn.validateBalance(e,N,P.totalAmount,v.shortName,!0);return H(t),!!t.isValid||(E(`Insufficient balance: ${t.errors.join(", ")}`),!1)}catch(t){return E(`Failed to check balance: ${t.message}`),!1}};if(!l)return null;const Y="dark"===m;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(Y?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[t.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(Y?"border-gray-700":"border-gray-200"),children:[t.jsxs("div",{className:"text-center flex-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:"splitpayment"===u?"Split Payment QR":"QR Code Payment"}),r.amount&&t.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",r.amount.toFixed(2)]}),t.jsx("p",{className:"text-xs text-blue-600",children:"splitpayment"===u?"๐ฑ Scan to redirect to payment screen":"๐ฑ Scan with mobile wallet"})]}),t.jsx("button",{onClick:c,className:"ml-4 text-gray-500 hover:text-gray-700 "+(Y?"hover:text-gray-300":""),children:"โ"})]}),t.jsxs("div",{className:"p-4 min-h-[400px]",children:[A&&t.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[A,t.jsx("button",{onClick:()=>E(""),className:"ml-2 text-red-500 hover:text-red-700",children:"โ"})]}),"network"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsx("h3",{className:"font-medium text-center",children:"Select Network"}),t.jsx("div",{className:"space-y-2",children:f.map(e=>{var n;const s=null==(n=r.merchantWalletAddresses)?void 0:n[e.shortName];return t.jsxs("button",{onClick:()=>{k(e),g("token")},disabled:!s,className:"w-full p-3 border rounded-lg text-left transition-colors "+(s?"hover:border-purple-500 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"):"opacity-50 cursor-not-allowed "+(Y?"border-gray-700":"border-gray-100")),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsxs("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:[e.shortName.toUpperCase(),!s&&" (No merchant address configured)"]})]},e.id)})})]}),"token"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("button",{onClick:()=>g("network"),className:""+(Y?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"โ"}),t.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==v?void 0:v.name]})]}),t.jsx("div",{className:"space-y-2",children:x.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==v?void 0:v.shortName)}).map(e=>t.jsxs("button",{onClick:()=>{C(e),(async e=>{var t,n;try{S(!0),E("");const s={amount:r.amount,currency:e.symbol,network:v.shortName,customerEmail:r.customerEmail,callbackUrl:r.callbackUrl,metadata:{...r.metadata,merchantWalletAddresses:r.merchantWalletAddresses,paymentMethod:"split_payment_qr",selectedNetwork:v.shortName,selectedToken:e.symbol}},a=await q.current.createPayment(s);j(a.payment);const i=(null==(t=r.merchantWalletAddresses)?void 0:t.splitPaymentContract)||(null==(n=r.merchantWalletAddresses)?void 0:n[v.shortName]);if(!i)throw new Error("Split payment contract address not found in config");const o=new URLSearchParams({merchant:r.merchantName||"Coinley Merchant",amount:a.payment.totalAmount.toString(),productAmount:(.95*a.payment.totalAmount).toFixed(2),platformFee:(.03*a.payment.totalAmount).toFixed(2),networkFee:(.02*a.payment.totalAmount).toFixed(2),token:e.symbol,network:v.name,merchantAddress:i,paymentId:a.payment.id}),c=h+"?"+o.toString();U(c);const l=await d.toDataURL(c,{width:256,margin:2,color:{dark:"#7c3aed",light:"#ffffff"}});T(l),g("scan")}catch(s){E(s.message||"Failed to generate split payment QR code")}finally{S(!1)}})(e)},disabled:I,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsx("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:e.symbol})]},e.id))})]}),"scan"===y&&t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("h3",{className:"font-medium mb-4",children:"splitpayment"===u?"Scan QR Code to Open Payment Screen":"Scan QR Code with Mobile Wallet"}),D?t.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[t.jsx("div",{className:"p-4 rounded-lg "+(Y?"bg-gray-800":"bg-gray-50"),children:t.jsx("img",{src:D,alt:"Payment QR Code",className:"mx-auto",style:{width:"200px",height:"200px"}})}),t.jsxs("div",{className:"text-sm space-y-1 "+(Y?"text-gray-300":"text-gray-600"),children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Amount:"}),t.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Network:"}),t.jsx("span",{className:"font-medium",children:null==v?void 0:v.name})]}),"splitpayment"===u&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Merchant:"}),t.jsx("span",{className:"font-medium",children:r.merchantName||"Coinley Merchant"})]})]}),t.jsx("div",{className:"p-3 rounded-lg text-xs "+(Y?"bg-blue-900 text-blue-200":"bg-blue-50 text-blue-600"),children:"splitpayment"===u?t.jsxs(t.Fragment,{children:["๐ฑ Scan this QR code with your mobile wallet to open the payment screen.",t.jsx("br",{}),"The payment screen will auto-connect your wallet and execute the split payment."]}):"๐ฑ Open your mobile wallet and scan this QR code to connect and pay"}),"splitpayment"===u?t.jsx("button",{onClick:()=>window.open(F,"_blank"),className:"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm",children:"๐ Test Payment Screen (Opens in new tab)"}):t.jsx("button",{onClick:async()=>{try{S(!0),E("");const e="0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4";G(e),R(!0),await Z(e),g("confirm")}catch(e){E("Failed to simulate wallet connection")}finally{S(!1)}},disabled:I,className:"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm",children:I?"Connecting...":"๐งช Simulate Wallet Scan (Test)"})]}):t.jsxs("div",{className:"flex items-center justify-center py-8",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"}),t.jsx("span",{className:"ml-2",children:"Generating QR Code..."})]})]})}),"confirm"===y&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:t.jsx("span",{className:"text-2xl",children:"๐ฑ"})}),t.jsx("h3",{className:"font-medium",children:"Mobile Wallet Connected"}),t.jsx("p",{className:"text-sm mt-2 "+(Y?"text-gray-300":"text-gray-600"),children:"Ready to complete payment"})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[t.jsx("p",{className:"text-green-600 text-sm font-medium",children:"โ
Wallet Connected"}),t.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==$?void 0:$.slice(0,6),"...",null==$?void 0:$.slice(-4)]})]}),W&&t.jsx("div",{className:"p-3 rounded-lg border "+(W.isValid?"bg-green-50 border-green-200":"bg-red-50 border-red-200"),children:t.jsxs("div",{className:"space-y-2 text-sm",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Required:"}),t.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Your Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughTokens?"text-green-600":"text-red-600"),children:Hn.formatBalance(null==(p=W.tokenBalance)?void 0:p.balance,null==N?void 0:N.symbol)})]}),W.nativeBalance&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Gas Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughForGas?"text-green-600":"text-red-600"),children:Hn.formatBalance(W.nativeBalance.balance,W.nativeBalance.symbol)})]})]})}),t.jsx("button",{onClick:async()=>{try{z(!0),E("");const e=`0x${Math.random().toString(16).substring(2,66)}`;await new Promise(e=>setTimeout(e,3e3)),g("success"),null==i||i(P.id,e,{network:v.name,token:N.symbol,amount:P.totalAmount,method:"qr_code",walletAddress:$})}catch(e){E("Transaction confirmation failed")}finally{z(!1)}},disabled:O||!(null==W?void 0:W.isValid),className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium",children:O?"Processing Payment...":(null==W?void 0:W.isValid)?`Confirm Payment of ${null==P?void 0:P.totalAmount} ${null==N?void 0:N.symbol}`:"Insufficient Balance"})]})]}),"success"===y&&t.jsxs("div",{className:"text-center space-y-4",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:t.jsx("span",{className:"text-2xl",children:"โ
"})}),t.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),t.jsx("p",{className:"text-sm "+(Y?"text-gray-300":"text-gray-600"),children:"Transaction completed via QR code scan"}),t.jsx("button",{onClick:c,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium",children:"Close"})]}),I&&"scan"!==y&&"confirm"!==y&&t.jsx("div",{className:"flex items-center justify-center py-8",children:t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:s})=>{const[a,r]=n.useState(e);return n.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",a)},[a]),t.jsx("div",{className:`coinley-theme-${a}`,children:s})},e.USAGE_EXAMPLES=Jn,e.VERSION="0.0.26",e.generatePaymentQR=(e,t)=>Zn.generateQRCode(e,t),e.generatePaymentURL=e=>Zn.generatePaymentURL(e),e.paymentQR=Zn,e.useCoinley=()=>{const e=n.useContext(Gn);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=Yn,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react/jsx-runtime"),require("react"),require("wagmi"),require("@tanstack/react-query"),require("@wagmi/core"),require("@wagmi/core/chains"),require("@wagmi/connectors"),require("viem"),require("react-dom"),require("qrcode"),require("axios"),require("react-dom/client")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react","wagmi","@tanstack/react-query","@wagmi/core","@wagmi/core/chains","@wagmi/connectors","viem","react-dom","qrcode","axios","react-dom/client"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.React,e.Wagmi,e.ReactQuery,e.WagmiCore,e.chains,e.connectors,e.Viem,e.ReactDOM,e.QRCode,e.axios,e.ReactDOM)}(this,function(e,t,r,n,i,o,s,a,c,l,u,h,d){"use strict";var p,f=Object.defineProperty,m=(e,t,r)=>((e,t,r)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),g=["buffer","Buffer"];if("undefined"==typeof window){var y={hostname:""};p={crypto:{randomUUID:function(){throw Error("unsupported")}},navigator:{userAgent:"",onLine:!0},document:{createElement:function(){return{}},location:y,referrer:""},screen:{width:0,height:0},location:y,addEventListener:function(){},removeEventListener:function(){}}}else p=window;function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function b(e,t,r,n,i,o,s){try{var a=e[o](s),c=a.value}catch(vu){return void r(vu)}a.done?t(c):Promise.resolve(c).then(n,i)}function w(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var o=e.apply(t,r);function s(e){b(o,n,i,s,a,"next",e)}function a(e){b(o,n,i,s,a,"throw",e)}s(void 0)})}}function x(e,t,r){return(x=P()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var i=new(Function.bind.apply(e,n));return r&&A(i,r.prototype),i}).apply(null,arguments)}function k(e,t,r){return t&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}(e.prototype,t),e}function _(){return _=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},_.apply(this,arguments)}function S(e){return(S=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function C(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&A(e,t)}function I(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!t[Symbol.hasInstance](e):e instanceof t}function E(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}function A(e,t){return(A=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function M(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function N(e){var t="function"==typeof Map?new Map:void 0;return N=function(e){if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;var r;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return x(e,arguments,S(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),A(n,e)},N(e)}function P(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(P=function(){return!!e})()}function B(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return v(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(r):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(e,t):void 0}}(e))||t){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function T(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(a){o=[6,a],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}}function O(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}var R,L=Object.defineProperty,U=function(e,t,r){return function(e,t,r){return t in e?L(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r}(e,"symbol"!==(void 0===t?"undefined":M(t))?t+"":t,r)},j=Object.defineProperty,D=function(e,t,r){return function(e,t,r){return t in e?j(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r}(e,"symbol"!==(void 0===t?"undefined":M(t))?t+"":t,r)},F=function(e){return e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e}(F||{}),z={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},q={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},W={};function $(e){if(W[e])return W[e];var t=globalThis[e],r=t.prototype,n=e in z?z[e]:void 0,i=Boolean(n&&n.every(function(e){var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),o=e in q?q[e]:void 0,s=Boolean(o&&o.every(function(e){var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(i&&s&&!globalThis.Zone)return W[e]=t.prototype,t.prototype;try{var a=document.createElement("iframe");document.body.appendChild(a);var c=a.contentWindow;if(!c)return t.prototype;var l=c[e].prototype;return document.body.removeChild(a),l?W[e]=l:r}catch(u){return r}}var G={};function V(e,t,r){var n,i=e+"."+String(r);if(G[i])return G[i].call(t);var o=$(e),s=null==(n=Object.getOwnPropertyDescriptor(o,r))?void 0:n.get;return s?(G[i]=s,s.call(t)):t[r]}var H={};function K(e,t,r){var n=e+"."+String(r);if(H[n])return H[n].bind(t);var i=$(e)[r];return"function"!=typeof i?t[r]:(H[n]=i,i.bind(t))}var Z={childNodes:function(e){return V("Node",e,"childNodes")},parentNode:function(e){return V("Node",e,"parentNode")},parentElement:function(e){return V("Node",e,"parentElement")},textContent:function(e){return V("Node",e,"textContent")},contains:function(e,t){return K("Node",e,"contains")(t)},getRootNode:function(e){return K("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?V("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?V("Element",e,"shadowRoot"):null},querySelector:function(e,t){return V("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return V("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return $("MutationObserver").constructor},patch:function(e,t,r){try{if(!(t in e))return function(){};var n=e[t],i=r(n);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=i,function(){e[t]=n}}catch(o){return function(){}}}};function Y(e){return e.nodeType===e.ELEMENT_NODE}function J(e){var t=e&&"host"in e&&"mode"in e&&Z.host(e)||null;return Boolean(t&&"shadowRoot"in t&&Z.shadowRoot(t)===e)}function X(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function Q(e){try{var t=e.rules||e.cssRules;if(!t)return null;var r=e.href;!r&&e.ownerNode&&e.ownerNode.ownerDocument&&(r=e.ownerNode.ownerDocument.location.href);var n=Array.from(t,function(e){return ee(e,r)}).join("");return(i=n).includes(" background-clip: text;")&&!i.includes(" -webkit-background-clip: text;")&&(i=i.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),i}catch(vu){return null}var i}function ee(e,t){if(function(e){return"styleSheet"in e}(e)){var r;try{r=Q(e.styleSheet)||function(e){var t=e.cssText;if(t.split('"').length<3)return t;var r=["@import","url("+JSON.stringify(e.href)+")"];return""===e.layerName?r.push("layer"):e.layerName&&r.push("layer("+e.layerName+")"),e.supportsText&&r.push("supports("+e.supportsText+")"),e.media.length&&r.push(e.media.mediaText),r.join(" ")+";"}(e)}catch(vu){r=e.cssText}return e.styleSheet.href?he(r,e.styleSheet.href):r}var n,i=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(n=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm,i=i.replace(n,"$1\\$2")),t?he(i,t):i}var te=function(){function e(){D(this,"idNodeMap",new Map),D(this,"nodeMetaMap",new WeakMap)}var t=e.prototype;return t.getId=function(e){var t;if(!e)return-1;var r=null==(t=this.getMeta(e))?void 0:t.id;return null!=r?r:-1},t.getNode=function(e){return this.idNodeMap.get(e)||null},t.getIds=function(){return Array.from(this.idNodeMap.keys())},t.getMeta=function(e){return this.nodeMetaMap.get(e)||null},t.removeNodeFromMap=function(e){var t=this,r=this.getId(e);this.idNodeMap.delete(r),e.childNodes&&e.childNodes.forEach(function(e){return t.removeNodeFromMap(e)})},t.has=function(e){return this.idNodeMap.has(e)},t.hasNode=function(e){return this.nodeMetaMap.has(e)},t.add=function(e,t){var r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)},t.replace=function(e,t){var r=this.getNode(e);if(r){var n=this.nodeMetaMap.get(r);n&&this.nodeMetaMap.set(t,n)}this.idNodeMap.set(e,t)},t.reset=function(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap},e}();function re(e){var t=e.element,r=e.maskInputOptions,n=e.tagName,i=e.type,o=e.value,s=e.maskInputFn,a=o||"",c=i&&ne(i);return(r[n.toLowerCase()]||c&&r[c])&&(a=s?s(a,t):"*".repeat(a.length)),a}function ne(e){return e.toLowerCase()}var ie="__rrweb_original__";function oe(e){var t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?ne(t):null}function se(e,t){var r;try{r=new URL(e,null!=t?t:window.location.href)}catch(o){return null}var n,i=r.pathname.match(/\.([0-9a-z]+)(?:$)/i);return null!=(n=null==i?void 0:i[1])?n:null}var ae=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,ce=/^(?:[a-z+]+:)?\/\//i,le=/^www\..*/i,ue=/^(data:)([^,]*),(.*)/i;function he(e,t){return(e||"").replace(ae,function(e,r,n,i,o,s){var a,c=n||o||s,l=r||i||"";if(!c)return e;if(ce.test(c)||le.test(c))return"url("+l+c+l+")";if(ue.test(c))return"url("+l+c+l+")";if("/"===c[0])return"url("+l+(((a=t).indexOf("//")>-1?a.split("/").slice(0,3).join("/"):a.split("/")[0]).split("?")[0]+c)+l+")";var u=t.split("/"),h=c.split("/");u.pop();for(var d,p=B(h);!(d=p()).done;){var f=d.value;"."!==f&&(".."===f?u.pop():u.push(f))}return"url("+l+u.join("/")+l+")"})}function de(e,t){return void 0===t&&(t=!1),t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}function pe(e,t){return function(e,t,r){void 0===r&&(r=!1);var n=Array.from(t.childNodes),i=[],o=0;if(n.length>1&&e&&"string"==typeof e)for(var s=de(e,r),a=s.length/e.length,c=1;c<n.length;c++)if(n[c].textContent&&"string"==typeof n[c].textContent){for(var l=de(n[c].textContent,r),u=3;u<l.length&&(l[u].match(/[a-zA-Z0-9]/)||-1!==l.indexOf(l.substring(0,u),1));u++);for(;u<l.length;u++){var h=l.substring(0,u),d=s.split(h),p=-1;if(2===d.length)p=d[0].length;else if(d.length>2&&""===d[0]&&""!==n[c-1].textContent)p=s.indexOf(h,1);else if(1===d.length){if(h=h.substring(0,h.length-1),(d=s.split(h)).length<=1)return i.push(e),i;u=101}else u===l.length-1&&(p=s.indexOf(h));if(d.length>=2&&u>100){var f=n[c-1].textContent;if(f&&"string"==typeof f){var m=de(f).length;p=s.indexOf(h,m)}-1===p&&(p=d[0].length)}if(-1!==p){for(var g=Math.floor(p/a);g>0&&g<e.length;){if((o+=1)>50*n.length)return i.push(e),i;var y=de(e.substring(0,g),r);if(y.length===p){i.push(e.substring(0,g)),e=e.substring(g),s=s.substring(p);break}y.length<p?g+=Math.max(1,Math.floor((p-y.length)/a)):g-=Math.max(1,Math.floor((y.length-p)*a))}break}}}return i.push(e),i}(e,t).join("/* rr_split */")}var fe,me,ge=1,ye=new RegExp("[^a-z0-9-_:]");function ve(){return ge++}var be=/^[^ \t\n\r\u000c]+/,we=/^[, \t\n\r\u000c]+/;var xe=new WeakMap;function ke(e,t){return t&&""!==t.trim()?Se(e,t):t}function _e(e){return Boolean("svg"===e.tagName||e.ownerSVGElement)}function Se(e,t){var r=xe.get(e);if(r||(r=e.createElement("a"),xe.set(e,r)),t){if(t.startsWith("blob:")||t.startsWith("data:"))return t}else t="";return r.setAttribute("href",t),r.href}function Ce(e,t,r,n){return n?"src"===r||"href"===r&&("use"!==t||"#"!==n[0])||"xlink:href"===r&&"#"!==n[0]?ke(e,n):"background"!==r||"table"!==t&&"td"!==t&&"th"!==t?"srcset"===r?function(e,t){if(""===t.trim())return t;var r=0;function n(e){var n,i=e.exec(t.substring(r));return i?(n=i[0],r+=n.length,n):""}for(var i=[];n(we),!(r>=t.length);){var o=n(be);if(","===o.slice(-1))o=ke(e,o.substring(0,o.length-1)),i.push(o);else{var s="";o=ke(e,o);for(var a=!1;;){var c=t.charAt(r);if(""===c){i.push((o+s).trim());break}if(a)")"===c&&(a=!1);else{if(","===c){r+=1,i.push((o+s).trim());break}"("===c&&(a=!0)}s+=c,r+=1}}}return i.join(", ")}(e,n):"style"===r?he(n,Se(e)):"object"===t&&"data"===r?ke(e,n):n:ke(e,n):n}function Ie(e,t,r){return("video"===e||"audio"===e)&&"autoplay"===t}function Ee(e,t,r){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!r&&Ee(Z.parentNode(e),t,r);for(var n=e.classList.length;n--;){var i=e.classList[n];if(t.test(i))return!0}return!!r&&Ee(Z.parentNode(e),t,r)}function Ae(e,t,r,n){var i;if(Y(e)){if(i=e,!Z.childNodes(i).length)return!1}else{if(null===Z.parentElement(e))return!1;i=Z.parentElement(e)}try{if("string"==typeof t){if(n){if(i.closest("."+t))return!0}else if(i.classList.contains(t))return!0}else if(Ee(i,t,n))return!0;if(r)if(n){if(i.closest(r))return!0}else if(i.matches(r))return!0}catch(o){}return!1}function Me(e,t){var r=t.doc,n=t.mirror,i=t.blockClass,o=t.blockSelector,s=t.needsMask,a=t.inlineStylesheet,c=t.maskInputOptions,l=void 0===c?{}:c,u=t.maskTextFn,h=t.maskInputFn,d=t.dataURLOptions,p=void 0===d?{}:d,f=t.inlineImages,m=t.recordCanvas,g=t.keepIframeSrcFn,y=t.newlyAddedElement,v=void 0!==y&&y,b=t.cssCaptured,w=void 0!==b&&b,x=function(e,t){if(!t.hasNode(e))return;var r=t.getId(e);return 1===r?void 0:r}(r,n);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:F.Document,childNodes:[],compatMode:e.compatMode}:{type:F.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:F.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:x};case e.ELEMENT_NODE:return function(e,t){for(var r,n=t.doc,i=t.blockClass,o=t.blockSelector,s=t.inlineStylesheet,a=t.maskInputOptions,c=void 0===a?{}:a,l=t.maskInputFn,u=t.dataURLOptions,h=void 0===u?{}:u,d=t.inlineImages,p=t.recordCanvas,f=t.keepIframeSrcFn,m=t.newlyAddedElement,g=void 0!==m&&m,y=t.rootId,v=function(e,t,r){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(var n=e.classList.length;n--;){var i=e.classList[n];if(t.test(i))return!0}if(r)return e.matches(r)}catch(o){}return!1}(e,i,o),b=function(e){if(I(e,HTMLFormElement))return"form";var t=ne(e.tagName);return ye.test(t)?"div":t}(e),w={},x=e.attributes.length,k=0;k<x;k++){var _=e.attributes[k];Ie(b,_.name,_.value)||(w[_.name]=Ce(n,b,ne(_.name),_.value))}if("link"===b&&s){var S=Array.from(n.styleSheets).find(function(t){return t.href===e.href}),C=null;S&&(C=Q(S)),C&&(delete w.rel,delete w.href,w._cssText=C)}if("style"===b&&e.sheet){var E=Q(e.sheet);E&&(e.childNodes.length>1&&(E=pe(E,e)),w._cssText=E)}if("input"===b||"textarea"===b||"select"===b){var A=e.value,M=e.checked;"radio"!==w.type&&"checkbox"!==w.type&&"submit"!==w.type&&"button"!==w.type&&A?w.value=re({element:e,type:oe(e),tagName:b,value:A,maskInputOptions:c,maskInputFn:l}):M&&(w.checked=M)}"option"===b&&(e.selected&&!c.select?w.selected=!0:delete w.selected);"dialog"===b&&e.open&&(w.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal");if("canvas"===b&&p)if("2d"===e.__context)(function(e){var t=e.getContext("2d");if(!t)return!0;for(var r=0;r<e.width;r+=50)for(var n=0;n<e.height;n+=50){var i=t.getImageData,o=ie in i?i[ie]:i;if(new Uint32Array(o.call(t,r,n,Math.min(50,e.width-r),Math.min(50,e.height-n)).data.buffer).some(function(e){return 0!==e}))return!1}return!0})(e)||(w.rr_dataURL=e.toDataURL(h.type,h.quality));else if(!("__context"in e)){var N=e.toDataURL(h.type,h.quality),P=n.createElement("canvas");P.width=e.width,P.height=e.height,N!==P.toDataURL(h.type,h.quality)&&(w.rr_dataURL=N)}if("img"===b&&d){fe||(fe=n.createElement("canvas"),me=fe.getContext("2d"));var B=e,T=B.currentSrc||B.getAttribute("src")||"<unknown-src>",O=B.crossOrigin,R=function(){B.removeEventListener("load",R);try{fe.width=B.naturalWidth,fe.height=B.naturalHeight,me.drawImage(B,0,0),w.rr_dataURL=fe.toDataURL(h.type,h.quality)}catch(e){if("anonymous"!==B.crossOrigin)return B.crossOrigin="anonymous",void(B.complete&&0!==B.naturalWidth?R():B.addEventListener("load",R));console.warn("Cannot inline img src="+T+"! Error: "+e)}"anonymous"===B.crossOrigin&&(O?w.crossOrigin=O:B.removeAttribute("crossorigin"))};B.complete&&0!==B.naturalWidth?R():B.addEventListener("load",R)}if("audio"===b||"video"===b){var L=w;L.rr_mediaState=e.paused?"paused":"played",L.rr_mediaCurrentTime=e.currentTime,L.rr_mediaPlaybackRate=e.playbackRate,L.rr_mediaMuted=e.muted,L.rr_mediaLoop=e.loop,L.rr_mediaVolume=e.volume}g||(e.scrollLeft&&(w.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(w.rr_scrollTop=e.scrollTop));if(v){var U=e.getBoundingClientRect(),j=U.width,D=U.height;w={class:w.class,rr_width:j+"px",rr_height:D+"px"}}"iframe"!==b||f(w.src)||(e.contentDocument||(w.rr_src=w.src),delete w.src);try{customElements.get(b)&&(r=!0)}catch(z){}return{type:F.Element,tagName:b,attributes:w,childNodes:[],isSVG:_e(e)||void 0,needBlock:v,rootId:y,isCustom:r}}(e,{doc:r,blockClass:i,blockSelector:o,inlineStylesheet:a,maskInputOptions:l,maskInputFn:h,dataURLOptions:p,inlineImages:f,recordCanvas:m,keepIframeSrcFn:g,newlyAddedElement:v,rootId:x});case e.TEXT_NODE:return function(e,t){var r=t.needsMask,n=t.maskTextFn,i=t.rootId,o=t.cssCaptured,s=Z.parentNode(e),a=s&&s.tagName,c="",l="STYLE"===a||void 0,u="SCRIPT"===a||void 0;u?c="SCRIPT_PLACEHOLDER":o||(c=Z.textContent(e),l&&c&&(c=he(c,Se(t.doc))));!l&&!u&&c&&r&&(c=n?n(c,Z.parentElement(e)):c.replace(/[\S]/g,"*"));return{type:F.Text,textContent:c||"",rootId:i}}(e,{doc:r,needsMask:s,maskTextFn:u,rootId:x,cssCaptured:w});case e.CDATA_SECTION_NODE:return{type:F.CDATA,textContent:"",rootId:x};case e.COMMENT_NODE:return{type:F.Comment,textContent:Z.textContent(e)||"",rootId:x};default:return!1}}function Ne(e){return null==e?"":e.toLowerCase()}function Pe(e,t){var r=t.doc,n=t.mirror,i=t.blockClass,o=t.blockSelector,s=t.maskTextClass,a=t.maskTextSelector,c=t.skipChild,l=void 0!==c&&c,u=t.inlineStylesheet,h=void 0===u||u,d=t.maskInputOptions,p=void 0===d?{}:d,f=t.maskTextFn,m=t.maskInputFn,g=t.slimDOMOptions,y=t.dataURLOptions,v=void 0===y?{}:y,b=t.inlineImages,w=void 0!==b&&b,x=t.recordCanvas,k=void 0!==x&&x,_=t.onSerialize,S=t.onIframeLoad,C=t.iframeLoadTimeout,I=void 0===C?5e3:C,E=t.onStylesheetLoad,A=t.stylesheetLoadTimeout,M=void 0===A?5e3:A,N=t.keepIframeSrcFn,P=void 0===N?function(){return!1}:N,T=t.newlyAddedElement,O=void 0!==T&&T,R=t.cssCaptured,L=void 0!==R&&R,U=t.needsMask,j=t.preserveWhiteSpace,D=void 0===j||j;U||(U=Ae(e,s,a,void 0===U));var z,q=Me(e,{doc:r,mirror:n,blockClass:i,blockSelector:o,needsMask:U,inlineStylesheet:h,maskInputOptions:p,maskTextFn:f,maskInputFn:m,dataURLOptions:v,inlineImages:w,recordCanvas:k,keepIframeSrcFn:P,newlyAddedElement:O,cssCaptured:L});if(!q)return console.warn(e,"not serialized"),null;z=n.hasNode(e)?n.getId(e):function(e,t){if(t.comment&&e.type===F.Comment)return!0;if(e.type===F.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===se(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(Ne(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===Ne(e.attributes.name)||"icon"===Ne(e.attributes.rel)||"apple-touch-icon"===Ne(e.attributes.rel)||"shortcut icon"===Ne(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&Ne(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(Ne(e.attributes.property).match(/^(og|twitter|fb):/)||Ne(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===Ne(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===Ne(e.attributes.name)||"googlebot"===Ne(e.attributes.name)||"bingbot"===Ne(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===Ne(e.attributes.name)||"generator"===Ne(e.attributes.name)||"framework"===Ne(e.attributes.name)||"publisher"===Ne(e.attributes.name)||"progid"===Ne(e.attributes.name)||Ne(e.attributes.property).match(/^article:/)||Ne(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===Ne(e.attributes.name)||"yandex-verification"===Ne(e.attributes.name)||"csrf-token"===Ne(e.attributes.name)||"p:domain_verify"===Ne(e.attributes.name)||"verify-v1"===Ne(e.attributes.name)||"verification"===Ne(e.attributes.name)||"shopify-checkout-api-token"===Ne(e.attributes.name)))return!0}}return!1}(q,g)||!D&&q.type===F.Text&&!q.textContent.replace(/^\s+|\s+$/gm,"").length?-2:ve();var W=Object.assign(q,{id:z});if(n.add(e,W),-2===z)return null;_&&_(e);var $=!l;if(W.type===F.Element){$=$&&!W.needBlock,delete W.needBlock;var G=Z.shadowRoot(e);G&&X(G)&&(W.isShadowHost=!0)}if((W.type===F.Document||W.type===F.Element)&&$){g.headWhitespace&&W.type===F.Element&&"head"===W.tagName&&(D=!1);var V={doc:r,mirror:n,blockClass:i,blockSelector:o,needsMask:U,maskTextClass:s,maskTextSelector:a,skipChild:l,inlineStylesheet:h,maskInputOptions:p,maskTextFn:f,maskInputFn:m,slimDOMOptions:g,dataURLOptions:v,inlineImages:w,recordCanvas:k,preserveWhiteSpace:D,onSerialize:_,onIframeLoad:S,iframeLoadTimeout:I,onStylesheetLoad:E,stylesheetLoadTimeout:M,keepIframeSrcFn:P,cssCaptured:!1};if(W.type===F.Element&&"textarea"===W.tagName&&void 0!==W.attributes.value);else{W.type===F.Element&&void 0!==W.attributes._cssText&&"string"==typeof W.attributes._cssText&&(V.cssCaptured=!0);for(var H,K=B(Array.from(Z.childNodes(e)));!(H=K()).done;){var Q=Pe(H.value,V);Q&&W.childNodes.push(Q)}}var ee=null;if(Y(e)&&(ee=Z.shadowRoot(e)))for(var te,re=B(Array.from(Z.childNodes(ee)));!(te=re()).done;){var ne=Pe(te.value,V);ne&&(X(ee)&&(ne.isShadow=!0),W.childNodes.push(ne))}}var ie=Z.parentNode(e);return ie&&J(ie)&&X(ie)&&(W.isShadow=!0),W.type===F.Element&&"iframe"===W.tagName&&function(e,t,r){var n=e.contentWindow;if(n){var i,o=!1;try{i=n.document.readyState}catch(vu){return}if("complete"===i){var s="about:blank";if(n.location.href!==s||e.src===s||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}else{var a=setTimeout(function(){o||(t(),o=!0)},r);e.addEventListener("load",function(){clearTimeout(a),o=!0,t()})}}}(e,function(){var t=e.contentDocument;if(t&&S){var r=Pe(t,{doc:t,mirror:n,blockClass:i,blockSelector:o,needsMask:U,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:h,maskInputOptions:p,maskTextFn:f,maskInputFn:m,slimDOMOptions:g,dataURLOptions:v,inlineImages:w,recordCanvas:k,preserveWhiteSpace:D,onSerialize:_,onIframeLoad:S,iframeLoadTimeout:I,onStylesheetLoad:E,stylesheetLoadTimeout:M,keepIframeSrcFn:P});r&&S(e,r)}},I),W.type===F.Element&&"link"===W.tagName&&"string"==typeof W.attributes.rel&&("stylesheet"===W.attributes.rel||"preload"===W.attributes.rel&&"string"==typeof W.attributes.href&&"css"===se(W.attributes.href))&&function(e,t,r){var n,i=!1;try{n=e.sheet}catch(vu){return}if(!n){var o=setTimeout(function(){i||(t(),i=!0)},r);e.addEventListener("load",function(){clearTimeout(o),i=!0,t()})}}(e,function(){if(E){var t=Pe(e,{doc:r,mirror:n,blockClass:i,blockSelector:o,needsMask:U,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:h,maskInputOptions:p,maskTextFn:f,maskInputFn:m,slimDOMOptions:g,dataURLOptions:v,inlineImages:w,recordCanvas:k,preserveWhiteSpace:D,onSerialize:_,onIframeLoad:S,iframeLoadTimeout:I,onStylesheetLoad:E,stylesheetLoadTimeout:M,keepIframeSrcFn:P});t&&E(e,t)}},M),W}function Be(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Te(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return I(this,e)?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var Oe={exports:{}},Re=String,Le=function(){return{isColorSupported:!1,reset:Re,bold:Re,dim:Re,italic:Re,underline:Re,inverse:Re,hidden:Re,strikethrough:Re,black:Re,red:Re,green:Re,yellow:Re,blue:Re,magenta:Re,cyan:Re,white:Re,gray:Re,bgBlack:Re,bgRed:Re,bgGreen:Re,bgYellow:Re,bgBlue:Re,bgMagenta:Re,bgCyan:Re,bgWhite:Re}};Oe.exports=Le(),Oe.exports.createColors=Le;var Ue=Oe.exports,je=Te(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}))),De=Ue,Fe=je,ze=function(e){function t(r,n,i,o,s,a){var c;return(c=e.call(this,r)||this).name="CssSyntaxError",c.reason=r,s&&(c.file=s),o&&(c.source=o),a&&(c.plugin=a),void 0!==n&&void 0!==i&&("number"==typeof n?(c.line=n,c.column=i):(c.line=n.line,c.column=n.column,c.endLine=i.line,c.endColumn=i.column)),c.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(c,t),c}C(t,e);var r=t.prototype;return r.setMessage=function(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason},r.showSourceCode=function(e){var t=this;if(!this.source)return"";var r=this.source;null==e&&(e=De.isColorSupported),Fe&&e&&(r=Fe(r));var n,i,o=r.split(/\r?\n/),s=Math.max(this.line-3,0),a=Math.min(this.line+2,o.length),c=String(a).length;if(e){var l=De.createColors(!0),u=l.bold,h=l.gray,d=l.red;n=function(e){return u(d(e))},i=function(e){return h(e)}}else n=i=function(e){return e};return o.slice(s,a).map(function(e,r){var o=s+1+r,a=" "+(" "+o).slice(-c)+" | ";if(o===t.line){var l=i(a.replace(/\d/g," "))+e.slice(0,t.column-1).replace(/[^\t]/g," ");return n(">")+i(a)+e+"\n "+l+n("^")}return" "+i(a)+e}).join("\n")},r.toString=function(){var e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e},t}(N(Error)),qe=ze;ze.default=ze;var We={};We.isClean=Symbol("isClean"),We.my=Symbol("my");var $e={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};var Ge=function(){function e(e){this.builder=e}var t=e.prototype;return t.atrule=function(e,t){var r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{var i=(e.raws.between||"")+(t?";":"");this.builder(r+n+i,e)}},t.beforeAfter=function(e,t){var r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");for(var n=e.parent,i=0;n&&"root"!==n.type;)i+=1,n=n.parent;if(r.includes("\n")){var o=this.raw(e,null,"indent");if(o.length)for(var s=0;s<i;s++)r+=o}return r},t.block=function(e,t){var r,n=this.raw(e,"between","beforeOpen");this.builder(t+n+"{",e,"start"),e.nodes&&e.nodes.length?(this.body(e),r=this.raw(e,"after")):r=this.raw(e,"after","emptyBody"),r&&this.builder(r),this.builder("}",e,"end")},t.body=function(e){for(var t=e.nodes.length-1;t>0&&"comment"===e.nodes[t].type;)t-=1;for(var r=this.raw(e,"semicolon"),n=0;n<e.nodes.length;n++){var i=e.nodes[n],o=this.raw(i,"before");o&&this.builder(o),this.stringify(i,t!==n||r)}},t.comment=function(e){var t=this.raw(e,"left","commentLeft"),r=this.raw(e,"right","commentRight");this.builder("/*"+t+e.text+r+"*/",e)},t.decl=function(e,t){var r=this.raw(e,"between","colon"),n=e.prop+r+this.rawValue(e,"value");e.important&&(n+=e.raws.important||" !important"),t&&(n+=";"),this.builder(n,e)},t.document=function(e){this.body(e)},t.raw=function(e,t,r){var n;if(r||(r=t),t&&void 0!==(n=e.raws[t]))return n;var i=e.parent;if("before"===r){if(!i||"root"===i.type&&i.first===e)return"";if(i&&"document"===i.type)return""}if(!i)return $e[r];var o=e.root();if(o.rawCache||(o.rawCache={}),void 0!==o.rawCache[r])return o.rawCache[r];if("before"===r||"after"===r)return this.beforeAfter(e,r);var s,a="raw"+((s=r)[0].toUpperCase()+s.slice(1));return this[a]?n=this[a](o,e):o.walk(function(e){if(void 0!==(n=e.raws[t]))return!1}),void 0===n&&(n=$e[r]),o.rawCache[r]=n,n},t.rawBeforeClose=function(e){var t;return e.walk(function(e){if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return(t=e.raws.after).includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t},t.rawBeforeComment=function(e,t){var r;return e.walkComments(function(e){if(void 0!==e.raws.before)return(r=e.raws.before).includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r},t.rawBeforeDecl=function(e,t){var r;return e.walkDecls(function(e){if(void 0!==e.raws.before)return(r=e.raws.before).includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r},t.rawBeforeOpen=function(e){var t;return e.walk(function(e){if("decl"!==e.type&&void 0!==(t=e.raws.between))return!1}),t},t.rawBeforeRule=function(e){var t;return e.walk(function(r){if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return(t=r.raws.before).includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t},t.rawColon=function(e){var t;return e.walkDecls(function(e){if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t},t.rawEmptyBody=function(e){var t;return e.walk(function(e){if(e.nodes&&0===e.nodes.length&&void 0!==(t=e.raws.after))return!1}),t},t.rawIndent=function(e){return e.raws.indent?e.raws.indent:(e.walk(function(r){var n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){var i=r.raws.before.split("\n");return t=(t=i[i.length-1]).replace(/\S/g,""),!1}}),t);var t},t.rawSemicolon=function(e){var t;return e.walk(function(e){if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&void 0!==(t=e.raws.semicolon))return!1}),t},t.rawValue=function(e,t){var r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r},t.root=function(e){this.body(e),e.raws.after&&this.builder(e.raws.after)},t.rule=function(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")},t.stringify=function(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)},e}(),Ve=Ge;Ge.default=Ge;var He=Ve;function Ke(e,t){new He(t).stringify(e)}var Ze=Ke;Ke.default=Ke;var Ye=We.isClean,Je=We.my,Xe=qe,Qe=Ve,et=Ze;function tt(e,t){var r=new e.constructor;for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&"proxyCache"!==n){var i=e[n],o=void 0===i?"undefined":M(i);"parent"===n&&"object"===o?t&&(r[n]=t):"source"===n?r[n]=i:Array.isArray(i)?r[n]=i.map(function(e){return tt(e,r)}):("object"===o&&null!==i&&(i=tt(i)),r[n]=i)}return r}var rt=function(){function e(e){for(var t in void 0===e&&(e={}),this.raws={},this[Ye]=!1,this[Je]=!0,e)if("nodes"===t){this.nodes=[];for(var r,n=B(e[t]);!(r=n()).done;){var i=r.value;"function"==typeof i.clone?this.append(i.clone()):this.append(i)}}else this[t]=e[t]}var t=e.prototype;return t.addToError=function(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){var t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,"$&"+t.input.from+":"+t.start.line+":"+t.start.column+"$&")}return e},t.after=function(e){return this.parent.insertAfter(this,e),this},t.assign=function(e){for(var t in void 0===e&&(e={}),e)this[t]=e[t];return this},t.before=function(e){return this.parent.insertBefore(this,e),this},t.cleanRaws=function(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between},t.clone=function(e){void 0===e&&(e={});var t=tt(this);for(var r in e)t[r]=e[r];return t},t.cloneAfter=function(e){void 0===e&&(e={});var t=this.clone(e);return this.parent.insertAfter(this,t),t},t.cloneBefore=function(e){void 0===e&&(e={});var t=this.clone(e);return this.parent.insertBefore(this,t),t},t.error=function(e,t){if(void 0===t&&(t={}),this.source){var r=this.rangeBy(t),n=r.end,i=r.start;return this.source.input.error(e,{column:i.column,line:i.line},{column:n.column,line:n.line},t)}return new Xe(e)},t.getProxyProcessor=function(){return{get:function(e,t){return"proxyOf"===t?e:"root"===t?function(){return e.root().toProxy()}:e[t]},set:function(e,t,r){return e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0}}},t.markDirty=function(){if(this[Ye]){this[Ye]=!1;for(var e=this;e=e.parent;)e[Ye]=!1}},t.next=function(){if(this.parent){var e=this.parent.index(this);return this.parent.nodes[e+1]}},t.positionBy=function(e,t){var r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){var n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r},t.positionInside=function(e,t){for(var r=t||this.toString(),n=this.source.start.column,i=this.source.start.line,o=0;o<e;o++)"\n"===r[o]?(n=1,i+=1):n+=1;return{column:n,line:i}},t.prev=function(){if(this.parent){var e=this.parent.index(this);return this.parent.nodes[e-1]}},t.rangeBy=function(e){var t={column:this.source.start.column,line:this.source.start.line},r=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){var n=this.toString(),i=n.indexOf(e.word);-1!==i&&(t=this.positionInside(i,n),r=this.positionInside(i+e.word.length,n))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?r={column:e.end.column,line:e.end.line}:"number"==typeof e.endIndex?r=this.positionInside(e.endIndex):e.index&&(r=this.positionInside(e.index+1));return(r.line<t.line||r.line===t.line&&r.column<=t.column)&&(r={column:t.column+1,line:t.line}),{end:r,start:t}},t.raw=function(e,t){return(new Qe).raw(this,e,t)},t.remove=function(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this},t.replaceWith=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];if(this.parent){for(var n,i=this,o=!1,s=B(t);!(n=s()).done;){var a=n.value;a===this?o=!0:o?(this.parent.insertAfter(i,a),i=a):this.parent.insertBefore(i,a)}o||this.remove()}return this},t.root=function(){for(var e=this;e.parent&&"document"!==e.parent.type;)e=e.parent;return e},t.toJSON=function(e,t){var r={},n=null==t;t=t||new Map;var i=0;for(var o in this)if(Object.prototype.hasOwnProperty.call(this,o)&&"parent"!==o&&"proxyCache"!==o){var s=this[o];if(Array.isArray(s))r[o]=s.map(function(e){return"object"===(void 0===e?"undefined":M(e))&&e.toJSON?e.toJSON(null,t):e});else if("object"===(void 0===s?"undefined":M(s))&&s.toJSON)r[o]=s.toJSON(null,t);else if("source"===o){var a=t.get(s.input);null==a&&(a=i,t.set(s.input,i),i++),r[o]={end:s.end,inputId:a,start:s.start}}else r[o]=s}return n&&(r.inputs=[].concat(t.keys()).map(function(e){return e.toJSON()})),r},t.toProxy=function(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache},t.toString=function(e){void 0===e&&(e=et),e.stringify&&(e=e.stringify);var t="";return e(this,function(e){t+=e}),t},t.warn=function(e,t,r){var n={node:this};for(var i in r)n[i]=r[i];return e.warn(t,n)},k(e,[{key:"proxyOf",get:function(){return this}}]),e}(),nt=rt;rt.default=rt;var it=function(e){function t(t){var r;return t&&void 0!==t.value&&"string"!=typeof t.value&&(t=_({},t,{value:String(t.value)})),(r=e.call(this,t)||this).type="decl",r}return C(t,e),k(t,[{key:"variable",get:function(){return this.prop.startsWith("--")||"$"===this.prop[0]}}]),t}(nt),ot=it;it.default=it;var st=function(e){void 0===e&&(e=21);for(var t="",r=e;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t},at=je.SourceMapConsumer,ct=je.SourceMapGenerator,lt=je.existsSync,ut=je.readFileSync,ht=je.dirname,dt=je.join;var pt=function(){function e(e,t){if(!1!==t.map){this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");var r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=ht(this.mapFile)),n&&(this.text=n)}}var t=e.prototype;return t.consumer=function(){return this.consumerCache||(this.consumerCache=new at(this.text)),this.consumerCache},t.decodeInline=function(e){var t;if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),g?g.from(t,"base64").toString():window.atob(t);var r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)},t.getAnnotationURL=function(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()},t.isMap=function(e){return"object"===(void 0===e?"undefined":M(e))&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))},t.loadAnnotation=function(e){var t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(t){var r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}},t.loadFile=function(e){if(this.root=ht(e),lt(e))return this.mapFile=e,ut(e,"utf-8").toString().trim()},t.loadMap=function(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(I(t,at))return ct.fromSourceMap(t).toString();if(I(t,ct))return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}var r=t(e);if(r){var n=this.loadFile(r);if(!n)throw new Error("Unable to load previous source map: "+r.toString());return n}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){var i=this.annotation;return e&&(i=dt(ht(e),i)),this.loadFile(i)}}},t.startWith=function(e,t){return!!e&&e.substr(0,t.length)===t},t.withContent=function(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)},e}(),ft=pt;pt.default=pt;var mt=je.SourceMapConsumer,gt=je.SourceMapGenerator,yt=je.fileURLToPath,vt=je.pathToFileURL,bt=je.isAbsolute,wt=je.resolve,xt=st,kt=je,_t=qe,St=ft,Ct=Symbol("fromOffsetCache"),It=Boolean(mt&>),Et=Boolean(wt&&bt),At=function(){function e(e,t){if(void 0===t&&(t={}),null==e||"object"===(void 0===e?"undefined":M(e))&&!e.toString)throw new Error("PostCSS received "+e+" instead of CSS string");if(this.css=e.toString(),"\ufeff"===this.css[0]||"๏ฟพ"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!Et||/^\w+:\/\//.test(t.from)||bt(t.from)?this.file=t.from:this.file=wt(t.from)),Et&&It){var r=new St(this.css,t);if(r.text){this.map=r;var n=r.consumer().file;!this.file&&n&&(this.file=this.mapResolve(n))}}this.file||(this.id="<input css "+xt(6)+">"),this.map&&(this.map.file=this.from)}var t=e.prototype;return t.error=function(e,t,r,n){var i,o,s;if(void 0===n&&(n={}),t&&"object"===(void 0===t?"undefined":M(t))){var a=t,c=r;if("number"==typeof a.offset){var l=this.fromOffset(a.offset);t=l.line,r=l.col}else t=a.line,r=a.column;if("number"==typeof c.offset){var u=this.fromOffset(c.offset);o=u.line,s=u.col}else o=c.line,s=c.column}else if(!r){var h=this.fromOffset(t);t=h.line,r=h.col}var d=this.origin(t,r,o,s);return(i=d?new _t(e,void 0===d.endLine?d.line:{column:d.column,line:d.line},void 0===d.endLine?d.column:{column:d.endColumn,line:d.endLine},d.source,d.file,n.plugin):new _t(e,void 0===o?t:{column:r,line:t},void 0===o?r:{column:s,line:o},this.css,this.file,n.plugin)).input={column:r,endColumn:s,endLine:o,line:t,source:this.css},this.file&&(vt&&(i.input.url=vt(this.file).toString()),i.input.file=this.file),i},t.fromOffset=function(e){var t;if(this[Ct])t=this[Ct];else{var r=this.css.split("\n");t=new Array(r.length);for(var n=0,i=0,o=r.length;i<o;i++)t[i]=n,n+=r[i].length+1;this[Ct]=t}var s=0;if(e>=t[t.length-1])s=t.length-1;else for(var a,c=t.length-2;s<c;)if(e<t[a=s+(c-s>>1)])c=a-1;else{if(!(e>=t[a+1])){s=a;break}s=a+1}return{col:e-t[s]+1,line:s+1}},t.mapResolve=function(e){return/^\w+:\/\//.test(e)?e:wt(this.map.consumer().sourceRoot||this.map.root||".",e)},t.origin=function(e,t,r,n){if(!this.map)return!1;var i,o,s=this.map.consumer(),a=s.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(i=s.originalPositionFor({column:n,line:r})),o=bt(a.source)?vt(a.source):new URL(a.source,this.map.consumer().sourceRoot||vt(this.map.mapFile));var c={column:a.column,endColumn:i&&i.column,endLine:i&&i.line,line:a.line,url:o.toString()};if("file:"===o.protocol){if(!yt)throw new Error("file: protocol is not available in this PostCSS build");c.file=yt(o)}var l=s.sourceContentFor(a.source);return l&&(c.source=l),c},t.toJSON=function(){for(var e={},t=0,r=["hasBOM","css","file","id"];t<r.length;t++){var n=r[t];null!=this[n]&&(e[n]=this[n])}return this.map&&(e.map=_({},this.map),e.map.consumerCache&&(e.map.consumerCache=void 0)),e},k(e,[{key:"from",get:function(){return this.file||this.id}}]),e}(),Mt=At;At.default=At,kt&&kt.registerInput&&kt.registerInput(At);var Nt=je.SourceMapConsumer,Pt=je.SourceMapGenerator,Bt=je.dirname,Tt=je.relative,Ot=je.resolve,Rt=je.sep,Lt=je.pathToFileURL,Ut=Mt,jt=Boolean(Nt&&Pt),Dt=Boolean(Bt&&Ot&&Tt&&Rt),Ft=function(){function e(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}var t=e.prototype;return t.addAnnotation=function(){var e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";var t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"},t.applyPrevMaps=function(){for(var e,t=B(this.previous());!(e=t()).done;){var r=e.value,n=this.toUrl(this.path(r.file)),i=r.root||Bt(r.file),o=void 0;!1===this.mapOpts.sourcesContent?(o=new Nt(r.text)).sourcesContent&&(o.sourcesContent=null):o=r.consumer(),this.map.applySourceMap(o,n,this.toUrl(this.path(i)))}},t.clearAnnotation=function(){if(!1!==this.mapOpts.annotation)if(this.root)for(var e,t=this.root.nodes.length-1;t>=0;t--)"comment"===(e=this.root.nodes[t]).type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t);else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))},t.generate=function(){if(this.clearAnnotation(),Dt&&jt&&this.isMap())return this.generateMap();var e="";return this.stringify(this.root,function(t){e+=t}),[e]},t.generateMap=function(){if(this.root)this.generateString();else if(1===this.previous().length){var e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Pt.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Pt({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]},t.generateString=function(){var e=this;this.css="",this.map=new Pt({file:this.outputFile(),ignoreInvalidMapping:!0});var t,r,n=1,i=1,o="<no source>",s={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,function(a,c,l){if(e.css+=a,c&&"end"!==l&&(s.generated.line=n,s.generated.column=i-1,c.source&&c.source.start?(s.source=e.sourcePath(c),s.original.line=c.source.start.line,s.original.column=c.source.start.column-1,e.map.addMapping(s)):(s.source=o,s.original.line=1,s.original.column=0,e.map.addMapping(s))),(t=a.match(/\n/g))?(n+=t.length,r=a.lastIndexOf("\n"),i=a.length-r):i+=a.length,c&&"start"!==l){var u=c.parent||{raws:{}};("decl"===c.type||"atrule"===c.type&&!c.nodes)&&c===u.last&&!u.raws.semicolon||(c.source&&c.source.end?(s.source=e.sourcePath(c),s.original.line=c.source.end.line,s.original.column=c.source.end.column-1,s.generated.line=n,s.generated.column=i-2,e.map.addMapping(s)):(s.source=o,s.original.line=1,s.original.column=0,s.generated.line=n,s.generated.column=i-1,e.map.addMapping(s)))}})},t.isAnnotation=function(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(function(e){return e.annotation}))},t.isInline=function(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;var e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(function(e){return e.inline}))},t.isMap=function(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0},t.isSourcesContent=function(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(function(e){return e.withContent()})},t.outputFile=function(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"},t.path=function(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;var t=this.memoizedPaths.get(e);if(t)return t;var r=this.opts.to?Bt(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=Bt(Ot(r,this.mapOpts.annotation)));var n=Tt(r,e);return this.memoizedPaths.set(e,n),n},t.previous=function(){var e=this;if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(function(t){if(t.source&&t.source.input.map){var r=t.source.input.map;e.previousMaps.includes(r)||e.previousMaps.push(r)}});else{var t=new Ut(this.originalCSS,this.opts);t.map&&this.previousMaps.push(t.map)}return this.previousMaps},t.setSourcesContent=function(){var e=this,t={};if(this.root)this.root.walk(function(r){if(r.source){var n=r.source.input.from;if(n&&!t[n]){t[n]=!0;var i=e.usesFileUrls?e.toFileUrl(n):e.toUrl(e.path(n));e.map.setSourceContent(i,r.source.input.css)}}});else if(this.css){var r=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(r,this.css)}},t.sourcePath=function(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))},t.toBase64=function(e){return g?g.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))},t.toFileUrl=function(e){var t=this.memoizedFileURLs.get(e);if(t)return t;if(Lt){var r=Lt(e).toString();return this.memoizedFileURLs.set(e,r),r}throw new Error("`map.absolute` option is not available in this PostCSS build")},t.toUrl=function(e){var t=this.memoizedURLs.get(e);if(t)return t;"\\"===Rt&&(e=e.replace(/\\/g,"/"));var r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r},e}(),zt=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="comment",r}return C(t,e),t}(nt),qt=zt;zt.default=zt;var Wt,$t,Gt,Vt,Ht=We.isClean,Kt=We.my,Zt=ot,Yt=qt;function Jt(e){return e.map(function(e){return e.nodes&&(e.nodes=Jt(e.nodes)),delete e.source,e})}function Xt(e){if(e[Ht]=!1,e.proxyOf.nodes)for(var t,r=B(e.proxyOf.nodes);!(t=r()).done;){Xt(t.value)}}var Qt=function(e){function t(){return e.apply(this,arguments)||this}C(t,e);var r=t.prototype;return r.append=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n,i=B(t);!(n=i()).done;)for(var o,s=n.value,a=B(this.normalize(s,this.last));!(o=a()).done;){var c=o.value;this.proxyOf.nodes.push(c)}return this.markDirty(),this},r.cleanRaws=function(t){if(e.prototype.cleanRaws.call(this,t),this.nodes)for(var r,n=B(this.nodes);!(r=n()).done;){r.value.cleanRaws(t)}},r.each=function(e){if(this.proxyOf.nodes){for(var t,r,n=this.getIterator();this.indexes[n]<this.proxyOf.nodes.length&&(t=this.indexes[n],!1!==(r=e(this.proxyOf.nodes[t],t)));)this.indexes[n]+=1;return delete this.indexes[n],r}},r.every=function(e){return this.nodes.every(e)},r.getIterator=function(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;var e=this.lastEach;return this.indexes[e]=0,e},r.getProxyProcessor=function(){return{get:function(e,t){return"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];var o;return(o=e)[t].apply(o,[].concat(n.map(function(e){return"function"==typeof e?function(t,r){return e(t.toProxy(),r)}:e})))}:"every"===t||"some"===t?function(r){return e[t](function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return r.apply(void 0,[].concat([e.toProxy()],n))})}:"root"===t?function(){return e.root().toProxy()}:"nodes"===t?e.nodes.map(function(e){return e.toProxy()}):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t]},set:function(e,t,r){return e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0}}},r.index=function(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))},r.insertAfter=function(e,t){var r,n=this.index(e),i=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(var o,s=B(i);!(o=s()).done;){var a=o.value;this.proxyOf.nodes.splice(n+1,0,a)}for(var c in this.indexes)n<(r=this.indexes[c])&&(this.indexes[c]=r+i.length);return this.markDirty(),this},r.insertBefore=function(e,t){var r,n=this.index(e),i=0===n&&"prepend",o=this.normalize(t,this.proxyOf.nodes[n],i).reverse();n=this.index(e);for(var s,a=B(o);!(s=a()).done;){var c=s.value;this.proxyOf.nodes.splice(n,0,c)}for(var l in this.indexes)n<=(r=this.indexes[l])&&(this.indexes[l]=r+o.length);return this.markDirty(),this},r.normalize=function(e,r){var n=this;if("string"==typeof e)e=Jt(Wt(e).nodes);else if(void 0===e)e=[];else if(Array.isArray(e))for(var i,o=B(e=e.slice(0));!(i=o()).done;){var s=i.value;s.parent&&s.parent.removeChild(s,"ignore")}else if("root"===e.type&&"document"!==this.type)for(var a,c=B(e=e.nodes.slice(0));!(a=c()).done;){var l=a.value;l.parent&&l.parent.removeChild(l,"ignore")}else if(e.type)e=[e];else if(e.prop){if(void 0===e.value)throw new Error("Value field is missed in node creation");"string"!=typeof e.value&&(e.value=String(e.value)),e=[new Zt(e)]}else if(e.selector)e=[new $t(e)];else if(e.name)e=[new Gt(e)];else{if(!e.text)throw new Error("Unknown node type in node creation");e=[new Yt(e)]}return e.map(function(e){return e[Kt]||t.rebuild(e),(e=e.proxyOf).parent&&e.parent.removeChild(e),e[Ht]&&Xt(e),void 0===e.raws.before&&r&&void 0!==r.raws.before&&(e.raws.before=r.raws.before.replace(/\S/g,"")),e.parent=n.proxyOf,e})},r.prepend=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n,i=B(t=t.reverse());!(n=i()).done;){for(var o,s=n.value,a=this.normalize(s,this.first,"prepend").reverse(),c=B(a);!(o=c()).done;){var l=o.value;this.proxyOf.nodes.unshift(l)}for(var u in this.indexes)this.indexes[u]=this.indexes[u]+a.length}return this.markDirty(),this},r.push=function(e){return e.parent=this,this.proxyOf.nodes.push(e),this},r.removeAll=function(){for(var e,t=B(this.proxyOf.nodes);!(e=t()).done;){e.value.parent=void 0}return this.proxyOf.nodes=[],this.markDirty(),this},r.removeChild=function(e){var t;for(var r in e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1),this.indexes)(t=this.indexes[r])>=e&&(this.indexes[r]=t-1);return this.markDirty(),this},r.replaceValues=function(e,t,r){return r||(r=t,t={}),this.walkDecls(function(n){t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this},r.some=function(e){return this.nodes.some(e)},r.walk=function(e){return this.each(function(t,r){var n;try{n=e(t,r)}catch(i){throw t.addToError(i)}return!1!==n&&t.walk&&(n=t.walk(e)),n})},r.walkAtRules=function(e,t){return t?I(e,RegExp)?this.walk(function(r,n){if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk(function(r,n){if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk(function(e,r){if("atrule"===e.type)return t(e,r)}))},r.walkComments=function(e){return this.walk(function(t,r){if("comment"===t.type)return e(t,r)})},r.walkDecls=function(e,t){return t?I(e,RegExp)?this.walk(function(r,n){if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk(function(r,n){if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk(function(e,r){if("decl"===e.type)return t(e,r)}))},r.walkRules=function(e,t){return t?I(e,RegExp)?this.walk(function(r,n){if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk(function(r,n){if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk(function(e,r){if("rule"===e.type)return t(e,r)}))},k(t,[{key:"first",get:function(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}},{key:"last",get:function(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}}]),t}(nt);Qt.registerParse=function(e){Wt=e},Qt.registerRule=function(e){$t=e},Qt.registerAtRule=function(e){Gt=e},Qt.registerRoot=function(e){Vt=e};var er=Qt;Qt.default=Qt,Qt.rebuild=function(e){"atrule"===e.type?Object.setPrototypeOf(e,Gt.prototype):"rule"===e.type?Object.setPrototypeOf(e,$t.prototype):"decl"===e.type?Object.setPrototypeOf(e,Zt.prototype):"comment"===e.type?Object.setPrototypeOf(e,Yt.prototype):"root"===e.type&&Object.setPrototypeOf(e,Vt.prototype),e[Kt]=!0,e.nodes&&e.nodes.forEach(function(e){Qt.rebuild(e)})};var tr,rr,nr=function(e){function t(t){var r;return(r=e.call(this,_({type:"document"},t))||this).nodes||(r.nodes=[]),r}return C(t,e),t.prototype.toResult=function(e){return void 0===e&&(e={}),new tr(new rr,this,e).stringify()},t}(er);nr.registerLazyResult=function(e){tr=e},nr.registerProcessor=function(e){rr=e};var ir=nr;nr.default=nr;var or=function(){function e(e,t){if(void 0===t&&(t={}),this.type="warning",this.text=e,t.node&&t.node.source){var r=t.node.rangeBy(t);this.line=r.start.line,this.column=r.start.column,this.endLine=r.end.line,this.endColumn=r.end.column}for(var n in t)this[n]=t[n]}return e.prototype.toString=function(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text},e}(),sr=or;or.default=or;var ar=sr,cr=function(){function e(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}var t=e.prototype;return t.toString=function(){return this.css},t.warn=function(e,t){void 0===t&&(t={}),t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);var r=new ar(e,t);return this.messages.push(r),r},t.warnings=function(){return this.messages.filter(function(e){return"warning"===e.type})},k(e,[{key:"content",get:function(){return this.css}}]),e}(),lr=cr;cr.default=cr;var ur="'".charCodeAt(0),hr='"'.charCodeAt(0),dr="\\".charCodeAt(0),pr="/".charCodeAt(0),fr="\n".charCodeAt(0),mr=" ".charCodeAt(0),gr="\f".charCodeAt(0),yr="\t".charCodeAt(0),vr="\r".charCodeAt(0),br="[".charCodeAt(0),wr="]".charCodeAt(0),xr="(".charCodeAt(0),kr=")".charCodeAt(0),_r="{".charCodeAt(0),Sr="}".charCodeAt(0),Cr=";".charCodeAt(0),Ir="*".charCodeAt(0),Er=":".charCodeAt(0),Ar="@".charCodeAt(0),Mr=/[\t\n\f\r "#'()/;[\\\]{}]/g,Nr=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Pr=/.[\r\n"'(/\\]/,Br=/[\da-f]/i,Tr=er,Or=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="atrule",r}C(t,e);var r=t.prototype;return r.append=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i;return this.proxyOf.nodes||(this.nodes=[]),(i=e.prototype.append).call.apply(i,[].concat([this],r))},r.prepend=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i;return this.proxyOf.nodes||(this.nodes=[]),(i=e.prototype.prepend).call.apply(i,[].concat([this],r))},t}(Tr),Rr=Or;Or.default=Or,Tr.registerAtRule(Or);var Lr,Ur,jr=er,Dr=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="root",r.nodes||(r.nodes=[]),r}C(t,e);var r=t.prototype;return r.normalize=function(t,r,n){var i=e.prototype.normalize.call(this,t);if(r)if("prepend"===n)this.nodes.length>1?r.raws.before=this.nodes[1].raws.before:delete r.raws.before;else if(this.first!==r)for(var o,s=B(i);!(o=s()).done;){o.value.raws.before=r.raws.before}return i},r.removeChild=function(t,r){var n=this.index(t);return!r&&0===n&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[n].raws.before),e.prototype.removeChild.call(this,t)},r.toResult=function(e){return void 0===e&&(e={}),new Lr(new Ur,this,e).stringify()},t}(jr);Dr.registerLazyResult=function(e){Lr=e},Dr.registerProcessor=function(e){Ur=e};var Fr=Dr;Dr.default=Dr,jr.registerRoot(Dr);var zr={comma:function(e){return zr.split(e,[","],!0)},space:function(e){return zr.split(e,[" ","\n","\t"])},split:function(e,t,r){for(var n,i=[],o="",s=!1,a=0,c=!1,l="",u=!1,h=B(e);!(n=h()).done;){var d=n.value;u?u=!1:"\\"===d?u=!0:c?d===l&&(c=!1):'"'===d||"'"===d?(c=!0,l=d):"("===d?a+=1:")"===d?a>0&&(a-=1):0===a&&t.includes(d)&&(s=!0),s?(""!==o&&i.push(o.trim()),o="",s=!1):o+=d}return(r||""!==o)&&i.push(o.trim()),i}},qr=zr;zr.default=zr;var Wr=er,$r=qr,Gr=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="rule",r.nodes||(r.nodes=[]),r}return C(t,e),k(t,[{key:"selectors",get:function(){return $r.comma(this.selector)},set:function(e){var t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}}]),t}(Wr),Vr=Gr;Gr.default=Gr,Wr.registerRule(Gr);var Hr=ot,Kr=function(e,t){void 0===t&&(t={});var r,n,i,o,s,a,c,l,u,h,d=e.css.valueOf(),p=t.ignoreErrors,f=d.length,m=0,g=[],y=[];function v(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(!(m>=f)){var t=!!e&&e.ignoreUnclosed;switch(r=d.charCodeAt(m)){case fr:case mr:case yr:case vr:case gr:n=m;do{n+=1,r=d.charCodeAt(n)}while(r===mr||r===fr||r===yr||r===vr||r===gr);h=["space",d.slice(m,n)],m=n-1;break;case br:case wr:case _r:case Sr:case Er:case Cr:case kr:var b=String.fromCharCode(r);h=[b,b,m];break;case xr:if(l=g.length?g.pop()[1]:"",u=d.charCodeAt(m+1),"url"===l&&u!==ur&&u!==hr&&u!==mr&&u!==fr&&u!==yr&&u!==gr&&u!==vr){n=m;do{if(a=!1,-1===(n=d.indexOf(")",n+1))){if(p||t){n=m;break}v("bracket")}for(c=n;d.charCodeAt(c-1)===dr;)c-=1,a=!a}while(a);h=["brackets",d.slice(m,n+1),m,n],m=n}else n=d.indexOf(")",m+1),o=d.slice(m,n+1),-1===n||Pr.test(o)?h=["(","(",m]:(h=["brackets",o,m,n],m=n);break;case ur:case hr:i=r===ur?"'":'"',n=m;do{if(a=!1,-1===(n=d.indexOf(i,n+1))){if(p||t){n=m+1;break}v("string")}for(c=n;d.charCodeAt(c-1)===dr;)c-=1,a=!a}while(a);h=["string",d.slice(m,n+1),m,n],m=n;break;case Ar:Mr.lastIndex=m+1,Mr.test(d),n=0===Mr.lastIndex?d.length-1:Mr.lastIndex-2,h=["at-word",d.slice(m,n+1),m,n],m=n;break;case dr:for(n=m,s=!0;d.charCodeAt(n+1)===dr;)n+=1,s=!s;if(r=d.charCodeAt(n+1),s&&r!==pr&&r!==mr&&r!==fr&&r!==yr&&r!==vr&&r!==gr&&(n+=1,Br.test(d.charAt(n)))){for(;Br.test(d.charAt(n+1));)n+=1;d.charCodeAt(n+1)===mr&&(n+=1)}h=["word",d.slice(m,n+1),m,n],m=n;break;default:r===pr&&d.charCodeAt(m+1)===Ir?(0===(n=d.indexOf("*/",m+2)+1)&&(p||t?n=d.length:v("comment")),h=["comment",d.slice(m,n+1),m,n],m=n):(Nr.lastIndex=m+1,Nr.test(d),n=0===Nr.lastIndex?d.length-1:Nr.lastIndex-2,h=["word",d.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h}},position:function(){return m}}},Zr=qt,Yr=Rr,Jr=Fr,Xr=Vr,Qr={empty:!0,space:!0};var en=function(){function e(e){this.input=e,this.root=new Jr,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}var t=e.prototype;return t.atrule=function(e){var t,r,n,i=new Yr;i.name=e[1].slice(1),""===i.name&&this.unnamedAtrule(i,e),this.init(i,e[2]);for(var o=!1,s=!1,a=[],c=[];!this.tokenizer.endOfFile();){if("("===(t=(e=this.tokenizer.nextToken())[0])||"["===t?c.push("("===t?")":"]"):"{"===t&&c.length>0?c.push("}"):t===c[c.length-1]&&c.pop(),0===c.length){if(";"===t){i.source.end=this.getPosition(e[2]),i.source.end.offset++,this.semicolon=!0;break}if("{"===t){s=!0;break}if("}"===t){if(a.length>0){for(r=a[n=a.length-1];r&&"space"===r[0];)r=a[--n];r&&(i.source.end=this.getPosition(r[3]||r[2]),i.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){o=!0;break}}i.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(i.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(i,"params",a),o&&(e=a[a.length-1],i.source.end=this.getPosition(e[3]||e[2]),i.source.end.offset++,this.spaces=i.raws.between,i.raws.between="")):(i.raws.afterName="",i.params=""),s&&(i.nodes=[],this.current=i)},t.checkMissedSemicolon=function(e){var t=this.colon(e);if(!1!==t){for(var r,n=0,i=t-1;i>=0&&("space"===(r=e[i])[0]||2!==(n+=1));i--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}},t.colon=function(e){for(var t,r,n,i,o=0,s=B(e.entries());!(i=s()).done;){var a=i.value,c=a[0];if("("===(r=(t=a[1])[0])&&(o+=1),")"===r&&(o-=1),0===o&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return c}this.doubleColon(t)}n=t}return!1},t.comment=function(e){var t=new Zr;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;var r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{var n=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=n[2],t.raws.left=n[1],t.raws.right=n[3]}},t.createTokenizer=function(){this.tokenizer=Kr(this.input)},t.decl=function(e,t){var r=new Hr;this.init(r,e[0][2]);var n,i=e[e.length-1];for(";"===i[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(i[3]||i[2]||function(e){for(var t=e.length-1;t>=0;t--){var r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){var o=e[0][0];if(":"===o||"space"===o||"comment"===o)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(":"===(n=e.shift())[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));for(var s,a=[];e.length&&("space"===(s=e[0][0])||"comment"===s);)a.push(e.shift());this.precheckMissedSemicolon(e);for(var c=e.length-1;c>=0;c--){if("!important"===(n=e[c])[1].toLowerCase()){r.important=!0;var l=this.stringFrom(e,c);" !important"!==(l=this.spacesFromEnd(e)+l)&&(r.raws.important=l);break}if("important"===n[1].toLowerCase()){for(var u=e.slice(0),h="",d=c;d>0;d--){var p=u[d][0];if(0===h.trim().indexOf("!")&&"space"!==p)break;h=u.pop()[1]+h}0===h.trim().indexOf("!")&&(r.important=!0,r.raws.important=h,e=u)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(function(e){return"space"!==e[0]&&"comment"!==e[0]})&&(r.raws.between+=a.map(function(e){return e[1]}).join(""),a=[]),this.raw(r,"value",a.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)},t.doubleColon=function(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})},t.emptyRule=function(e){var t=new Xr;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t},t.end=function(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)},t.endFile=function(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())},t.freeSemicolon=function(e){if(this.spaces+=e[1],this.current.nodes){var t=this.current.nodes[this.current.nodes.length-1];t&&"rule"===t.type&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces="")}},t.getPosition=function(e){var t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}},t.init=function(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)},t.other=function(e){for(var t=!1,r=null,n=!1,i=null,o=[],s=e[1].startsWith("--"),a=[],c=e;c;){if(r=c[0],a.push(c),"("===r||"["===r)i||(i=c),o.push("("===r?")":"]");else if(s&&n&&"{"===r)i||(i=c),o.push("}");else if(0===o.length){if(";"===r){if(n)return void this.decl(a,s);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===o[o.length-1]&&(o.pop(),0===o.length&&(i=null));c=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),o.length>0&&this.unclosedBracket(i),t&&n){if(!s)for(;a.length&&("space"===(c=a[a.length-1][0])||"comment"===c);)this.tokenizer.back(a.pop());this.decl(a,s)}else this.unknownWord(a)},t.parse=function(){for(var e;!this.tokenizer.endOfFile();)switch((e=this.tokenizer.nextToken())[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()},t.precheckMissedSemicolon=function(){},t.raw=function(e,t,r,n){for(var i,o,s,a,c=r.length,l="",u=!0,h=0;h<c;h+=1)"space"!==(o=(i=r[h])[0])||h!==c-1||n?"comment"===o?(a=r[h-1]?r[h-1][0]:"empty",s=r[h+1]?r[h+1][0]:"empty",Qr[a]||Qr[s]||","===l.slice(-1)?u=!1:l+=i[1]):l+=i[1]:u=!1;if(!u){var d=r.reduce(function(e,t){return e+t[1]},"");e.raws[t]={raw:d,value:l}}e[t]=l},t.rule=function(e){e.pop();var t=new Xr;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t},t.spacesAndCommentsFromEnd=function(e){for(var t,r="";e.length&&("space"===(t=e[e.length-1][0])||"comment"===t);)r=e.pop()[1]+r;return r},t.spacesAndCommentsFromStart=function(e){for(var t,r="";e.length&&("space"===(t=e[0][0])||"comment"===t);)r+=e.shift()[1];return r},t.spacesFromEnd=function(e){for(var t="";e.length&&"space"===e[e.length-1][0];)t=e.pop()[1]+t;return t},t.stringFrom=function(e,t){for(var r="",n=t;n<e.length;n++)r+=e[n][1];return e.splice(t,e.length-t),r},t.unclosedBlock=function(){var e=this.current.source.start;throw this.input.error("Unclosed block",e.line,e.column)},t.unclosedBracket=function(e){throw this.input.error("Unclosed bracket",{offset:e[2]},{offset:e[2]+1})},t.unexpectedClose=function(e){throw this.input.error("Unexpected }",{offset:e[2]},{offset:e[2]+1})},t.unknownWord=function(e){throw this.input.error("Unknown word",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})},t.unnamedAtrule=function(e,t){throw this.input.error("At-rule without name",{offset:t[2]},{offset:t[2]+t[1].length})},e}(),tn=er,rn=en,nn=Mt;function on(e,t){var r=new nn(e,t),n=new rn(r);try{n.parse()}catch(i){throw i}return n.root}var sn=on;on.default=on,tn.registerParse(on);var an=We.isClean,cn=We.my,ln=Ft,un=Ze,hn=er,dn=ir,pn=lr,fn=sn,mn=Fr,gn={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},yn={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},vn={Once:!0,postcssPlugin:!0,prepare:!0};function bn(e){return"object"===(void 0===e?"undefined":M(e))&&"function"==typeof e.then}function wn(e){var t=!1,r=gn[e.type];return"decl"===e.type?t=e.prop.toLowerCase():"atrule"===e.type&&(t=e.name.toLowerCase()),t&&e.append?[r,r+"-"+t,0,r+"Exit",r+"Exit-"+t]:t?[r,r+"-"+t,r+"Exit",r+"Exit-"+t]:e.append?[r,0,r+"Exit"]:[r,r+"Exit"]}function xn(e){return{eventIndex:0,events:"document"===e.type?["Document",0,"DocumentExit"]:"root"===e.type?["Root",0,"RootExit"]:wn(e),iterator:0,node:e,visitorIndex:0,visitors:[]}}function kn(e){return e[an]=!1,e.nodes&&e.nodes.forEach(function(e){return kn(e)}),e}var _n={},Sn=function(){function e(t,r,n){var i,o=this;if(this.stringified=!1,this.processed=!1,"object"!==(void 0===r?"undefined":M(r))||null===r||"root"!==r.type&&"document"!==r.type)if(I(r,e)||I(r,pn))i=kn(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{var s=fn;n.syntax&&(s=n.syntax.parse),n.parser&&(s=n.parser),s.parse&&(s=s.parse);try{i=s(r,n)}catch(vu){this.processed=!0,this.error=vu}i&&!i[cn]&&hn.rebuild(i)}else i=kn(r);this.result=new pn(t,i,n),this.helpers=_({},_n,{postcss:_n,result:this.result}),this.plugins=this.processor.plugins.map(function(e){return"object"===(void 0===e?"undefined":M(e))&&e.prepare?_({},e,e.prepare(o.result)):e})}var t=e.prototype;return t.async=function(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)},t.catch=function(e){return this.async().catch(e)},t.finally=function(e){return this.async().then(e,e)},t.getAsyncError=function(){throw new Error("Use process(css).then(cb) to work with async plugins")},t.handleError=function(e,t){var r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion){0}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(n){console&&console.error&&console.error(n)}return e},t.prepareVisitors=function(){var e=this;this.listeners={};for(var t,r=function(t,r,n){e.listeners[r]||(e.listeners[r]=[]),e.listeners[r].push([t,n])},n=B(this.plugins);!(t=n()).done;){var i=t.value;if("object"===(void 0===i?"undefined":M(i)))for(var o in i){if(!yn[o]&&/^[A-Z]/.test(o))throw new Error("Unknown event "+o+" in "+i.postcssPlugin+". Try to update PostCSS ("+this.processor.version+" now).");if(!vn[o])if("object"===M(i[o]))for(var s in i[o])r(i,"*"===s?o:o+"-"+s.toLowerCase(),i[o][s]);else"function"==typeof i[o]&&r(i,o,i[o])}}this.hasListener=Object.keys(this.listeners).length>0},t.runAsync=function(){var e=this;return w(function(){var t,r,n,i,o,s,a,c,l,u,h,d;return T(this,function(p){switch(p.label){case 0:e.plugin=0,t=0,p.label=1;case 1:if(!(t<e.plugins.length))return[3,6];if(r=e.plugins[t],!bn(n=e.runOnRoot(r)))return[3,5];p.label=2;case 2:return p.trys.push([2,4,,5]),[4,n];case 3:return p.sent(),[3,5];case 4:throw i=p.sent(),e.handleError(i);case 5:return t++,[3,1];case 6:if(e.prepareVisitors(),!e.hasListener)return[3,18];o=e.result.root,p.label=7;case 7:if(o[an])return[3,14];o[an]=!0,s=[xn(o)],p.label=8;case 8:if(!(s.length>0))return[3,13];if(!bn(a=e.visitTick(s)))return[3,12];p.label=9;case 9:return p.trys.push([9,11,,12]),[4,a];case 10:return p.sent(),[3,12];case 11:throw c=p.sent(),l=s[s.length-1].node,e.handleError(c,l);case 12:return[3,8];case 13:return[3,7];case 14:if(!e.listeners.OnceExit)return[3,18];u=function(){var t,r,n,i,s;return T(this,function(a){switch(a.label){case 0:t=d.value,r=t[0],n=t[1],e.result.lastPlugin=r,a.label=1;case 1:return a.trys.push([1,6,,7]),"document"!==o.type?[3,3]:(i=o.nodes.map(function(t){return n(t,e.helpers)}),[4,Promise.all(i)]);case 2:return a.sent(),[3,5];case 3:return[4,n(o,e.helpers)];case 4:a.sent(),a.label=5;case 5:return[3,7];case 6:throw s=a.sent(),e.handleError(s);case 7:return[2]}})},h=B(e.listeners.OnceExit),p.label=15;case 15:return(d=h()).done?[3,18]:[5,O(u())];case 16:p.sent(),p.label=17;case 17:return[3,15];case 18:return e.processed=!0,[2,e.stringify()]}})})()},t.runOnRoot=function(e){var t=this;this.result.lastPlugin=e;try{if("object"===(void 0===e?"undefined":M(e))&&e.Once){if("document"===this.result.root.type){var r=this.result.root.nodes.map(function(r){return e.Once(r,t.helpers)});return bn(r[0])?Promise.all(r):r}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(vu){throw this.handleError(vu)}},t.stringify=function(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();var e=this.result.opts,t=un;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);var r=new ln(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result},t.sync=function(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(var e,t=B(this.plugins);!(e=t()).done;){var r=e.value;if(bn(this.runOnRoot(r)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){for(var n=this.result.root;!n[an];)n[an]=!0,this.walkSync(n);if(this.listeners.OnceExit)if("document"===n.type)for(var i,o=B(n.nodes);!(i=o()).done;){var s=i.value;this.visitSync(this.listeners.OnceExit,s)}else this.visitSync(this.listeners.OnceExit,n)}return this.result},t.then=function(e,t){return this.async().then(e,t)},t.toString=function(){return this.css},t.visitSync=function(e,t){for(var r,n=B(e);!(r=n()).done;){var i=r.value,o=i[0],s=i[1];this.result.lastPlugin=o;var a=void 0;try{a=s(t,this.helpers)}catch(c){throw this.handleError(c,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(bn(a))throw this.getAsyncError()}},t.visitTick=function(e){var t=e[e.length-1],r=t.node,n=t.visitors;if("root"===r.type||"document"===r.type||r.parent){if(n.length>0&&t.visitorIndex<n.length){var i=n[t.visitorIndex],o=i[0],s=i[1];t.visitorIndex+=1,t.visitorIndex===n.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=o;try{return s(r.toProxy(),this.helpers)}catch(h){throw this.handleError(h,r)}}if(0!==t.iterator){for(var a,c=t.iterator;a=r.nodes[r.indexes[c]];)if(r.indexes[c]+=1,!a[an])return a[an]=!0,void e.push(xn(a));t.iterator=0,delete r.indexes[c]}for(var l=t.events;t.eventIndex<l.length;){var u=l[t.eventIndex];if(t.eventIndex+=1,0===u)return void(r.nodes&&r.nodes.length&&(r[an]=!0,t.iterator=r.getIterator()));if(this.listeners[u])return void(t.visitors=this.listeners[u])}e.pop()}else e.pop()},t.walkSync=function(e){var t=this;e[an]=!0;for(var r,n=B(wn(e));!(r=n()).done;){var i=r.value;if(0===i)e.nodes&&e.each(function(e){e[an]||t.walkSync(e)});else{var o=this.listeners[i];if(o&&this.visitSync(o,e.toProxy()))return}}},t.warnings=function(){return this.sync().warnings()},k(e,[{key:"content",get:function(){return this.stringify().content}},{key:"css",get:function(){return this.stringify().css}},{key:"map",get:function(){return this.stringify().map}},{key:"messages",get:function(){return this.sync().messages}},{key:"opts",get:function(){return this.result.opts}},{key:"processor",get:function(){return this.result.processor}},{key:"root",get:function(){return this.sync().root}},{key:Symbol.toStringTag,get:function(){return"LazyResult"}}]),e}();Sn.registerPostcss=function(e){_n=e};var Cn=Sn;Sn.default=Sn,mn.registerLazyResult(Sn),dn.registerLazyResult(Sn);var In=Ft,En=Ze,An=sn,Mn=lr,Nn=function(){function e(e,t,r){var n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;var i=En;this.result=new Mn(this._processor,n,this._opts),this.result.css=t;var o=this;Object.defineProperty(this.result,"root",{get:function(){return o.root}});var s=new In(i,n,this._opts,t);if(s.isMap()){var a=s.generate(),c=a[0],l=a[1];c&&(this.result.css=c),l&&(this.result.map=l)}else s.clearAnnotation(),this.result.css=s.css}var t=e.prototype;return t.async=function(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)},t.catch=function(e){return this.async().catch(e)},t.finally=function(e){return this.async().then(e,e)},t.sync=function(){if(this.error)throw this.error;return this.result},t.then=function(e,t){return this.async().then(e,t)},t.toString=function(){return this._css},t.warnings=function(){return[]},k(e,[{key:"content",get:function(){return this.result.css}},{key:"css",get:function(){return this.result.css}},{key:"map",get:function(){return this.result.map}},{key:"messages",get:function(){return[]}},{key:"opts",get:function(){return this.result.opts}},{key:"processor",get:function(){return this.result.processor}},{key:"root",get:function(){if(this._root)return this._root;var e,t=An;try{e=t(this._css,this._opts)}catch(vu){this.error=vu}if(this.error)throw this.error;return this._root=e,e}},{key:Symbol.toStringTag,get:function(){return"NoWorkResult"}}]),e}(),Pn=Nn;Nn.default=Nn;var Bn=Pn,Tn=Cn,On=ir,Rn=Fr,Ln=function(){function e(e){void 0===e&&(e=[]),this.version="8.4.38",this.plugins=this.normalize(e)}var t=e.prototype;return t.normalize=function(e){for(var t,r=[],n=B(e);!(t=n()).done;){var i=t.value;if(!0===i.postcss?i=i():i.postcss&&(i=i.postcss),"object"===(void 0===i?"undefined":M(i))&&Array.isArray(i.plugins))r=r.concat(i.plugins);else if("object"===(void 0===i?"undefined":M(i))&&i.postcssPlugin)r.push(i);else if("function"==typeof i)r.push(i);else if("object"!==(void 0===i?"undefined":M(i))||!i.parse&&!i.stringify)throw new Error(i+" is not a PostCSS plugin")}return r},t.process=function(e,t){return void 0===t&&(t={}),this.plugins.length||t.parser||t.stringifier||t.syntax?new Tn(this,e,t):new Bn(this,e,t)},t.use=function(e){return this.plugins=this.plugins.concat(this.normalize([e])),this},e}(),Un=Ln;Ln.default=Ln,Rn.registerProcessor(Ln),On.registerProcessor(Ln);var jn=ot,Dn=ft,Fn=qt,zn=Rr,qn=Mt,Wn=Fr,$n=Vr;function Gn(e,t){if(Array.isArray(e))return e.map(function(e){return Gn(e)});var r=e.inputs,n=E(e,["inputs"]);if(r){t=[];for(var i,o=B(r);!(i=o()).done;){var s=_({},i.value,{__proto__:qn.prototype});s.map&&(s.map=_({},s.map,{__proto__:Dn.prototype})),t.push(s)}}if(n.nodes&&(n.nodes=e.nodes.map(function(e){return Gn(e,t)})),n.source){var a=n.source,c=a.inputId,l=E(a,["inputId"]);n.source=l,null!=c&&(n.source.input=t[c])}if("root"===n.type)return new Wn(n);if("decl"===n.type)return new jn(n);if("rule"===n.type)return new $n(n);if("comment"===n.type)return new Fn(n);if("atrule"===n.type)return new zn(n);throw new Error("Unknown node type: "+e.type)}var Vn=Gn;Gn.default=Gn;var Hn=qe,Kn=ot,Zn=Cn,Yn=er,Jn=Un,Xn=Ze,Qn=Vn,ei=ir,ti=sr,ri=qt,ni=Rr,ii=lr,oi=Mt,si=sn,ai=qr,ci=Vr,li=Fr,ui=nt;function hi(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return 1===t.length&&Array.isArray(t[0])&&(t=t[0]),new Jn(t)}hi.plugin=function(e,t){var r,n=!1;function i(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": ้้ข postcss.plugin ่ขซๅผ็จ. ่ฟ็งปๆๅ:\nhttps://www.w3ctech.com/topic/2226"));var s=t.apply(void 0,[].concat(i));return s.postcssPlugin=e,s.postcssVersion=(new Jn).version,s}return Object.defineProperty(i,"postcss",{get:function(){return r||(r=i()),r}}),i.process=function(e,t,r){return hi([i(r)]).process(e,t)},i},hi.stringify=Xn,hi.parse=si,hi.fromJSON=Qn,hi.list=ai,hi.comment=function(e){return new ri(e)},hi.atRule=function(e){return new ni(e)},hi.decl=function(e){return new Kn(e)},hi.rule=function(e){return new ci(e)},hi.root=function(e){return new li(e)},hi.document=function(e){return new ei(e)},hi.CssSyntaxError=Hn,hi.Declaration=Kn,hi.Container=Yn,hi.Processor=Jn,hi.Document=ei,hi.Comment=ri,hi.Warning=ti,hi.AtRule=ni,hi.Result=ii,hi.Input=oi,hi.Rule=ci,hi.Root=li,hi.Node=ui,Zn.registerPostcss(hi);var di=hi;hi.default=hi;var pi=Be(di);pi.stringify,pi.fromJSON,pi.plugin,pi.parse,pi.list,pi.document,pi.comment,pi.atRule,pi.rule,pi.decl,pi.root,pi.CssSyntaxError,pi.Declaration,pi.Container,pi.Processor,pi.Document,pi.Comment,pi.Warning,pi.AtRule,pi.Result,pi.Input,pi.Rule,pi.Root,pi.Node;var fi=Object.defineProperty,mi=function(e,t,r){return function(e,t,r){return t in e?fi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r}(e,"symbol"!==(void 0===t?"undefined":M(t))?t+"":t,r)};function gi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function yi(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return I(this,e)?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var vi={exports:{}},bi=String,wi=function(){return{isColorSupported:!1,reset:bi,bold:bi,dim:bi,italic:bi,underline:bi,inverse:bi,hidden:bi,strikethrough:bi,black:bi,red:bi,green:bi,yellow:bi,blue:bi,magenta:bi,cyan:bi,white:bi,gray:bi,bgBlack:bi,bgRed:bi,bgGreen:bi,bgYellow:bi,bgBlue:bi,bgMagenta:bi,bgCyan:bi,bgWhite:bi}};vi.exports=wi(),vi.exports.createColors=wi;var xi=vi.exports,ki=yi(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}))),_i=xi,Si=ki,Ci=function(e){function t(r,n,i,o,s,a){var c;return(c=e.call(this,r)||this).name="CssSyntaxError",c.reason=r,s&&(c.file=s),o&&(c.source=o),a&&(c.plugin=a),void 0!==n&&void 0!==i&&("number"==typeof n?(c.line=n,c.column=i):(c.line=n.line,c.column=n.column,c.endLine=i.line,c.endColumn=i.column)),c.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(c,t),c}C(t,e);var r=t.prototype;return r.setMessage=function(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason},r.showSourceCode=function(e){var t=this;if(!this.source)return"";var r=this.source;null==e&&(e=_i.isColorSupported),Si&&e&&(r=Si(r));var n,i,o=r.split(/\r?\n/),s=Math.max(this.line-3,0),a=Math.min(this.line+2,o.length),c=String(a).length;if(e){var l=_i.createColors(!0),u=l.bold,h=l.gray,d=l.red;n=function(e){return u(d(e))},i=function(e){return h(e)}}else n=i=function(e){return e};return o.slice(s,a).map(function(e,r){var o=s+1+r,a=" "+(" "+o).slice(-c)+" | ";if(o===t.line){var l=i(a.replace(/\d/g," "))+e.slice(0,t.column-1).replace(/[^\t]/g," ");return n(">")+i(a)+e+"\n "+l+n("^")}return" "+i(a)+e}).join("\n")},r.toString=function(){var e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e},t}(N(Error)),Ii=Ci;Ci.default=Ci;var Ei={};Ei.isClean=Symbol("isClean"),Ei.my=Symbol("my");var Ai={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};var Mi=function(){function e(e){this.builder=e}var t=e.prototype;return t.atrule=function(e,t){var r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{var i=(e.raws.between||"")+(t?";":"");this.builder(r+n+i,e)}},t.beforeAfter=function(e,t){var r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");for(var n=e.parent,i=0;n&&"root"!==n.type;)i+=1,n=n.parent;if(r.includes("\n")){var o=this.raw(e,null,"indent");if(o.length)for(var s=0;s<i;s++)r+=o}return r},t.block=function(e,t){var r,n=this.raw(e,"between","beforeOpen");this.builder(t+n+"{",e,"start"),e.nodes&&e.nodes.length?(this.body(e),r=this.raw(e,"after")):r=this.raw(e,"after","emptyBody"),r&&this.builder(r),this.builder("}",e,"end")},t.body=function(e){for(var t=e.nodes.length-1;t>0&&"comment"===e.nodes[t].type;)t-=1;for(var r=this.raw(e,"semicolon"),n=0;n<e.nodes.length;n++){var i=e.nodes[n],o=this.raw(i,"before");o&&this.builder(o),this.stringify(i,t!==n||r)}},t.comment=function(e){var t=this.raw(e,"left","commentLeft"),r=this.raw(e,"right","commentRight");this.builder("/*"+t+e.text+r+"*/",e)},t.decl=function(e,t){var r=this.raw(e,"between","colon"),n=e.prop+r+this.rawValue(e,"value");e.important&&(n+=e.raws.important||" !important"),t&&(n+=";"),this.builder(n,e)},t.document=function(e){this.body(e)},t.raw=function(e,t,r){var n;if(r||(r=t),t&&void 0!==(n=e.raws[t]))return n;var i=e.parent;if("before"===r){if(!i||"root"===i.type&&i.first===e)return"";if(i&&"document"===i.type)return""}if(!i)return Ai[r];var o=e.root();if(o.rawCache||(o.rawCache={}),void 0!==o.rawCache[r])return o.rawCache[r];if("before"===r||"after"===r)return this.beforeAfter(e,r);var s,a="raw"+((s=r)[0].toUpperCase()+s.slice(1));return this[a]?n=this[a](o,e):o.walk(function(e){if(void 0!==(n=e.raws[t]))return!1}),void 0===n&&(n=Ai[r]),o.rawCache[r]=n,n},t.rawBeforeClose=function(e){var t;return e.walk(function(e){if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return(t=e.raws.after).includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t},t.rawBeforeComment=function(e,t){var r;return e.walkComments(function(e){if(void 0!==e.raws.before)return(r=e.raws.before).includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r},t.rawBeforeDecl=function(e,t){var r;return e.walkDecls(function(e){if(void 0!==e.raws.before)return(r=e.raws.before).includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r},t.rawBeforeOpen=function(e){var t;return e.walk(function(e){if("decl"!==e.type&&void 0!==(t=e.raws.between))return!1}),t},t.rawBeforeRule=function(e){var t;return e.walk(function(r){if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return(t=r.raws.before).includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t},t.rawColon=function(e){var t;return e.walkDecls(function(e){if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t},t.rawEmptyBody=function(e){var t;return e.walk(function(e){if(e.nodes&&0===e.nodes.length&&void 0!==(t=e.raws.after))return!1}),t},t.rawIndent=function(e){return e.raws.indent?e.raws.indent:(e.walk(function(r){var n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){var i=r.raws.before.split("\n");return t=(t=i[i.length-1]).replace(/\S/g,""),!1}}),t);var t},t.rawSemicolon=function(e){var t;return e.walk(function(e){if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&void 0!==(t=e.raws.semicolon))return!1}),t},t.rawValue=function(e,t){var r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r},t.root=function(e){this.body(e),e.raws.after&&this.builder(e.raws.after)},t.rule=function(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")},t.stringify=function(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)},e}(),Ni=Mi;Mi.default=Mi;var Pi=Ni;function Bi(e,t){new Pi(t).stringify(e)}var Ti=Bi;Bi.default=Bi;var Oi=Ei.isClean,Ri=Ei.my,Li=Ii,Ui=Ni,ji=Ti;function Di(e,t){var r=new e.constructor;for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&"proxyCache"!==n){var i=e[n],o=void 0===i?"undefined":M(i);"parent"===n&&"object"===o?t&&(r[n]=t):"source"===n?r[n]=i:Array.isArray(i)?r[n]=i.map(function(e){return Di(e,r)}):("object"===o&&null!==i&&(i=Di(i)),r[n]=i)}return r}var Fi=function(){function e(e){for(var t in void 0===e&&(e={}),this.raws={},this[Oi]=!1,this[Ri]=!0,e)if("nodes"===t){this.nodes=[];for(var r,n=B(e[t]);!(r=n()).done;){var i=r.value;"function"==typeof i.clone?this.append(i.clone()):this.append(i)}}else this[t]=e[t]}var t=e.prototype;return t.addToError=function(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){var t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,"$&"+t.input.from+":"+t.start.line+":"+t.start.column+"$&")}return e},t.after=function(e){return this.parent.insertAfter(this,e),this},t.assign=function(e){for(var t in void 0===e&&(e={}),e)this[t]=e[t];return this},t.before=function(e){return this.parent.insertBefore(this,e),this},t.cleanRaws=function(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between},t.clone=function(e){void 0===e&&(e={});var t=Di(this);for(var r in e)t[r]=e[r];return t},t.cloneAfter=function(e){void 0===e&&(e={});var t=this.clone(e);return this.parent.insertAfter(this,t),t},t.cloneBefore=function(e){void 0===e&&(e={});var t=this.clone(e);return this.parent.insertBefore(this,t),t},t.error=function(e,t){if(void 0===t&&(t={}),this.source){var r=this.rangeBy(t),n=r.end,i=r.start;return this.source.input.error(e,{column:i.column,line:i.line},{column:n.column,line:n.line},t)}return new Li(e)},t.getProxyProcessor=function(){return{get:function(e,t){return"proxyOf"===t?e:"root"===t?function(){return e.root().toProxy()}:e[t]},set:function(e,t,r){return e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0}}},t.markDirty=function(){if(this[Oi]){this[Oi]=!1;for(var e=this;e=e.parent;)e[Oi]=!1}},t.next=function(){if(this.parent){var e=this.parent.index(this);return this.parent.nodes[e+1]}},t.positionBy=function(e,t){var r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){var n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r},t.positionInside=function(e,t){for(var r=t||this.toString(),n=this.source.start.column,i=this.source.start.line,o=0;o<e;o++)"\n"===r[o]?(n=1,i+=1):n+=1;return{column:n,line:i}},t.prev=function(){if(this.parent){var e=this.parent.index(this);return this.parent.nodes[e-1]}},t.rangeBy=function(e){var t={column:this.source.start.column,line:this.source.start.line},r=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){var n=this.toString(),i=n.indexOf(e.word);-1!==i&&(t=this.positionInside(i,n),r=this.positionInside(i+e.word.length,n))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?r={column:e.end.column,line:e.end.line}:"number"==typeof e.endIndex?r=this.positionInside(e.endIndex):e.index&&(r=this.positionInside(e.index+1));return(r.line<t.line||r.line===t.line&&r.column<=t.column)&&(r={column:t.column+1,line:t.line}),{end:r,start:t}},t.raw=function(e,t){return(new Ui).raw(this,e,t)},t.remove=function(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this},t.replaceWith=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];if(this.parent){for(var n,i=this,o=!1,s=B(t);!(n=s()).done;){var a=n.value;a===this?o=!0:o?(this.parent.insertAfter(i,a),i=a):this.parent.insertBefore(i,a)}o||this.remove()}return this},t.root=function(){for(var e=this;e.parent&&"document"!==e.parent.type;)e=e.parent;return e},t.toJSON=function(e,t){var r={},n=null==t;t=t||new Map;var i=0;for(var o in this)if(Object.prototype.hasOwnProperty.call(this,o)&&"parent"!==o&&"proxyCache"!==o){var s=this[o];if(Array.isArray(s))r[o]=s.map(function(e){return"object"===(void 0===e?"undefined":M(e))&&e.toJSON?e.toJSON(null,t):e});else if("object"===(void 0===s?"undefined":M(s))&&s.toJSON)r[o]=s.toJSON(null,t);else if("source"===o){var a=t.get(s.input);null==a&&(a=i,t.set(s.input,i),i++),r[o]={end:s.end,inputId:a,start:s.start}}else r[o]=s}return n&&(r.inputs=[].concat(t.keys()).map(function(e){return e.toJSON()})),r},t.toProxy=function(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache},t.toString=function(e){void 0===e&&(e=ji),e.stringify&&(e=e.stringify);var t="";return e(this,function(e){t+=e}),t},t.warn=function(e,t,r){var n={node:this};for(var i in r)n[i]=r[i];return e.warn(t,n)},k(e,[{key:"proxyOf",get:function(){return this}}]),e}(),zi=Fi;Fi.default=Fi;var qi=function(e){function t(t){var r;return t&&void 0!==t.value&&"string"!=typeof t.value&&(t=_({},t,{value:String(t.value)})),(r=e.call(this,t)||this).type="decl",r}return C(t,e),k(t,[{key:"variable",get:function(){return this.prop.startsWith("--")||"$"===this.prop[0]}}]),t}(zi),Wi=qi;qi.default=qi;var $i=function(e){void 0===e&&(e=21);for(var t="",r=e;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t},Gi=ki.SourceMapConsumer,Vi=ki.SourceMapGenerator,Hi=ki.existsSync,Ki=ki.readFileSync,Zi=ki.dirname,Yi=ki.join;var Ji=function(){function e(e,t){if(!1!==t.map){this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");var r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=Zi(this.mapFile)),n&&(this.text=n)}}var t=e.prototype;return t.consumer=function(){return this.consumerCache||(this.consumerCache=new Gi(this.text)),this.consumerCache},t.decodeInline=function(e){var t;if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),g?g.from(t,"base64").toString():window.atob(t);var r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)},t.getAnnotationURL=function(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()},t.isMap=function(e){return"object"===(void 0===e?"undefined":M(e))&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))},t.loadAnnotation=function(e){var t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(t){var r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}},t.loadFile=function(e){if(this.root=Zi(e),Hi(e))return this.mapFile=e,Ki(e,"utf-8").toString().trim()},t.loadMap=function(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(I(t,Gi))return Vi.fromSourceMap(t).toString();if(I(t,Vi))return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}var r=t(e);if(r){var n=this.loadFile(r);if(!n)throw new Error("Unable to load previous source map: "+r.toString());return n}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){var i=this.annotation;return e&&(i=Yi(Zi(e),i)),this.loadFile(i)}}},t.startWith=function(e,t){return!!e&&e.substr(0,t.length)===t},t.withContent=function(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)},e}(),Xi=Ji;Ji.default=Ji;var Qi=ki.SourceMapConsumer,eo=ki.SourceMapGenerator,to=ki.fileURLToPath,ro=ki.pathToFileURL,no=ki.isAbsolute,io=ki.resolve,oo=$i,so=ki,ao=Ii,co=Xi,lo=Symbol("fromOffsetCache"),uo=Boolean(Qi&&eo),ho=Boolean(io&&no),po=function(){function e(e,t){if(void 0===t&&(t={}),null==e||"object"===(void 0===e?"undefined":M(e))&&!e.toString)throw new Error("PostCSS received "+e+" instead of CSS string");if(this.css=e.toString(),"\ufeff"===this.css[0]||"๏ฟพ"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!ho||/^\w+:\/\//.test(t.from)||no(t.from)?this.file=t.from:this.file=io(t.from)),ho&&uo){var r=new co(this.css,t);if(r.text){this.map=r;var n=r.consumer().file;!this.file&&n&&(this.file=this.mapResolve(n))}}this.file||(this.id="<input css "+oo(6)+">"),this.map&&(this.map.file=this.from)}var t=e.prototype;return t.error=function(e,t,r,n){var i,o,s;if(void 0===n&&(n={}),t&&"object"===(void 0===t?"undefined":M(t))){var a=t,c=r;if("number"==typeof a.offset){var l=this.fromOffset(a.offset);t=l.line,r=l.col}else t=a.line,r=a.column;if("number"==typeof c.offset){var u=this.fromOffset(c.offset);o=u.line,s=u.col}else o=c.line,s=c.column}else if(!r){var h=this.fromOffset(t);t=h.line,r=h.col}var d=this.origin(t,r,o,s);return(i=d?new ao(e,void 0===d.endLine?d.line:{column:d.column,line:d.line},void 0===d.endLine?d.column:{column:d.endColumn,line:d.endLine},d.source,d.file,n.plugin):new ao(e,void 0===o?t:{column:r,line:t},void 0===o?r:{column:s,line:o},this.css,this.file,n.plugin)).input={column:r,endColumn:s,endLine:o,line:t,source:this.css},this.file&&(ro&&(i.input.url=ro(this.file).toString()),i.input.file=this.file),i},t.fromOffset=function(e){var t;if(this[lo])t=this[lo];else{var r=this.css.split("\n");t=new Array(r.length);for(var n=0,i=0,o=r.length;i<o;i++)t[i]=n,n+=r[i].length+1;this[lo]=t}var s=0;if(e>=t[t.length-1])s=t.length-1;else for(var a,c=t.length-2;s<c;)if(e<t[a=s+(c-s>>1)])c=a-1;else{if(!(e>=t[a+1])){s=a;break}s=a+1}return{col:e-t[s]+1,line:s+1}},t.mapResolve=function(e){return/^\w+:\/\//.test(e)?e:io(this.map.consumer().sourceRoot||this.map.root||".",e)},t.origin=function(e,t,r,n){if(!this.map)return!1;var i,o,s=this.map.consumer(),a=s.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(i=s.originalPositionFor({column:n,line:r})),o=no(a.source)?ro(a.source):new URL(a.source,this.map.consumer().sourceRoot||ro(this.map.mapFile));var c={column:a.column,endColumn:i&&i.column,endLine:i&&i.line,line:a.line,url:o.toString()};if("file:"===o.protocol){if(!to)throw new Error("file: protocol is not available in this PostCSS build");c.file=to(o)}var l=s.sourceContentFor(a.source);return l&&(c.source=l),c},t.toJSON=function(){for(var e={},t=0,r=["hasBOM","css","file","id"];t<r.length;t++){var n=r[t];null!=this[n]&&(e[n]=this[n])}return this.map&&(e.map=_({},this.map),e.map.consumerCache&&(e.map.consumerCache=void 0)),e},k(e,[{key:"from",get:function(){return this.file||this.id}}]),e}(),fo=po;po.default=po,so&&so.registerInput&&so.registerInput(po);var mo=ki.SourceMapConsumer,go=ki.SourceMapGenerator,yo=ki.dirname,vo=ki.relative,bo=ki.resolve,wo=ki.sep,xo=ki.pathToFileURL,ko=fo,_o=Boolean(mo&&go),So=Boolean(yo&&bo&&vo&&wo),Co=function(){function e(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}var t=e.prototype;return t.addAnnotation=function(){var e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";var t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"},t.applyPrevMaps=function(){for(var e,t=B(this.previous());!(e=t()).done;){var r=e.value,n=this.toUrl(this.path(r.file)),i=r.root||yo(r.file),o=void 0;!1===this.mapOpts.sourcesContent?(o=new mo(r.text)).sourcesContent&&(o.sourcesContent=null):o=r.consumer(),this.map.applySourceMap(o,n,this.toUrl(this.path(i)))}},t.clearAnnotation=function(){if(!1!==this.mapOpts.annotation)if(this.root)for(var e,t=this.root.nodes.length-1;t>=0;t--)"comment"===(e=this.root.nodes[t]).type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t);else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))},t.generate=function(){if(this.clearAnnotation(),So&&_o&&this.isMap())return this.generateMap();var e="";return this.stringify(this.root,function(t){e+=t}),[e]},t.generateMap=function(){if(this.root)this.generateString();else if(1===this.previous().length){var e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=go.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new go({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]},t.generateString=function(){var e=this;this.css="",this.map=new go({file:this.outputFile(),ignoreInvalidMapping:!0});var t,r,n=1,i=1,o="<no source>",s={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,function(a,c,l){if(e.css+=a,c&&"end"!==l&&(s.generated.line=n,s.generated.column=i-1,c.source&&c.source.start?(s.source=e.sourcePath(c),s.original.line=c.source.start.line,s.original.column=c.source.start.column-1,e.map.addMapping(s)):(s.source=o,s.original.line=1,s.original.column=0,e.map.addMapping(s))),(t=a.match(/\n/g))?(n+=t.length,r=a.lastIndexOf("\n"),i=a.length-r):i+=a.length,c&&"start"!==l){var u=c.parent||{raws:{}};("decl"===c.type||"atrule"===c.type&&!c.nodes)&&c===u.last&&!u.raws.semicolon||(c.source&&c.source.end?(s.source=e.sourcePath(c),s.original.line=c.source.end.line,s.original.column=c.source.end.column-1,s.generated.line=n,s.generated.column=i-2,e.map.addMapping(s)):(s.source=o,s.original.line=1,s.original.column=0,s.generated.line=n,s.generated.column=i-1,e.map.addMapping(s)))}})},t.isAnnotation=function(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(function(e){return e.annotation}))},t.isInline=function(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;var e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(function(e){return e.inline}))},t.isMap=function(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0},t.isSourcesContent=function(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(function(e){return e.withContent()})},t.outputFile=function(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"},t.path=function(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;var t=this.memoizedPaths.get(e);if(t)return t;var r=this.opts.to?yo(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=yo(bo(r,this.mapOpts.annotation)));var n=vo(r,e);return this.memoizedPaths.set(e,n),n},t.previous=function(){var e=this;if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(function(t){if(t.source&&t.source.input.map){var r=t.source.input.map;e.previousMaps.includes(r)||e.previousMaps.push(r)}});else{var t=new ko(this.originalCSS,this.opts);t.map&&this.previousMaps.push(t.map)}return this.previousMaps},t.setSourcesContent=function(){var e=this,t={};if(this.root)this.root.walk(function(r){if(r.source){var n=r.source.input.from;if(n&&!t[n]){t[n]=!0;var i=e.usesFileUrls?e.toFileUrl(n):e.toUrl(e.path(n));e.map.setSourceContent(i,r.source.input.css)}}});else if(this.css){var r=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(r,this.css)}},t.sourcePath=function(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))},t.toBase64=function(e){return g?g.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))},t.toFileUrl=function(e){var t=this.memoizedFileURLs.get(e);if(t)return t;if(xo){var r=xo(e).toString();return this.memoizedFileURLs.set(e,r),r}throw new Error("`map.absolute` option is not available in this PostCSS build")},t.toUrl=function(e){var t=this.memoizedURLs.get(e);if(t)return t;"\\"===wo&&(e=e.replace(/\\/g,"/"));var r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r},e}(),Io=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="comment",r}return C(t,e),t}(zi),Eo=Io;Io.default=Io;var Ao,Mo,No,Po,Bo=Ei.isClean,To=Ei.my,Oo=Wi,Ro=Eo;function Lo(e){return e.map(function(e){return e.nodes&&(e.nodes=Lo(e.nodes)),delete e.source,e})}function Uo(e){if(e[Bo]=!1,e.proxyOf.nodes)for(var t,r=B(e.proxyOf.nodes);!(t=r()).done;){Uo(t.value)}}var jo=function(e){function t(){return e.apply(this,arguments)||this}C(t,e);var r=t.prototype;return r.append=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n,i=B(t);!(n=i()).done;)for(var o,s=n.value,a=B(this.normalize(s,this.last));!(o=a()).done;){var c=o.value;this.proxyOf.nodes.push(c)}return this.markDirty(),this},r.cleanRaws=function(t){if(e.prototype.cleanRaws.call(this,t),this.nodes)for(var r,n=B(this.nodes);!(r=n()).done;){r.value.cleanRaws(t)}},r.each=function(e){if(this.proxyOf.nodes){for(var t,r,n=this.getIterator();this.indexes[n]<this.proxyOf.nodes.length&&(t=this.indexes[n],!1!==(r=e(this.proxyOf.nodes[t],t)));)this.indexes[n]+=1;return delete this.indexes[n],r}},r.every=function(e){return this.nodes.every(e)},r.getIterator=function(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;var e=this.lastEach;return this.indexes[e]=0,e},r.getProxyProcessor=function(){return{get:function(e,t){return"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?function(){for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];var o;return(o=e)[t].apply(o,[].concat(n.map(function(e){return"function"==typeof e?function(t,r){return e(t.toProxy(),r)}:e})))}:"every"===t||"some"===t?function(r){return e[t](function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return r.apply(void 0,[].concat([e.toProxy()],n))})}:"root"===t?function(){return e.root().toProxy()}:"nodes"===t?e.nodes.map(function(e){return e.toProxy()}):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t]},set:function(e,t,r){return e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0}}},r.index=function(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))},r.insertAfter=function(e,t){var r,n=this.index(e),i=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(var o,s=B(i);!(o=s()).done;){var a=o.value;this.proxyOf.nodes.splice(n+1,0,a)}for(var c in this.indexes)n<(r=this.indexes[c])&&(this.indexes[c]=r+i.length);return this.markDirty(),this},r.insertBefore=function(e,t){var r,n=this.index(e),i=0===n&&"prepend",o=this.normalize(t,this.proxyOf.nodes[n],i).reverse();n=this.index(e);for(var s,a=B(o);!(s=a()).done;){var c=s.value;this.proxyOf.nodes.splice(n,0,c)}for(var l in this.indexes)n<=(r=this.indexes[l])&&(this.indexes[l]=r+o.length);return this.markDirty(),this},r.normalize=function(e,r){var n=this;if("string"==typeof e)e=Lo(Ao(e).nodes);else if(void 0===e)e=[];else if(Array.isArray(e))for(var i,o=B(e=e.slice(0));!(i=o()).done;){var s=i.value;s.parent&&s.parent.removeChild(s,"ignore")}else if("root"===e.type&&"document"!==this.type)for(var a,c=B(e=e.nodes.slice(0));!(a=c()).done;){var l=a.value;l.parent&&l.parent.removeChild(l,"ignore")}else if(e.type)e=[e];else if(e.prop){if(void 0===e.value)throw new Error("Value field is missed in node creation");"string"!=typeof e.value&&(e.value=String(e.value)),e=[new Oo(e)]}else if(e.selector)e=[new Mo(e)];else if(e.name)e=[new No(e)];else{if(!e.text)throw new Error("Unknown node type in node creation");e=[new Ro(e)]}return e.map(function(e){return e[To]||t.rebuild(e),(e=e.proxyOf).parent&&e.parent.removeChild(e),e[Bo]&&Uo(e),void 0===e.raws.before&&r&&void 0!==r.raws.before&&(e.raws.before=r.raws.before.replace(/\S/g,"")),e.parent=n.proxyOf,e})},r.prepend=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n,i=B(t=t.reverse());!(n=i()).done;){for(var o,s=n.value,a=this.normalize(s,this.first,"prepend").reverse(),c=B(a);!(o=c()).done;){var l=o.value;this.proxyOf.nodes.unshift(l)}for(var u in this.indexes)this.indexes[u]=this.indexes[u]+a.length}return this.markDirty(),this},r.push=function(e){return e.parent=this,this.proxyOf.nodes.push(e),this},r.removeAll=function(){for(var e,t=B(this.proxyOf.nodes);!(e=t()).done;){e.value.parent=void 0}return this.proxyOf.nodes=[],this.markDirty(),this},r.removeChild=function(e){var t;for(var r in e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1),this.indexes)(t=this.indexes[r])>=e&&(this.indexes[r]=t-1);return this.markDirty(),this},r.replaceValues=function(e,t,r){return r||(r=t,t={}),this.walkDecls(function(n){t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this},r.some=function(e){return this.nodes.some(e)},r.walk=function(e){return this.each(function(t,r){var n;try{n=e(t,r)}catch(i){throw t.addToError(i)}return!1!==n&&t.walk&&(n=t.walk(e)),n})},r.walkAtRules=function(e,t){return t?I(e,RegExp)?this.walk(function(r,n){if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk(function(r,n){if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk(function(e,r){if("atrule"===e.type)return t(e,r)}))},r.walkComments=function(e){return this.walk(function(t,r){if("comment"===t.type)return e(t,r)})},r.walkDecls=function(e,t){return t?I(e,RegExp)?this.walk(function(r,n){if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk(function(r,n){if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk(function(e,r){if("decl"===e.type)return t(e,r)}))},r.walkRules=function(e,t){return t?I(e,RegExp)?this.walk(function(r,n){if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk(function(r,n){if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk(function(e,r){if("rule"===e.type)return t(e,r)}))},k(t,[{key:"first",get:function(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}},{key:"last",get:function(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}}]),t}(zi);jo.registerParse=function(e){Ao=e},jo.registerRule=function(e){Mo=e},jo.registerAtRule=function(e){No=e},jo.registerRoot=function(e){Po=e};var Do=jo;jo.default=jo,jo.rebuild=function(e){"atrule"===e.type?Object.setPrototypeOf(e,No.prototype):"rule"===e.type?Object.setPrototypeOf(e,Mo.prototype):"decl"===e.type?Object.setPrototypeOf(e,Oo.prototype):"comment"===e.type?Object.setPrototypeOf(e,Ro.prototype):"root"===e.type&&Object.setPrototypeOf(e,Po.prototype),e[To]=!0,e.nodes&&e.nodes.forEach(function(e){jo.rebuild(e)})};var Fo,zo,qo=function(e){function t(t){var r;return(r=e.call(this,_({type:"document"},t))||this).nodes||(r.nodes=[]),r}return C(t,e),t.prototype.toResult=function(e){return void 0===e&&(e={}),new Fo(new zo,this,e).stringify()},t}(Do);qo.registerLazyResult=function(e){Fo=e},qo.registerProcessor=function(e){zo=e};var Wo=qo;qo.default=qo;var $o=function(){function e(e,t){if(void 0===t&&(t={}),this.type="warning",this.text=e,t.node&&t.node.source){var r=t.node.rangeBy(t);this.line=r.start.line,this.column=r.start.column,this.endLine=r.end.line,this.endColumn=r.end.column}for(var n in t)this[n]=t[n]}return e.prototype.toString=function(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text},e}(),Go=$o;$o.default=$o;var Vo=Go,Ho=function(){function e(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}var t=e.prototype;return t.toString=function(){return this.css},t.warn=function(e,t){void 0===t&&(t={}),t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);var r=new Vo(e,t);return this.messages.push(r),r},t.warnings=function(){return this.messages.filter(function(e){return"warning"===e.type})},k(e,[{key:"content",get:function(){return this.css}}]),e}(),Ko=Ho;Ho.default=Ho;var Zo="'".charCodeAt(0),Yo='"'.charCodeAt(0),Jo="\\".charCodeAt(0),Xo="/".charCodeAt(0),Qo="\n".charCodeAt(0),es=" ".charCodeAt(0),ts="\f".charCodeAt(0),rs="\t".charCodeAt(0),ns="\r".charCodeAt(0),is="[".charCodeAt(0),os="]".charCodeAt(0),ss="(".charCodeAt(0),as=")".charCodeAt(0),cs="{".charCodeAt(0),ls="}".charCodeAt(0),us=";".charCodeAt(0),hs="*".charCodeAt(0),ds=":".charCodeAt(0),ps="@".charCodeAt(0),fs=/[\t\n\f\r "#'()/;[\\\]{}]/g,ms=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,gs=/.[\r\n"'(/\\]/,ys=/[\da-f]/i,vs=Do,bs=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="atrule",r}C(t,e);var r=t.prototype;return r.append=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i;return this.proxyOf.nodes||(this.nodes=[]),(i=e.prototype.append).call.apply(i,[].concat([this],r))},r.prepend=function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var i;return this.proxyOf.nodes||(this.nodes=[]),(i=e.prototype.prepend).call.apply(i,[].concat([this],r))},t}(vs),ws=bs;bs.default=bs,vs.registerAtRule(bs);var xs,ks,_s=Do,Ss=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="root",r.nodes||(r.nodes=[]),r}C(t,e);var r=t.prototype;return r.normalize=function(t,r,n){var i=e.prototype.normalize.call(this,t);if(r)if("prepend"===n)this.nodes.length>1?r.raws.before=this.nodes[1].raws.before:delete r.raws.before;else if(this.first!==r)for(var o,s=B(i);!(o=s()).done;){o.value.raws.before=r.raws.before}return i},r.removeChild=function(t,r){var n=this.index(t);return!r&&0===n&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[n].raws.before),e.prototype.removeChild.call(this,t)},r.toResult=function(e){return void 0===e&&(e={}),new xs(new ks,this,e).stringify()},t}(_s);Ss.registerLazyResult=function(e){xs=e},Ss.registerProcessor=function(e){ks=e};var Cs=Ss;Ss.default=Ss,_s.registerRoot(Ss);var Is={comma:function(e){return Is.split(e,[","],!0)},space:function(e){return Is.split(e,[" ","\n","\t"])},split:function(e,t,r){for(var n,i=[],o="",s=!1,a=0,c=!1,l="",u=!1,h=B(e);!(n=h()).done;){var d=n.value;u?u=!1:"\\"===d?u=!0:c?d===l&&(c=!1):'"'===d||"'"===d?(c=!0,l=d):"("===d?a+=1:")"===d?a>0&&(a-=1):0===a&&t.includes(d)&&(s=!0),s?(""!==o&&i.push(o.trim()),o="",s=!1):o+=d}return(r||""!==o)&&i.push(o.trim()),i}},Es=Is;Is.default=Is;var As=Do,Ms=Es,Ns=function(e){function t(t){var r;return(r=e.call(this,t)||this).type="rule",r.nodes||(r.nodes=[]),r}return C(t,e),k(t,[{key:"selectors",get:function(){return Ms.comma(this.selector)},set:function(e){var t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}}]),t}(As),Ps=Ns;Ns.default=Ns,As.registerRule(Ns);var Bs=Wi,Ts=function(e,t){void 0===t&&(t={});var r,n,i,o,s,a,c,l,u,h,d=e.css.valueOf(),p=t.ignoreErrors,f=d.length,m=0,g=[],y=[];function v(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(!(m>=f)){var t=!!e&&e.ignoreUnclosed;switch(r=d.charCodeAt(m)){case Qo:case es:case rs:case ns:case ts:n=m;do{n+=1,r=d.charCodeAt(n)}while(r===es||r===Qo||r===rs||r===ns||r===ts);h=["space",d.slice(m,n)],m=n-1;break;case is:case os:case cs:case ls:case ds:case us:case as:var b=String.fromCharCode(r);h=[b,b,m];break;case ss:if(l=g.length?g.pop()[1]:"",u=d.charCodeAt(m+1),"url"===l&&u!==Zo&&u!==Yo&&u!==es&&u!==Qo&&u!==rs&&u!==ts&&u!==ns){n=m;do{if(a=!1,-1===(n=d.indexOf(")",n+1))){if(p||t){n=m;break}v("bracket")}for(c=n;d.charCodeAt(c-1)===Jo;)c-=1,a=!a}while(a);h=["brackets",d.slice(m,n+1),m,n],m=n}else n=d.indexOf(")",m+1),o=d.slice(m,n+1),-1===n||gs.test(o)?h=["(","(",m]:(h=["brackets",o,m,n],m=n);break;case Zo:case Yo:i=r===Zo?"'":'"',n=m;do{if(a=!1,-1===(n=d.indexOf(i,n+1))){if(p||t){n=m+1;break}v("string")}for(c=n;d.charCodeAt(c-1)===Jo;)c-=1,a=!a}while(a);h=["string",d.slice(m,n+1),m,n],m=n;break;case ps:fs.lastIndex=m+1,fs.test(d),n=0===fs.lastIndex?d.length-1:fs.lastIndex-2,h=["at-word",d.slice(m,n+1),m,n],m=n;break;case Jo:for(n=m,s=!0;d.charCodeAt(n+1)===Jo;)n+=1,s=!s;if(r=d.charCodeAt(n+1),s&&r!==Xo&&r!==es&&r!==Qo&&r!==rs&&r!==ns&&r!==ts&&(n+=1,ys.test(d.charAt(n)))){for(;ys.test(d.charAt(n+1));)n+=1;d.charCodeAt(n+1)===es&&(n+=1)}h=["word",d.slice(m,n+1),m,n],m=n;break;default:r===Xo&&d.charCodeAt(m+1)===hs?(0===(n=d.indexOf("*/",m+2)+1)&&(p||t?n=d.length:v("comment")),h=["comment",d.slice(m,n+1),m,n],m=n):(ms.lastIndex=m+1,ms.test(d),n=0===ms.lastIndex?d.length-1:ms.lastIndex-2,h=["word",d.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h}},position:function(){return m}}},Os=Eo,Rs=ws,Ls=Cs,Us=Ps,js={empty:!0,space:!0};var Ds=function(){function e(e){this.input=e,this.root=new Ls,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}var t=e.prototype;return t.atrule=function(e){var t,r,n,i=new Rs;i.name=e[1].slice(1),""===i.name&&this.unnamedAtrule(i,e),this.init(i,e[2]);for(var o=!1,s=!1,a=[],c=[];!this.tokenizer.endOfFile();){if("("===(t=(e=this.tokenizer.nextToken())[0])||"["===t?c.push("("===t?")":"]"):"{"===t&&c.length>0?c.push("}"):t===c[c.length-1]&&c.pop(),0===c.length){if(";"===t){i.source.end=this.getPosition(e[2]),i.source.end.offset++,this.semicolon=!0;break}if("{"===t){s=!0;break}if("}"===t){if(a.length>0){for(r=a[n=a.length-1];r&&"space"===r[0];)r=a[--n];r&&(i.source.end=this.getPosition(r[3]||r[2]),i.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){o=!0;break}}i.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(i.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(i,"params",a),o&&(e=a[a.length-1],i.source.end=this.getPosition(e[3]||e[2]),i.source.end.offset++,this.spaces=i.raws.between,i.raws.between="")):(i.raws.afterName="",i.params=""),s&&(i.nodes=[],this.current=i)},t.checkMissedSemicolon=function(e){var t=this.colon(e);if(!1!==t){for(var r,n=0,i=t-1;i>=0&&("space"===(r=e[i])[0]||2!==(n+=1));i--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}},t.colon=function(e){for(var t,r,n,i,o=0,s=B(e.entries());!(i=s()).done;){var a=i.value,c=a[0];if("("===(r=(t=a[1])[0])&&(o+=1),")"===r&&(o-=1),0===o&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return c}this.doubleColon(t)}n=t}return!1},t.comment=function(e){var t=new Os;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;var r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{var n=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=n[2],t.raws.left=n[1],t.raws.right=n[3]}},t.createTokenizer=function(){this.tokenizer=Ts(this.input)},t.decl=function(e,t){var r=new Bs;this.init(r,e[0][2]);var n,i=e[e.length-1];for(";"===i[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(i[3]||i[2]||function(e){for(var t=e.length-1;t>=0;t--){var r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){var o=e[0][0];if(":"===o||"space"===o||"comment"===o)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(":"===(n=e.shift())[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));for(var s,a=[];e.length&&("space"===(s=e[0][0])||"comment"===s);)a.push(e.shift());this.precheckMissedSemicolon(e);for(var c=e.length-1;c>=0;c--){if("!important"===(n=e[c])[1].toLowerCase()){r.important=!0;var l=this.stringFrom(e,c);" !important"!==(l=this.spacesFromEnd(e)+l)&&(r.raws.important=l);break}if("important"===n[1].toLowerCase()){for(var u=e.slice(0),h="",d=c;d>0;d--){var p=u[d][0];if(0===h.trim().indexOf("!")&&"space"!==p)break;h=u.pop()[1]+h}0===h.trim().indexOf("!")&&(r.important=!0,r.raws.important=h,e=u)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(function(e){return"space"!==e[0]&&"comment"!==e[0]})&&(r.raws.between+=a.map(function(e){return e[1]}).join(""),a=[]),this.raw(r,"value",a.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)},t.doubleColon=function(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})},t.emptyRule=function(e){var t=new Us;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t},t.end=function(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)},t.endFile=function(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())},t.freeSemicolon=function(e){if(this.spaces+=e[1],this.current.nodes){var t=this.current.nodes[this.current.nodes.length-1];t&&"rule"===t.type&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces="")}},t.getPosition=function(e){var t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}},t.init=function(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)},t.other=function(e){for(var t=!1,r=null,n=!1,i=null,o=[],s=e[1].startsWith("--"),a=[],c=e;c;){if(r=c[0],a.push(c),"("===r||"["===r)i||(i=c),o.push("("===r?")":"]");else if(s&&n&&"{"===r)i||(i=c),o.push("}");else if(0===o.length){if(";"===r){if(n)return void this.decl(a,s);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===o[o.length-1]&&(o.pop(),0===o.length&&(i=null));c=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),o.length>0&&this.unclosedBracket(i),t&&n){if(!s)for(;a.length&&("space"===(c=a[a.length-1][0])||"comment"===c);)this.tokenizer.back(a.pop());this.decl(a,s)}else this.unknownWord(a)},t.parse=function(){for(var e;!this.tokenizer.endOfFile();)switch((e=this.tokenizer.nextToken())[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()},t.precheckMissedSemicolon=function(){},t.raw=function(e,t,r,n){for(var i,o,s,a,c=r.length,l="",u=!0,h=0;h<c;h+=1)"space"!==(o=(i=r[h])[0])||h!==c-1||n?"comment"===o?(a=r[h-1]?r[h-1][0]:"empty",s=r[h+1]?r[h+1][0]:"empty",js[a]||js[s]||","===l.slice(-1)?u=!1:l+=i[1]):l+=i[1]:u=!1;if(!u){var d=r.reduce(function(e,t){return e+t[1]},"");e.raws[t]={raw:d,value:l}}e[t]=l},t.rule=function(e){e.pop();var t=new Us;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t},t.spacesAndCommentsFromEnd=function(e){for(var t,r="";e.length&&("space"===(t=e[e.length-1][0])||"comment"===t);)r=e.pop()[1]+r;return r},t.spacesAndCommentsFromStart=function(e){for(var t,r="";e.length&&("space"===(t=e[0][0])||"comment"===t);)r+=e.shift()[1];return r},t.spacesFromEnd=function(e){for(var t="";e.length&&"space"===e[e.length-1][0];)t=e.pop()[1]+t;return t},t.stringFrom=function(e,t){for(var r="",n=t;n<e.length;n++)r+=e[n][1];return e.splice(t,e.length-t),r},t.unclosedBlock=function(){var e=this.current.source.start;throw this.input.error("Unclosed block",e.line,e.column)},t.unclosedBracket=function(e){throw this.input.error("Unclosed bracket",{offset:e[2]},{offset:e[2]+1})},t.unexpectedClose=function(e){throw this.input.error("Unexpected }",{offset:e[2]},{offset:e[2]+1})},t.unknownWord=function(e){throw this.input.error("Unknown word",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})},t.unnamedAtrule=function(e,t){throw this.input.error("At-rule without name",{offset:t[2]},{offset:t[2]+t[1].length})},e}(),Fs=Do,zs=Ds,qs=fo;function Ws(e,t){var r=new qs(e,t),n=new zs(r);try{n.parse()}catch(i){throw i}return n.root}var $s=Ws;Ws.default=Ws,Fs.registerParse(Ws);var Gs=Ei.isClean,Vs=Ei.my,Hs=Co,Ks=Ti,Zs=Do,Ys=Wo,Js=Ko,Xs=$s,Qs=Cs,ea={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},ta={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},ra={Once:!0,postcssPlugin:!0,prepare:!0};function na(e){return"object"===(void 0===e?"undefined":M(e))&&"function"==typeof e.then}function ia(e){var t=!1,r=ea[e.type];return"decl"===e.type?t=e.prop.toLowerCase():"atrule"===e.type&&(t=e.name.toLowerCase()),t&&e.append?[r,r+"-"+t,0,r+"Exit",r+"Exit-"+t]:t?[r,r+"-"+t,r+"Exit",r+"Exit-"+t]:e.append?[r,0,r+"Exit"]:[r,r+"Exit"]}function oa(e){return{eventIndex:0,events:"document"===e.type?["Document",0,"DocumentExit"]:"root"===e.type?["Root",0,"RootExit"]:ia(e),iterator:0,node:e,visitorIndex:0,visitors:[]}}function sa(e){return e[Gs]=!1,e.nodes&&e.nodes.forEach(function(e){return sa(e)}),e}var aa={},ca=function(){function e(t,r,n){var i,o=this;if(this.stringified=!1,this.processed=!1,"object"!==(void 0===r?"undefined":M(r))||null===r||"root"!==r.type&&"document"!==r.type)if(I(r,e)||I(r,Js))i=sa(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{var s=Xs;n.syntax&&(s=n.syntax.parse),n.parser&&(s=n.parser),s.parse&&(s=s.parse);try{i=s(r,n)}catch(vu){this.processed=!0,this.error=vu}i&&!i[Vs]&&Zs.rebuild(i)}else i=sa(r);this.result=new Js(t,i,n),this.helpers=_({},aa,{postcss:aa,result:this.result}),this.plugins=this.processor.plugins.map(function(e){return"object"===(void 0===e?"undefined":M(e))&&e.prepare?_({},e,e.prepare(o.result)):e})}var t=e.prototype;return t.async=function(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)},t.catch=function(e){return this.async().catch(e)},t.finally=function(e){return this.async().then(e,e)},t.getAsyncError=function(){throw new Error("Use process(css).then(cb) to work with async plugins")},t.handleError=function(e,t){var r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion){0}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(n){console&&console.error&&console.error(n)}return e},t.prepareVisitors=function(){var e=this;this.listeners={};for(var t,r=function(t,r,n){e.listeners[r]||(e.listeners[r]=[]),e.listeners[r].push([t,n])},n=B(this.plugins);!(t=n()).done;){var i=t.value;if("object"===(void 0===i?"undefined":M(i)))for(var o in i){if(!ta[o]&&/^[A-Z]/.test(o))throw new Error("Unknown event "+o+" in "+i.postcssPlugin+". Try to update PostCSS ("+this.processor.version+" now).");if(!ra[o])if("object"===M(i[o]))for(var s in i[o])r(i,"*"===s?o:o+"-"+s.toLowerCase(),i[o][s]);else"function"==typeof i[o]&&r(i,o,i[o])}}this.hasListener=Object.keys(this.listeners).length>0},t.runAsync=function(){var e=this;return w(function(){var t,r,n,i,o,s,a,c,l,u,h,d;return T(this,function(p){switch(p.label){case 0:e.plugin=0,t=0,p.label=1;case 1:if(!(t<e.plugins.length))return[3,6];if(r=e.plugins[t],!na(n=e.runOnRoot(r)))return[3,5];p.label=2;case 2:return p.trys.push([2,4,,5]),[4,n];case 3:return p.sent(),[3,5];case 4:throw i=p.sent(),e.handleError(i);case 5:return t++,[3,1];case 6:if(e.prepareVisitors(),!e.hasListener)return[3,18];o=e.result.root,p.label=7;case 7:if(o[Gs])return[3,14];o[Gs]=!0,s=[oa(o)],p.label=8;case 8:if(!(s.length>0))return[3,13];if(!na(a=e.visitTick(s)))return[3,12];p.label=9;case 9:return p.trys.push([9,11,,12]),[4,a];case 10:return p.sent(),[3,12];case 11:throw c=p.sent(),l=s[s.length-1].node,e.handleError(c,l);case 12:return[3,8];case 13:return[3,7];case 14:if(!e.listeners.OnceExit)return[3,18];u=function(){var t,r,n,i,s;return T(this,function(a){switch(a.label){case 0:t=d.value,r=t[0],n=t[1],e.result.lastPlugin=r,a.label=1;case 1:return a.trys.push([1,6,,7]),"document"!==o.type?[3,3]:(i=o.nodes.map(function(t){return n(t,e.helpers)}),[4,Promise.all(i)]);case 2:return a.sent(),[3,5];case 3:return[4,n(o,e.helpers)];case 4:a.sent(),a.label=5;case 5:return[3,7];case 6:throw s=a.sent(),e.handleError(s);case 7:return[2]}})},h=B(e.listeners.OnceExit),p.label=15;case 15:return(d=h()).done?[3,18]:[5,O(u())];case 16:p.sent(),p.label=17;case 17:return[3,15];case 18:return e.processed=!0,[2,e.stringify()]}})})()},t.runOnRoot=function(e){var t=this;this.result.lastPlugin=e;try{if("object"===(void 0===e?"undefined":M(e))&&e.Once){if("document"===this.result.root.type){var r=this.result.root.nodes.map(function(r){return e.Once(r,t.helpers)});return na(r[0])?Promise.all(r):r}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(vu){throw this.handleError(vu)}},t.stringify=function(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();var e=this.result.opts,t=Ks;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);var r=new Hs(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result},t.sync=function(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(var e,t=B(this.plugins);!(e=t()).done;){var r=e.value;if(na(this.runOnRoot(r)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){for(var n=this.result.root;!n[Gs];)n[Gs]=!0,this.walkSync(n);if(this.listeners.OnceExit)if("document"===n.type)for(var i,o=B(n.nodes);!(i=o()).done;){var s=i.value;this.visitSync(this.listeners.OnceExit,s)}else this.visitSync(this.listeners.OnceExit,n)}return this.result},t.then=function(e,t){return this.async().then(e,t)},t.toString=function(){return this.css},t.visitSync=function(e,t){for(var r,n=B(e);!(r=n()).done;){var i=r.value,o=i[0],s=i[1];this.result.lastPlugin=o;var a=void 0;try{a=s(t,this.helpers)}catch(c){throw this.handleError(c,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(na(a))throw this.getAsyncError()}},t.visitTick=function(e){var t=e[e.length-1],r=t.node,n=t.visitors;if("root"===r.type||"document"===r.type||r.parent){if(n.length>0&&t.visitorIndex<n.length){var i=n[t.visitorIndex],o=i[0],s=i[1];t.visitorIndex+=1,t.visitorIndex===n.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=o;try{return s(r.toProxy(),this.helpers)}catch(h){throw this.handleError(h,r)}}if(0!==t.iterator){for(var a,c=t.iterator;a=r.nodes[r.indexes[c]];)if(r.indexes[c]+=1,!a[Gs])return a[Gs]=!0,void e.push(oa(a));t.iterator=0,delete r.indexes[c]}for(var l=t.events;t.eventIndex<l.length;){var u=l[t.eventIndex];if(t.eventIndex+=1,0===u)return void(r.nodes&&r.nodes.length&&(r[Gs]=!0,t.iterator=r.getIterator()));if(this.listeners[u])return void(t.visitors=this.listeners[u])}e.pop()}else e.pop()},t.walkSync=function(e){var t=this;e[Gs]=!0;for(var r,n=B(ia(e));!(r=n()).done;){var i=r.value;if(0===i)e.nodes&&e.each(function(e){e[Gs]||t.walkSync(e)});else{var o=this.listeners[i];if(o&&this.visitSync(o,e.toProxy()))return}}},t.warnings=function(){return this.sync().warnings()},k(e,[{key:"content",get:function(){return this.stringify().content}},{key:"css",get:function(){return this.stringify().css}},{key:"map",get:function(){return this.stringify().map}},{key:"messages",get:function(){return this.sync().messages}},{key:"opts",get:function(){return this.result.opts}},{key:"processor",get:function(){return this.result.processor}},{key:"root",get:function(){return this.sync().root}},{key:Symbol.toStringTag,get:function(){return"LazyResult"}}]),e}();ca.registerPostcss=function(e){aa=e};var la=ca;ca.default=ca,Qs.registerLazyResult(ca),Ys.registerLazyResult(ca);var ua=Co,ha=Ti,da=$s,pa=Ko,fa=function(){function e(e,t,r){var n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;var i=ha;this.result=new pa(this._processor,n,this._opts),this.result.css=t;var o=this;Object.defineProperty(this.result,"root",{get:function(){return o.root}});var s=new ua(i,n,this._opts,t);if(s.isMap()){var a=s.generate(),c=a[0],l=a[1];c&&(this.result.css=c),l&&(this.result.map=l)}else s.clearAnnotation(),this.result.css=s.css}var t=e.prototype;return t.async=function(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)},t.catch=function(e){return this.async().catch(e)},t.finally=function(e){return this.async().then(e,e)},t.sync=function(){if(this.error)throw this.error;return this.result},t.then=function(e,t){return this.async().then(e,t)},t.toString=function(){return this._css},t.warnings=function(){return[]},k(e,[{key:"content",get:function(){return this.result.css}},{key:"css",get:function(){return this.result.css}},{key:"map",get:function(){return this.result.map}},{key:"messages",get:function(){return[]}},{key:"opts",get:function(){return this.result.opts}},{key:"processor",get:function(){return this.result.processor}},{key:"root",get:function(){if(this._root)return this._root;var e,t=da;try{e=t(this._css,this._opts)}catch(vu){this.error=vu}if(this.error)throw this.error;return this._root=e,e}},{key:Symbol.toStringTag,get:function(){return"NoWorkResult"}}]),e}(),ma=fa;fa.default=fa;var ga=ma,ya=la,va=Wo,ba=Cs,wa=function(){function e(e){void 0===e&&(e=[]),this.version="8.4.38",this.plugins=this.normalize(e)}var t=e.prototype;return t.normalize=function(e){for(var t,r=[],n=B(e);!(t=n()).done;){var i=t.value;if(!0===i.postcss?i=i():i.postcss&&(i=i.postcss),"object"===(void 0===i?"undefined":M(i))&&Array.isArray(i.plugins))r=r.concat(i.plugins);else if("object"===(void 0===i?"undefined":M(i))&&i.postcssPlugin)r.push(i);else if("function"==typeof i)r.push(i);else if("object"!==(void 0===i?"undefined":M(i))||!i.parse&&!i.stringify)throw new Error(i+" is not a PostCSS plugin")}return r},t.process=function(e,t){return void 0===t&&(t={}),this.plugins.length||t.parser||t.stringifier||t.syntax?new ya(this,e,t):new ga(this,e,t)},t.use=function(e){return this.plugins=this.plugins.concat(this.normalize([e])),this},e}(),xa=wa;wa.default=wa,ba.registerProcessor(wa),va.registerProcessor(wa);var ka=Wi,_a=Xi,Sa=Eo,Ca=ws,Ia=fo,Ea=Cs,Aa=Ps;function Ma(e,t){if(Array.isArray(e))return e.map(function(e){return Ma(e)});var r=e.inputs,n=E(e,["inputs"]);if(r){t=[];for(var i,o=B(r);!(i=o()).done;){var s=_({},i.value,{__proto__:Ia.prototype});s.map&&(s.map=_({},s.map,{__proto__:_a.prototype})),t.push(s)}}if(n.nodes&&(n.nodes=e.nodes.map(function(e){return Ma(e,t)})),n.source){var a=n.source,c=a.inputId,l=E(a,["inputId"]);n.source=l,null!=c&&(n.source.input=t[c])}if("root"===n.type)return new Ea(n);if("decl"===n.type)return new ka(n);if("rule"===n.type)return new Aa(n);if("comment"===n.type)return new Sa(n);if("atrule"===n.type)return new Ca(n);throw new Error("Unknown node type: "+e.type)}var Na=Ma;Ma.default=Ma;var Pa=Ii,Ba=Wi,Ta=la,Oa=Do,Ra=xa,La=Ti,Ua=Na,ja=Wo,Da=Go,Fa=Eo,za=ws,qa=Ko,Wa=fo,$a=$s,Ga=Es,Va=Ps,Ha=Cs,Ka=zi;function Za(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return 1===t.length&&Array.isArray(t[0])&&(t=t[0]),new Ra(t)}Za.plugin=function(e,t){var r,n=!1;function i(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": ้้ข postcss.plugin ่ขซๅผ็จ. ่ฟ็งปๆๅ:\nhttps://www.w3ctech.com/topic/2226"));var s=t.apply(void 0,[].concat(i));return s.postcssPlugin=e,s.postcssVersion=(new Ra).version,s}return Object.defineProperty(i,"postcss",{get:function(){return r||(r=i()),r}}),i.process=function(e,t,r){return Za([i(r)]).process(e,t)},i},Za.stringify=La,Za.parse=$a,Za.fromJSON=Ua,Za.list=Ga,Za.comment=function(e){return new Fa(e)},Za.atRule=function(e){return new za(e)},Za.decl=function(e){return new Ba(e)},Za.rule=function(e){return new Va(e)},Za.root=function(e){return new Ha(e)},Za.document=function(e){return new ja(e)},Za.CssSyntaxError=Pa,Za.Declaration=Ba,Za.Container=Oa,Za.Processor=Ra,Za.Document=ja,Za.Comment=Fa,Za.Warning=Da,Za.AtRule=za,Za.Result=qa,Za.Input=Wa,Za.Rule=Va,Za.Root=Ha,Za.Node=Ka,Ta.registerPostcss(Za);var Ya=Za;Za.default=Za;var Ja=gi(Ya);Ja.stringify,Ja.fromJSON,Ja.plugin,Ja.parse,Ja.list,Ja.document,Ja.comment,Ja.atRule,Ja.rule,Ja.decl,Ja.root,Ja.CssSyntaxError,Ja.Declaration,Ja.Container,Ja.Processor,Ja.Document,Ja.Comment,Ja.Warning,Ja.AtRule,Ja.Result,Ja.Input,Ja.Rule,Ja.Root,Ja.Node;var Xa=function(){function e(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];mi(this,"parentElement",null),mi(this,"parentNode",null),mi(this,"ownerDocument"),mi(this,"firstChild",null),mi(this,"lastChild",null),mi(this,"previousSibling",null),mi(this,"nextSibling",null),mi(this,"ELEMENT_NODE",1),mi(this,"TEXT_NODE",3),mi(this,"nodeType"),mi(this,"nodeName"),mi(this,"RRNodeType")}var t=e.prototype;return t.contains=function(t){if(!I(t,e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1},t.appendChild=function(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")},t.insertBefore=function(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")},t.removeChild=function(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")},t.toString=function(){return"RRNode"},k(e,[{key:"childNodes",get:function(){for(var e=[],t=this.firstChild;t;)e.push(t),t=t.nextSibling;return e}}]),e}(),Qa={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},ec={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},tc={};function rc(e){if(tc[e])return tc[e];var t=globalThis[e],r=t.prototype,n=e in Qa?Qa[e]:void 0,i=Boolean(n&&n.every(function(e){var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),o=e in ec?ec[e]:void 0,s=Boolean(o&&o.every(function(e){var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(i&&s&&!globalThis.Zone)return tc[e]=t.prototype,t.prototype;try{var a=document.createElement("iframe");document.body.appendChild(a);var c=a.contentWindow;if(!c)return t.prototype;var l=c[e].prototype;return document.body.removeChild(a),l?tc[e]=l:r}catch(u){return r}}var nc={};function ic(e,t,r){var n,i=e+"."+String(r);if(nc[i])return nc[i].call(t);var o=rc(e),s=null==(n=Object.getOwnPropertyDescriptor(o,r))?void 0:n.get;return s?(nc[i]=s,s.call(t)):t[r]}var oc={};function sc(e,t,r){var n=e+"."+String(r);if(oc[n])return oc[n].bind(t);var i=rc(e)[r];return"function"!=typeof i?t[r]:(oc[n]=i,i.bind(t))}function ac(){return rc("MutationObserver").constructor}function cc(e,t,r){try{if(!(t in e))return function(){};var n=e[t],i=r(n);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=i,function(){e[t]=n}}catch(o){return function(){}}}var lc={childNodes:function(e){return ic("Node",e,"childNodes")},parentNode:function(e){return ic("Node",e,"parentNode")},parentElement:function(e){return ic("Node",e,"parentElement")},textContent:function(e){return ic("Node",e,"textContent")},contains:function(e,t){return sc("Node",e,"contains")(t)},getRootNode:function(e){return sc("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?ic("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?ic("Element",e,"shadowRoot"):null},querySelector:function(e,t){return ic("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return ic("Element",e,"querySelectorAll")(t)},mutationObserver:ac,patch:cc};function uc(e,t,r){void 0===r&&(r=document);var n={capture:!0,passive:!0};return r.addEventListener(e,t,n),function(){return r.removeEventListener(e,t,n)}}var hc="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.",dc={map:{},getId:function(){return console.error(hc),-1},getNode:function(){return console.error(hc),null},removeNodeFromMap:function(){console.error(hc)},has:function(){return console.error(hc),!1},reset:function(){console.error(hc)}};function pc(e,t,r){void 0===r&&(r={});var n=null,i=0;return function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];var c=Date.now();i||!1!==r.leading||(i=c);var l=t-(c-i),u=this;l<=0||l>t?(n&&(clearTimeout(n),n=null),i=c,e.apply(u,s)):n||!1===r.trailing||(n=setTimeout(function(){i=!1===r.leading?0:Date.now(),n=null,e.apply(u,s)},l))}}function fc(e,t,r,n,i){void 0===i&&(i=window);var o=i.Object.getOwnPropertyDescriptor(e,t);return i.Object.defineProperty(e,t,n?r:{set:function(e){var t=this;setTimeout(function(){r.set.call(t,e)},0),o&&o.set&&o.set.call(this,e)}}),function(){return fc(e,t,o||{},!0)}}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(dc=new Proxy(dc,{get:function(e,t,r){return"map"===t&&console.error(hc),Reflect.get(e,t,r)}}));var mc=Date.now;function gc(e){var t,r,n,i,o=e.document;return{left:o.scrollingElement?o.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:o.documentElement.scrollLeft||(null==o?void 0:o.body)&&(null==(t=lc.parentElement(o.body))?void 0:t.scrollLeft)||(null==(r=null==o?void 0:o.body)?void 0:r.scrollLeft)||0,top:o.scrollingElement?o.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==o?void 0:o.documentElement.scrollTop)||(null==o?void 0:o.body)&&(null==(n=lc.parentElement(o.body))?void 0:n.scrollTop)||(null==(i=null==o?void 0:o.body)?void 0:i.scrollTop)||0}}function yc(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function vc(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function bc(e){return e?e.nodeType===e.ELEMENT_NODE?e:lc.parentElement(e):null}function wc(e,t,r,n){if(!e)return!1;var i=bc(e);if(!i)return!1;try{if("string"==typeof t){if(i.classList.contains(t))return!0;if(n&&null!==i.closest("."+t))return!0}else if(Ee(i,t,n))return!0}catch(o){}if(r){if(i.matches(r))return!0;if(n&&null!==i.closest(r))return!0}return!1}function xc(e,t,r){return!("TITLE"!==e.tagName||!r.headTitleMutations)||-2===t.getId(e)}function kc(e,t){if(J(e))return!1;var r=t.getId(e);if(!t.has(r))return!0;var n=lc.parentNode(e);return(!n||n.nodeType!==e.DOCUMENT_NODE)&&(!n||kc(n,t))}function _c(e){return Boolean(e.changedTouches)}function Sc(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function Cc(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function Ic(e){return!!e&&(I(e,Xa)&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(lc.shadowRoot(e)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(mc=function(){return(new Date).getTime()});var Ec=function(){function e(){U(this,"id",1),U(this,"styleIDMap",new WeakMap),U(this,"idStyleMap",new Map)}var t=e.prototype;return t.getId=function(e){var t;return null!=(t=this.styleIDMap.get(e))?t:-1},t.has=function(e){return this.styleIDMap.has(e)},t.add=function(e,t){return this.has(e)?this.getId(e):(r=void 0===t?this.id++:t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r);var r},t.getStyle=function(e){return this.idStyleMap.get(e)||null},t.reset=function(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1},t.generateId=function(){return this.id++},e}();function Ac(e){var t,r=null;return"getRootNode"in e&&(null==(t=lc.getRootNode(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&lc.host(lc.getRootNode(e))&&(r=lc.host(lc.getRootNode(e))),r}function Mc(e){var t=e.ownerDocument;if(!t)return!1;var r=function(e){for(var t,r=e;t=Ac(r);)r=t;return r}(e);return lc.contains(t,r)}function Nc(e){var t=e.ownerDocument;return!!t&&(lc.contains(t,e)||Mc(e))}var Pc=function(e){return e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e}(Pc||{}),Bc=function(e){return e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e}(Bc||{}),Tc=function(e){return e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e}(Tc||{}),Oc=function(e){return e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e}(Oc||{}),Rc=function(e){return e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e}(Rc||{}),Lc=function(e){return e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e}(Lc||{}),Uc=function(e){return e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e}(Uc||{});function jc(e){return"__ln"in e}var Dc,Fc=function(){function e(){U(this,"length",0),U(this,"head",null),U(this,"tail",null)}var t=e.prototype;return t.get=function(e){if(e>=this.length)throw new Error("Position outside of list range");for(var t=this.head,r=0;r<e;r++)t=(null==t?void 0:t.next)||null;return t},t.addNode=function(e){var t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&jc(e.previousSibling)){var r=e.previousSibling.__ln.next;t.next=r,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,r&&(r.previous=t)}else if(e.nextSibling&&jc(e.nextSibling)&&e.nextSibling.__ln.previous){var n=e.nextSibling.__ln.previous;t.previous=n,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,n&&(n.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;null===t.next&&(this.tail=t),this.length++},t.removeNode=function(e){var t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)},e}(),zc=function(e,t){return e+"@"+t},qc=function(){function e(){var e=this;U(this,"frozen",!1),U(this,"locked",!1),U(this,"texts",[]),U(this,"attributes",[]),U(this,"attributeMap",new WeakMap),U(this,"removes",[]),U(this,"mapRemoves",[]),U(this,"movedMap",{}),U(this,"addedSet",new Set),U(this,"movedSet",new Set),U(this,"droppedSet",new Set),U(this,"removesSubTreeCache",new Set),U(this,"mutationCb"),U(this,"blockClass"),U(this,"blockSelector"),U(this,"maskTextClass"),U(this,"maskTextSelector"),U(this,"inlineStylesheet"),U(this,"maskInputOptions"),U(this,"maskTextFn"),U(this,"maskInputFn"),U(this,"keepIframeSrcFn"),U(this,"recordCanvas"),U(this,"inlineImages"),U(this,"slimDOMOptions"),U(this,"dataURLOptions"),U(this,"doc"),U(this,"mirror"),U(this,"iframeManager"),U(this,"stylesheetManager"),U(this,"shadowDomManager"),U(this,"canvasManager"),U(this,"processedNodeManager"),U(this,"unattachedDoc"),U(this,"processMutations",function(t){t.forEach(e.processMutation),e.emit()}),U(this,"emit",function(){if(!e.frozen&&!e.locked){for(var t=[],r=new Set,n=new Fc,i=function(t){for(var r=t,n=-2;-2===n;)n=(r=r&&r.nextSibling)&&e.mirror.getId(r);return n},o=function(o){var s=lc.parentNode(o);if(s&&Nc(o)){var a=!1;if(o.nodeType===Node.TEXT_NODE){var c=s.tagName;if("TEXTAREA"===c)return;"STYLE"===c&&e.addedSet.has(s)&&(a=!0)}var l=J(s)?e.mirror.getId(Ac(o)):e.mirror.getId(s),u=i(o);if(-1===l||-1===u)return n.addNode(o);var h=Pe(o,{doc:e.doc,mirror:e.mirror,blockClass:e.blockClass,blockSelector:e.blockSelector,maskTextClass:e.maskTextClass,maskTextSelector:e.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:e.inlineStylesheet,maskInputOptions:e.maskInputOptions,maskTextFn:e.maskTextFn,maskInputFn:e.maskInputFn,slimDOMOptions:e.slimDOMOptions,dataURLOptions:e.dataURLOptions,recordCanvas:e.recordCanvas,inlineImages:e.inlineImages,onSerialize:function(t){Sc(t,e.mirror)&&e.iframeManager.addIframe(t),Cc(t,e.mirror)&&e.stylesheetManager.trackLinkElement(t),Ic(o)&&e.shadowDomManager.addShadowRoot(lc.shadowRoot(o),e.doc)},onIframeLoad:function(t,r){e.iframeManager.attachIframe(t,r),e.shadowDomManager.observeAttachShadow(t)},onStylesheetLoad:function(t,r){e.stylesheetManager.attachLinkElement(t,r)},cssCaptured:a});h&&(t.push({parentId:l,nextId:u,node:h}),r.add(h.id))}};e.mapRemoves.length;)e.mirror.removeNodeFromMap(e.mapRemoves.shift());for(var s,a=B(e.movedSet);!(s=a()).done;){var c=s.value;$c(e.removesSubTreeCache,c,e.mirror)&&!e.movedSet.has(lc.parentNode(c))||o(c)}for(var l,u=B(e.addedSet);!(l=u()).done;){var h=l.value;Gc(e.droppedSet,h)||$c(e.removesSubTreeCache,h,e.mirror)?Gc(e.movedSet,h)?o(h):e.droppedSet.add(h):o(h)}for(var d=null;n.length;){var p=null;if(d){var f=e.mirror.getId(lc.parentNode(d.value)),m=i(d.value);-1!==f&&-1!==m&&(p=d)}if(!p)for(var g=n.tail;g;){var y=g;if(g=g.previous,y){var v=e.mirror.getId(lc.parentNode(y.value));if(-1===i(y.value))continue;if(-1!==v){p=y;break}var b=y.value,w=lc.parentNode(b);if(w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var x=lc.host(w);if(-1!==e.mirror.getId(x)){p=y;break}}}}if(!p){for(;n.head;)n.removeNode(n.head.value);break}d=p.previous,n.removeNode(p.value),o(p.value)}var k={texts:e.texts.map(function(t){var r=t.node,n=lc.parentNode(r);return n&&"TEXTAREA"===n.tagName&&e.genTextAreaValueMutation(n),{id:e.mirror.getId(r),value:t.value}}).filter(function(e){return!r.has(e.id)}).filter(function(t){return e.mirror.has(t.id)}),attributes:e.attributes.map(function(t){var r=t.attributes;if("string"==typeof r.style){var n=JSON.stringify(t.styleDiff),i=JSON.stringify(t._unchangedStyles);n.length<r.style.length&&(n+i).split("var(").length===r.style.split("var(").length&&(r.style=t.styleDiff)}return{id:e.mirror.getId(t.node),attributes:r}}).filter(function(e){return!r.has(e.id)}).filter(function(t){return e.mirror.has(t.id)}),removes:e.removes,adds:t};(k.texts.length||k.attributes.length||k.removes.length||k.adds.length)&&(e.texts=[],e.attributes=[],e.attributeMap=new WeakMap,e.removes=[],e.addedSet=new Set,e.movedSet=new Set,e.droppedSet=new Set,e.removesSubTreeCache=new Set,e.movedMap={},e.mutationCb(k))}}),U(this,"genTextAreaValueMutation",function(t){var r=e.attributeMap.get(t);r||(r={node:t,attributes:{},styleDiff:{},_unchangedStyles:{}},e.attributes.push(r),e.attributeMap.set(t,r));var n=Array.from(lc.childNodes(t),function(e){return lc.textContent(e)||""}).join("");r.attributes.value=re({element:t,maskInputOptions:e.maskInputOptions,tagName:t.tagName,type:oe(t),value:n,maskInputFn:e.maskInputFn})}),U(this,"processMutation",function(t){if(!xc(t.target,e.mirror,e.slimDOMOptions))switch(t.type){case"characterData":var r=lc.textContent(t.target);wc(t.target,e.blockClass,e.blockSelector,!1)||r===t.oldValue||e.texts.push({value:Ae(t.target,e.maskTextClass,e.maskTextSelector,!0)&&r?e.maskTextFn?e.maskTextFn(r,bc(t.target)):r.replace(/[\S]/g,"*"):r,node:t.target});break;case"attributes":var n=t.target,i=t.attributeName,o=t.target.getAttribute(i);if("value"===i){var s=oe(n);o=re({element:n,maskInputOptions:e.maskInputOptions,tagName:n.tagName,type:s,value:o,maskInputFn:e.maskInputFn})}if(wc(t.target,e.blockClass,e.blockSelector,!1)||o===t.oldValue)return;var a=e.attributeMap.get(t.target);if("IFRAME"===n.tagName&&"src"===i&&!e.keepIframeSrcFn(o)){if(n.contentDocument)return;i="rr_src"}if(a||(a={node:t.target,attributes:{},styleDiff:{},_unchangedStyles:{}},e.attributes.push(a),e.attributeMap.set(t.target,a)),"type"===i&&"INPUT"===n.tagName&&"password"===(t.oldValue||"").toLowerCase()&&n.setAttribute("data-rr-is-password","true"),!Ie(n.tagName,i))if(a.attributes[i]=Ce(e.doc,ne(n.tagName),ne(i),o),"style"===i){if(!e.unattachedDoc)try{e.unattachedDoc=document.implementation.createHTMLDocument()}catch(y){e.unattachedDoc=e.doc}var c=e.unattachedDoc.createElement("span");t.oldValue&&c.setAttribute("style",t.oldValue);for(var l,u=B(Array.from(n.style));!(l=u()).done;){var h=l.value,d=n.style.getPropertyValue(h),p=n.style.getPropertyPriority(h);d!==c.style.getPropertyValue(h)||p!==c.style.getPropertyPriority(h)?a.styleDiff[h]=""===p?d:[d,p]:a._unchangedStyles[h]=[d,p]}for(var f,m=B(Array.from(c.style));!(f=m()).done;){var g=f.value;""===n.style.getPropertyValue(g)&&(a.styleDiff[g]=!1)}}else"open"===i&&"DIALOG"===n.tagName&&(n.matches("dialog:modal")?a.attributes.rr_open_mode="modal":a.attributes.rr_open_mode="non-modal");break;case"childList":if(wc(t.target,e.blockClass,e.blockSelector,!0))return;if("TEXTAREA"===t.target.tagName)return void e.genTextAreaValueMutation(t.target);t.addedNodes.forEach(function(r){return e.genAdds(r,t.target)}),t.removedNodes.forEach(function(r){var n=e.mirror.getId(r),i=J(t.target)?e.mirror.getId(lc.host(t.target)):e.mirror.getId(t.target);wc(t.target,e.blockClass,e.blockSelector,!1)||xc(r,e.mirror,e.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(r,e.mirror)||(e.addedSet.has(r)?(Wc(e.addedSet,r),e.droppedSet.add(r)):e.addedSet.has(t.target)&&-1===n||kc(t.target,e.mirror)||(e.movedSet.has(r)&&e.movedMap[zc(n,i)]?Wc(e.movedSet,r):(e.removes.push({parentId:i,id:n,isShadow:!(!J(t.target)||!X(t.target))||void 0}),function(e,t){var r=[e];for(;r.length;){var n=r.pop();t.has(n)||(t.add(n),lc.childNodes(n).forEach(function(e){return r.push(e)}))}}(r,e.removesSubTreeCache))),e.mapRemoves.push(r))})}}),U(this,"genAdds",function(t,r){if(!e.processedNodeManager.inOtherBuffer(t,e)&&!e.addedSet.has(t)&&!e.movedSet.has(t)){if(e.mirror.hasNode(t)){if(xc(t,e.mirror,e.slimDOMOptions))return;e.movedSet.add(t);var n=null;r&&e.mirror.hasNode(r)&&(n=e.mirror.getId(r)),n&&-1!==n&&(e.movedMap[zc(e.mirror.getId(t),n)]=!0)}else e.addedSet.add(t),e.droppedSet.delete(t);wc(t,e.blockClass,e.blockSelector,!1)||(lc.childNodes(t).forEach(function(t){return e.genAdds(t)}),Ic(t)&&lc.childNodes(lc.shadowRoot(t)).forEach(function(r){e.processedNodeManager.add(r,e),e.genAdds(r,t)}))}})}var t=e.prototype;return t.init=function(e){var t=this;["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(function(r){t[r]=e[r]})},t.freeze=function(){this.frozen=!0,this.canvasManager.freeze()},t.unfreeze=function(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()},t.isFrozen=function(){return this.frozen},t.lock=function(){this.locked=!0,this.canvasManager.lock()},t.unlock=function(){this.locked=!1,this.canvasManager.unlock(),this.emit()},t.reset=function(){this.shadowDomManager.reset(),this.canvasManager.reset()},e}();function Wc(e,t){e.delete(t),lc.childNodes(t).forEach(function(t){return Wc(e,t)})}function $c(e,t,r){return 0!==e.size&&function(e,t){var r=lc.parentNode(t);return!!r&&e.has(r)}(e,t)}function Gc(e,t){return 0!==e.size&&Vc(e,t)}function Vc(e,t){var r=lc.parentNode(t);return!!r&&(!!e.has(r)||Vc(e,r))}var Hc=function(e){if(!Dc)return e;return function(){for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];try{return e.apply(void 0,[].concat(r))}catch(vu){if(Dc&&!0===Dc(vu))return;throw vu}}},Kc=[];function Zc(e){try{if("composedPath"in e){var t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch(r){}return e&&e.target}function Yc(e,t){var r=new qc;Kc.push(r),r.init(e);var n=new(ac())(Hc(r.processMutations.bind(r)));return n.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),n}function Jc(e){var t=e.mouseInteractionCb,r=e.doc,n=e.mirror,i=e.blockClass,o=e.blockSelector,s=e.sampling;if(!1===s.mouseInteraction)return function(){};var a=!0===s.mouseInteraction||void 0===s.mouseInteraction?{}:s.mouseInteraction,c=[],l=null;return Object.keys(Tc).filter(function(e){return Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==a[e]}).forEach(function(e){var s=ne(e),a=function(e){return function(r){var s=Zc(r);if(!wc(s,i,o,!0)){var a=null,c=e;if("pointerType"in r){switch(r.pointerType){case"mouse":a=Oc.Mouse;break;case"touch":a=Oc.Touch;break;case"pen":a=Oc.Pen}a===Oc.Touch?Tc[e]===Tc.MouseDown?c="TouchStart":Tc[e]===Tc.MouseUp&&(c="TouchEnd"):Oc.Pen}else _c(r)&&(a=Oc.Touch);null!==a?(l=a,(c.startsWith("Touch")&&a===Oc.Touch||c.startsWith("Mouse")&&a===Oc.Mouse)&&(a=null)):Tc[e]===Tc.Click&&(a=l,l=null);var u=_c(r)?r.changedTouches[0]:r;if(u){var h=n.getId(s),d=u.clientX,p=u.clientY;Hc(t)(_({type:Tc[c],id:h,x:d,y:p},null!==a&&{pointerType:a}))}}}}(e);if(window.PointerEvent)switch(Tc[e]){case Tc.MouseDown:case Tc.MouseUp:s=s.replace("mouse","pointer");break;case Tc.TouchStart:case Tc.TouchEnd:return}c.push(uc(s,a,r))}),Hc(function(){c.forEach(function(e){return e()})})}function Xc(e){var t=e.scrollCb,r=e.doc,n=e.mirror,i=e.blockClass,o=e.blockSelector,s=e.sampling;return uc("scroll",Hc(pc(Hc(function(e){var s=Zc(e);if(s&&!wc(s,i,o,!0)){var a=n.getId(s);if(s===r&&r.defaultView){var c=gc(r.defaultView);t({id:a,x:c.left,y:c.top})}else t({id:a,x:s.scrollLeft,y:s.scrollTop})}}),s.scroll||100)),r)}var Qc=["INPUT","TEXTAREA","SELECT"],el=new WeakMap;function tl(e){return function(e,t){if(ol("CSSGroupingRule")&&I(e.parentRule,CSSGroupingRule)||ol("CSSMediaRule")&&I(e.parentRule,CSSMediaRule)||ol("CSSSupportsRule")&&I(e.parentRule,CSSSupportsRule)||ol("CSSConditionRule")&&I(e.parentRule,CSSConditionRule)){var r=Array.from(e.parentRule.cssRules).indexOf(e);t.unshift(r)}else if(e.parentStyleSheet){var n=Array.from(e.parentStyleSheet.cssRules).indexOf(e);t.unshift(n)}return t}(e,[])}function rl(e,t,r){var n,i;return e?(e.ownerNode?n=t.getId(e.ownerNode):i=r.getId(e),{styleId:i,id:n}):{}}function nl(e,t){var r,n,i,o=e.mirror,s=e.stylesheetManager,a=null;a="#document"===t.nodeName?o.getId(t):o.getId(lc.host(t));var c="#document"===t.nodeName?null==(r=t.defaultView)?void 0:r.Document:null==(i=null==(n=t.ownerDocument)?void 0:n.defaultView)?void 0:i.ShadowRoot,l=(null==c?void 0:c.prototype)?Object.getOwnPropertyDescriptor(null==c?void 0:c.prototype,"adoptedStyleSheets"):void 0;return null!==a&&-1!==a&&c&&l?(Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:function(){var e;return null==(e=l.get)?void 0:e.call(this)},set:function(e){var t,r=null==(t=l.set)?void 0:t.call(this,e);if(null!==a&&-1!==a)try{s.adoptStyleSheets(e,a)}catch(n){}return r}}),Hc(function(){Object.defineProperty(t,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})):function(){}}function il(e,t){void 0===t&&(t={});var r,n=e.doc.defaultView;if(!n)return function(){};!function(e,t){var r=e.mutationCb,n=e.mousemoveCb,i=e.mouseInteractionCb,o=e.scrollCb,s=e.viewportResizeCb,a=e.inputCb,c=e.mediaInteractionCb,l=e.styleSheetRuleCb,u=e.styleDeclarationCb,h=e.canvasMutationCb,d=e.fontCb,p=e.selectionCb,f=e.customElementCb;e.mutationCb=function(){for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];var o;t.mutation&&(o=t).mutation.apply(o,[].concat(n)),r.apply(void 0,[].concat(n))},e.mousemoveCb=function(){for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];var o;t.mousemove&&(o=t).mousemove.apply(o,[].concat(r)),n.apply(void 0,[].concat(r))},e.mouseInteractionCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var o;t.mouseInteraction&&(o=t).mouseInteraction.apply(o,[].concat(r)),i.apply(void 0,[].concat(r))},e.scrollCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.scroll&&(i=t).scroll.apply(i,[].concat(r)),o.apply(void 0,[].concat(r))},e.viewportResizeCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.viewportResize&&(i=t).viewportResize.apply(i,[].concat(r)),s.apply(void 0,[].concat(r))},e.inputCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.input&&(i=t).input.apply(i,[].concat(r)),a.apply(void 0,[].concat(r))},e.mediaInteractionCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.mediaInteaction&&(i=t).mediaInteaction.apply(i,[].concat(r)),c.apply(void 0,[].concat(r))},e.styleSheetRuleCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.styleSheetRule&&(i=t).styleSheetRule.apply(i,[].concat(r)),l.apply(void 0,[].concat(r))},e.styleDeclarationCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.styleDeclaration&&(i=t).styleDeclaration.apply(i,[].concat(r)),u.apply(void 0,[].concat(r))},e.canvasMutationCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.canvasMutation&&(i=t).canvasMutation.apply(i,[].concat(r)),h.apply(void 0,[].concat(r))},e.fontCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.font&&(i=t).font.apply(i,[].concat(r)),d.apply(void 0,[].concat(r))},e.selectionCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.selection&&(i=t).selection.apply(i,[].concat(r)),p.apply(void 0,[].concat(r))},e.customElementCb=function(){for(var e=arguments.length,r=new Array(e),n=0;n<e;n++)r[n]=arguments[n];var i;t.customElement&&(i=t).customElement.apply(i,[].concat(r)),f.apply(void 0,[].concat(r))}}(e,t),e.recordDOM&&(r=Yc(e,e.doc));var i,o,s,a,c,l=function(e){var t=e.mousemoveCb,r=e.sampling,n=e.doc,i=e.mirror;if(!1===r.mousemove)return function(){};var o,s="number"==typeof r.mousemove?r.mousemove:50,a="number"==typeof r.mousemoveCallback?r.mousemoveCallback:500,c=[],l=pc(Hc(function(e){var r=Date.now()-o;t(c.map(function(e){return e.timeOffset-=r,e}),e),c=[],o=null}),a),u=Hc(pc(Hc(function(e){var t=Zc(e),r=_c(e)?e.changedTouches[0]:e,n=r.clientX,s=r.clientY;o||(o=mc()),c.push({x:n,y:s,id:i.getId(t),timeOffset:mc()-o}),l("undefined"!=typeof DragEvent&&I(e,DragEvent)?Bc.Drag:I(e,MouseEvent)?Bc.MouseMove:Bc.TouchMove)}),s,{trailing:!1})),h=[uc("mousemove",u,n),uc("touchmove",u,n),uc("drag",u,n)];return Hc(function(){h.forEach(function(e){return e()})})}(e),u=Jc(e),h=Xc(e),d=(i={win:n},o=e.viewportResizeCb,s=i.win,a=-1,c=-1,uc("resize",Hc(pc(Hc(function(){var e=yc(),t=vc();a===e&&c===t||(o({width:Number(t),height:Number(e)}),a=e,c=t)}),200)),s)),p=function(e){var t=e.inputCb,r=e.doc,n=e.mirror,i=e.blockClass,o=e.blockSelector,s=e.ignoreClass,a=e.ignoreSelector,c=e.maskInputOptions,l=e.maskInputFn,u=e.sampling,h=e.userTriggeredOnInput;function d(e){var t=Zc(e),n=e.isTrusted,u=t&&t.tagName;if(t&&"OPTION"===u&&(t=lc.parentElement(t)),t&&u&&!(Qc.indexOf(u)<0)&&!wc(t,i,o,!0)&&!(t.classList.contains(s)||a&&t.matches(a))){var d=t.value,f=!1,m=oe(t)||"";"radio"===m||"checkbox"===m?f=t.checked:(c[u.toLowerCase()]||c[m])&&(d=re({element:t,maskInputOptions:c,tagName:u,type:m,value:d,maskInputFn:l})),p(t,h?{text:d,isChecked:f,userTriggered:n}:{text:d,isChecked:f});var g=t.name;"radio"===m&&g&&f&&r.querySelectorAll('input[type="radio"][name="'+g+'"]').forEach(function(e){if(e!==t){var r=e.value;p(e,h?{text:r,isChecked:!f,userTriggered:!1}:{text:r,isChecked:!f})}})}}function p(e,r){var i=el.get(e);if(!i||i.text!==r.text||i.isChecked!==r.isChecked){el.set(e,r);var o=n.getId(e);Hc(t)(_({},r,{id:o}))}}var f=("last"===u.input?["change"]:["input","change"]).map(function(e){return uc(e,Hc(d),r)}),m=r.defaultView;if(!m)return function(){f.forEach(function(e){return e()})};var g,y=m.Object.getOwnPropertyDescriptor(m.HTMLInputElement.prototype,"value"),v=[[m.HTMLInputElement.prototype,"value"],[m.HTMLInputElement.prototype,"checked"],[m.HTMLSelectElement.prototype,"value"],[m.HTMLTextAreaElement.prototype,"value"],[m.HTMLSelectElement.prototype,"selectedIndex"],[m.HTMLOptionElement.prototype,"selected"]];return y&&y.set&&(g=f).push.apply(g,[].concat(v.map(function(e){return fc(e[0],e[1],{set:function(){Hc(d)({target:this,isTrusted:!1})}},!1,m)}))),Hc(function(){f.forEach(function(e){return e()})})}(e),f=function(e){var t=e.mediaInteractionCb,r=e.blockClass,n=e.blockSelector,i=e.mirror,o=e.sampling,s=e.doc,a=Hc(function(e){return pc(Hc(function(o){var s=Zc(o);if(s&&!wc(s,r,n,!0)){var a=s.currentTime,c=s.volume,l=s.muted,u=s.playbackRate,h=s.loop;t({type:e,id:i.getId(s),currentTime:a,volume:c,muted:l,playbackRate:u,loop:h})}}),o.media||500)}),c=[uc("play",a(Lc.Play),s),uc("pause",a(Lc.Pause),s),uc("seeked",a(Lc.Seeked),s),uc("volumechange",a(Lc.VolumeChange),s),uc("ratechange",a(Lc.RateChange),s)];return Hc(function(){c.forEach(function(e){return e()})})}(e),m=function(){},g=function(){},y=function(){},v=function(){};e.recordDOM&&(m=function(e,t){var r=e.styleSheetRuleCb,n=e.mirror,i=e.stylesheetManager,o=t.win;if(!o.CSSStyleSheet||!o.CSSStyleSheet.prototype)return function(){};var s=o.CSSStyleSheet.prototype.insertRule;o.CSSStyleSheet.prototype.insertRule=new Proxy(s,{apply:Hc(function(e,t,o){var s=o[0],a=o[1],c=rl(t,n,i.styleMirror),l=c.id,u=c.styleId;return(l&&-1!==l||u&&-1!==u)&&r({id:l,styleId:u,adds:[{rule:s,index:a}]}),e.apply(t,o)})}),o.CSSStyleSheet.prototype.addRule=function(e,t,r){void 0===r&&(r=this.cssRules.length);var n=e+" { "+t+" }";return o.CSSStyleSheet.prototype.insertRule.apply(this,[n,r])};var a,c,l=o.CSSStyleSheet.prototype.deleteRule;o.CSSStyleSheet.prototype.deleteRule=new Proxy(l,{apply:Hc(function(e,t,o){var s=o[0],a=rl(t,n,i.styleMirror),c=a.id,l=a.styleId;return(c&&-1!==c||l&&-1!==l)&&r({id:c,styleId:l,removes:[{index:s}]}),e.apply(t,o)})}),o.CSSStyleSheet.prototype.removeRule=function(e){return o.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},o.CSSStyleSheet.prototype.replace&&(a=o.CSSStyleSheet.prototype.replace,o.CSSStyleSheet.prototype.replace=new Proxy(a,{apply:Hc(function(e,t,o){var s=o[0],a=rl(t,n,i.styleMirror),c=a.id,l=a.styleId;return(c&&-1!==c||l&&-1!==l)&&r({id:c,styleId:l,replace:s}),e.apply(t,o)})})),o.CSSStyleSheet.prototype.replaceSync&&(c=o.CSSStyleSheet.prototype.replaceSync,o.CSSStyleSheet.prototype.replaceSync=new Proxy(c,{apply:Hc(function(e,t,o){var s=o[0],a=rl(t,n,i.styleMirror),c=a.id,l=a.styleId;return(c&&-1!==c||l&&-1!==l)&&r({id:c,styleId:l,replaceSync:s}),e.apply(t,o)})}));var u={};sl("CSSGroupingRule")?u.CSSGroupingRule=o.CSSGroupingRule:(sl("CSSMediaRule")&&(u.CSSMediaRule=o.CSSMediaRule),sl("CSSConditionRule")&&(u.CSSConditionRule=o.CSSConditionRule),sl("CSSSupportsRule")&&(u.CSSSupportsRule=o.CSSSupportsRule));var h={};return Object.entries(u).forEach(function(e){var t=e[0],o=e[1];h[t]={insertRule:o.prototype.insertRule,deleteRule:o.prototype.deleteRule},o.prototype.insertRule=new Proxy(h[t].insertRule,{apply:Hc(function(e,t,o){var s=o[0],a=o[1],c=rl(t.parentStyleSheet,n,i.styleMirror),l=c.id,u=c.styleId;return(l&&-1!==l||u&&-1!==u)&&r({id:l,styleId:u,adds:[{rule:s,index:[].concat(tl(t),[a||0])}]}),e.apply(t,o)})}),o.prototype.deleteRule=new Proxy(h[t].deleteRule,{apply:Hc(function(e,t,o){var s=o[0],a=rl(t.parentStyleSheet,n,i.styleMirror),c=a.id,l=a.styleId;return(c&&-1!==c||l&&-1!==l)&&r({id:c,styleId:l,removes:[{index:[].concat(tl(t),[s])}]}),e.apply(t,o)})})}),Hc(function(){o.CSSStyleSheet.prototype.insertRule=s,o.CSSStyleSheet.prototype.deleteRule=l,a&&(o.CSSStyleSheet.prototype.replace=a),c&&(o.CSSStyleSheet.prototype.replaceSync=c),Object.entries(u).forEach(function(e){var t=e[0],r=e[1];r.prototype.insertRule=h[t].insertRule,r.prototype.deleteRule=h[t].deleteRule})})}(e,{win:n}),g=nl(e,e.doc),y=function(e,t){var r=e.styleDeclarationCb,n=e.mirror,i=e.ignoreCSSAttributes,o=e.stylesheetManager,s=t.win,a=s.CSSStyleDeclaration.prototype.setProperty;s.CSSStyleDeclaration.prototype.setProperty=new Proxy(a,{apply:Hc(function(e,t,s){var c,l=s[0],u=s[1],h=s[2];if(i.has(l))return a.apply(t,[l,u,h]);var d=rl(null==(c=t.parentRule)?void 0:c.parentStyleSheet,n,o.styleMirror),p=d.id,f=d.styleId;return(p&&-1!==p||f&&-1!==f)&&r({id:p,styleId:f,set:{property:l,value:u,priority:h},index:tl(t.parentRule)}),e.apply(t,s)})});var c=s.CSSStyleDeclaration.prototype.removeProperty;return s.CSSStyleDeclaration.prototype.removeProperty=new Proxy(c,{apply:Hc(function(e,t,s){var a,l=s[0];if(i.has(l))return c.apply(t,[l]);var u=rl(null==(a=t.parentRule)?void 0:a.parentStyleSheet,n,o.styleMirror),h=u.id,d=u.styleId;return(h&&-1!==h||d&&-1!==d)&&r({id:h,styleId:d,remove:{property:l},index:tl(t.parentRule)}),e.apply(t,s)})}),Hc(function(){s.CSSStyleDeclaration.prototype.setProperty=a,s.CSSStyleDeclaration.prototype.removeProperty=c})}(e,{win:n}),e.collectFonts&&(v=function(e){var t=e.fontCb,r=e.doc,n=r.defaultView;if(!n)return function(){};var i=[],o=new WeakMap,s=n.FontFace;n.FontFace=function(e,t,r){var n=new s(e,t,r);return o.set(n,{family:e,buffer:"string"!=typeof t,descriptors:r,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),n};var a=cc(r.fonts,"add",function(e){return function(r){return setTimeout(Hc(function(){var e=o.get(r);e&&(t(e),o.delete(r))}),0),e.apply(this,[r])}});return i.push(function(){n.FontFace=s}),i.push(a),Hc(function(){i.forEach(function(e){return e()})})}(e)));for(var b,w=function(e){var t=e.doc,r=e.mirror,n=e.blockClass,i=e.blockSelector,o=e.selectionCb,s=!0,a=Hc(function(){var e=t.getSelection();if(!(!e||s&&(null==e?void 0:e.isCollapsed))){s=e.isCollapsed||!1;for(var a=[],c=e.rangeCount||0,l=0;l<c;l++){var u=e.getRangeAt(l),h=u.startContainer,d=u.startOffset,p=u.endContainer,f=u.endOffset;wc(h,n,i,!0)||wc(p,n,i,!0)||a.push({start:r.getId(h),startOffset:d,end:r.getId(p),endOffset:f})}o({ranges:a})}});return a(),uc("selectionchange",a)}(e),x=function(e){var t=e.doc,r=e.customElementCb,n=t.defaultView;return n&&n.customElements?cc(n.customElements,"define",function(e){return function(t,n,i){try{r({define:{name:t}})}catch(o){console.warn("Custom element callback failed for "+t)}return e.apply(this,[t,n,i])}}):function(){}}(e),k=[],S=B(e.plugins);!(b=S()).done;){var C=b.value;k.push(C.observer(C.callback,n,C.options))}return Hc(function(){Kc.forEach(function(e){return e.reset()}),null==r||r.disconnect(),l(),u(),h(),d(),p(),f(),m(),g(),y(),v(),w(),x(),k.forEach(function(e){return e()})})}function ol(e){return void 0!==window[e]}function sl(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}for(var al=function(){function e(e){U(this,"iframeIdToRemoteIdMap",new WeakMap),U(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=e}var t=e.prototype;return t.getId=function(e,t,r,n){var i=r||this.getIdToRemoteIdMap(e),o=n||this.getRemoteIdToIdMap(e),s=i.get(t);return s||(s=this.generateIdFn(),i.set(t,s),o.set(s,t)),s},t.getIds=function(e,t){var r=this,n=this.getIdToRemoteIdMap(e),i=this.getRemoteIdToIdMap(e);return t.map(function(t){return r.getId(e,t,n,i)})},t.getRemoteId=function(e,t,r){var n=r||this.getRemoteIdToIdMap(e);if("number"!=typeof t)return t;var i=n.get(t);return i||-1},t.getRemoteIds=function(e,t){var r=this,n=this.getRemoteIdToIdMap(e);return t.map(function(t){return r.getRemoteId(e,t,n)})},t.reset=function(e){if(!e)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)},t.getIdToRemoteIdMap=function(e){var t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t},t.getRemoteIdToIdMap=function(e){var t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t},e}(),cl=function(){function e(e){U(this,"iframes",new WeakMap),U(this,"crossOriginIframeMap",new WeakMap),U(this,"crossOriginIframeMirror",new al(ve)),U(this,"crossOriginIframeStyleMirror"),U(this,"crossOriginIframeRootIdMap",new WeakMap),U(this,"mirror"),U(this,"mutationCb"),U(this,"wrappedEmit"),U(this,"loadListener"),U(this,"stylesheetManager"),U(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new al(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}var t=e.prototype;return t.addIframe=function(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)},t.addLoadListener=function(e){this.loadListener=e},t.attachIframe=function(e,t){var r,n;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(r=e.contentWindow)||r.addEventListener("message",this.handleMessage.bind(this))),null==(n=this.loadListener)||n.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))},t.handleMessage=function(e){var t=e;if("rrweb"===t.data.type&&t.origin===t.data.origin&&e.source){var r=this.crossOriginIframeMap.get(e.source);if(r){var n=this.transformCrossOriginEvent(r,t.data.event);n&&this.wrappedEmit(n,t.data.isCheckout)}}},t.transformCrossOriginEvent=function(e,t){var r,n=this;switch(t.type){case Pc.FullSnapshot:this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);var i=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,i),this.patchRootIdOnNode(t.data.node,i),{timestamp:t.timestamp,type:Pc.IncrementalSnapshot,data:{source:Bc.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}};case Pc.Meta:case Pc.Load:case Pc.DomContentLoaded:return!1;case Pc.Plugin:return t;case Pc.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case Pc.IncrementalSnapshot:switch(t.data.source){case Bc.Mutation:return t.data.adds.forEach(function(t){n.replaceIds(t,e,["parentId","nextId","previousId"]),n.replaceIdOnNode(t.node,e);var r=n.crossOriginIframeRootIdMap.get(e);r&&n.patchRootIdOnNode(t.node,r)}),t.data.removes.forEach(function(t){n.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(function(t){n.replaceIds(t,e,["id"])}),t.data.texts.forEach(function(t){n.replaceIds(t,e,["id"])}),t;case Bc.Drag:case Bc.TouchMove:case Bc.MouseMove:return t.data.positions.forEach(function(t){n.replaceIds(t,e,["id"])}),t;case Bc.ViewportResize:return!1;case Bc.MediaInteraction:case Bc.MouseInteraction:case Bc.Scroll:case Bc.CanvasMutation:case Bc.Input:return this.replaceIds(t.data,e,["id"]),t;case Bc.StyleSheetRule:case Bc.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case Bc.Font:return t;case Bc.Selection:return t.data.ranges.forEach(function(t){n.replaceIds(t,e,["start","end"])}),t;case Bc.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(r=t.data.styles)||r.forEach(function(t){n.replaceStyleIds(t,e,["styleId"])}),t}}return!1},t.replace=function(e,t,r,n){for(var i,o=B(n);!(i=o()).done;){var s=i.value;(Array.isArray(t[s])||"number"==typeof t[s])&&(Array.isArray(t[s])?t[s]=e.getIds(r,t[s]):t[s]=e.getId(r,t[s]))}return t},t.replaceIds=function(e,t,r){return this.replace(this.crossOriginIframeMirror,e,t,r)},t.replaceStyleIds=function(e,t,r){return this.replace(this.crossOriginIframeStyleMirror,e,t,r)},t.replaceIdOnNode=function(e,t){var r=this;this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(function(e){r.replaceIdOnNode(e,t)})},t.patchRootIdOnNode=function(e,t){var r=this;e.type===Uc.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(function(e){r.patchRootIdOnNode(e,t)})},e}(),ll=function(){function e(e){U(this,"shadowDoms",new WeakSet),U(this,"mutationCb"),U(this,"scrollCb"),U(this,"bypassOptions"),U(this,"mirror"),U(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}var t=e.prototype;return t.init=function(){this.reset(),this.patchAttachShadow(Element,document)},t.addShadowRoot=function(e,t){var r=this;if(X(e)&&!this.shadowDoms.has(e)){this.shadowDoms.add(e);var n=Yc(_({},this.bypassOptions,{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e);this.restoreHandlers.push(function(){return n.disconnect()}),this.restoreHandlers.push(Xc(_({},this.bypassOptions,{scrollCb:this.scrollCb,doc:e,mirror:this.mirror}))),setTimeout(function(){e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&r.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,r.mirror.getId(lc.host(e))),r.restoreHandlers.push(nl({mirror:r.mirror,stylesheetManager:r.bypassOptions.stylesheetManager},e))},0)}},t.observeAttachShadow=function(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)},t.patchAttachShadow=function(e,t){var r=this;this.restoreHandlers.push(cc(e.prototype,"attachShadow",function(e){return function(n){var i=e.call(this,n),o=lc.shadowRoot(this);return o&&Nc(this)&&r.addShadowRoot(o,t),i}}))},t.reset=function(){this.restoreHandlers.forEach(function(e){try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet},e}(),ul="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",hl="undefined"==typeof Uint8Array?[]:new Uint8Array(256),dl=0;dl<64;dl++)hl[ul.charCodeAt(dl)]=dl;var pl=new Map;var fl=function(e,t,r){if(e&&(yl(e,t)||"object"===(void 0===e?"undefined":M(e)))){var n=function(e,t){var r=pl.get(e);return r||(r=new Map,pl.set(e,r)),r.has(t)||r.set(t,[]),r.get(t)}(r,e.constructor.name),i=n.indexOf(e);return-1===i&&(i=n.length,n.push(e)),i}};function ml(e,t,r){if(I(e,Array))return e.map(function(e){return ml(e,t,r)});if(null===e)return e;if(I(e,Float32Array)||I(e,Float64Array)||I(e,Int32Array)||I(e,Uint32Array)||I(e,Uint8Array)||I(e,Uint16Array)||I(e,Int16Array)||I(e,Int8Array)||I(e,Uint8ClampedArray))return{rr_type:e.constructor.name,args:[Object.values(e)]};if(I(e,ArrayBuffer))return{rr_type:e.constructor.name,base64:function(e){var t,r=new Uint8Array(e),n=r.length,i="";for(t=0;t<n;t+=3)i+=ul[r[t]>>2],i+=ul[(3&r[t])<<4|r[t+1]>>4],i+=ul[(15&r[t+1])<<2|r[t+2]>>6],i+=ul[63&r[t+2]];return n%3==2?i=i.substring(0,i.length-1)+"=":n%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(e)};if(I(e,DataView))return{rr_type:e.constructor.name,args:[ml(e.buffer,t,r),e.byteOffset,e.byteLength]};if(I(e,HTMLImageElement))return{rr_type:e.constructor.name,src:e.src};if(I(e,HTMLCanvasElement)){return{rr_type:"HTMLImageElement",src:e.toDataURL()}}return I(e,ImageData)?{rr_type:e.constructor.name,args:[ml(e.data,t,r),e.width,e.height]}:yl(e,t)||"object"===(void 0===e?"undefined":M(e))?{rr_type:e.constructor.name,index:fl(e,t,r)}:e}var gl=function(e,t,r){return e.map(function(e){return ml(e,t,r)})},yl=function(e,t){var r=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(function(e){return"function"==typeof t[e]});return Boolean(r.find(function(r){return I(e,t[r])}))};function vl(e,t,r,n){var i=[];try{var o=cc(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(i){for(var o=arguments.length,s=new Array(o>1?o-1:0),a=1;a<o;a++)s[a-1]=arguments[a];if(!wc(this,t,r,!0)){var c=function(e){return"experimental-webgl"===e?"webgl":e}(i);if("__context"in this||(this.__context=c),n&&["webgl","webgl2"].includes(c))if(s[0]&&"object"===M(s[0])){var l=s[0];l.preserveDrawingBuffer||(l.preserveDrawingBuffer=!0)}else s.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[].concat([i],s))}});i.push(o)}catch(s){console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return function(){i.forEach(function(e){return e()})}}function bl(e,t,r,n,i,o){for(var s,a=function(){var a=s.value;if(["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(a))return"continue";try{if("function"!=typeof e[a])return"continue";var l=cc(e,a,function(e){return function(){for(var s=arguments.length,c=new Array(s),l=0;l<s;l++)c[l]=arguments[l];var u=e.apply(this,c);if(fl(u,o,this),"tagName"in this.canvas&&!wc(this.canvas,n,i,!0)){var h=gl(c,o,this),d={type:t,property:a,args:h};r(this.canvas,d)}return u}});c.push(l)}catch(h){var u=fc(e,a,{set:function(e){r(this.canvas,{type:t,property:a,args:[e],setter:!0})}});c.push(u)}},c=[],l=B(Object.getOwnPropertyNames(e));!(s=l()).done;)a();return c}var wl,xl="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",kl="undefined"!=typeof window&&window.Blob&&new Blob([(wl=xl,Uint8Array.from(atob(wl),function(e){return e.charCodeAt(0)}))],{type:"text/javascript;charset=utf-8"});function _l(e){var t;try{if(!(t=kl&&(window.URL||window.webkitURL).createObjectURL(kl)))throw"";var r=new Worker(t,{name:null==e?void 0:e.name});return r.addEventListener("error",function(){(window.URL||window.webkitURL).revokeObjectURL(t)}),r}catch(n){return new Worker("data:text/javascript;base64,"+xl,{name:null==e?void 0:e.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}var Sl,Cl,Il,El=function(){function e(e){var t=this;U(this,"pendingCanvasMutations",new Map),U(this,"rafStamps",{latestId:0,invokeId:null}),U(this,"mirror"),U(this,"mutationCb"),U(this,"resetObservers"),U(this,"frozen",!1),U(this,"locked",!1),U(this,"processMutation",function(e,r){!(t.rafStamps.invokeId&&t.rafStamps.latestId!==t.rafStamps.invokeId)&&t.rafStamps.invokeId||(t.rafStamps.invokeId=t.rafStamps.latestId),t.pendingCanvasMutations.has(e)||t.pendingCanvasMutations.set(e,[]),t.pendingCanvasMutations.get(e).push(r)});var r=e.sampling,n=void 0===r?"all":r,i=e.win,o=e.blockClass,s=e.blockSelector,a=e.recordCanvas,c=e.dataURLOptions;this.mutationCb=e.mutationCb,this.mirror=e.mirror,a&&"all"===n&&this.initCanvasMutationObserver(i,o,s),a&&"number"==typeof n&&this.initCanvasFPSObserver(n,i,o,s,{dataURLOptions:c})}var t=e.prototype;return t.reset=function(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()},t.freeze=function(){this.frozen=!0},t.unfreeze=function(){this.frozen=!1},t.lock=function(){this.locked=!0},t.unlock=function(){this.locked=!1},t.initCanvasFPSObserver=function(e,t,r,n,i){var o=this,s=vl(t,r,n,!0),a=new Map,c=new _l;c.onmessage=function(e){var t=e.data.id;if(a.set(t,!1),"base64"in e.data){var r=e.data,n=r.base64,i=r.type,s=r.width,c=r.height;o.mutationCb({id:t,type:Rc["2D"],commands:[{property:"clearRect",args:[0,0,s,c]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:n}],type:i}]},0,0]}]})}};var l,u=1e3/e,h=0,d=function(e){if(h&&e-h<u)l=requestAnimationFrame(d);else{h=e;var s,p=o;(s=[],t.document.querySelectorAll("canvas").forEach(function(e){wc(e,r,n,!0)||s.push(e)}),s).forEach(w(function(e){var t,r,n,o;return T(this,function(s){switch(s.label){case 0:return r=p.mirror.getId(e),a.get(r)?[2]:0===e.width||0===e.height?[2]:(a.set(r,!0),["webgl","webgl2"].includes(e.__context)&&(n=e.getContext(e.__context),!1===(null==(t=null==n?void 0:n.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&n.clear(n.COLOR_BUFFER_BIT)),[4,createImageBitmap(e)]);case 1:return o=s.sent(),c.postMessage({id:r,bitmap:o,width:e.width,height:e.height,dataURLOptions:i.dataURLOptions},[o]),[2]}})})),l=requestAnimationFrame(d)}};l=requestAnimationFrame(d),this.resetObservers=function(){s(),cancelAnimationFrame(l)}},t.initCanvasMutationObserver=function(e,t,r){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();var n=vl(e,t,r,!1),i=function(e,t,r,n){for(var i,o=function(){var o=i.value;try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[o])return"continue";var a=cc(t.CanvasRenderingContext2D.prototype,o,function(i){return function(){for(var s=this,a=arguments.length,c=new Array(a),l=0;l<a;l++)c[l]=arguments[l];return wc(this.canvas,r,n,!0)||setTimeout(function(){var r=gl(c,t,s);e(s.canvas,{type:Rc["2D"],property:o,args:r})},0),i.apply(this,c)}});s.push(a)}catch(l){var c=fc(t.CanvasRenderingContext2D.prototype,o,{set:function(t){e(this.canvas,{type:Rc["2D"],property:o,args:[t],setter:!0})}});s.push(c)}},s=[],a=B(Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype));!(i=a()).done;)o();return function(){s.forEach(function(e){return e()})}}(this.processMutation.bind(this),e,t,r),o=function(e,t,r,n){var i,o,s=[];return(i=s).push.apply(i,[].concat(bl(t.WebGLRenderingContext.prototype,Rc.WebGL,e,r,n,t))),void 0!==t.WebGL2RenderingContext&&(o=s).push.apply(o,[].concat(bl(t.WebGL2RenderingContext.prototype,Rc.WebGL2,e,r,n,t))),function(){s.forEach(function(e){return e()})}}(this.processMutation.bind(this),e,t,r);this.resetObservers=function(){n(),i(),o()}},t.startPendingCanvasMutationFlusher=function(){var e=this;requestAnimationFrame(function(){return e.flushPendingCanvasMutations()})},t.startRAFTimestamping=function(){var e=this,t=function(r){e.rafStamps.latestId=r,requestAnimationFrame(t)};requestAnimationFrame(t)},t.flushPendingCanvasMutations=function(){var e=this;this.pendingCanvasMutations.forEach(function(t,r){var n=e.mirror.getId(r);e.flushPendingCanvasMutationFor(r,n)}),requestAnimationFrame(function(){return e.flushPendingCanvasMutations()})},t.flushPendingCanvasMutationFor=function(e,t){if(!this.frozen&&!this.locked){var r=this.pendingCanvasMutations.get(e);if(r&&-1!==t){var n=r.map(function(e){return e.type,E(e,["type"])}),i=r[0].type;this.mutationCb({id:t,type:i,commands:n}),this.pendingCanvasMutations.delete(e)}}},e}(),Al=function(){function e(e){U(this,"trackedLinkElements",new WeakSet),U(this,"mutationCb"),U(this,"adoptedStyleSheetCb"),U(this,"styleMirror",new Ec),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}var t=e.prototype;return t.attachLinkElement=function(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)},t.trackLinkElement=function(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))},t.adoptStyleSheets=function(e,t){var r,n=function(){var e=i.value,t=void 0;r.styleMirror.has(e)?t=r.styleMirror.getId(e):(t=r.styleMirror.add(e),s.push({styleId:t,rules:Array.from(e.rules||CSSRule,function(t,r){return{rule:ee(t,e.href),index:r}})})),o.styleIds.push(t)};if(0!==e.length){for(var i,o={id:t,styleIds:[]},s=[],a=B(e);!(i=a()).done;)r=this,n();s.length>0&&(o.styles=s),this.adoptedStyleSheetCb(o)}},t.reset=function(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet},t.trackStylesheetInLinkElement=function(e){},e}(),Ml=function(){function e(){U(this,"nodeMap",new WeakMap),U(this,"active",!1)}var t=e.prototype;return t.inOtherBuffer=function(e,t){var r=this.nodeMap.get(e);return r&&Array.from(r).some(function(e){return e!==t})},t.add=function(e,t){var r=this;this.active||(this.active=!0,requestAnimationFrame(function(){r.nodeMap=new WeakMap,r.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))},t.destroy=function(){},e}(),Nl=!1;try{if(2!==Array.from([1],function(e){return 2*e})[0]){var Pl=document.createElement("iframe");document.body.appendChild(Pl),Array.from=(null==(R=Pl.contentWindow)?void 0:R.Array.from)||Array.from,document.body.removeChild(Pl)}}catch(EE){}var Bl,Tl,Ol=new te;function Rl(e){void 0===e&&(e={});var t=e.emit,r=e.checkoutEveryNms,n=e.checkoutEveryNth,i=e.blockClass,o=void 0===i?"rr-block":i,s=e.blockSelector,a=void 0===s?null:s,c=e.ignoreClass,l=void 0===c?"rr-ignore":c,u=e.ignoreSelector,h=void 0===u?null:u,d=e.maskTextClass,p=void 0===d?"rr-mask":d,f=e.maskTextSelector,m=void 0===f?null:f,g=e.inlineStylesheet,y=void 0===g||g,v=e.maskAllInputs,b=e.maskInputOptions,w=e.slimDOMOptions,x=e.maskInputFn,k=e.maskTextFn,S=e.hooks,C=e.packFn,I=e.sampling,E=void 0===I?{}:I,A=e.dataURLOptions,M=void 0===A?{}:A,N=e.mousemoveWait,P=e.recordDOM,T=void 0===P||P,O=e.recordCanvas,R=void 0!==O&&O,L=e.recordCrossOriginIframes,U=void 0!==L&&L,j=e.recordAfter,D=void 0===j?"DOMContentLoaded"===e.recordAfter?e.recordAfter:"load":j,F=e.userTriggeredOnInput,z=void 0!==F&&F,q=e.collectFonts,W=void 0!==q&&q,$=e.inlineImages,G=void 0!==$&&$,V=e.plugins,H=e.keepIframeSrcFn,K=void 0===H?function(){return!1}:H,Z=e.ignoreCSSAttributes,Y=void 0===Z?new Set([]):Z,J=e.errorHandler;Dc=J;var X=!U||window.parent===window,Q=!1;if(!X)try{window.parent.document&&(Q=!1)}catch(we){Q=!0}if(X&&!t)throw new Error("emit function is required");if(!X&&!Q)return function(){};void 0!==N&&void 0===E.mousemove&&(E.mousemove=N),Ol.reset();var ee,re,ne=!0===v?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0,hidden:!0}:void 0!==b?b:{password:!0},ie=!0===w||"all"===w?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===w,headMetaDescKeywords:"all"===w,headTitleMutations:"all"===w}:w||{};void 0===ee&&(ee=window),"NodeList"in ee&&!ee.NodeList.prototype.forEach&&(ee.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in ee&&!ee.DOMTokenList.prototype.forEach&&(ee.DOMTokenList.prototype.forEach=Array.prototype.forEach);var oe=0,se=function(e){for(var t,r=B(V||[]);!(t=r()).done;){var n=t.value;n.eventProcessor&&(e=n.eventProcessor(e))}return C&&!Q&&(e=C(e)),e};Sl=function(e,i){var o,s=e;if(s.timestamp=mc(),!(null==(o=Kc[0])?void 0:o.isFrozen())||s.type===Pc.FullSnapshot||s.type===Pc.IncrementalSnapshot&&s.data.source===Bc.Mutation||Kc.forEach(function(e){return e.unfreeze()}),X)null==t||t(se(s),i);else if(Q){var a={type:"rrweb",event:se(s),origin:window.location.origin,isCheckout:i};window.parent.postMessage(a,"*")}if(s.type===Pc.FullSnapshot)re=s,oe=0;else if(s.type===Pc.IncrementalSnapshot){if(s.data.source===Bc.Mutation&&s.data.isAttachIframe)return;oe++;var c=n&&oe>=n,l=r&&s.timestamp-re.timestamp>r;(c||l)&&Cl(!0)}};for(var ae,ce=function(e){Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.Mutation},e)})},le=function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.Scroll},e)})},ue=function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.CanvasMutation},e)})},he=new Al({mutationCb:ce,adoptedStyleSheetCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.AdoptedStyleSheet},e)})}}),de=new cl({mirror:Ol,mutationCb:ce,stylesheetManager:he,recordCrossOriginIframes:U,wrappedEmit:Sl}),pe=B(V||[]);!(ae=pe()).done;){var fe=ae.value;fe.getMirror&&fe.getMirror({nodeMirror:Ol,crossOriginIframeMirror:de.crossOriginIframeMirror,crossOriginIframeStyleMirror:de.crossOriginIframeStyleMirror})}var me=new Ml;Il=new El({recordCanvas:R,mutationCb:ue,win:window,blockClass:o,blockSelector:a,mirror:Ol,sampling:E.canvas,dataURLOptions:M});var ge=new ll({mutationCb:ce,scrollCb:le,bypassOptions:{blockClass:o,blockSelector:a,maskTextClass:p,maskTextSelector:m,inlineStylesheet:y,maskInputOptions:ne,dataURLOptions:M,maskTextFn:k,maskInputFn:x,recordCanvas:R,inlineImages:G,sampling:E,slimDOMOptions:ie,iframeManager:de,stylesheetManager:he,canvasManager:Il,keepIframeSrcFn:K,processedNodeManager:me},mirror:Ol});Cl=function(e){if(void 0===e&&(e=!1),T){Sl({type:Pc.Meta,data:{href:window.location.href,width:vc(),height:yc()}},e),he.reset(),ge.init(),Kc.forEach(function(e){return e.lock()});var t=function(e,t){var r=t||{},n=r.mirror,i=void 0===n?new te:n,o=r.blockClass,s=void 0===o?"rr-block":o,a=r.blockSelector,c=void 0===a?null:a,l=r.maskTextClass,u=void 0===l?"rr-mask":l,h=r.maskTextSelector,d=void 0===h?null:h,p=r.inlineStylesheet,f=void 0===p||p,m=r.inlineImages,g=void 0!==m&&m,y=r.recordCanvas,v=void 0!==y&&y,b=r.maskAllInputs,w=void 0!==b&&b,x=r.maskTextFn,k=r.maskInputFn,_=r.slimDOM,S=void 0!==_&&_,C=r.dataURLOptions,I=r.preserveWhiteSpace,E=r.onSerialize,A=r.onIframeLoad,M=r.iframeLoadTimeout,N=r.onStylesheetLoad,P=r.stylesheetLoadTimeout,B=r.keepIframeSrcFn;return Pe(e,{doc:e,mirror:i,blockClass:s,blockSelector:c,maskTextClass:u,maskTextSelector:d,skipChild:!1,inlineStylesheet:f,maskInputOptions:!0===w?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0,hidden:!0}:!1===w?{password:!0}:w,maskTextFn:x,maskInputFn:k,slimDOMOptions:!0===S||"all"===S?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:"all"===S,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:!1===S?{}:S,dataURLOptions:C,inlineImages:g,recordCanvas:v,preserveWhiteSpace:I,onSerialize:E,onIframeLoad:A,iframeLoadTimeout:M,onStylesheetLoad:N,stylesheetLoadTimeout:P,keepIframeSrcFn:void 0===B?function(){return!1}:B,newlyAddedElement:!1})}(document,{mirror:Ol,blockClass:o,blockSelector:a,maskTextClass:p,maskTextSelector:m,inlineStylesheet:y,maskAllInputs:ne,maskTextFn:k,maskInputFn:x,slimDOM:ie,dataURLOptions:M,recordCanvas:R,inlineImages:G,onSerialize:function(e){Sc(e,Ol)&&de.addIframe(e),Cc(e,Ol)&&he.trackLinkElement(e),Ic(e)&&ge.addShadowRoot(lc.shadowRoot(e),document)},onIframeLoad:function(e,t){de.attachIframe(e,t),ge.observeAttachShadow(e)},onStylesheetLoad:function(e,t){he.attachLinkElement(e,t)},keepIframeSrcFn:K});if(!t)return console.warn("Failed to snapshot the document");Sl({type:Pc.FullSnapshot,data:{node:t,initialOffset:gc(window)}},e),Kc.forEach(function(e){return e.unlock()}),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&he.adoptStyleSheets(document.adoptedStyleSheets,Ol.getId(document))}};try{var ye=[],ve=function(e){var t;return Hc(il)({mutationCb:ce,mousemoveCb:function(e,t){return Sl({type:Pc.IncrementalSnapshot,data:{source:t,positions:e}})},mouseInteractionCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.MouseInteraction},e)})},scrollCb:le,viewportResizeCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.ViewportResize},e)})},inputCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.Input},e)})},mediaInteractionCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.MediaInteraction},e)})},styleSheetRuleCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.StyleSheetRule},e)})},styleDeclarationCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.StyleDeclaration},e)})},canvasMutationCb:ue,fontCb:function(e){return Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.Font},e)})},selectionCb:function(e){Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.Selection},e)})},customElementCb:function(e){Sl({type:Pc.IncrementalSnapshot,data:_({source:Bc.CustomElement},e)})},blockClass:o,ignoreClass:l,ignoreSelector:h,maskTextClass:p,maskTextSelector:m,maskInputOptions:ne,inlineStylesheet:y,sampling:E,recordDOM:T,recordCanvas:R,inlineImages:G,userTriggeredOnInput:z,collectFonts:W,doc:e,maskInputFn:x,maskTextFn:k,keepIframeSrcFn:K,blockSelector:a,slimDOMOptions:ie,dataURLOptions:M,mirror:Ol,iframeManager:de,stylesheetManager:he,shadowDomManager:ge,processedNodeManager:me,canvasManager:Il,ignoreCSSAttributes:Y,plugins:(null==(t=null==V?void 0:V.filter(function(e){return e.observer}))?void 0:t.map(function(e){return{observer:e.observer,options:e.options,callback:function(t){return Sl({type:Pc.Plugin,data:{plugin:e.name,payload:t}})}}}))||[]},S)};de.addLoadListener(function(e){try{ye.push(ve(e.contentDocument))}catch(vu){console.warn(vu)}});var be=function(){Cl(),ye.push(ve(document)),Nl=!0};return"interactive"===document.readyState||"complete"===document.readyState?be():(ye.push(uc("DOMContentLoaded",function(){Sl({type:Pc.DomContentLoaded,data:{}}),"DOMContentLoaded"===D&&be()})),ye.push(uc("load",function(){Sl({type:Pc.Load,data:{}}),"load"===D&&be()},window))),function(){ye.forEach(function(e){try{e()}catch(vu){String(vu).toLowerCase().includes("cross-origin")||console.warn(vu)}}),me.destroy(),Nl=!1,Dc=void 0}}catch(vu){console.warn(vu)}}Rl.addCustomEvent=function(e,t){if(!Nl)throw new Error("please add custom event after start recording");Sl({type:Pc.Custom,data:{tag:e,payload:t}})},Rl.freezePage=function(){Kc.forEach(function(e){return e.freeze()})},Rl.takeFullSnapshot=function(e){if(!Nl)throw new Error("please take full snapshot after start recording");Cl(e)},Rl.mirror=Ol,(Tl=Bl||(Bl={}))[Tl.NotStarted=0]="NotStarted",Tl[Tl.Running=1]="Running",Tl[Tl.Stopped=2]="Stopped",Rl.addCustomEvent,Rl.freezePage,Rl.takeFullSnapshot;var Ll=Object.defineProperty,Ul=function(e,t,r){return function(e,t,r){return t in e?Ll(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r}(e,"symbol"!==(void 0===t?"undefined":M(t))?t+"":t,r)};var jl=function(){function e(e){Ul(this,"fileName"),Ul(this,"functionName"),Ul(this,"lineNumber"),Ul(this,"columnNumber"),this.fileName=e.fileName||"",this.functionName=e.functionName||"",this.lineNumber=e.lineNumber,this.columnNumber=e.columnNumber}return e.prototype.toString=function(){var e=this.lineNumber||"",t=this.columnNumber||"";return this.functionName?this.functionName+" ("+this.fileName+":"+e+":"+t+")":this.fileName+":"+e+":"+t},e}(),Dl=/(^|@)\S+:\d+/,Fl=/^\s*at .*(\S+:\d+|\(native\))/m,zl=/^(eval@)?(\[native code])?$/,ql={parse:function(e){return e?void 0!==e.stacktrace||void 0!==e["opera#sourceloc"]?this.parseOpera(e):e.stack&&e.stack.match(Fl)?this.parseV8OrIE(e):e.stack?this.parseFFOrSafari(e):(console.warn("[console-record-plugin]: Failed to parse error object:",e),[]):[]},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];var t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));if(!t)throw new Error("Cannot parse given url: "+e);return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(Fl)},this).map(function(e){e.indexOf("(eval ")>-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(\),.*$)/g,""));var t=e.replace(/^\s+/,"").replace(/\(eval code/g,"("),r=t.match(/ (\((.+):(\d+):(\d+)\)$)/),n=(t=r?t.replace(r[0],""):t).split(/\s+/).slice(1),i=this.extractLocation(r?r[1]:n.pop()),o=n.join(" ")||void 0,s=["eval","<anonymous>"].indexOf(i[0])>-1?void 0:i[0];return new jl({functionName:o,fileName:s,lineNumber:i[1],columnNumber:i[2]})},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(zl)},this).map(function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new jl({functionName:e});var t=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(t),n=r&&r[1]?r[1]:void 0,i=this.extractLocation(e.replace(t,""));return new jl({functionName:n,fileName:i[0],lineNumber:i[1],columnNumber:i[2]})},this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),n=[],i=2,o=r.length;i<o;i+=2){var s=t.exec(r[i]);s&&n.push(new jl({fileName:s[2],lineNumber:parseFloat(s[1])}))}return n},parseOpera10:function(e){for(var t=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i,r=e.stacktrace.split("\n"),n=[],i=0,o=r.length;i<o;i+=2){var s=t.exec(r[i]);s&&n.push(new jl({functionName:s[3]||void 0,fileName:s[2],lineNumber:parseFloat(s[1])}))}return n},parseOpera11:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(Dl)&&!e.match(/^Error created at/)},this).map(function(e){var t=e.split("@"),r=this.extractLocation(t.pop()),n=(t.shift()||"").replace(/<anonymous function(: (\w+))?>/,"$2").replace(/\([^)]*\)/g,"")||void 0;return new jl({functionName:n,fileName:r[0],lineNumber:r[1],columnNumber:r[2]})},this)}};function Wl(e){if(!e||!e.outerHTML)return"";for(var t="";e.parentElement;){var r=e.localName;if(!r)break;r=r.toLowerCase();var n=e.parentElement,i=[];if(n.children&&n.children.length>0)for(var o=0;o<n.children.length;o++){var s=n.children[o];s.localName&&s.localName.toLowerCase&&s.localName.toLowerCase()===r&&i.push(s)}i.length>1&&(r+=":eq("+i.indexOf(e)+")"),t=r+(t?">"+t:""),e=n}return t}function $l(e){return"[object Object]"===Object.prototype.toString.call(e)}function Gl(e,t){if(0===t)return!0;for(var r,n=B(Object.keys(e));!(r=n()).done;){var i=r.value;if($l(e[i])&&Gl(e[i],t-1))return!0}return!1}function Vl(e,t){var r={numOfKeysLimit:50,depthOfLimit:4};Object.assign(r,t);var n=[],i=[];return JSON.stringify(e,function(e,t){if(n.length>0){var o=n.indexOf(this);~o?n.splice(o+1):n.push(this),~o?i.splice(o,1/0,e):i.push(e),~n.indexOf(t)&&(t=n[0]===t?"[Circular ~]":"[Circular ~."+i.slice(0,n.indexOf(t)).join(".")+"]")}else n.push(t);if(null===t)return t;if(void 0===t)return"undefined";if(function(e){if($l(e)&&Object.keys(e).length>r.numOfKeysLimit)return!0;if("function"==typeof e)return!0;if($l(e)&&Gl(e,r.depthOfLimit))return!0;return!1}(t))return function(e){var t=e.toString();r.stringLengthLimit&&t.length>r.stringLengthLimit&&(t=t.slice(0,r.stringLengthLimit)+"...");return t}(t);if("bigint"===(void 0===t?"undefined":M(t)))return t.toString()+"n";if(I(t,Event)){var s={};for(var a in t){var c=t[a];Array.isArray(c)?s[a]=Wl(c.length?c[0]:null):s[a]=c}return s}return I(t,Node)?I(t,HTMLElement)?t?t.outerHTML:"":t.nodeName:I(t,Error)?t.stack?t.stack+"\nEnd of stack for Error object":t.name+": "+t.message:t})}var Hl={level:["assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],lengthThreshold:1e3,logger:"console"};function Kl(e,t,r){var n,i=r?Object.assign({},Hl,r):Hl,o=i.logger;if(!o)return function(){};n="string"==typeof o?t[o]:o;var s=0,a=!1,c=[];if(i.level.includes("error")){var l=function(t){var r=t.message,n=t.error,o=ql.parse(n).map(function(e){return e.toString()}),s=[Vl(r,i.stringifyOptions)];e({level:"error",trace:o,payload:s})};t.addEventListener("error",l),c.push(function(){t.removeEventListener("error",l)});var u=function(t){var r,n;I(t.reason,Error)?n=[Vl("Uncaught (in promise) "+(r=t.reason).name+": "+r.message,i.stringifyOptions)]:(r=new Error,n=[Vl("Uncaught (in promise)",i.stringifyOptions),Vl(t.reason,i.stringifyOptions)]);var o=ql.parse(r).map(function(e){return e.toString()});e({level:"error",trace:o,payload:n})};t.addEventListener("unhandledrejection",u),c.push(function(){t.removeEventListener("unhandledrejection",u)})}for(var h,d=B(i.level);!(h=d()).done;){var p=h.value;c.push(f(n,p))}return function(){c.forEach(function(e){return e()})};function f(t,r){var n=this;return t[r]?function(e,t,r){try{if(!(t in e))return function(){};var n=e[t],i=r(n);return"function"==typeof i&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=i,function(){e[t]=n}}catch(o){return function(){}}}(t,r,function(t){var o=n;return function(){for(var n=arguments.length,c=new Array(n),l=0;l<n;l++)c[l]=arguments[l];if(t.apply(o,c),!("assert"===r&&c[0]||a)){a=!0;try{var u=ql.parse(new Error).map(function(e){return e.toString()}).splice(1),h=("assert"===r?c.slice(1):c).map(function(e){return Vl(e,i.stringifyOptions)});++s<i.lengthThreshold?e({level:r,trace:u,payload:h}):s===i.lengthThreshold&&e({level:"warn",trace:[],payload:[Vl("The number of log records reached the threshold.")]})}catch(vu){t.apply(void 0,[].concat(["rrweb logger error:",vu],c))}finally{a=!1}}}}):function(){}}}var Zl,Yl,Jl,Xl=p.setImmediate,Ql=Object.prototype.toString,eu=void 0!==Xl?function(e){return Xl(e)}:setTimeout;try{Object.defineProperty({},"x",{}),Zl=function(e,t,r,n){return Object.defineProperty(e,t,{value:r,writable:!0,configurable:!1!==n})}}catch(EE){Zl=function(e,t,r){return e[t]=r,e}}function tu(e,t){Jl.add(e,t),Yl||(Yl=eu(Jl.drain))}function ru(e){var t,r=typeof e;return null===e||"object"!==r&&"function"!==r||(t=e.then),"function"==typeof t&&t}function nu(){for(var e=0;e<this.chain.length;e++)iu(this,1===this.state?this.chain[e].success:this.chain[e].failure,this.chain[e]);this.chain.length=0}function iu(e,t,r){var n,i;try{!1===t?r.reject(e.msg):(n=!0===t?e.msg:t.call(void 0,e.msg))===r.promise?r.reject(TypeError("Promise-chain cycle")):(i=ru(n))?i.call(n,r.resolve,r.reject):r.resolve(n)}catch(EE){r.reject(EE)}}function ou(e){var t,r=this;if(!r.triggered){r.triggered=!0,r.def&&(r=r.def);try{(t=ru(e))?tu(function(){var n=new cu(r);try{t.call(e,function(){ou.apply(n,arguments)},function(){su.apply(n,arguments)})}catch(EE){su.call(n,EE)}}):(r.msg=e,r.state=1,r.chain.length>0&&tu(nu,r))}catch(EE){su.call(new cu(r),EE)}}}function su(e){var t=this;t.triggered||(t.triggered=!0,t.def&&(t=t.def),t.msg=e,t.state=2,t.chain.length>0&&tu(nu,t))}function au(e,t,r,n){for(var i=0;i<t.length;i++)(function(i){e.resolve(t[i]).then(function(e){r(i,e)},n)})(i)}function cu(e){this.def=e,this.triggered=!1}function lu(e){this.promise=e,this.state=0,this.triggered=!1,this.chain=[],this.msg=void 0}function uu(e){if("function"!=typeof e)throw TypeError("Not a function");if(0!==this.__NPO__)throw TypeError("Not a promise");this.__NPO__=1;var t=new lu(this);this.then=function(e,r){var n={success:"function"!=typeof e||e,failure:"function"==typeof r&&r};return n.promise=new this.constructor(function(e,t){if("function"!=typeof e||"function"!=typeof t)throw TypeError("Not a function");n.resolve=e,n.reject=t}),t.chain.push(n),0!==t.state&&tu(nu,t),n.promise},this.catch=function(e){return this.then(void 0,e)};try{e.call(void 0,function(e){ou.call(t,e)},function(e){su.call(t,e)})}catch(EE){su.call(t,EE)}}Jl=function(){var e,t,r;function n(e,t){this.fn=e,this.self=t,this.next=void 0}return{add:function(i,o){r=new n(i,o),t?t.next=r:e=r,t=r,r=void 0},drain:function(){var r=e;for(e=t=Yl=void 0;r;)r.fn.call(r.self),r=r.next}}}();var hu,du=Zl({},"constructor",uu,!1);uu.prototype=du,Zl(du,"__NPO__",0,!1),Zl(uu,"resolve",function(e){return e&&"object"==typeof e&&1===e.__NPO__?e:new this(function(t,r){if("function"!=typeof t||"function"!=typeof r)throw TypeError("Not a function");t(e)})}),Zl(uu,"reject",function(e){return new this(function(t,r){if("function"!=typeof t||"function"!=typeof r)throw TypeError("Not a function");r(e)})}),Zl(uu,"all",function(e){var t=this;return"[object Array]"!==Ql.call(e)?t.reject(TypeError("Not an array")):0===e.length?t.resolve([]):new t(function(r,n){if("function"!=typeof r||"function"!=typeof n)throw TypeError("Not a function");var i=e.length,o=Array(i),s=0;au(t,e,function(e,t){o[e]=t,++s===i&&r(o)},n)})}),Zl(uu,"race",function(e){var t=this;return"[object Array]"!==Ql.call(e)?t.reject(TypeError("Not an array")):new t(function(r,n){if("function"!=typeof r||"function"!=typeof n)throw TypeError("Not a function");au(t,e,function(e,t){r(t)},n)})}),hu="undefined"!=typeof Promise&&-1!==Promise.toString().indexOf("[native code]")?Promise:uu;var pu,fu,mu,gu,yu,vu,bu,wu,xu,ku,_u={DEBUG:!1,LIB_VERSION:"2.72.0"},Su=864e5,Cu=8e3,Iu=Array.prototype,Eu=Function.prototype,Au=Object.prototype,Mu=Iu.slice,Nu=Au.toString,Pu=Au.hasOwnProperty,Bu=p.console,Tu=p.navigator,Ou=p.document,Ru=p.opera,Lu=p.screen,Uu=Tu.userAgent,ju=Eu.bind,Du=Iu.forEach,Fu=Iu.indexOf,zu=Iu.map,qu=Array.isArray,Wu={},$u={trim:function(e){return e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},Gu={log:function(){if(_u.DEBUG&&!$u.isUndefined(Bu)&&Bu)try{Bu.log.apply(Bu,arguments)}catch(EE){$u.each(arguments,function(e){Bu.log(e)})}},warn:function(){if(_u.DEBUG&&!$u.isUndefined(Bu)&&Bu){var e=["Mixpanel warning:"].concat($u.toArray(arguments));try{Bu.warn.apply(Bu,e)}catch(EE){$u.each(e,function(e){Bu.warn(e)})}}},error:function(){if(_u.DEBUG&&!$u.isUndefined(Bu)&&Bu){var e=["Mixpanel error:"].concat($u.toArray(arguments));try{Bu.error.apply(Bu,e)}catch(EE){$u.each(e,function(e){Bu.error(e)})}}},critical:function(){if(!$u.isUndefined(Bu)&&Bu){var e=["Mixpanel error:"].concat($u.toArray(arguments));try{Bu.error.apply(Bu,e)}catch(EE){$u.each(e,function(e){Bu.error(e)})}}}},Vu=function(e,t){return function(){return arguments[0]="["+t+"] "+arguments[0],e.apply(Gu,arguments)}},Hu=function(e){return{log:Vu(Gu.log,e),error:Vu(Gu.error,e),critical:Vu(Gu.critical,e)}},Ku=function(e){return function(){try{return e.apply(this,arguments)}catch(t){Gu.critical("Implementation error. Please turn on debug and contact support@mixpanel.com."),_u.DEBUG&&Gu.critical(t)}}},Zu=function(e){var t=e.prototype;for(var r in t)"function"==typeof t[r]&&(t[r]=Ku(t[r]))};$u.bind=function(e,t){var r,n;if(ju&&e.bind===ju)return ju.apply(e,Mu.call(arguments,1));if(!$u.isFunction(e))throw new TypeError;return r=Mu.call(arguments,2),n=function(){if(!(this instanceof n))return e.apply(t,r.concat(Mu.call(arguments)));var i={};i.prototype=e.prototype;var o=new i;i.prototype=null;var s=e.apply(o,r.concat(Mu.call(arguments)));return Object(s)===s?s:o},n},$u.each=function(e,t,r){if(null!=e)if(Du&&e.forEach===Du)e.forEach(t,r);else if(e.length===+e.length){for(var n=0,i=e.length;n<i;n++)if(n in e&&t.call(r,e[n],n,e)===Wu)return}else for(var o in e)if(Pu.call(e,o)&&t.call(r,e[o],o,e)===Wu)return},$u.extend=function(e){return $u.each(Mu.call(arguments,1),function(t){for(var r in t)void 0!==t[r]&&(e[r]=t[r])}),e},$u.isArray=qu||function(e){return"[object Array]"===Nu.call(e)},$u.isFunction=function(e){try{return/^\s*\bfunction\b/.test(e)}catch(t){return!1}},$u.isArguments=function(e){return!(!e||!Pu.call(e,"callee"))},$u.toArray=function(e){return e?e.toArray?e.toArray():$u.isArray(e)||$u.isArguments(e)?Mu.call(e):$u.values(e):[]},$u.map=function(e,t,r){if(zu&&e.map===zu)return e.map(t,r);var n=[];return $u.each(e,function(e){n.push(t.call(r,e))}),n},$u.keys=function(e){var t=[];return null===e||$u.each(e,function(e,r){t[t.length]=r}),t},$u.values=function(e){var t=[];return null===e||$u.each(e,function(e){t[t.length]=e}),t},$u.include=function(e,t){var r=!1;return null===e?r:Fu&&e.indexOf===Fu?-1!=e.indexOf(t):($u.each(e,function(e){if(r||(r=e===t))return Wu}),r)},$u.includes=function(e,t){return-1!==e.indexOf(t)},$u.inherit=function(e,t){return e.prototype=new t,e.prototype.constructor=e,e.superclass=t.prototype,e},$u.isObject=function(e){return e===Object(e)&&!$u.isArray(e)},$u.isEmptyObject=function(e){if($u.isObject(e)){for(var t in e)if(Pu.call(e,t))return!1;return!0}return!1},$u.isUndefined=function(e){return void 0===e},$u.isString=function(e){return"[object String]"==Nu.call(e)},$u.isDate=function(e){return"[object Date]"==Nu.call(e)},$u.isNumber=function(e){return"[object Number]"==Nu.call(e)},$u.isElement=function(e){return!(!e||1!==e.nodeType)},$u.encodeDates=function(e){return $u.each(e,function(t,r){$u.isDate(t)?e[r]=$u.formatDate(t):$u.isObject(t)&&(e[r]=$u.encodeDates(t))}),e},$u.timestamp=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},$u.formatDate=function(e){function t(e){return e<10?"0"+e:e}return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())},$u.strip_empty_properties=function(e){var t={};return $u.each(e,function(e,r){$u.isString(e)&&e.length>0&&(t[r]=e)}),t},$u.truncate=function(e,t){var r;return"string"==typeof e?r=e.slice(0,t):$u.isArray(e)?(r=[],$u.each(e,function(e){r.push($u.truncate(e,t))})):$u.isObject(e)?(r={},$u.each(e,function(e,n){r[n]=$u.truncate(e,t)})):r=e,r},$u.JSONEncode=function(){return function(e){var t=function(e){var t=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return t.lastIndex=0,t.test(e)?'"'+e.replace(t,function(e){var t=r[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'},r=function(e,n){var i="",o=0,s="",a="",c=0,l=i,u=[],h=n[e];switch(h&&"object"==typeof h&&"function"==typeof h.toJSON&&(h=h.toJSON(e)),typeof h){case"string":return t(h);case"number":return isFinite(h)?String(h):"null";case"boolean":case"null":return String(h);case"object":if(!h)return"null";if(i+=" ",u=[],"[object Array]"===Nu.apply(h)){for(c=h.length,o=0;o<c;o+=1)u[o]=r(o,h)||"null";return a=0===u.length?"[]":i?"[\n"+i+u.join(",\n"+i)+"\n"+l+"]":"["+u.join(",")+"]",i=l,a}for(s in h)Pu.call(h,s)&&(a=r(s,h))&&u.push(t(s)+(i?": ":":")+a);return a=0===u.length?"{}":i?"{"+u.join(",")+l+"}":"{"+u.join(",")+"}",i=l,a}};return r("",{"":e})}}(),$u.JSONDecode=(yu={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},vu=function(e){var t=new SyntaxError(e);throw t.at=pu,t.text=mu,t},bu=function(e){return e&&e!==fu&&vu("Expected '"+e+"' instead of '"+fu+"'"),fu=mu.charAt(pu),pu+=1,fu},wu=function(){var e,t="";for("-"===fu&&(t="-",bu("-"));fu>="0"&&fu<="9";)t+=fu,bu();if("."===fu)for(t+=".";bu()&&fu>="0"&&fu<="9";)t+=fu;if("e"===fu||"E"===fu)for(t+=fu,bu(),"-"!==fu&&"+"!==fu||(t+=fu,bu());fu>="0"&&fu<="9";)t+=fu,bu();if(e=+t,isFinite(e))return e;vu("Bad number")},xu=function(){var e,t,r,n="";if('"'===fu)for(;bu();){if('"'===fu)return bu(),n;if("\\"===fu)if(bu(),"u"===fu){for(r=0,t=0;t<4&&(e=parseInt(bu(),16),isFinite(e));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else{if("string"!=typeof yu[fu])break;n+=yu[fu]}else n+=fu}vu("Bad string")},ku=function(){for(;fu&&fu<=" ";)bu()},gu=function(){switch(ku(),fu){case"{":return function(){var e,t={};if("{"===fu){if(bu("{"),ku(),"}"===fu)return bu("}"),t;for(;fu;){if(e=xu(),ku(),bu(":"),Object.hasOwnProperty.call(t,e)&&vu('Duplicate key "'+e+'"'),t[e]=gu(),ku(),"}"===fu)return bu("}"),t;bu(","),ku()}}vu("Bad object")}();case"[":return function(){var e=[];if("["===fu){if(bu("["),ku(),"]"===fu)return bu("]"),e;for(;fu;){if(e.push(gu()),ku(),"]"===fu)return bu("]"),e;bu(","),ku()}}vu("Bad array")}();case'"':return xu();case"-":return wu();default:return fu>="0"&&fu<="9"?wu():function(){switch(fu){case"t":return bu("t"),bu("r"),bu("u"),bu("e"),!0;case"f":return bu("f"),bu("a"),bu("l"),bu("s"),bu("e"),!1;case"n":return bu("n"),bu("u"),bu("l"),bu("l"),null}vu('Unexpected "'+fu+'"')}()}},function(e){var t;return mu=e,pu=0,fu=" ",t=gu(),ku(),fu&&vu("Syntax error"),t}),$u.base64Encode=function(e){var t,r,n,i,o,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,l="",u=[];if(!e)return e;e=$u.utf8Encode(e);do{t=(o=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,r=o>>12&63,n=o>>6&63,i=63&o,u[c++]=s.charAt(t)+s.charAt(r)+s.charAt(n)+s.charAt(i)}while(a<e.length);switch(l=u.join(""),e.length%3){case 1:l=l.slice(0,-2)+"==";break;case 2:l=l.slice(0,-1)+"="}return l},$u.utf8Encode=function(e){var t,r,n,i,o="";for(t=r=0,n=(e=(e+"").replace(/\r\n/g,"\n").replace(/\r/g,"\n")).length,i=0;i<n;i++){var s=e.charCodeAt(i),a=null;s<128?r++:a=s>127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),null!==a&&(r>t&&(o+=e.substring(t,r)),o+=a,t=r=i+1)}return r>t&&(o+=e.substring(t,e.length)),o},$u.UUID=function(){try{return p.crypto.randomUUID()}catch(EE){for(var e=new Array(36),t=0;t<36;t++)e[t]=Math.floor(16*Math.random());return e[14]=4,e[19]=e[19]&=-5,e[19]=e[19]|=8,e[8]=e[13]=e[18]=e[23]="-",$u.map(e,function(e){return e.toString(16)}).join("")}};var Yu=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];$u.isBlockedUA=function(e){var t;for(e=e.toLowerCase(),t=0;t<Yu.length;t++)if(-1!==e.indexOf(Yu[t]))return!0;return!1},$u.HTTPBuildQuery=function(e,t){var r,n,i=[];return $u.isUndefined(t)&&(t="&"),$u.each(e,function(e,t){r=encodeURIComponent(e.toString()),n=encodeURIComponent(t),i[i.length]=n+"="+r}),i.join(t)},$u.getQueryParam=function(e,t){t=t.replace(/[[]/g,"\\[").replace(/[\]]/g,"\\]");var r=new RegExp("[\\?&]"+t+"=([^&#]*)").exec(e);if(null===r||r&&"string"!=typeof r[1]&&r[1].length)return"";var n=r[1];try{n=decodeURIComponent(n)}catch(EE){Gu.error("Skipping decoding for malformed query param: "+n)}return n.replace(/\+/g," ")},$u.cookie={get:function(e){for(var t=e+"=",r=Ou.cookie.split(";"),n=0;n<r.length;n++){for(var i=r[n];" "==i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length,i.length))}return null},parse:function(e){var t;try{t=$u.JSONDecode($u.cookie.get(e))||{}}catch(EE){}return t},set_seconds:function(e,t,r,n,i,o,s){var a="",c="",l="";if(s)a="; domain="+s;else if(n){var u=ch(Ou.location.hostname);a=u?"; domain=."+u:""}if(r){var h=new Date;h.setTime(h.getTime()+1e3*r),c="; expires="+h.toGMTString()}o&&(i=!0,l="; SameSite=None"),i&&(l+="; secure"),Ou.cookie=e+"="+encodeURIComponent(t)+c+"; path=/"+a+l},set:function(e,t,r,n,i,o,s){var a="",c="",l="";if(s)a="; domain="+s;else if(n){var u=ch(Ou.location.hostname);a=u?"; domain=."+u:""}if(r){var h=new Date;h.setTime(h.getTime()+24*r*60*60*1e3),c="; expires="+h.toGMTString()}o&&(i=!0,l="; SameSite=None"),i&&(l+="; secure");var d=e+"="+encodeURIComponent(t)+c+"; path=/"+a+l;return Ou.cookie=d,d},remove:function(e,t,r){$u.cookie.set(e,"",-1,t,!1,!1,r)}};var Ju=function(e){var t=!0;try{var r="__mplss_"+oh(8);e.setItem(r,"xyz"),"xyz"!==e.getItem(r)&&(t=!1),e.removeItem(r)}catch(EE){t=!1}return t},Xu=null,Qu=function(e,t){return null===Xu||t?Xu=Ju(e||p.localStorage):Xu},eh=null;function th(e,t,r){var n=function(e){Gu.error(t+" error: "+e)};return{is_supported:function(n){var i=r(e,n);return i||Gu.error(t+" unsupported"),i},error:n,get:function(t){try{return e.getItem(t)}catch(EE){n(EE)}return null},parse:function(t){try{return $u.JSONDecode(e.getItem(t))||{}}catch(EE){}return null},set:function(t,r){try{e.setItem(t,r)}catch(EE){n(EE)}},remove:function(t){try{e.removeItem(t)}catch(EE){n(EE)}}}}$u.localStorage=th(p.localStorage,"localStorage",Qu),$u.sessionStorage=th(p.sessionStorage,"sessionStorage",function(e,t){return null===eh||t?eh=Ju(e||p.sessionStorage):eh}),$u.register_event=function(){function e(t){return t&&(t.preventDefault=e.preventDefault,t.stopPropagation=e.stopPropagation),t}return e.preventDefault=function(){this.returnValue=!1},e.stopPropagation=function(){this.cancelBubble=!0},function(t,r,n,i,o){if(t)if(t.addEventListener&&!i)t.addEventListener(r,n,!!o);else{var s="on"+r,a=t[s];t[s]=function(t,r,n){var i=function(i){if(i=i||e(p.event)){var o,s,a=!0;return $u.isFunction(n)&&(o=n(i)),s=r.call(t,i),!1!==o&&!1!==s||(a=!1),a}};return i}(t,n,a)}else Gu.error("No valid element provided to register_event")}}();var rh=new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');$u.dom_query=function(){function e(e){return e.all?e.all:e.getElementsByTagName("*")}var t=/[\t\r\n]/g;function r(e,r){var n=" "+r+" ";return(" "+e.className+" ").replace(t," ").indexOf(n)>=0}function n(t){if(!Ou.getElementsByTagName)return[];var n,i,o,s,a,c,l,u,h,d,p=t.split(" "),f=[Ou];for(c=0;c<p.length;c++)if((n=p[c].replace(/^\s+/,"").replace(/\s+$/,"")).indexOf("#")>-1){o=(i=n.split("#"))[0];var m=i[1],g=Ou.getElementById(m);if(!g||o&&g.nodeName.toLowerCase()!=o)return[];f=[g]}else if(n.indexOf(".")>-1){o=(i=n.split("."))[0];var y=i[1];for(o||(o="*"),s=[],a=0,l=0;l<f.length;l++)for(h="*"==o?e(f[l]):f[l].getElementsByTagName(o),u=0;u<h.length;u++)s[a++]=h[u];for(f=[],d=0,l=0;l<s.length;l++)s[l].className&&$u.isString(s[l].className)&&r(s[l],y)&&(f[d++]=s[l])}else{var v=n.match(rh);if(v){o=v[1];var b,w=v[2],x=v[3],k=v[4];for(o||(o="*"),s=[],a=0,l=0;l<f.length;l++)for(h="*"==o?e(f[l]):f[l].getElementsByTagName(o),u=0;u<h.length;u++)s[a++]=h[u];switch(f=[],d=0,x){case"=":b=function(e){return e.getAttribute(w)==k};break;case"~":b=function(e){return e.getAttribute(w).match(new RegExp("\\b"+k+"\\b"))};break;case"|":b=function(e){return e.getAttribute(w).match(new RegExp("^"+k+"-?"))};break;case"^":b=function(e){return 0===e.getAttribute(w).indexOf(k)};break;case"$":b=function(e){return e.getAttribute(w).lastIndexOf(k)==e.getAttribute(w).length-k.length};break;case"*":b=function(e){return e.getAttribute(w).indexOf(k)>-1};break;default:b=function(e){return e.getAttribute(w)}}for(f=[],d=0,l=0;l<s.length;l++)b(s[l])&&(f[d++]=s[l])}else{for(o=n,s=[],a=0,l=0;l<f.length;l++)for(h=f[l].getElementsByTagName(o),u=0;u<h.length;u++)s[a++]=h[u];f=s}}return f}return function(e){return $u.isElement(e)?[e]:$u.isObject(e)&&!$u.isUndefined(e.length)?e:n.call(this,e)}}();var nh=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","utm_id","utm_source_platform","utm_campaign_id","utm_creative_format","utm_marketing_tactic"],ih=["dclid","fbclid","gclid","ko_click_id","li_fat_id","msclkid","sccid","ttclid","twclid","wbraid"];$u.info={campaignParams:function(e){var t="",r={};return $u.each(nh,function(n){(t=$u.getQueryParam(Ou.URL,n)).length?r[n]=t:void 0!==e&&(r[n]=e)}),r},clickParams:function(){var e="",t={};return $u.each(ih,function(r){(e=$u.getQueryParam(Ou.URL,r)).length&&(t[r]=e)}),t},marketingParams:function(){return $u.extend($u.info.campaignParams(),$u.info.clickParams())},searchEngine:function(e){return 0===e.search("https?://(.*)google.([^/?]*)")?"google":0===e.search("https?://(.*)bing.com")?"bing":0===e.search("https?://(.*)yahoo.com")?"yahoo":0===e.search("https?://(.*)duckduckgo.com")?"duckduckgo":null},searchInfo:function(e){var t=$u.info.searchEngine(e),r="yahoo"!=t?"q":"p",n={};if(null!==t){n.$search_engine=t;var i=$u.getQueryParam(e,r);i.length&&(n.mp_keyword=i)}return n},browser:function(e,t,r){return t=t||"",r||$u.includes(e," OPR/")?$u.includes(e,"Mini")?"Opera Mini":"Opera":/(BlackBerry|PlayBook|BB10)/i.test(e)?"BlackBerry":$u.includes(e,"IEMobile")||$u.includes(e,"WPDesktop")?"Internet Explorer Mobile":$u.includes(e,"SamsungBrowser/")?"Samsung Internet":$u.includes(e,"Edge")||$u.includes(e,"Edg/")?"Microsoft Edge":$u.includes(e,"FBIOS")?"Facebook Mobile":$u.includes(e,"Whale/")?"Whale Browser":$u.includes(e,"Chrome")?"Chrome":$u.includes(e,"CriOS")?"Chrome iOS":$u.includes(e,"UCWEB")||$u.includes(e,"UCBrowser")?"UC Browser":$u.includes(e,"FxiOS")?"Firefox iOS":$u.includes(t,"Apple")?$u.includes(e,"Mobile")?"Mobile Safari":"Safari":$u.includes(e,"Android")?"Android Mobile":$u.includes(e,"Konqueror")?"Konqueror":$u.includes(e,"Firefox")?"Firefox":$u.includes(e,"MSIE")||$u.includes(e,"Trident/")?"Internet Explorer":$u.includes(e,"Gecko")?"Mozilla":""},browserVersion:function(e,t,r){var n={"Internet Explorer Mobile":/rv:(\d+(\.\d+)?)/,"Microsoft Edge":/Edge?\/(\d+(\.\d+)?)/,Chrome:/Chrome\/(\d+(\.\d+)?)/,"Chrome iOS":/CriOS\/(\d+(\.\d+)?)/,"UC Browser":/(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,Safari:/Version\/(\d+(\.\d+)?)/,"Mobile Safari":/Version\/(\d+(\.\d+)?)/,Opera:/(Opera|OPR)\/(\d+(\.\d+)?)/,Firefox:/Firefox\/(\d+(\.\d+)?)/,"Firefox iOS":/FxiOS\/(\d+(\.\d+)?)/,Konqueror:/Konqueror:(\d+(\.\d+)?)/,BlackBerry:/BlackBerry (\d+(\.\d+)?)/,"Android Mobile":/android\s(\d+(\.\d+)?)/,"Samsung Internet":/SamsungBrowser\/(\d+(\.\d+)?)/,"Internet Explorer":/(rv:|MSIE )(\d+(\.\d+)?)/,Mozilla:/rv:(\d+(\.\d+)?)/,"Whale Browser":/Whale\/(\d+(\.\d+)?)/}[$u.info.browser(e,t,r)];if(void 0===n)return null;var i=e.match(n);return i?parseFloat(i[i.length-2]):null},os:function(){var e=Uu;return/Windows/i.test(e)?/Phone/.test(e)||/WPDesktop/.test(e)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(e)?"iOS":/Android/.test(e)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(e)?"BlackBerry":/Mac/i.test(e)?"Mac OS X":/Linux/.test(e)?"Linux":/CrOS/.test(e)?"Chrome OS":""},device:function(e){return/Windows Phone/i.test(e)||/WPDesktop/.test(e)?"Windows Phone":/iPad/.test(e)?"iPad":/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(BlackBerry|PlayBook|BB10)/i.test(e)?"BlackBerry":/Android/.test(e)?"Android":""},referringDomain:function(e){var t=e.split("/");return t.length>=3?t[2]:""},currentUrl:function(){return p.location.href},properties:function(e){return"object"!=typeof e&&(e={}),$u.extend($u.strip_empty_properties({$os:$u.info.os(),$browser:$u.info.browser(Uu,Tu.vendor,Ru),$referrer:Ou.referrer,$referring_domain:$u.info.referringDomain(Ou.referrer),$device:$u.info.device(Uu)}),{$current_url:$u.info.currentUrl(),$browser_version:$u.info.browserVersion(Uu,Tu.vendor,Ru),$screen_height:Lu.height,$screen_width:Lu.width,mp_lib:"web",$lib_version:_u.LIB_VERSION,$insert_id:oh(),time:$u.timestamp()/1e3},$u.strip_empty_properties(e))},people_properties:function(){return $u.extend($u.strip_empty_properties({$os:$u.info.os(),$browser:$u.info.browser(Uu,Tu.vendor,Ru)}),{$browser_version:$u.info.browserVersion(Uu,Tu.vendor,Ru)})},mpPageViewProperties:function(){return $u.strip_empty_properties({current_page_title:Ou.title,current_domain:p.location.hostname,current_url_path:p.location.pathname,current_url_protocol:p.location.protocol,current_url_search:p.location.search})}};var oh=function(e){var t=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return e?t.substring(0,e):t},sh=/[a-z0-9][a-z0-9-]*\.[a-z]+$/i,ah=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,ch=function(e){var t=ah,r=e.split("."),n=r[r.length-1];(n.length>4||"com"===n||"org"===n)&&(t=sh);var i=e.match(t);return i?i[0]:""},lh=function(){},uh=null,hh=null;"undefined"!=typeof JSON&&(uh=JSON.stringify,hh=JSON.parse),uh=uh||$u.JSONEncode,hh=hh||$u.JSONDecode;$u.info=$u.info,$u.info.browser=$u.info.browser,$u.info.browserVersion=$u.info.browserVersion,$u.info.device=$u.info.device,$u.info.properties=$u.info.properties,$u.isBlockedUA=$u.isBlockedUA,$u.isEmptyObject=$u.isEmptyObject,$u.isObject=$u.isObject,$u.JSONDecode=$u.JSONDecode,$u.JSONEncode=$u.JSONEncode,$u.toArray=$u.toArray,$u.NPO=uu;var dh="mixpanelRecordingEvents",ph="mixpanelRecordingRegistry",fh=[dh,ph],mh=function(e){this.dbPromise=null,this.storeName=e};mh.prototype._openDb=function(){return new hu(function(e,t){var r=p.indexedDB.open("mixpanelBrowserDb",1);r.onerror=function(){t(r.error)},r.onsuccess=function(){e(r.result)},r.onupgradeneeded=function(e){var t=e.target.result;fh.forEach(function(e){t.createObjectStore(e)})}})},mh.prototype.init=function(){return p.indexedDB?(this.dbPromise||(this.dbPromise=this._openDb()),this.dbPromise.then(function(e){return e instanceof p.IDBDatabase?hu.resolve():hu.reject(e)})):hu.reject("indexedDB is not supported in this browser")},mh.prototype.isInitialized=function(){return!!this.dbPromise},mh.prototype.makeTransaction=function(e,t){var r=this.storeName,n=function(n){return new hu(function(i,o){var s=n.transaction(r,e);s.oncomplete=function(){i(s)},s.onabort=s.onerror=function(){o(s.error)},t(s.objectStore(r))})};return this.dbPromise.then(n).catch(function(e){return e&&"InvalidStateError"===e.name?(this.dbPromise=this._openDb(),this.dbPromise.then(n)):hu.reject(e)}.bind(this))},mh.prototype.setItem=function(e,t){return this.makeTransaction("readwrite",function(r){r.put(t,e)})},mh.prototype.getItem=function(e){var t;return this.makeTransaction("readonly",function(r){t=r.get(e)}).then(function(){return t.result})},mh.prototype.removeItem=function(e){return this.makeTransaction("readwrite",function(t){t.delete(e)})},mh.prototype.getAll=function(){var e;return this.makeTransaction("readonly",function(t){e=t.getAll()}).then(function(){return e.result})};function gh(e,t){Eh(!0,e,t)}function yh(e,t){Eh(!1,e,t)}function vh(e,t){return"1"===Ih(e,t)}function bh(e,t){if(function(e){if(e&&e.ignoreDnt)return!1;var t=e&&e.window||p,r=t.navigator||{},n=!1;return $u.each([r.doNotTrack,r.msDoNotTrack,t.doNotTrack],function(e){$u.includes([!0,1,"1","yes"],e)&&(n=!0)}),n}(t))return Gu.warn('This browser has "Do Not Track" enabled. This will prevent the Mixpanel SDK from sending any data. To ignore the "Do Not Track" browser setting, initialize the Mixpanel instance with the config "ignore_dnt: true"'),!0;var r="0"===Ih(e,t);return r&&Gu.warn("You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data."),r}function wh(e){return Ah(e,function(e){return this.get_config(e)})}function xh(e){return Ah(e,function(e){return this._get_config(e)})}function kh(e){return Ah(e,function(e){return this._get_config(e)})}function _h(e,t){Sh(t=t||{}).remove(Ch(e,t),!!t.crossSubdomainCookie,t.cookieDomain)}function Sh(e){return"localStorage"===(e=e||{}).persistenceType?$u.localStorage:$u.cookie}function Ch(e,t){return((t=t||{}).persistencePrefix||"__mp_opt_in_out_")+e}function Ih(e,t){return Sh(t).get(Ch(e,t))}function Eh(e,t,r){$u.isString(t)&&t.length?(Sh(r=r||{}).set(Ch(t,r),e?1:0,$u.isNumber(r.cookieExpiration)?r.cookieExpiration:null,!!r.crossSubdomainCookie,!!r.secureCookie,!!r.crossSiteCookie,r.cookieDomain),r.track&&e&&r.track(r.trackEventName||"$opt_in",r.trackProperties,{send_immediately:!0})):Gu.error("gdpr."+(e?"optIn":"optOut")+" called with an invalid token")}function Ah(e,t){return function(){var r=!1;try{var n=t.call(this,"token"),i=t.call(this,"ignore_dnt"),o=t.call(this,"opt_out_tracking_persistence_type"),s=t.call(this,"opt_out_tracking_cookie_prefix"),a=t.call(this,"window");n&&(r=bh(n,{ignoreDnt:i,persistenceType:o,persistencePrefix:s,window:a}))}catch(EE){Gu.error("Unexpected error when checking tracking opt-out status: "+EE)}if(!r)return e.apply(this,arguments);var c=arguments[arguments.length-1];"function"==typeof c&&c(0)}}var Mh=Hu("lock"),Nh=function(e,t){t=t||{},this.storageKey=e,this.storage=t.storage||p.localStorage,this.pollIntervalMS=t.pollIntervalMS||100,this.timeoutMS=t.timeoutMS||2e3,this.promiseImpl=t.promiseImpl||hu};Nh.prototype.withLock=function(e,t){return new(0,this.promiseImpl)($u.bind(function(r,n){var i=t||(new Date).getTime()+"|"+Math.random(),o=(new Date).getTime(),s=this.storageKey,a=this.pollIntervalMS,c=this.timeoutMS,l=this.storage,u=s+":X",h=s+":Y",d=s+":Z",p=function(e){if((new Date).getTime()-o>c)return Mh.error("Timeout waiting for mutex on "+s+"; clearing lock. ["+i+"]"),l.removeItem(d),l.removeItem(h),void g();setTimeout(function(){try{e()}catch(EE){n(EE)}},a*(Math.random()+.1))},f=function(e,t){e()?t():p(function(){f(e,t)})},m=function(){var e=l.getItem(h);return(!e||e===i)&&(l.setItem(h,i),l.getItem(h)===i||(Qu(l,!0)||n(new Error("localStorage support dropped while acquiring lock")),!1))},g=function(){l.setItem(u,i),f(m,function(){l.getItem(u)!==i?p(function(){l.getItem(h)===i?f(function(){return!l.getItem(d)},y):g()}):y()})},y=function(){l.setItem(d,"1");var t=function(){l.removeItem(d),l.getItem(h)===i&&l.removeItem(h),l.getItem(u)===i&&l.removeItem(u)};e().then(function(e){t(),r(e)}).catch(function(e){t(),n(e)})};try{if(!Qu(l,!0))throw new Error("localStorage support check failed");g()}catch(EE){n(EE)}},this))};var Ph=function(e){this.storage=e||p.localStorage};Ph.prototype.init=function(){return hu.resolve()},Ph.prototype.isInitialized=function(){return!0},Ph.prototype.setItem=function(e,t){return new hu($u.bind(function(r,n){try{this.storage.setItem(e,uh(t))}catch(i){n(i)}r()},this))},Ph.prototype.getItem=function(e){return new hu($u.bind(function(t,r){var n;try{n=hh(this.storage.getItem(e))}catch(i){r(i)}t(n)},this))},Ph.prototype.removeItem=function(e){return new hu($u.bind(function(t,r){try{this.storage.removeItem(e)}catch(n){r(n)}t()},this))};var Bh=Hu("batch"),Th=function(e,t){var r,n,i,o;t=t||{},this.storageKey=e,this.usePersistence=t.usePersistence,this.usePersistence&&(this.queueStorage=t.queueStorage||new Ph,this.lock=new Nh(e,{storage:t.sharedLockStorage||p.localStorage,timeoutMS:t.sharedLockTimeoutMS})),this.reportError=t.errorReporter||$u.bind(Bh.error,Bh),this.pid=t.pid||null,this.memQueue=[],this.initialized=!1,t.enqueueThrottleMs?this.enqueuePersisted=(r=$u.bind(this._enqueuePersisted,this),n=t.enqueueThrottleMs,i=null,o=[],function(e){var t=this;return o.push(e),i||(i=new hu(function(e){setTimeout(function(){var n=r.apply(t,[o]);i=null,o=[],e(n)},n)})),i}):this.enqueuePersisted=$u.bind(function(e){return this._enqueuePersisted([e])},this)};Th.prototype.ensureInit=function(){return this.initialized||!this.usePersistence?hu.resolve():this.queueStorage.init().then($u.bind(function(){this.initialized=!0},this)).catch($u.bind(function(e){this.reportError("Error initializing queue persistence. Disabling persistence",e),this.initialized=!0,this.usePersistence=!1},this))},Th.prototype.enqueue=function(e,t){var r={id:oh(),flushAfter:(new Date).getTime()+2*t,payload:e};return this.usePersistence?this.enqueuePersisted(r):(this.memQueue.push(r),hu.resolve(!0))},Th.prototype._enqueuePersisted=function(e){var t=$u.bind(function(){return this.ensureInit().then($u.bind(function(){return this.readFromStorage()},this)).then($u.bind(function(t){return this.saveToStorage(t.concat(e))},this)).then($u.bind(function(t){return t&&(this.memQueue=this.memQueue.concat(e)),t},this)).catch($u.bind(function(t){return this.reportError("Error enqueueing items",t,e),!1},this))},this);return this.lock.withLock(t,this.pid).catch($u.bind(function(e){return this.reportError("Error acquiring storage lock",e),!1},this))},Th.prototype.fillBatch=function(e){var t=this.memQueue.slice(0,e);return this.usePersistence&&t.length<e?this.ensureInit().then($u.bind(function(){return this.readFromStorage()},this)).then($u.bind(function(r){if(r.length){var n={};$u.each(t,function(e){n[e.id]=!0});for(var i=0;i<r.length;i++){var o=r[i];if((new Date).getTime()>o.flushAfter&&!n[o.id]&&(o.orphaned=!0,t.push(o),t.length>=e))break}}return t},this)):hu.resolve(t)};var Oh=function(e,t){var r=[];return $u.each(e,function(e){e.id&&!t[e.id]&&r.push(e)}),r};Th.prototype.removeItemsByID=function(e){var t={};if($u.each(e,function(e){t[e]=!0}),this.memQueue=Oh(this.memQueue,t),this.usePersistence){var r=$u.bind(function(){return this.ensureInit().then($u.bind(function(){return this.readFromStorage()},this)).then($u.bind(function(e){return e=Oh(e,t),this.saveToStorage(e)},this)).then($u.bind(function(){return this.readFromStorage()},this)).then($u.bind(function(e){for(var r=0;r<e.length;r++){var n=e[r];if(n.id&&t[n.id])throw new Error("Item not removed from storage")}return!0},this)).catch($u.bind(function(t){return this.reportError("Error removing items",t,e),!1},this))},this);return this.lock.withLock(r,this.pid).catch($u.bind(function(e){return this.reportError("Error acquiring storage lock",e),!Qu(this.lock.storage,!0)&&r().then($u.bind(function(e){return e||this.queueStorage.removeItem(this.storageKey).then(function(){return e})},this)).catch($u.bind(function(e){return this.reportError("Error clearing queue",e),!1},this))},this))}return hu.resolve(!0)};var Rh=function(e,t){var r=[];return $u.each(e,function(e){var n=e.id;if(n in t){var i=t[n];null!==i&&(e.payload=i,r.push(e))}else r.push(e)}),r};Th.prototype.updatePayloads=function(e){return this.memQueue=Rh(this.memQueue,e),this.usePersistence?this.lock.withLock($u.bind(function(){return this.ensureInit().then($u.bind(function(){return this.readFromStorage()},this)).then($u.bind(function(t){return t=Rh(t,e),this.saveToStorage(t)},this)).catch($u.bind(function(t){return this.reportError("Error updating items",e,t),!1},this))},this),this.pid).catch($u.bind(function(e){return this.reportError("Error acquiring storage lock",e),!1},this)):hu.resolve(!0)},Th.prototype.readFromStorage=function(){return this.ensureInit().then($u.bind(function(){return this.queueStorage.getItem(this.storageKey)},this)).then($u.bind(function(e){return e&&($u.isArray(e)||(this.reportError("Invalid storage entry:",e),e=null)),e||[]},this)).catch($u.bind(function(e){return this.reportError("Error retrieving queue",e),[]},this))},Th.prototype.saveToStorage=function(e){return this.ensureInit().then($u.bind(function(){return this.queueStorage.setItem(this.storageKey,e)},this)).then(function(){return!0}).catch($u.bind(function(e){return this.reportError("Error saving queue",e),!1},this))},Th.prototype.clear=function(){return this.memQueue=[],this.usePersistence?this.ensureInit().then($u.bind(function(){return this.queueStorage.removeItem(this.storageKey)},this)):hu.resolve()};var Lh=Hu("batch"),Uh=function(e,t){this.errorReporter=t.errorReporter,this.queue=new Th(e,{errorReporter:$u.bind(this.reportError,this),queueStorage:t.queueStorage,sharedLockStorage:t.sharedLockStorage,sharedLockTimeoutMS:t.sharedLockTimeoutMS,usePersistence:t.usePersistence,enqueueThrottleMs:t.enqueueThrottleMs}),this.libConfig=t.libConfig,this.sendRequest=t.sendRequestFunc,this.beforeSendHook=t.beforeSendHook,this.stopAllBatching=t.stopAllBatchingFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopped=!this.libConfig.batch_autostart,this.consecutiveRemovalFailures=0,this.itemIdsSentSuccessfully={},this.flushOnlyOnInterval=t.flushOnlyOnInterval||!1,this._flushPromise=null};Uh.prototype.enqueue=function(e){return this.queue.enqueue(e,this.flushInterval)},Uh.prototype.start=function(){return this.stopped=!1,this.consecutiveRemovalFailures=0,this.flush()},Uh.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},Uh.prototype.clear=function(){return this.queue.clear()},Uh.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},Uh.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},Uh.prototype.scheduleFlush=function(e){this.flushInterval=e,this.stopped||(this.timeoutID=setTimeout($u.bind(function(){this.stopped||(this._flushPromise=this.flush())},this),this.flushInterval))},Uh.prototype.sendRequestPromise=function(e,t){return new hu($u.bind(function(r){this.sendRequest(e,t,r)},this))},Uh.prototype.flush=function(e){if(this.requestInProgress)return Lh.log("Flush: Request already in progress"),hu.resolve();this.requestInProgress=!0,e=e||{};var t=this.libConfig.batch_request_timeout_ms,r=(new Date).getTime(),n=this.batchSize;return this.queue.fillBatch(n).then($u.bind(function(i){var o=i.length===n,s=[],a={};if($u.each(i,function(e){var t=e.payload;if(this.beforeSendHook&&!e.orphaned&&(t=this.beforeSendHook(t)),t){t.event&&t.properties&&(t.properties=$u.extend({},t.properties,{mp_sent_by_lib_version:_u.LIB_VERSION}));var r=!0,n=e.id;n?(this.itemIdsSentSuccessfully[n]||0)>5&&(this.reportError("[dupe] item ID sent too many times, not sending",{item:e,batchSize:i.length,timesSent:this.itemIdsSentSuccessfully[n]}),r=!1):this.reportError("[dupe] found item with no ID",{item:e}),r&&s.push(t)}a[e.id]=t},this),s.length<1)return this.requestInProgress=!1,this.resetFlush(),hu.resolve();var c=$u.bind(function(){return this.queue.removeItemsByID($u.map(i,function(e){return e.id})).then($u.bind(function(e){return $u.each(i,$u.bind(function(e){var t=e.id;t?(this.itemIdsSentSuccessfully[t]=this.itemIdsSentSuccessfully[t]||0,this.itemIdsSentSuccessfully[t]++,this.itemIdsSentSuccessfully[t]>5&&this.reportError("[dupe] item ID sent too many times",{item:e,batchSize:i.length,timesSent:this.itemIdsSentSuccessfully[t]})):this.reportError("[dupe] found item with no ID while removing",{item:e})},this)),e?(this.consecutiveRemovalFailures=0,this.flushOnlyOnInterval&&!o?(this.resetFlush(),hu.resolve()):this.flush()):(++this.consecutiveRemovalFailures>5?(this.reportError("Too many queue failures; disabling batching system."),this.stopAllBatching()):this.resetFlush(),hu.resolve())},this))},this),l=$u.bind(function(o){this.requestInProgress=!1;try{if(e.unloading)return this.queue.updatePayloads(a);if($u.isObject(o)&&"timeout"===o.error&&(new Date).getTime()-r>=t)return this.reportError("Network timeout; retrying"),this.flush();if($u.isObject(o)&&(o.httpStatusCode>=500||429===o.httpStatusCode||o.httpStatusCode<=0&&(u=p.navigator.onLine,!$u.isUndefined(u)&&!u)||"timeout"===o.error)){var s=2*this.flushInterval;return o.retryAfter&&(s=1e3*parseInt(o.retryAfter,10)||s),s=Math.min(6e5,s),this.reportError("Error; retry in "+s+" ms"),this.scheduleFlush(s),hu.resolve()}if($u.isObject(o)&&413===o.httpStatusCode){if(i.length>1){var l=Math.max(1,Math.floor(n/2));return this.batchSize=Math.min(this.batchSize,l,i.length-1),this.reportError("413 response; reducing batch size to "+this.batchSize),this.resetFlush(),hu.resolve()}return this.reportError("Single-event request too large; dropping",i),this.resetBatchSize(),c()}return c()}catch(EE){this.reportError("Error handling API response",EE),this.resetFlush()}var u},this),u={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:t};return e.unloading&&(u.transport="sendBeacon"),Lh.log("MIXPANEL REQUEST:",s),this.sendRequestPromise(s,u).then(l)},this)).catch($u.bind(function(e){this.reportError("Error flushing request queue",e),this.resetFlush()},this))},Uh.prototype.reportError=function(e,t){if(Lh.error.apply(Lh.error,arguments),this.errorReporter)try{t instanceof Error||(t=new Error(e)),this.errorReporter(e,t)}catch(r){Lh.error(r)}};var jh=function(e){var t=Date.now();return!e||t>e.maxExpires||t>e.idleExpires},Dh=Hu("recorder"),Fh=p.CompressionStream,zh={batch_size:1e3,batch_flush_interval_ms:1e4,batch_request_timeout_ms:9e4,batch_autostart:!0},qh=new Set([Bc.MouseMove,Bc.MouseInteraction,Bc.Scroll,Bc.ViewportResize,Bc.Input,Bc.TouchMove,Bc.MediaInteraction,Bc.Drag,Bc.Selection]);var Wh=function(e){this._mixpanel=e.mixpanelInstance,this._onIdleTimeout=e.onIdleTimeout||lh,this._onMaxLengthReached=e.onMaxLengthReached||lh,this._onBatchSent=e.onBatchSent||lh,this._rrwebRecord=e.rrwebRecord||null,this._stopRecording=null,this.replayId=e.replayId,this.batchStartUrl=e.batchStartUrl||null,this.replayStartUrl=e.replayStartUrl||null,this.idleExpires=e.idleExpires||null,this.maxExpires=e.maxExpires||null,this.replayStartTime=e.replayStartTime||null,this.lastEventTimestamp=e.lastEventTimestamp||null,this.seqNo=e.seqNo||0,this.idleTimeoutId=null,this.maxTimeoutId=null,this.recordMaxMs=Su,this.recordMinMs=0;var t=Qu(e.sharedLockStorage,!0)&&!this.getConfig("disable_persistence");this.batcherKey="__mprec_"+this.getConfig("name")+"_"+this.getConfig("token")+"_"+this.replayId,this.queueStorage=new mh(dh),this.batcher=new Uh(this.batcherKey,{errorReporter:this.reportError.bind(this),flushOnlyOnInterval:!0,libConfig:zh,sendRequestFunc:this.flushEventsWithOptOut.bind(this),queueStorage:this.queueStorage,sharedLockStorage:e.sharedLockStorage,usePersistence:t,stopAllBatchingFunc:this.stopRecording.bind(this),enqueueThrottleMs:250,sharedLockTimeoutMS:1e4})};Wh.prototype.getUserIdInfo=function(){if(this.finalFlushUserIdInfo)return this.finalFlushUserIdInfo;var e={distinct_id:String(this._mixpanel.get_distinct_id())},t=this._mixpanel.get_property("$device_id");t&&(e.$device_id=t);var r=this._mixpanel.get_property("$user_id");return r&&(e.$user_id=r),e},Wh.prototype.unloadPersistedData=function(){return this.batcher.stop(),this.queueStorage.init().catch(function(){this.reportError("Error initializing IndexedDB storage for unloading persisted data.")}.bind(this)).then(function(){return this.getDurationMs()<this._getRecordMinMs()?this.queueStorage.removeItem(this.batcherKey):this.batcher.flush().then(function(){return this.queueStorage.removeItem(this.batcherKey)}.bind(this))}.bind(this))},Wh.prototype.getConfig=function(e){return this._mixpanel.get_config(e)},Wh.prototype.get_config=function(e){return this.getConfig(e)},Wh.prototype.startRecording=function(e){if(null!==this._rrwebRecord)if(null===this._stopRecording){this.recordMaxMs=this.getConfig("record_max_ms"),this.recordMaxMs>Su&&(this.recordMaxMs=Su,Dh.critical("record_max_ms cannot be greater than "+Su+"ms. Capping value.")),this.maxExpires||(this.maxExpires=(new Date).getTime()+this.recordMaxMs),this.recordMinMs=this._getRecordMinMs(),this.replayStartTime||(this.replayStartTime=(new Date).getTime(),this.batchStartUrl=$u.info.currentUrl(),this.replayStartUrl=$u.info.currentUrl()),e||this.recordMinMs>0?this.batcher.stop():this.batcher.start();var t=function(){clearTimeout(this.idleTimeoutId);var e=this.getConfig("record_idle_timeout_ms");this.idleTimeoutId=setTimeout(this._onIdleTimeout,e),this.idleExpires=(new Date).getTime()+e}.bind(this);t();var r,n=this.getConfig("record_block_selector");""!==n&&null!==n||(n=void 0);try{this._stopRecording=this._rrwebRecord({emit:function(e){this.idleExpires&&this.idleExpires<e.timestamp?this._onIdleTimeout():(function(e){return e.type===Pc.IncrementalSnapshot&&qh.has(e.data.source)}(e)&&(this.batcher.stopped&&(new Date).getTime()-this.replayStartTime>=this.recordMinMs&&this.batcher.start(),t()),this.__enqueuePromise=this.batcher.enqueue(e),(null===this.lastEventTimestamp||e.timestamp>this.lastEventTimestamp)&&(this.lastEventTimestamp=e.timestamp))}.bind(this),blockClass:this.getConfig("record_block_class"),blockSelector:n,collectFonts:this.getConfig("record_collect_fonts"),dataURLOptions:{type:"image/webp",quality:.6},maskAllInputs:!0,maskTextClass:this.getConfig("record_mask_text_class"),maskTextSelector:this.getConfig("record_mask_text_selector"),recordCanvas:this.getConfig("record_canvas"),sampling:{canvas:15},plugins:this.getConfig("record_console")?[(r={stringifyOptions:{stringLengthLimit:1e3,numOfKeysLimit:50,depthOfLimit:2}},{name:"rrweb/console@1",observer:Kl,options:r})]:[]})}catch(EE){this.reportError("Unexpected error when starting rrweb recording.",EE)}if("function"!=typeof this._stopRecording)return this.reportError("rrweb failed to start, skipping this recording."),this._stopRecording=null,void this.stopRecording();var i=this.maxExpires-(new Date).getTime();this.maxTimeoutId=setTimeout(this._onMaxLengthReached.bind(this),i)}else Dh.log("Recording already in progress, skipping startRecording.");else this.reportError("rrweb record function not provided. ")},Wh.prototype.stopRecording=function(e){if(this.finalFlushUserIdInfo=this.getUserIdInfo(),!this.isRrwebStopped()){try{this._stopRecording()}catch(EE){this.reportError("Error with rrweb stopRecording",EE)}this._stopRecording=null}var t;return this.batcher.stopped?t=this.batcher.clear():e||(t=this.batcher.flush()),this.batcher.stop(),clearTimeout(this.idleTimeoutId),clearTimeout(this.maxTimeoutId),t},Wh.prototype.isRrwebStopped=function(){return null===this._stopRecording},Wh.prototype.flushEventsWithOptOut=function(e,t,r){var n=function(e){0===e&&(this.stopRecording(),r({error:"Tracking has been opted out, stopping recording."}))}.bind(this);this._flushEvents(e,t,r,n)},Wh.prototype.serialize=function(){var e;try{e=this._mixpanel.get_tab_id()}catch(t){this.reportError("Error getting tab ID for serialization ",t),e=null}return{replayId:this.replayId,seqNo:this.seqNo,replayStartTime:this.replayStartTime,batchStartUrl:this.batchStartUrl,replayStartUrl:this.replayStartUrl,lastEventTimestamp:this.lastEventTimestamp,idleExpires:this.idleExpires,maxExpires:this.maxExpires,tabId:e}},Wh.deserialize=function(e,t){return new Wh($u.extend({},t,{replayId:e.replayId,batchStartUrl:e.batchStartUrl,replayStartUrl:e.replayStartUrl,idleExpires:e.idleExpires,maxExpires:e.maxExpires,replayStartTime:e.replayStartTime,lastEventTimestamp:e.lastEventTimestamp,seqNo:e.seqNo,sharedLockStorage:t.sharedLockStorage}))},Wh.prototype._sendRequest=function(e,t,r,n){var i=function(t,r){200===t.status&&this.replayId===e&&(this.seqNo++,this.batchStartUrl=$u.info.currentUrl()),this._onBatchSent(),n({status:0,httpStatusCode:t.status,responseBody:r,retryAfter:t.headers.get("Retry-After")})}.bind(this),o=this._mixpanel.get_api_host&&this._mixpanel.get_api_host("record")||this.getConfig("api_host");p.fetch(o+"/"+this.getConfig("api_routes").record+"?"+new URLSearchParams(t),{method:"POST",headers:{Authorization:"Basic "+btoa(this.getConfig("token")+":"),"Content-Type":"application/octet-stream"},body:r}).then(function(e){e.json().then(function(t){i(e,t)}).catch(function(e){n({error:e})})}).catch(function(e){n({error:e,httpStatusCode:0})})},Wh.prototype._flushEvents=wh(function(e,t,r){var n=e.length;if(n>0){for(var i=this.replayId,o=1/0,s=-1/0,a=!1,c=0;c<n;c++)o=Math.min(o,e[c].timestamp),s=Math.max(s,e[c].timestamp),e[c].type===Pc.FullSnapshot&&(a=!0);if(0===this.seqNo){if(!a)return r({error:"First batch does not contain a full snapshot. Aborting recording."}),void this.stopRecording(!0);this.replayStartTime=o}else this.replayStartTime||(this.reportError("Replay start time not set but seqNo is not 0. Using current batch start time as a fallback."),this.replayStartTime=o);var l=s-this.replayStartTime,u={$current_url:this.batchStartUrl,$lib_version:_u.LIB_VERSION,batch_start_time:o/1e3,mp_lib:"web",replay_id:i,replay_length_ms:l,replay_start_time:this.replayStartTime/1e3,replay_start_url:this.replayStartUrl,seq:this.seqNo},h=JSON.stringify(e);if(Object.assign(u,this.getUserIdInfo()),function(e,t,r){if(!p.CompressionStream)return!1;var n=$u.info.browser(e,t,r),i=$u.info.browserVersion(e,t,r);return!(("Safari"===n||"Mobile Safari"===n)&&i>=16.4&&i<16.6)}(Uu,Tu.vendor,Ru)){var d=new Blob([h],{type:"application/json"}).stream().pipeThrough(new Fh("gzip"));new Response(d).blob().then(function(e){u.format="gzip",this._sendRequest(i,u,e,r)}.bind(this))}else u.format="body",this._sendRequest(i,u,h,r)}}),Wh.prototype.reportError=function(e,t){Dh.error.apply(Dh.error,arguments);try{t||e instanceof Error||(e=new Error(e)),this.getConfig("error_reporter")(e,t)}catch(r){Dh.error(r)}},Wh.prototype.getDurationMs=function(){return null===this.replayStartTime?0:null===this.lastEventTimestamp?(new Date).getTime()-this.replayStartTime:this.lastEventTimestamp-this.replayStartTime},Wh.prototype._getRecordMinMs=function(){var e=this.getConfig("record_min_ms");return e>Cu?(Dh.critical("record_min_ms cannot be greater than 8000ms. Capping value."),Cu):e};var $h=function(e){this.idb=new mh(ph),this.errorReporter=e.errorReporter,this.mixpanelInstance=e.mixpanelInstance,this.sharedLockStorage=e.sharedLockStorage};$h.prototype.isPersistenceEnabled=function(){return!this.mixpanelInstance.get_config("disable_persistence")},$h.prototype.handleError=function(e){this.errorReporter("IndexedDB error: ",e)},$h.prototype.setActiveRecording=function(e){if(!this.isPersistenceEnabled())return hu.resolve();var t=e.tabId;return t?this.idb.init().then(function(){return this.idb.setItem(t,e)}.bind(this)).catch(this.handleError.bind(this)):(console.warn("No tab ID is set, cannot persist recording metadata."),hu.resolve())},$h.prototype.getActiveRecording=function(){return this.isPersistenceEnabled()?this.idb.init().then(function(){return this.idb.getItem(this.mixpanelInstance.get_tab_id())}.bind(this)).then(function(e){return jh(e)?null:e}.bind(this)).catch(this.handleError.bind(this)):hu.resolve(null)},$h.prototype.clearActiveRecording=function(){return this.isPersistenceEnabled()?this.markActiveRecordingExpired():this.deleteActiveRecording()},$h.prototype.markActiveRecordingExpired=function(){return this.getActiveRecording().then(function(e){if(e)return e.maxExpires=0,this.setActiveRecording(e)}.bind(this)).catch(this.handleError.bind(this))},$h.prototype.deleteActiveRecording=function(){return this.idb.isInitialized()?this.idb.removeItem(this.mixpanelInstance.get_tab_id()).catch(this.handleError.bind(this)):hu.resolve()},$h.prototype.flushInactiveRecordings=function(){return this.isPersistenceEnabled()?this.idb.init().then(function(){return this.idb.getAll()}.bind(this)).then(function(e){var t=e.filter(function(e){return jh(e)}).map(function(e){return Wh.deserialize(e,{mixpanelInstance:this.mixpanelInstance,sharedLockStorage:this.sharedLockStorage}).unloadPersistedData().then(function(){return this.idb.removeItem(e.tabId)}.bind(this)).catch(this.handleError.bind(this))}.bind(this));return hu.all(t)}.bind(this)).catch(this.handleError.bind(this)):hu.resolve([])};var Gh=Hu("recorder"),Vh=function(e,t,r){this.mixpanelInstance=e,this.rrwebRecord=t||Rl,this.sharedLockStorage=r,this.recordingRegistry=new $h({mixpanelInstance:this.mixpanelInstance,errorReporter:Gh.error,sharedLockStorage:r}),this._flushInactivePromise=this.recordingRegistry.flushInactiveRecordings(),this.activeRecording=null,this.stopRecordingInProgress=!1};Vh.prototype.startRecording=function(e){if(e=e||{},!this.activeRecording||this.activeRecording.isRrwebStopped()){var t=function(){Gh.log("Idle timeout reached, restarting recording."),this.resetRecording()}.bind(this),r=function(){Gh.log("Max recording length reached, stopping recording."),this.resetRecording()}.bind(this),n=function(){this.recordingRegistry.setActiveRecording(this.activeRecording.serialize()),this.__flushPromise=this.activeRecording.batcher._flushPromise}.bind(this),i={mixpanelInstance:this.mixpanelInstance,onBatchSent:n,onIdleTimeout:t,onMaxLengthReached:r,replayId:$u.UUID(),rrwebRecord:this.rrwebRecord,sharedLockStorage:this.sharedLockStorage};return e.activeSerializedRecording?this.activeRecording=Wh.deserialize(e.activeSerializedRecording,i):this.activeRecording=new Wh(i),this.activeRecording.startRecording(e.shouldStopBatcher),this.recordingRegistry.setActiveRecording(this.activeRecording.serialize())}Gh.log("Recording already in progress, skipping startRecording.")},Vh.prototype.stopRecording=function(){return this.stopRecordingInProgress=!0,this._stopCurrentRecording(!1,!0).then(function(){return this.recordingRegistry.clearActiveRecording()}.bind(this)).then(function(){this.stopRecordingInProgress=!1}.bind(this))},Vh.prototype.pauseRecording=function(){return this._stopCurrentRecording(!1)},Vh.prototype._stopCurrentRecording=function(e,t){if(this.activeRecording){var r=this.activeRecording.stopRecording(e);return t&&(this.activeRecording=null),r}return hu.resolve()},Vh.prototype.resumeRecording=function(e){return this.activeRecording&&this.activeRecording.isRrwebStopped()?(this.activeRecording.startRecording(!1),hu.resolve(null)):this.recordingRegistry.getActiveRecording().then(function(t){return t&&!this.stopRecordingInProgress?this.startRecording({activeSerializedRecording:t}):e?this.startRecording({shouldStopBatcher:!1}):(Gh.log("No resumable recording found."),null)}.bind(this))},Vh.prototype.resetRecording=function(){this.stopRecording(),this.startRecording({shouldStopBatcher:!0})},Vh.prototype.getActiveReplayId=function(){return this.activeRecording&&!this.activeRecording.isRrwebStopped()?this.activeRecording.replayId:null},Object.defineProperty(Vh.prototype,"replayId",{get:function(){return this.getActiveReplayId()}}),p.__mp_recorder=Vh;var Hh="change",Kh="click",Zh="hashchange",Yh="load",Jh="mp_locationchange",Xh="popstate",Qh="scrollend",ed="scroll",td="submit",rd="visibilitychange",nd=["clientX","clientY","offsetX","offsetY","pageX","pageY","screenX","screenY","x","y"],id=["mp-include"],od=["mp-no-track"],sd=od.concat(["mp-sensitive"]),ad=["aria-label","aria-labelledby","aria-describedby","href","name","role","title","type"],cd={button:!0,checkbox:!0,combobox:!0,grid:!0,link:!0,listbox:!0,menu:!0,menubar:!0,menuitem:!0,menuitemcheckbox:!0,menuitemradio:!0,navigation:!0,option:!0,radio:!0,radiogroup:!0,searchbox:!0,slider:!0,spinbutton:!0,switch:!0,tab:!0,tablist:!0,textbox:!0,tree:!0,treegrid:!0,treeitem:!0},ld={base:!0,head:!0,html:!0,link:!0,meta:!0,script:!0,style:!0,title:!0,br:!0,hr:!0,wbr:!0,noscript:!0,picture:!0,source:!0,template:!0,track:!0},ud={article:!0,div:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,p:!0,section:!0,span:!0},hd=["onclick","onmousedown","onmouseup","onpointerdown","onpointerup","ontouchend","ontouchstart"],dd=Hu("autocapture");function pd(e){for(var t={},r=fd(e).split(" "),n=0;n<r.length;n++){var i=r[n];i&&(t[i]=!0)}return t}function fd(e){switch(typeof e.className){case"string":return e.className;case"object":return e.className.baseVal||e.getAttribute("class")||"";default:return""}}function md(e){if(e.previousElementSibling)return e.previousElementSibling;do{e=e.previousSibling}while(e&&!xd(e));return e}function gd(e,t,r,n,i,o){var s={$classes:fd(e).split(" "),$tag_name:e.tagName.toLowerCase()},a=e.id;a&&(s.$id=a),Sd(e,t,i,o)&&$u.each(ad.concat(n),function(t){if(e.hasAttribute(t)&&!r[t]){var n=e.getAttribute(t);Cd(n)&&(s["$attr-"+t]=n)}});for(var c=1,l=1,u=e;u=md(u);)c++,u.tagName===e.tagName&&l++;return s.$nth_child=c,s.$nth_of_type=l,s}function yd(e,t){var r=t.allowElementCallback,n=t.allowSelectors||[],i=t.blockAttrs||[],o=t.blockElementCallback,s=t.blockSelectors||[],a=t.captureTextContent||!1,c=t.captureExtraAttrs||[],l=t.capturedForHeatMap||!1,u={};$u.each(i,function(e){u[e]=!0});var h=null,d=void 0===e.target?e.srcElement:e.target;if(_d(d)&&(d=d.parentNode),function(e,t){if(!e||kd(e,"html")||!xd(e))return!1;switch(e.tagName.toLowerCase()){case"form":return t.type===td;case"input":return-1===["button","submit"].indexOf(e.getAttribute("type"))?t.type===Hh:t.type===Kh;case"select":case"textarea":return t.type===Hh;default:return t.type===Kh}}(d,e)&&bd(d,e,r,n)&&!wd(d,e,o,s)){for(var f=[d],m=d;m.parentNode&&!kd(m,"body");)f.push(m.parentNode),m=m.parentNode;var g,y=[],v=!1;if($u.each(f,function(t){var i=Sd(t,e,r,n);u.href||"a"!==t.tagName.toLowerCase()||(g=t.getAttribute("href"),g=i&&Cd(g)&&g),wd(t,e,o,s)&&(v=!0),y.push(gd(t,e,u,c,r,n))},this),!v){var b=Ou.documentElement;if(h={$event_type:e.type,$host:p.location.host,$pathname:p.location.pathname,$elements:y,$el_attr__href:g,$viewportHeight:Math.max(b.clientHeight,p.innerHeight||0),$viewportWidth:Math.max(b.clientWidth,p.innerWidth||0),$pageHeight:Ou.body.offsetHeight||0,$pageWidth:Ou.body.offsetWidth||0},$u.each(c,function(e){if(!u[e]&&d.hasAttribute(e)){var t=d.getAttribute(e);Cd(t)&&(h["$el_attr__"+e]=t)}}),a&&(w=vd(d,e,r,n))&&w.length&&(h.$el_text=w),e.type===Kh&&($u.each(nd,function(t){t in e&&(h["$"+t]=e[t])}),l&&(h.$captured_for_heatmap=!0),d=function(e){for(var t=e.target,r=e.composedPath(),n=0;n<r.length;n++){var i=r[n];if(kd(i,"a")||kd(i,"button")||kd(i,"input")||kd(i,"select")||i.getAttribute&&"button"===i.getAttribute("role")){t=i;break}if(i===t)break}return t}(e)),a){var w=vd(d,e,r,n);w&&w.length&&(h.$el_text=w)}if(d){if(!bd(d,e,r,n)||wd(d,e,o,s))return null;var x=gd(d,e,u,c,r,n);h.$target=x,h.$el_classes=x.$classes,$u.extend(h,$u.strip_empty_properties({$el_id:x.$id,$el_tag_name:x.$tag_name}))}}}return h}function vd(e,t,r,n){var i="";return Sd(e,t,r,n)&&e.childNodes&&e.childNodes.length&&$u.each(e.childNodes,function(e){_d(e)&&e.textContent&&(i+=$u.trim(e.textContent).split(/(\s+)/).filter(Cd).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),$u.trim(i)}function bd(e,t,r,n){if(r)try{if(!r(e,t))return!1}catch(EE){return dd.critical("Error while checking element in allowElementCallback",EE),!1}if(!n.length)return!0;for(var i=0;i<n.length;i++){var o=n[i];try{if(e.matches(o))return!0}catch(EE){dd.critical("Error while checking selector: "+o,EE)}}return!1}function wd(e,t,r,n){var i;if(r)try{if(r(e,t))return!0}catch(EE){return dd.critical("Error while checking element in blockElementCallback",EE),!0}if(n&&n.length)for(i=0;i<n.length;i++){var o=n[i];try{if(e.matches(o))return!0}catch(EE){dd.critical("Error while checking selector: "+o,EE)}}var s=pd(e);for(i=0;i<od.length;i++)if(s[od[i]])return!0;return!1}function xd(e){return e&&1===e.nodeType}function kd(e,t){return e&&e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function _d(e){return e&&3===e.nodeType}function Sd(e,t,r,n){var i;if(!bd(e,t,r,n))return!1;for(var o=e;o.parentNode&&!kd(o,"body");o=o.parentNode){var s=pd(o);for(i=0;i<sd.length;i++)if(s[sd[i]])return!1}var a=pd(e);for(i=0;i<id.length;i++)if(a[id[i]])return!0;if(kd(e,"input")||kd(e,"select")||kd(e,"textarea")||"true"===e.getAttribute("contenteditable"))return!1;var c=e.type||"";if("string"==typeof c)switch(c.toLowerCase()){case"hidden":case"password":return!1}var l=e.name||e.id||"";if("string"==typeof l){if(/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(l.replace(/[^a-zA-Z0-9]/g,"")))return!1}return!0}function Cd(e){if(null===e||$u.isUndefined(e))return!1;if("string"==typeof e){e=$u.trim(e);if(/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,"")))return!1;if(/(^\d{3}-?\d{2}-?\d{4}$)/.test(e))return!1}return!0}function Id(e){var t="onscrollend"in p,r=Ku(e),n=Qh;if(!t){var i=null;r=Ku(function(){clearTimeout(i),i=setTimeout(e,100)}),n=ed}return{listener:r,eventType:n}}function Ed(e){var t=e.tagName.toLowerCase();return"button"===t||"input"===t||"select"===t||"textarea"===t||"details"===t||"dialog"===t||(!!e.isContentEditable||(!!(e.onclick||e.onmousedown||e.onmouseup||e.ontouchstart||e.ontouchend)||(!!function(e){for(var t=0;t<hd.length;t++)if(e.hasAttribute(hd[t]))return!0;return!1}(e)||(!!function(e){var t=e.getAttribute("role");if(!t)return!1;var r=t.trim().split(/\s+/)[0].toLowerCase();return cd[r]}(e)||(!("a"!==t||!e.hasAttribute("href"))||!!e.hasAttribute("tabindex"))))))}function Ad(e){if(!e||!e.tagName)return!0;var t=e.tagName.toLowerCase();if(ld[t])return!0;if(Ed(e))return!1;for(var r=e.parentElement,n=0;r&&n<5;){if(Ed(r))return!1;if(r.getRootNode&&r.getRootNode()!==Ou){var i=r.getRootNode();if(i.host&&Ed(i.host))return!1}r=r.parentElement,n++}return!!ud[t]}function Md(e){return"composedPath"in e?e.composedPath():[]}function Nd(e){var t=Md(e);return t&&t.length>0?t[0]:e.target||e.srcElement}function Pd(){this.clicks=[]}function Bd(e,t){this.changeCallback=e||function(){},this.observerConfig=t,this.observedShadowRoots=null,this.shadowObservers=[]}Pd.prototype.isRageClick=function(e,t){var r=(t=t||{}).threshold_px||30,n=t.timeout_ms||1e3,i=t.click_count||4;if(t.interactive_elements_only||false){var o=Nd(e);if(!o||Ad(o))return!1}var s=Date.now(),a=e.pageX,c=e.pageY,l=this.clicks[this.clicks.length-1];if(l&&s-l.timestamp<n&&Math.sqrt(Math.pow(a-l.x,2)+Math.pow(c-l.y,2))<r){if(this.clicks.push({x:a,y:c,timestamp:s}),this.clicks.length>=i)return this.clicks=[],!0}else this.clicks=[{x:a,y:c,timestamp:s}];return!1},Bd.prototype.getEventTarget=function(e){if(this.observedShadowRoots)return Nd(e)},Bd.prototype.observeFromEvent=function(e){if(this.observedShadowRoots)for(var t=Md(e),r=0;r<t.length;r++){var n=t[r];n&&n.shadowRoot&&this.observeShadowRoot(n.shadowRoot)}},Bd.prototype.observeShadowRoot=function(e){if(this.observedShadowRoots&&!this.observedShadowRoots.has(e)){var t=this;try{this.observedShadowRoots.add(e);var r=new window.MutationObserver(function(){t.changeCallback()});r.observe(e,this.observerConfig),this.shadowObservers.push(r)}catch(n){dd.critical("Error while observing shadow root",n)}}},Bd.prototype.start=function(){this.observedShadowRoots||("undefined"!=typeof WeakSet?this.observedShadowRoots=new WeakSet:dd.critical("Shadow DOM observation unavailable: WeakSet not supported"))},Bd.prototype.stop=function(){if(this.observedShadowRoots){for(var e=0;e<this.shadowObservers.length;e++)try{this.shadowObservers[e].disconnect()}catch(t){dd.critical("Error while disconnecting shadow DOM observer",t)}this.shadowObservers=[],this.observedShadowRoots=null}};var Td=[Hh,"input",td,"select","toggle"],Od=[Qh],Rd=[Zh],Ld={characterData:!0,childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","class","hidden","checked","selected","value","display","visibility"]};function Ud(e){this.eventListeners=[],this.mutationObserver=null,this.shadowDOMObserver=null,this.isTracking=!1,this.lastChangeEventTimestamp=0,this.pendingClicks=[],this.onDeadClickCallback=e,this.processingActive=!1,this.processingTimeout=null}Ud.prototype.addClick=function(e){var t=this.shadowDOMObserver&&this.shadowDOMObserver.getEventTarget(e);return t||(t=e.target||e.srcElement),!(!t||Ad(t))&&(this.shadowDOMObserver&&this.shadowDOMObserver.observeFromEvent(e),this.pendingClicks.push({element:t,event:e,timestamp:Date.now()}),!0)},Ud.prototype.trackClick=function(e,t){if(!this.isTracking)return!1;var r=this.addClick(e);return r&&this.triggerProcessing(t),r},Ud.prototype.getDeadClicks=function(e){if(0===this.pendingClicks.length)return[];var t=e.timeout_ms,r=Date.now(),n=this.pendingClicks.slice();this.pendingClicks=[];for(var i=[],o=0;o<n.length;o++){var s=n[o];r-s.timestamp>=t?this.hasChangesAfter(s.timestamp)||i.push(s):this.pendingClicks.push(s)}return i},Ud.prototype.hasChangesAfter=function(e){return this.lastChangeEventTimestamp>=e-100},Ud.prototype.recordChangeEvent=function(){this.lastChangeEventTimestamp=Date.now()},Ud.prototype.triggerProcessing=function(e){this.processingActive||(this.processingActive=!0,this.processRecursively(e))},Ud.prototype.processRecursively=function(e){if(this.isTracking&&this.onDeadClickCallback){var t=e.timeout_ms,r=this;this.processingTimeout=setTimeout(function(){if(r.processingActive){for(var t=r.getDeadClicks(e),n=0;n<t.length;n++)r.onDeadClickCallback(t[n].event);r.pendingClicks.length>0?r.processRecursively(e):r.processingActive=!1}},t)}else this.processingActive=!1},Ud.prototype.startTracking=function(){if(!this.isTracking){this.isTracking=!0;var e=this;Td.forEach(function(t){var r=function(){e.recordChangeEvent()};document.addEventListener(t,r,{capture:!0,passive:!0}),e.eventListeners.push({target:document,event:t,handler:r,options:{capture:!0,passive:!0}})}),Rd.forEach(function(t){var r=function(){e.recordChangeEvent()};window.addEventListener(t,r),e.eventListeners.push({target:window,event:t,handler:r})}),Od.forEach(function(t){var r=function(){e.recordChangeEvent()};window.addEventListener(t,r,{passive:!0}),e.eventListeners.push({target:window,event:t,handler:r,options:{passive:!0}})});var t=function(){e.recordChangeEvent()};if(document.addEventListener("selectionchange",t),e.eventListeners.push({target:document,event:"selectionchange",handler:t}),window.MutationObserver)try{this.mutationObserver=new window.MutationObserver(function(){e.recordChangeEvent()}),this.mutationObserver.observe(document.body||document.documentElement,Ld)}catch(r){dd.critical("Error while setting up mutation observer",r)}if(window.customElements)try{this.shadowDOMObserver=new Bd(function(){e.recordChangeEvent()},Ld),this.shadowDOMObserver.start()}catch(r){dd.critical("Error while setting up shadow DOM observer",r),this.shadowDOMObserver=null}}},Ud.prototype.stopTracking=function(){if(this.isTracking){this.isTracking=!1,this.pendingClicks=[],this.lastChangeEventTimestamp=0,this.processingActive=!1,this.processingTimeout&&(clearTimeout(this.processingTimeout),this.processingTimeout=null);for(var e=0;e<this.eventListeners.length;e++){var t=this.eventListeners[e];try{t.target.removeEventListener(t.event,t.handler,t.options)}catch(r){dd.critical("Error while removing event listener",r)}}if(this.eventListeners=[],this.mutationObserver){try{this.mutationObserver.disconnect()}catch(r){dd.critical("Error while disconnecting mutation observer",r)}this.mutationObserver=null}if(this.shadowDOMObserver){try{this.shadowDOMObserver.stop()}catch(r){dd.critical("Error while stopping shadow DOM observer",r)}this.shadowDOMObserver=null}}};var jd="autocapture",Dd="full-url",Fd="allow_selectors",zd="allow_url_regexes",qd="block_attrs",Wd="block_element_callback",$d="block_selectors",Gd="block_url_regexes",Vd="capture_extra_attrs",Hd="capture_text_content",Kd="scroll_capture_all",Zd="scroll_depth_percent_checkpoints",Yd="click",Jd="dead_click",Xd="input",Qd="pageview",ep="rage_click",tp="scroll",rp="page_leave",np="submit",ip={};ip[Fd]=[],ip[zd]=[],ip[qd]=[],ip[Wd]=null,ip[$d]=[],ip[Gd]=[],ip[Vd]=[],ip[Hd]=!1,ip[Kd]=!1,ip[Zd]=[25,50,75,100],ip[Yd]=!0,ip[Jd]=!0,ip[Xd]=!0,ip[Qd]=Dd,ip[ep]=!0,ip[tp]=!0,ip[rp]=!1,ip[np]=!0;var op={$mp_autocapture:!0},sp="$mp_click",ap="$mp_dead_click",cp="$mp_rage_click",lp=function(e){this.mp=e,this.maxScrollViewDepth=0,this.hasTrackedScrollSession=!1,this.previousScrollHeight=0};lp.prototype.init=function(){!function(){try{return!!Ou.createElement("div").matches}catch(EE){return!1}}()?dd.critical("Autocapture unavailable: missing required DOM APIs"):(this.initPageListeners(),this.initPageviewTracking(),this.initClickTracking(),this.initDeadClickTracking(),this.initInputTracking(),this.initScrollTracking(),this.initSubmitTracking(),this.initRageClickTracking(),this.initPageLeaveTracking())},lp.prototype.getFullConfig=function(){var e=this.mp.get_config(jd);return e?$u.isObject(e)?$u.extend({},ip,e):ip:{}},lp.prototype.getConfig=function(e){return this.getFullConfig()[e]},lp.prototype.currentUrlBlocked=function(){var e,t=$u.info.currentUrl(),r=this.getConfig(zd)||[];if(r.length){var n=!1;for(e=0;e<r.length;e++){var i=r[e];try{if(t.match(i)){n=!0;break}}catch(EE){return dd.critical("Error while checking block URL regex: "+i,EE),!0}}if(!n)return!0}var o=this.getConfig(Gd)||[];if(!o||!o.length)return!1;for(e=0;e<o.length;e++)try{if(t.match(o[e]))return!0}catch(EE){return dd.critical("Error while checking block URL regex: "+o[e],EE),!0}return!1},lp.prototype.pageviewTrackingConfig=function(){return this.mp.get_config(jd)?this.getConfig(Qd):this.mp.get_config("track_pageview")},lp.prototype.trackDomEvent=function(e,t){if(!this.currentUrlBlocked()){var r=this.mp.is_recording_heatmap_data()&&(t===sp&&!this.getConfig(Yd)||t===cp&&!this._getClickTrackingConfig(ep)||t===ap&&!this._getClickTrackingConfig(Jd)),n=yd(e,{allowElementCallback:this.getConfig("allow_element_callback"),allowSelectors:this.getConfig(Fd),blockAttrs:this.getConfig(qd),blockElementCallback:this.getConfig(Wd),blockSelectors:this.getConfig($d),captureExtraAttrs:this.getConfig(Vd),captureTextContent:this.getConfig(Hd),capturedForHeatMap:r});n&&($u.extend(n,op),this.mp.track(t,n))}},lp.prototype.initPageListeners=function(){if(p.removeEventListener(Xh,this.listenerPopstate),p.removeEventListener(Zh,this.listenerHashchange),this.pageviewTrackingConfig()||this.getConfig(rp)||this.mp.get_config("record_heatmap_data")){this.listenerPopstate=function(){p.dispatchEvent(new Event(Jh))},this.listenerHashchange=function(){p.dispatchEvent(new Event(Jh))},p.addEventListener(Xh,this.listenerPopstate),p.addEventListener(Zh,this.listenerHashchange);var e=p.history.pushState;"function"==typeof e&&(p.history.pushState=function(t,r,n){e.call(p.history,t,r,n),p.dispatchEvent(new Event(Jh))});var t=p.history.replaceState;"function"==typeof t&&(p.history.replaceState=function(e,r,n){t.call(p.history,e,r,n),p.dispatchEvent(new Event(Jh))})}},lp.prototype._getClickTrackingConfig=function(e){var t=this.getConfig(e);return t?!0===t?{}:"object"==typeof t?t:{}:null},lp.prototype._trackPageLeave=function(e,t,r){if(!this.hasTrackedScrollSession&&(this.getConfig(rp)||this.mp.is_recording_heatmap_data())){this.hasTrackedScrollSession=!0;var n=Math.max(Ou.documentElement.clientHeight,p.innerHeight||0),i=Math.round(Math.max(this.maxScrollViewDepth-n,0)/(r-n)*100),o=Math.round(n/r*100);r<=n&&(i=100,o=100);var s=$u.extend({$max_scroll_view_depth:this.maxScrollViewDepth,$max_scroll_percentage:i,$fold_line_percentage:o,$scroll_height:r,$event_type:e.type,$current_url:t||$u.info.currentUrl(),$viewportHeight:n,$viewportWidth:Math.max(Ou.documentElement.clientWidth,p.innerWidth||0),$captured_for_heatmap:this.mp.is_recording_heatmap_data()},op);this.mp.track("$mp_page_leave",s,{transport:"sendBeacon"})}},lp.prototype._initScrollDepthTracking=function(){if(p.removeEventListener(ed,this.listenerScrollDepth),p.removeEventListener(Qh,this.listenerScrollDepth),this.mp.get_config("record_heatmap_data")){dd.log("Initializing scroll depth tracking"),this.maxScrollViewDepth=Math.max(Ou.documentElement.clientHeight,p.innerHeight||0);var e=Id(function(){if(!this.currentUrlBlocked()){var e=Math.max(Ou.documentElement.clientHeight,p.innerHeight||0)+p.scrollY;e>this.maxScrollViewDepth&&(this.maxScrollViewDepth=e),this.previousScrollHeight=Ou.body.scrollHeight}}.bind(this));this.listenerScrollDepth=e.listener,p.addEventListener(e.eventType,this.listenerScrollDepth)}},lp.prototype.initClickTracking=function(){p.removeEventListener(Kh,this.listenerClick),(this.getConfig(Yd)||this.mp.get_config("record_heatmap_data"))&&(dd.log("Initializing click tracking"),this.listenerClick=function(e){(this.getConfig(Yd)||this.mp.is_recording_heatmap_data())&&this.trackDomEvent(e,sp)}.bind(this),p.addEventListener(Kh,this.listenerClick))},lp.prototype.initDeadClickTracking=function(){this._getClickTrackingConfig(Jd)||this.mp.get_config("record_heatmap_data")?(dd.log("Initializing dead click tracking"),this._deadClickTracker||(this._deadClickTracker=new Ud(function(e){this.trackDomEvent(e,ap)}.bind(this)),this._deadClickTracker.startTracking()),this.listenerDeadClick||(this.listenerDeadClick=function(e){var t=this._getClickTrackingConfig(Jd);if((t||this.mp.is_recording_heatmap_data())&&!this.currentUrlBlocked()){var r=t||{};r.timeout_ms||(r.timeout_ms=500),this._deadClickTracker.trackClick(e,r)}}.bind(this),p.addEventListener(Kh,this.listenerDeadClick))):this.stopDeadClickTracking()},lp.prototype.initInputTracking=function(){p.removeEventListener(Hh,this.listenerChange),this.getConfig(Xd)&&(dd.log("Initializing input tracking"),this.listenerChange=function(e){this.getConfig(Xd)&&this.trackDomEvent(e,"$mp_input_change")}.bind(this),p.addEventListener(Hh,this.listenerChange))},lp.prototype.initPageviewTracking=function(){if(p.removeEventListener(Jh,this.listenerLocationchange),this.pageviewTrackingConfig()){dd.log("Initializing pageview tracking");var e="",t=!1;this.currentUrlBlocked()||(t=this.mp.track_pageview(op)),t&&(e=$u.info.currentUrl()),this.listenerLocationchange=Ku(function(){if(!this.currentUrlBlocked()){var t=$u.info.currentUrl(),r=!1,n=t.split("#")[0].split("?")[0]!==e.split("#")[0].split("?")[0],i=this.pageviewTrackingConfig();if(i===Dd?r=t!==e:"url-with-path-and-query-string"===i?r=t.split("#")[0]!==e.split("#")[0]:"url-with-path"===i&&(r=n),r)this.mp.track_pageview(op)&&(e=t),n&&(this.lastScrollCheckpoint=0,dd.log("Path change: re-initializing scroll depth checkpoints"))}}.bind(this)),p.addEventListener(Jh,this.listenerLocationchange)}},lp.prototype.initRageClickTracking=function(){p.removeEventListener(Kh,this.listenerRageClick),(this._getClickTrackingConfig(ep)||this.mp.get_config("record_heatmap_data"))&&(dd.log("Initializing rage click tracking"),this._rageClickTracker||(this._rageClickTracker=new Pd),this.listenerRageClick=function(e){var t=this._getClickTrackingConfig(ep);(t||this.mp.is_recording_heatmap_data())&&(this.currentUrlBlocked()||this._rageClickTracker.isRageClick(e,t)&&this.trackDomEvent(e,cp))}.bind(this),p.addEventListener(Kh,this.listenerRageClick))},lp.prototype.initScrollTracking=function(){if(p.removeEventListener(Qh,this.listenerScroll),p.removeEventListener(ed,this.listenerScroll),this.getConfig(tp)){dd.log("Initializing scroll tracking"),this.lastScrollCheckpoint=0;var e=Id(function(){if(this.getConfig(tp)&&!this.currentUrlBlocked()){var e=this.getConfig(Kd),t=(this.getConfig(Zd)||[]).slice().sort(function(e,t){return e-t}),r=p.scrollY,n=$u.extend({$scroll_top:r},op);try{var i=Ou.body.scrollHeight,o=Math.round(r/(i-p.innerHeight)*100);if(n.$scroll_height=i,n.$scroll_percentage=o,o>this.lastScrollCheckpoint)for(var s=0;s<t.length;s++){var a=t[s];o>=a&&this.lastScrollCheckpoint<a&&(n.$scroll_checkpoint=a,this.lastScrollCheckpoint=a,e=!0)}}catch(EE){dd.critical("Error while calculating scroll percentage",EE)}e&&this.mp.track("$mp_scroll",n)}}.bind(this));this.listenerScroll=e.listener,p.addEventListener(e.eventType,this.listenerScroll)}},lp.prototype.initSubmitTracking=function(){p.removeEventListener(td,this.listenerSubmit),this.getConfig(np)&&(dd.log("Initializing submit tracking"),this.listenerSubmit=function(e){this.getConfig(np)&&this.trackDomEvent(e,"$mp_submit")}.bind(this),p.addEventListener(td,this.listenerSubmit))},lp.prototype.initPageLeaveTracking=function(){if(Ou.removeEventListener(rd,this.listenerPageLeaveVisibilitychange),p.removeEventListener(Jh,this.listenerPageLeaveLocationchange),p.removeEventListener(Yh,this.listenerPageLoad),this.getConfig(rp)||this.mp.get_config("record_heatmap_data")){dd.log("Initializing page visibility tracking."),this._initScrollDepthTracking();var e=$u.info.currentUrl();this.listenerPageLoad=function(){this.previousScrollHeight=Ou.body.scrollHeight}.bind(this),p.addEventListener(Yh,this.listenerPageLoad),this.listenerPageLeaveLocationchange=Ku(function(t){if(!this.currentUrlBlocked()){var r=$u.info.currentUrl();r!==e&&(this._trackPageLeave(t,e,this.previousScrollHeight),e=r,this.maxScrollViewDepth=Math.max(Ou.documentElement.clientHeight,p.innerHeight||0),this.previousScrollHeight=Ou.body.scrollHeight,this.hasTrackedScrollSession=!1)}}.bind(this)),p.addEventListener(Jh,this.listenerPageLeaveLocationchange),this.listenerPageLeaveVisibilitychange=function(t){Ou.hidden&&this._trackPageLeave(t,e,this.previousScrollHeight)}.bind(this),Ou.addEventListener(rd,this.listenerPageLeaveVisibilitychange)}},lp.prototype.stopDeadClickTracking=function(){this.listenerDeadClick&&(p.removeEventListener(Kh,this.listenerDeadClick),this.listenerDeadClick=null),this._deadClickTracker&&(this._deadClickTracker.stopTracking(),this._deadClickTracker=null)},Zu(lp);var up=Hu("flags"),hp="flags",dp="context",pp={};pp[dp]={};var fp=function(e){this.fetch=p.fetch,this.getFullApiRoute=e.getFullApiRoute,this.getMpConfig=e.getConfigFunc,this.setMpConfig=e.setConfigFunc,this.getMpProperty=e.getPropertyFunc,this.track=e.trackingFunc};fp.prototype.init=function(){this.minApisSupported()?(this.flags=null,this.fetchFlags(),this.trackedFeatures=new Set):up.critical("Feature Flags unavailable: missing minimum required APIs")},fp.prototype.getFullConfig=function(){var e=this.getMpConfig(hp);return e?$u.isObject(e)?$u.extend({},pp,e):pp:{}},fp.prototype.getConfig=function(e){return this.getFullConfig()[e]},fp.prototype.isSystemEnabled=function(){return!!this.getMpConfig(hp)},fp.prototype.updateContext=function(e,t){if(!this.isSystemEnabled())return up.critical("Feature Flags not enabled, cannot update context"),Promise.resolve();var r=this.getMpConfig(hp);$u.isObject(r)||(r={});var n=t&&t.replace?{}:this.getConfig(dp);return r[dp]=$u.extend({},n,e),this.setMpConfig(hp,r),this.fetchFlags()},fp.prototype.areFlagsReady=function(){return this.isSystemEnabled()||up.error("Feature Flags not enabled"),!!this.flags},fp.prototype.fetchFlags=function(){if(!this.isSystemEnabled())return Promise.resolve();var e=this.getMpProperty("distinct_id"),t=this.getMpProperty("$device_id"),r="00-"+$u.UUID().replace(/-/g,"")+"-"+$u.UUID().replace(/-/g,"").substring(0,16)+"-01";up.log("Fetching flags for distinct ID: "+e);var n=$u.extend({distinct_id:e,device_id:t},this.getConfig(dp)),i=new URLSearchParams;i.set("context",JSON.stringify(n)),i.set("token",this.getMpConfig("token")),i.set("mp_lib","web"),i.set("$lib_version",_u.LIB_VERSION);var o=this.getFullApiRoute()+"?"+i.toString();return this._fetchInProgressStartTime=Date.now(),this.fetchPromise=this.fetch.call(p,o,{method:"GET",headers:{Authorization:"Basic "+btoa(this.getMpConfig("token")+":"),traceparent:r}}).then(function(e){return this.markFetchComplete(),e.json().then(function(e){var t=e.flags;if(!t)throw new Error("No flags in API response");var n=new Map;$u.each(t,function(e,t){n.set(t,{key:e.variant_key,value:e.variant_value,experiment_id:e.experiment_id,is_experiment_active:e.is_experiment_active,is_qa_tester:e.is_qa_tester})}),this.flags=n,this._traceparent=r}.bind(this)).catch(function(e){this.markFetchComplete(),up.error(e)}.bind(this))}.bind(this)).catch(function(e){this.markFetchComplete(),up.error(e)}.bind(this)),this.fetchPromise},fp.prototype.markFetchComplete=function(){this._fetchInProgressStartTime?(this._fetchStartTime=this._fetchInProgressStartTime,this._fetchCompleteTime=Date.now(),this._fetchLatency=this._fetchCompleteTime-this._fetchStartTime,this._fetchInProgressStartTime=null):up.error("Fetch in progress started time not set, cannot mark fetch complete")},fp.prototype.getVariant=function(e,t){return this.fetchPromise?this.fetchPromise.then(function(){return this.getVariantSync(e,t)}.bind(this)).catch(function(e){return up.error(e),t}):new Promise(function(e){up.critical("Feature Flags not initialized"),e(t)})},fp.prototype.getVariantSync=function(e,t){if(!this.areFlagsReady())return up.log("Flags not loaded yet"),t;var r=this.flags.get(e);return r?(this.trackFeatureCheck(e,r),r):(up.log('No flag found: "'+e+'"'),t)},fp.prototype.getVariantValue=function(e,t){return this.getVariant(e,{value:t}).then(function(e){return e.value}).catch(function(e){return up.error(e),t})},fp.prototype.getFeatureData=function(e,t){return up.critical("mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead."),this.getVariantValue(e,t)},fp.prototype.getVariantValueSync=function(e,t){return this.getVariantSync(e,{value:t}).value},fp.prototype.isEnabled=function(e,t){return this.getVariantValue(e).then(function(){return this.isEnabledSync(e,t)}.bind(this)).catch(function(e){return up.error(e),t})},fp.prototype.isEnabledSync=function(e,t){t=t||!1;var r=this.getVariantValueSync(e,t);return!0!==r&&!1!==r&&(up.error('Feature flag "'+e+'" value: '+r+" is not a boolean; returning fallback value: "+t),r=t),r},fp.prototype.trackFeatureCheck=function(e,t){if(!this.trackedFeatures.has(e)){this.trackedFeatures.add(e);var r={"Experiment name":e,"Variant name":t.key,$experiment_type:"feature_flag","Variant fetch start time":new Date(this._fetchStartTime).toISOString(),"Variant fetch complete time":new Date(this._fetchCompleteTime).toISOString(),"Variant fetch latency (ms)":this._fetchLatency,"Variant fetch traceparent":this._traceparent};"undefined"!==t.experiment_id&&(r.$experiment_id=t.experiment_id),"undefined"!==t.is_experiment_active&&(r.$is_experiment_active=t.is_experiment_active),"undefined"!==t.is_qa_tester&&(r.$is_qa_tester=t.is_qa_tester),this.track("$experiment_started",r)}},fp.prototype.minApisSupported=function(){return!!this.fetch&&"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set},Zu(fp),fp.prototype.are_flags_ready=fp.prototype.areFlagsReady,fp.prototype.get_variant=fp.prototype.getVariant,fp.prototype.get_variant_sync=fp.prototype.getVariantSync,fp.prototype.get_variant_value=fp.prototype.getVariantValue,fp.prototype.get_variant_value_sync=fp.prototype.getVariantValueSync,fp.prototype.is_enabled=fp.prototype.isEnabled,fp.prototype.is_enabled_sync=fp.prototype.isEnabledSync,fp.prototype.update_context=fp.prototype.updateContext,fp.prototype.get_feature_data=fp.prototype.getFeatureData;var mp=function(){};mp.prototype.create_properties=function(){},mp.prototype.event_handler=function(){},mp.prototype.after_track_handler=function(){},mp.prototype.init=function(e){return this.mp=e,this},mp.prototype.track=function(e,t,r,n){var i=this,o=$u.dom_query(e);if(0!==o.length)return $u.each(o,function(e){$u.register_event(e,this.override_event,function(e){var o={},s=i.create_properties(r,this),a=i.mp.get_config("track_links_timeout");i.event_handler(e,this,o),window.setTimeout(i.track_callback(n,s,o,!0),a),i.mp.track(t,s,i.track_callback(n,s,o))})},this),!0;Gu.error("The DOM query ("+e+") returned 0 elements")},mp.prototype.track_callback=function(e,t,r,n){n=n||!1;var i=this;return function(){r.callback_fired||(r.callback_fired=!0,e&&!1===e(n,t)||i.after_track_handler(t,r,n))}},mp.prototype.create_properties=function(e,t){return"function"==typeof e?e(t):$u.extend({},e)};var gp=function(){this.override_event="click"};$u.inherit(gp,mp),gp.prototype.create_properties=function(e,t){var r=gp.superclass.create_properties.apply(this,arguments);return t.href&&(r.url=t.href),r},gp.prototype.event_handler=function(e,t,r){r.new_tab=2===e.which||e.metaKey||e.ctrlKey||"_blank"===t.target,r.href=t.href,r.new_tab||e.preventDefault()},gp.prototype.after_track_handler=function(e,t){t.new_tab||setTimeout(function(){window.location=t.href},0)};var yp=function(){this.override_event="submit"};$u.inherit(yp,mp),yp.prototype.event_handler=function(e,t,r){r.element=t,e.preventDefault()},yp.prototype.after_track_handler=function(e,t){setTimeout(function(){t.element.submit()},0)};var vp="$set",bp="$set_once",wp="$unset",xp="$add",kp="$append",_p="$union",Sp="$remove",Cp={set_action:function(e,t){var r={},n={};return $u.isObject(e)?$u.each(e,function(e,t){this._is_reserved_property(t)||(n[t]=e)},this):n[e]=t,r[vp]=n,r},unset_action:function(e){var t={},r=[];return $u.isArray(e)||(e=[e]),$u.each(e,function(e){this._is_reserved_property(e)||r.push(e)},this),t[wp]=r,t},set_once_action:function(e,t){var r={},n={};return $u.isObject(e)?$u.each(e,function(e,t){this._is_reserved_property(t)||(n[t]=e)},this):n[e]=t,r[bp]=n,r},union_action:function(e,t){var r={},n={};return $u.isObject(e)?$u.each(e,function(e,t){this._is_reserved_property(t)||(n[t]=$u.isArray(e)?e:[e])},this):n[e]=$u.isArray(t)?t:[t],r[_p]=n,r},append_action:function(e,t){var r={},n={};return $u.isObject(e)?$u.each(e,function(e,t){this._is_reserved_property(t)||(n[t]=e)},this):n[e]=t,r[kp]=n,r},remove_action:function(e,t){var r={},n={};return $u.isObject(e)?$u.each(e,function(e,t){this._is_reserved_property(t)||(n[t]=e)},this):n[e]=t,r[Sp]=n,r},delete_action:function(){var e={$delete:""};return e}},Ip=function(){};$u.extend(Ip.prototype,Cp),Ip.prototype._init=function(e,t,r){this._mixpanel=e,this._group_key=t,this._group_id=r},Ip.prototype.set=kh(function(e,t,r){var n=this.set_action(e,t);return $u.isObject(e)&&(r=t),this._send_request(n,r)}),Ip.prototype.set_once=kh(function(e,t,r){var n=this.set_once_action(e,t);return $u.isObject(e)&&(r=t),this._send_request(n,r)}),Ip.prototype.unset=kh(function(e,t){var r=this.unset_action(e);return this._send_request(r,t)}),Ip.prototype.union=kh(function(e,t,r){$u.isObject(e)&&(r=t);var n=this.union_action(e,t);return this._send_request(n,r)}),Ip.prototype.delete=kh(function(e){var t=this.delete_action();return this._send_request(t,e)}),Ip.prototype.remove=kh(function(e,t,r){var n=this.remove_action(e,t);return this._send_request(n,r)}),Ip.prototype._send_request=function(e,t){e.$group_key=this._group_key,e.$group_id=this._group_id,e.$token=this._get_config("token");var r=$u.encodeDates(e);return this._mixpanel._track_or_batch({type:"groups",data:r,endpoint:this._mixpanel.get_api_host("groups")+"/"+this._get_config("api_routes").groups,batcher:this._mixpanel.request_batchers.groups},t)},Ip.prototype._is_reserved_property=function(e){return"$group_key"===e||"$group_id"===e},Ip.prototype._get_config=function(e){return this._mixpanel.get_config(e)},Ip.prototype.toString=function(){return this._mixpanel.toString()+".group."+this._group_key+"."+this._group_id},Ip.prototype.remove=Ip.prototype.remove,Ip.prototype.set=Ip.prototype.set,Ip.prototype.set_once=Ip.prototype.set_once,Ip.prototype.union=Ip.prototype.union,Ip.prototype.unset=Ip.prototype.unset,Ip.prototype.toString=Ip.prototype.toString;var Ep=function(){};$u.extend(Ep.prototype,Cp),Ep.prototype._init=function(e){this._mixpanel=e},Ep.prototype.set=xh(function(e,t,r){var n=this.set_action(e,t);return $u.isObject(e)&&(r=t),this._get_config("save_referrer")&&this._mixpanel.persistence.update_referrer_info(document.referrer),n[vp]=$u.extend({},$u.info.people_properties(),n[vp]),this._send_request(n,r)}),Ep.prototype.set_once=xh(function(e,t,r){var n=this.set_once_action(e,t);return $u.isObject(e)&&(r=t),this._send_request(n,r)}),Ep.prototype.unset=xh(function(e,t){var r=this.unset_action(e);return this._send_request(r,t)}),Ep.prototype.increment=xh(function(e,t,r){var n={},i={};return $u.isObject(e)?($u.each(e,function(e,t){if(!this._is_reserved_property(t)){if(isNaN(parseFloat(e)))return void Gu.error("Invalid increment value passed to mixpanel.people.increment - must be a number");i[t]=e}},this),r=t):($u.isUndefined(t)&&(t=1),i[e]=t),n[xp]=i,this._send_request(n,r)}),Ep.prototype.append=xh(function(e,t,r){$u.isObject(e)&&(r=t);var n=this.append_action(e,t);return this._send_request(n,r)}),Ep.prototype.remove=xh(function(e,t,r){$u.isObject(e)&&(r=t);var n=this.remove_action(e,t);return this._send_request(n,r)}),Ep.prototype.union=xh(function(e,t,r){$u.isObject(e)&&(r=t);var n=this.union_action(e,t);return this._send_request(n,r)}),Ep.prototype.track_charge=xh(function(){Gu.error("mixpanel.people.track_charge() is deprecated and no longer has any effect.")}),Ep.prototype.clear_charges=function(e){return this.set("$transactions",[],e)},Ep.prototype.delete_user=function(){if(this._identify_called()){var e={$delete:this._mixpanel.get_distinct_id()};return this._send_request(e)}Gu.error("mixpanel.people.delete_user() requires you to call identify() first")},Ep.prototype.toString=function(){return this._mixpanel.toString()+".people"},Ep.prototype._send_request=function(e,t){e.$token=this._get_config("token"),e.$distinct_id=this._mixpanel.get_distinct_id();var r=this._mixpanel.get_property("$device_id"),n=this._mixpanel.get_property("$user_id"),i=this._mixpanel.get_property("$had_persisted_distinct_id");r&&(e.$device_id=r),n&&(e.$user_id=n),i&&(e.$had_persisted_distinct_id=i);var o=$u.encodeDates(e);return this._identify_called()?this._mixpanel._track_or_batch({type:"people",data:o,endpoint:this._mixpanel.get_api_host("people")+"/"+this._get_config("api_routes").engage,batcher:this._mixpanel.request_batchers.people},t):(this._enqueue(e),$u.isUndefined(t)||(this._get_config("verbose")?t({status:-1,error:null}):t(-1)),$u.truncate(o,255))},Ep.prototype._get_config=function(e){return this._mixpanel.get_config(e)},Ep.prototype._identify_called=function(){return!0===this._mixpanel._flags.identify_called},Ep.prototype._enqueue=function(e){vp in e?this._mixpanel.persistence._add_to_people_queue(vp,e):bp in e?this._mixpanel.persistence._add_to_people_queue(bp,e):wp in e?this._mixpanel.persistence._add_to_people_queue(wp,e):xp in e?this._mixpanel.persistence._add_to_people_queue(xp,e):kp in e?this._mixpanel.persistence._add_to_people_queue(kp,e):Sp in e?this._mixpanel.persistence._add_to_people_queue(Sp,e):_p in e?this._mixpanel.persistence._add_to_people_queue(_p,e):Gu.error("Invalid call to _enqueue():",e)},Ep.prototype._flush_one_queue=function(e,t,r,n){var i=this,o=$u.extend({},this._mixpanel.persistence.load_queue(e)),s=o;$u.isUndefined(o)||!$u.isObject(o)||$u.isEmptyObject(o)||(i._mixpanel.persistence._pop_from_people_queue(e,o),i._mixpanel.persistence.save(),n&&(s=n(o)),t.call(i,s,function(t,n){0===t&&i._mixpanel.persistence._add_to_people_queue(e,o),$u.isUndefined(r)||r(t,n)}))},Ep.prototype._flush=function(e,t,r,n,i,o,s){var a=this;this._flush_one_queue(vp,this.set,e),this._flush_one_queue(bp,this.set_once,n),this._flush_one_queue(wp,this.unset,o,function(e){return $u.keys(e)}),this._flush_one_queue(xp,this.increment,t),this._flush_one_queue(_p,this.union,i);var c=this._mixpanel.persistence.load_queue(kp);if(!$u.isUndefined(c)&&$u.isArray(c)&&c.length)for(var l,u=function(e,t){0===e&&a._mixpanel.persistence._add_to_people_queue(kp,l),$u.isUndefined(r)||r(e,t)},h=c.length-1;h>=0;h--)c=this._mixpanel.persistence.load_queue(kp),l=c.pop(),a._mixpanel.persistence.save(),$u.isEmptyObject(l)||a.append(l,u);var d=this._mixpanel.persistence.load_queue(Sp);if(!$u.isUndefined(d)&&$u.isArray(d)&&d.length)for(var p,f=function(e,t){0===e&&a._mixpanel.persistence._add_to_people_queue(Sp,p),$u.isUndefined(s)||s(e,t)},m=d.length-1;m>=0;m--)d=this._mixpanel.persistence.load_queue(Sp),p=d.pop(),a._mixpanel.persistence.save(),$u.isEmptyObject(p)||a.remove(p,f)},Ep.prototype._is_reserved_property=function(e){return"$distinct_id"===e||"$token"===e||"$device_id"===e||"$user_id"===e||"$had_persisted_distinct_id"===e},Ep.prototype.set=Ep.prototype.set,Ep.prototype.set_once=Ep.prototype.set_once,Ep.prototype.unset=Ep.prototype.unset,Ep.prototype.increment=Ep.prototype.increment,Ep.prototype.append=Ep.prototype.append,Ep.prototype.remove=Ep.prototype.remove,Ep.prototype.union=Ep.prototype.union,Ep.prototype.track_charge=Ep.prototype.track_charge,Ep.prototype.clear_charges=Ep.prototype.clear_charges,Ep.prototype.delete_user=Ep.prototype.delete_user,Ep.prototype.toString=Ep.prototype.toString;var Ap,Mp="__mps",Np="__mpso",Pp="__mpus",Bp="__mpa",Tp="__mpap",Op="__mpr",Rp="__mpu",Lp="$people_distinct_id",Up="__alias",jp="__timers",Dp=[Mp,Np,Pp,Bp,Tp,Op,Rp,Lp,Up,jp],Fp=function(e){this.props={},this.campaign_params_saved=!1,e.persistence_name?this.name="mp_"+e.persistence_name:this.name="mp_"+e.token+"_mixpanel";var t=e.persistence;"cookie"!==t&&"localStorage"!==t&&(Gu.critical("Unknown persistence type "+t+"; falling back to cookie"),t=e.persistence="cookie"),"localStorage"===t&&$u.localStorage.is_supported()?this.storage=$u.localStorage:this.storage=$u.cookie,this.load(),this.update_config(e),this.upgrade(),this.save()};Fp.prototype.properties=function(){var e={};return this.load(),$u.each(this.props,function(t,r){$u.include(Dp,r)||(e[r]=t)}),e},Fp.prototype.load=function(){if(!this.disabled){var e=this.storage.parse(this.name);e&&(this.props=$u.extend({},e))}},Fp.prototype.upgrade=function(){var e,t;this.storage===$u.localStorage?(e=$u.cookie.parse(this.name),$u.cookie.remove(this.name),$u.cookie.remove(this.name,!0),e&&this.register_once(e)):this.storage===$u.cookie&&(t=$u.localStorage.parse(this.name),$u.localStorage.remove(this.name),t&&this.register_once(t))},Fp.prototype.save=function(){this.disabled||this.storage.set(this.name,uh(this.props),this.expire_days,this.cross_subdomain,this.secure,this.cross_site,this.cookie_domain)},Fp.prototype.load_prop=function(e){return this.load(),this.props[e]},Fp.prototype.remove=function(){this.storage.remove(this.name,!1,this.cookie_domain),this.storage.remove(this.name,!0,this.cookie_domain)},Fp.prototype.clear=function(){this.remove(),this.props={}},Fp.prototype.register_once=function(e,t,r){return!!$u.isObject(e)&&(void 0===t&&(t="None"),this.expire_days=void 0===r?this.default_expiry:r,this.load(),$u.each(e,function(e,r){this.props.hasOwnProperty(r)&&this.props[r]!==t||(this.props[r]=e)},this),this.save(),!0)},Fp.prototype.register=function(e,t){return!!$u.isObject(e)&&(this.expire_days=void 0===t?this.default_expiry:t,this.load(),$u.extend(this.props,e),this.save(),!0)},Fp.prototype.unregister=function(e){this.load(),e in this.props&&(delete this.props[e],this.save())},Fp.prototype.update_search_keyword=function(e){this.register($u.info.searchInfo(e))},Fp.prototype.update_referrer_info=function(e){this.register_once({$initial_referrer:e||"$direct",$initial_referring_domain:$u.info.referringDomain(e)||"$direct"},"")},Fp.prototype.get_referrer_info=function(){return $u.strip_empty_properties({$initial_referrer:this.props.$initial_referrer,$initial_referring_domain:this.props.$initial_referring_domain})},Fp.prototype.update_config=function(e){this.default_expiry=this.expire_days=e.cookie_expiration,this.set_disabled(e.disable_persistence),this.set_cookie_domain(e.cookie_domain),this.set_cross_site(e.cross_site_cookie),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie)},Fp.prototype.set_disabled=function(e){this.disabled=e,this.disabled?this.remove():this.save()},Fp.prototype.set_cookie_domain=function(e){e!==this.cookie_domain&&(this.remove(),this.cookie_domain=e,this.save())},Fp.prototype.set_cross_site=function(e){e!==this.cross_site&&(this.cross_site=e,this.remove(),this.save())},Fp.prototype.set_cross_subdomain=function(e){e!==this.cross_subdomain&&(this.cross_subdomain=e,this.remove(),this.save())},Fp.prototype.get_cross_subdomain=function(){return this.cross_subdomain},Fp.prototype.set_secure=function(e){e!==this.secure&&(this.secure=!!e,this.remove(),this.save())},Fp.prototype._add_to_people_queue=function(e,t){var r=this._get_queue_key(e),n=t[e],i=this._get_or_create_queue(vp),o=this._get_or_create_queue(bp),s=this._get_or_create_queue(wp),a=this._get_or_create_queue(xp),c=this._get_or_create_queue(_p),l=this._get_or_create_queue(Sp,[]),u=this._get_or_create_queue(kp,[]);r===Mp?($u.extend(i,n),this._pop_from_people_queue(xp,n),this._pop_from_people_queue(_p,n),this._pop_from_people_queue(wp,n)):r===Np?($u.each(n,function(e,t){t in o||(o[t]=e)}),this._pop_from_people_queue(wp,n)):r===Pp?$u.each(n,function(e){$u.each([i,o,a,c],function(t){e in t&&delete t[e]}),$u.each(u,function(t){e in t&&delete t[e]}),s[e]=!0}):r===Bp?($u.each(n,function(e,t){t in i?i[t]+=e:(t in a||(a[t]=0),a[t]+=e)},this),this._pop_from_people_queue(wp,n)):r===Rp?($u.each(n,function(e,t){$u.isArray(e)&&(t in c||(c[t]=[]),$u.each(e,function(e){$u.include(c[t],e)||c[t].push(e)}))}),this._pop_from_people_queue(wp,n)):r===Op?(l.push(n),this._pop_from_people_queue(kp,n)):r===Tp&&(u.push(n),this._pop_from_people_queue(wp,n)),Gu.log("MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):"),Gu.log(t),this.save()},Fp.prototype._pop_from_people_queue=function(e,t){var r=this.props[this._get_queue_key(e)];$u.isUndefined(r)||$u.each(t,function(t,n){e===kp||e===Sp?$u.each(r,function(e){e[n]===t&&delete e[n]}):delete r[n]},this)},Fp.prototype.load_queue=function(e){return this.load_prop(this._get_queue_key(e))},Fp.prototype._get_queue_key=function(e){return e===vp?Mp:e===bp?Np:e===wp?Pp:e===xp?Bp:e===kp?Tp:e===Sp?Op:e===_p?Rp:void Gu.error("Invalid queue:",e)},Fp.prototype._get_or_create_queue=function(e,t){var r=this._get_queue_key(e);return t=$u.isUndefined(t)?{}:t,this.props[r]||(this.props[r]=t)},Fp.prototype.set_event_timer=function(e,t){var r=this.load_prop(jp)||{};r[e]=t,this.props[jp]=r,this.save()},Fp.prototype.remove_event_timer=function(e){var t=(this.load_prop(jp)||{})[e];return $u.isUndefined(t)||(delete this.props[jp][e],this.save()),t};var zp,qp=function(e,t){throw new Error(e+" not available in this build.")},Wp=function(e){return e},$p="mixpanel",Gp="base64",Vp="$device:",Hp=p.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,Kp=!Hp&&-1===Uu.indexOf("MSIE")&&-1===Uu.indexOf("Mozilla"),Zp=null;Tu.sendBeacon&&(Zp=function(){return Tu.sendBeacon.apply(Tu,arguments)});var Yp={track:"track/",engage:"engage/",groups:"groups/",record:"record/",flags:"flags/"},Jp={api_host:"https://api-js.mixpanel.com",api_hosts:{},api_routes:Yp,api_extra_query_params:{},api_method:"POST",api_transport:"XHR",api_payload_format:Gp,app_host:"https://mixpanel.com",autocapture:!1,cdn:"https://cdn.mxpnl.com",cross_site_cookie:!1,cross_subdomain_cookie:!0,error_reporter:lh,flags:!1,persistence:"cookie",persistence_name:"",cookie_domain:"",cookie_name:"",loaded:lh,mp_loader:null,track_marketing:!0,track_pageview:!1,skip_first_touch_marketing:!1,store_google:!0,stop_utm_persistence:!1,save_referrer:!0,test:!1,verbose:!1,img:!1,debug:!1,track_links_timeout:300,cookie_expiration:365,upgrade:!1,disable_persistence:!1,disable_cookie:!1,secure_cookie:!1,ip:!0,opt_out_tracking_by_default:!1,opt_out_persistence_by_default:!1,opt_out_tracking_persistence_type:"localStorage",opt_out_tracking_cookie_prefix:null,property_blacklist:[],xhr_headers:{},ignore_dnt:!1,batch_requests:!0,batch_size:50,batch_flush_interval_ms:5e3,batch_request_timeout_ms:9e4,batch_autostart:!0,hooks:{},record_block_class:new RegExp("^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$"),record_block_selector:"img, video, audio",record_canvas:!1,record_collect_fonts:!1,record_console:!0,record_heatmap_data:!1,record_idle_timeout_ms:18e5,record_mask_text_class:new RegExp("^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$"),record_mask_text_selector:"*",record_max_ms:Su,record_min_ms:0,record_sessions_percent:0,recorder_src:"https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js"},Xp=!1,Qp=function(){},ef=function(e,t,r){var n,i=r===$p?zp:zp[r];if(i&&0===Ap)n=i;else{if(i&&!$u.isArray(i))return void Gu.error("You have already initialized "+r);n=new Qp}if(n._cached_groups={},n._init(e,t,r),n.people=new Ep,n.people._init(n),!n.get_config("skip_first_touch_marketing")){var o=$u.info.campaignParams(null),s={},a=!1;$u.each(o,function(e,t){s["initial_"+t]=e,e&&(a=!0)}),a&&n.people.set_once(s)}return _u.DEBUG=_u.DEBUG||n.get_config("debug"),!$u.isUndefined(i)&&$u.isArray(i)&&(n._execute_array.call(n.people,i.people),n._execute_array(i)),n};Qp.prototype.init=function(e,t,r){if($u.isUndefined(r))this.report_error("You must name your new library: init(token, config, name)");else{if(r!==$p){var n=ef(e,t,r);return zp[r]=n,n._loaded(),n}this.report_error("You must initialize the main mixpanel object right after you include the Mixpanel js snippet")}},Qp.prototype._init=function(e,t,r){t=t||{},this.__loaded=!0,this.config={};var n={};"api_payload_format"in t||(t.api_host||Jp.api_host).match(/\.mixpanel\.com/)&&(n.api_payload_format="json");if(this.set_config($u.extend({},Jp,n,t,{name:r,token:e,callback_fn:(r===$p?r:$p+"."+r)+"._jsc"})),this._jsc=lh,this.__dom_loaded_queue=[],this.__request_queue=[],this.__disabled_events=[],this._flags={disable_all_events:!1,identify_called:!1},this.request_batchers={},this._batch_requests=this.get_config("batch_requests"),this._batch_requests)if($u.localStorage.is_supported(!0)&&Hp){if(this.init_batchers(),Zp&&p.addEventListener){var i=$u.bind(function(){this.request_batchers.events.stopped||this.request_batchers.events.flush({unloading:!0})},this);p.addEventListener("pagehide",function(e){e.persisted&&i()}),p.addEventListener("visibilitychange",function(){"hidden"===Ou.visibilityState&&i()})}}else this._batch_requests=!1,Gu.log("Turning off Mixpanel request-queueing; needs XHR and localStorage support"),$u.each(this.get_batcher_configs(),function(e){Gu.log("Clearing batch queue "+e.queue_key),$u.localStorage.remove(e.queue_key)});this.persistence=this.cookie=new Fp(this.config),this.unpersisted_superprops={},this._gdpr_init();var o=$u.UUID();this.get_distinct_id()||this.register_once({distinct_id:Vp+o,$device_id:o},""),this.flags=new fp({getFullApiRoute:$u.bind(function(){return this.get_api_host("flags")+"/"+this.get_config("api_routes").flags},this),getConfigFunc:$u.bind(this.get_config,this),setConfigFunc:$u.bind(this.set_config,this),getPropertyFunc:$u.bind(this.get_property,this),trackingFunc:$u.bind(this.track,this)}),this.flags.init(),this.flags=this.flags,this.autocapture=new lp(this),this.autocapture.init(),this._init_tab_id(),this._check_and_start_session_recording()},Qp.prototype._init_tab_id=function(){if(this.get_config("disable_persistence"))Gu.log("Tab ID initialization skipped due to disable_persistence config");else if($u.sessionStorage.is_supported())try{var e=this.get_config("name")+"_"+this.get_config("token"),t="mp_tab_id_"+e,r="mp_gen_new_tab_id_"+e;!$u.sessionStorage.get(r)&&$u.sessionStorage.get(t)||$u.sessionStorage.set(t,"$tab-"+$u.UUID()),$u.sessionStorage.set(r,"1"),this.tab_id=$u.sessionStorage.get(t),p.addEventListener("beforeunload",function(){$u.sessionStorage.remove(r)})}catch(EE){this.report_error("Error initializing tab id",EE)}else this.report_error("Session storage is not supported, cannot keep track of unique tab ID.")},Qp.prototype.get_tab_id=function(){return this.tab_id||null},Qp.prototype._should_load_recorder=function(){if(this.get_config("disable_persistence"))return Gu.log("Load recorder check skipped due to disable_persistence config"),Promise.resolve(!1);var e=new mh(ph),t=this.get_tab_id();return e.init().then(function(){return e.getAll()}).then(function(e){for(var r=0;r<e.length;r++)if(jh(e[r])||e[r].tabId===t)return!0;return!1}).catch($u.bind(function(e){this.report_error("Error checking recording registry",e)},this))},Qp.prototype._check_and_start_session_recording=wh(function(e){if(p.MutationObserver){var t=$u.bind(function(e){var t=$u.bind(function(){this._recorder=this._recorder||new p.__mp_recorder(this),this._recorder.resumeRecording(e)},this);$u.isUndefined(p.__mp_recorder)?qp(this.get_config("recorder_src"),t):t()},this),r=this.get_config("record_sessions_percent")>0&&100*Math.random()<=this.get_config("record_sessions_percent");e||r?t(!0):this._should_load_recorder().then(function(e){e&&t(!1)})}else Gu.critical("Browser does not support MutationObserver; skipping session recording")}),Qp.prototype.start_session_recording=function(){this._check_and_start_session_recording(!0)},Qp.prototype.stop_session_recording=function(){return this._recorder?this._recorder.stopRecording():Promise.resolve()},Qp.prototype.pause_session_recording=function(){return this._recorder?this._recorder.pauseRecording():Promise.resolve()},Qp.prototype.resume_session_recording=function(){return this._recorder?this._recorder.resumeRecording():Promise.resolve()},Qp.prototype.is_recording_heatmap_data=function(){return this._get_session_replay_id()&&this.get_config("record_heatmap_data")},Qp.prototype.get_session_recording_properties=function(){var e={},t=this._get_session_replay_id();return t&&(e.$mp_replay_id=t),e},Qp.prototype.get_session_replay_url=function(){var e=null,t=this._get_session_replay_id();t&&(e="https://mixpanel.com/projects/replay-redirect?"+$u.HTTPBuildQuery({replay_id:t,distinct_id:this.get_distinct_id(),token:this.get_config("token")}));return e},Qp.prototype._get_session_replay_id=function(){var e=null;return this._recorder&&(e=this._recorder.replayId),e||null},Qp.prototype.__get_recorder=function(){return this._recorder},Qp.prototype._loaded=function(){if(this.get_config("loaded")(this),this._set_default_superprops(),this.people.set_once(this.persistence.get_referrer_info()),this.get_config("store_google")&&this.get_config("stop_utm_persistence")){var e=$u.info.campaignParams(null);$u.each(e,function(e,t){this.unregister(t)}.bind(this))}},Qp.prototype._set_default_superprops=function(){this.persistence.update_search_keyword(Ou.referrer),this.get_config("store_google")&&!this.get_config("stop_utm_persistence")&&this.register($u.info.campaignParams()),this.get_config("save_referrer")&&this.persistence.update_referrer_info(Ou.referrer)},Qp.prototype._dom_loaded=function(){$u.each(this.__dom_loaded_queue,function(e){this._track_dom.apply(this,e)},this),this.has_opted_out_tracking()||$u.each(this.__request_queue,function(e){this._send_request.apply(this,e)},this),delete this.__dom_loaded_queue,delete this.__request_queue},Qp.prototype._track_dom=function(e,t){if(this.get_config("img"))return this.report_error("You can't use DOM tracking functions with img = true."),!1;if(!Xp)return this.__dom_loaded_queue.push([e,t]),!1;var r=(new e).init(this);return r.track.apply(r,t)},Qp.prototype._prepare_callback=function(e,t){if($u.isUndefined(e))return null;if(Hp){return function(r){e(r,t)}}var r=this._jsc,n=""+Math.floor(1e8*Math.random()),i=this.get_config("callback_fn")+"["+n+"]";return r[n]=function(i){delete r[n],e(i,t)},i},Qp.prototype._send_request=function(e,t,r,n){var i=!0;if(Kp)return this.__request_queue.push(arguments),i;var o={method:this.get_config("api_method"),transport:this.get_config("api_transport"),verbose:this.get_config("verbose")},s=null;n||!$u.isFunction(r)&&"string"!=typeof r||(n=r,r=null),r=$u.extend(o,r||{}),Hp||(r.method="GET");var a="POST"===r.method,c=Zp&&a&&"sendbeacon"===r.transport.toLowerCase(),l=r.verbose;t.verbose&&(l=!0),this.get_config("test")&&(t.test=1),l&&(t.verbose=1),this.get_config("img")&&(t.img=1),Hp||(n?t.callback=n:(l||this.get_config("test"))&&(t.callback="(function(){})")),t.ip=this.get_config("ip")?1:0,t._=(new Date).getTime().toString(),a&&(s="data="+encodeURIComponent(t.data),delete t.data),$u.extend(t,this.get_config("api_extra_query_params")),e+="?"+$u.HTTPBuildQuery(t);var u=this;if("img"in t){var h=Ou.createElement("img");h.src=e,Ou.body.appendChild(h)}else if(c){try{i=Zp(e,s)}catch(y){u.report_error(y),i=!1}try{n&&n(i?1:0)}catch(y){u.report_error(y)}}else if(Hp)try{var d=new XMLHttpRequest;d.open(r.method,e,!0);var p=this.get_config("xhr_headers");if(a&&(p["Content-Type"]="application/x-www-form-urlencoded"),$u.each(p,function(e,t){d.setRequestHeader(t,e)}),r.timeout_ms&&void 0!==d.timeout){d.timeout=r.timeout_ms;var f=(new Date).getTime()}d.withCredentials=!0,d.onreadystatechange=function(){var e;if(4===d.readyState)if(200===d.status){if(n)if(l){var t;try{t=$u.JSONDecode(d.responseText)}catch(y){if(u.report_error(y),!r.ignore_json_errors)return;t=d.responseText}n(t)}else n(Number(d.responseText))}else if(e=d.timeout&&!d.status&&(new Date).getTime()-f>=d.timeout?"timeout":"Bad HTTP status: "+d.status+" "+d.statusText,u.report_error(e),n)if(l){var i=d.responseHeaders||{};n({status:0,httpStatusCode:d.status,error:e,retryAfter:i["Retry-After"]})}else n(0)},d.send(s)}catch(y){u.report_error(y),i=!1}else{var m=Ou.createElement("script");m.type="text/javascript",m.async=!0,m.defer=!0,m.src=e;var g=Ou.getElementsByTagName("script")[0];g.parentNode.insertBefore(m,g)}return i},Qp.prototype._execute_array=function(e){var t,r=[],n=[],i=[];$u.each(e,function(e){e&&(t=e[0],$u.isArray(t)?i.push(e):"function"==typeof e?e.call(this):$u.isArray(e)&&"alias"===t?r.push(e):$u.isArray(e)&&-1!==t.indexOf("track")&&"function"==typeof this[t]?i.push(e):n.push(e))},this);var o=function(e,t){$u.each(e,function(e){if($u.isArray(e[0])){var r=t;$u.each(e,function(e){r=r[e[0]].apply(r,e.slice(1))})}else this[e[0]].apply(this,e.slice(1))},t)};o(r,this),o(n,this),o(i,this)},Qp.prototype.are_batchers_initialized=function(){return!!this.request_batchers.events},Qp.prototype.get_batcher_configs=function(){var e="__mpq_"+this.get_config("token");return this._batcher_configs=this._batcher_configs||{events:{type:"events",api_name:"track",queue_key:e+"_ev"},people:{type:"people",api_name:"engage",queue_key:e+"_pp"},groups:{type:"groups",api_name:"groups",queue_key:e+"_gr"}},this._batcher_configs},Qp.prototype.init_batchers=function(){if(!this.are_batchers_initialized()){var e=$u.bind(function(e){return new Uh(e.queue_key,{libConfig:this.config,errorReporter:this.get_config("error_reporter"),sendRequestFunc:$u.bind(function(t,r,n){var i=this.get_config("api_routes");this._send_request(this.get_api_host(e.api_name)+"/"+i[e.api_name],this._encode_data_for_request(t),r,this._prepare_callback(n,t))},this),beforeSendHook:$u.bind(function(t){return this._run_hook("before_send_"+e.type,t)},this),stopAllBatchingFunc:$u.bind(this.stop_batch_senders,this),usePersistence:!0})},this),t=this.get_batcher_configs();this.request_batchers={events:e(t.events),people:e(t.people),groups:e(t.groups)}}this.get_config("batch_autostart")&&this.start_batch_senders()},Qp.prototype.start_batch_senders=function(){this._batchers_were_started=!0,this.are_batchers_initialized()&&(this._batch_requests=!0,$u.each(this.request_batchers,function(e){e.start()}))},Qp.prototype.stop_batch_senders=function(){this._batch_requests=!1,$u.each(this.request_batchers,function(e){e.stop(),e.clear()})},Qp.prototype.push=function(e){this._execute_array([e])},Qp.prototype.disable=function(e){void 0===e?this._flags.disable_all_events=!0:this.__disabled_events=this.__disabled_events.concat(e)},Qp.prototype._encode_data_for_request=function(e){var t=uh(e);return this.get_config("api_payload_format")===Gp&&(t=$u.base64Encode(t)),{data:t}},Qp.prototype._track_or_batch=function(e,t){var r=$u.truncate(e.data,255),n=e.endpoint,i=e.batcher,o=e.should_send_immediately,s=e.send_request_options||{};t=t||lh;var a=!0,c=$u.bind(function(){return s.skip_hooks||(r=this._run_hook("before_send_"+e.type,r)),r?(Gu.log("MIXPANEL REQUEST:"),Gu.log(r),this._send_request(n,this._encode_data_for_request(r),s,this._prepare_callback(t,r))):null},this);return this._batch_requests&&!o?i.enqueue(r).then(function(e){e?t(1,r):c()}):a=c(),a&&r},Qp.prototype.track=wh(function(e,t,r,n){n||"function"!=typeof r||(n=r,r=null);var i=(r=r||{}).transport;i&&(r.transport=i);var o=r.send_immediately;if("function"!=typeof n&&(n=lh),$u.isUndefined(e))this.report_error("No event name provided to mixpanel.track");else{if(!this._event_is_disabled(e)){(t=$u.extend({},t)).token=this.get_config("token");var s=this.persistence.remove_event_timer(e);if(!$u.isUndefined(s)){var a=(new Date).getTime()-s;t.$duration=parseFloat((a/1e3).toFixed(3))}this._set_default_superprops();var c=this.get_config("track_marketing")?$u.info.marketingParams():{};t=$u.extend({},$u.info.properties({mp_loader:this.get_config("mp_loader")}),c,this.persistence.properties(),this.unpersisted_superprops,this.get_session_recording_properties(),t);var l=this.get_config("property_blacklist");$u.isArray(l)?$u.each(l,function(e){delete t[e]}):this.report_error("Invalid value for property_blacklist config: "+l);var u={event:e,properties:t};return this._track_or_batch({type:"events",data:u,endpoint:this.get_api_host("events")+"/"+this.get_config("api_routes").track,batcher:this.request_batchers.events,should_send_immediately:o,send_request_options:r},n)}n(0)}}),Qp.prototype.set_group=wh(function(e,t,r){$u.isArray(t)||(t=[t]);var n={};return n[e]=t,this.register(n),this.people.set(e,t,r)}),Qp.prototype.add_group=wh(function(e,t,r){var n=this.get_property(e),i={};return void 0===n?(i[e]=[t],this.register(i)):-1===n.indexOf(t)&&(n.push(t),i[e]=n,this.register(i)),this.people.union(e,t,r)}),Qp.prototype.remove_group=wh(function(e,t,r){var n=this.get_property(e);if(void 0!==n){var i=n.indexOf(t);i>-1&&(n.splice(i,1),this.register({group_key:n})),0===n.length&&this.unregister(e)}return this.people.remove(e,t,r)}),Qp.prototype.track_with_groups=wh(function(e,t,r,n){var i=$u.extend({},t||{});return $u.each(r,function(e,t){null!=e&&(i[t]=e)}),this.track(e,i,n)}),Qp.prototype._create_map_key=function(e,t){return e+"_"+JSON.stringify(t)},Qp.prototype._remove_group_from_cache=function(e,t){delete this._cached_groups[this._create_map_key(e,t)]},Qp.prototype.get_group=function(e,t){var r=this._create_map_key(e,t),n=this._cached_groups[r];return void 0!==n&&n._group_key===e&&n._group_id===t||((n=new Ip)._init(this,e,t),this._cached_groups[r]=n),n},Qp.prototype.track_pageview=wh(function(e,t){"object"!=typeof e&&(e={});var r=(t=t||{}).event_name||"$mp_web_page_view",n=$u.extend($u.info.mpPageViewProperties(),$u.info.campaignParams(),$u.info.clickParams()),i=$u.extend({},n,e);return this.track(r,i)}),Qp.prototype.track_links=function(){return this._track_dom.call(this,gp,arguments)},Qp.prototype.track_forms=function(){return this._track_dom.call(this,yp,arguments)},Qp.prototype.time_event=function(e){$u.isUndefined(e)?this.report_error("No event name provided to mixpanel.time_event"):this._event_is_disabled(e)||this.persistence.set_event_timer(e,(new Date).getTime())};var tf={persistent:!0},rf=function(e){var t;return t=$u.isObject(e)?e:$u.isUndefined(e)?{}:{days:e},$u.extend({},tf,t)};Qp.prototype.register=function(e,t){var r=rf(t);r.persistent?this.persistence.register(e,r.days):$u.extend(this.unpersisted_superprops,e)},Qp.prototype.register_once=function(e,t,r){var n=rf(r);n.persistent?this.persistence.register_once(e,t,n.days):(void 0===t&&(t="None"),$u.each(e,function(e,r){this.unpersisted_superprops.hasOwnProperty(r)&&this.unpersisted_superprops[r]!==t||(this.unpersisted_superprops[r]=e)},this))},Qp.prototype.unregister=function(e,t){(t=rf(t)).persistent?this.persistence.unregister(e):delete this.unpersisted_superprops[e]},Qp.prototype._register_single=function(e,t){var r={};r[e]=t,this.register(r)},Qp.prototype.identify=function(e,t,r,n,i,o,s,a){var c=this.get_distinct_id();if(e&&c!==e){if("string"==typeof e&&0===e.indexOf(Vp))return this.report_error("distinct_id cannot have $device: prefix"),-1;this.register({$user_id:e})}if(!this.get_property("$device_id")){var l=c;this.register_once({$had_persisted_distinct_id:!0,$device_id:l},"")}e!==c&&e!==this.get_property(Up)&&(this.unregister(Up),this.register({distinct_id:e})),this._flags.identify_called=!0,this.people._flush(t,r,n,i,o,s,a),e!==c&&this.track("$identify",{distinct_id:e,$anon_distinct_id:c},{skip_hooks:!0}),e!==c&&this.flags.fetchFlags()},Qp.prototype.reset=function(){this.stop_session_recording(),this.persistence.clear(),this._flags.identify_called=!1;var e=$u.UUID();this.register_once({distinct_id:Vp+e,$device_id:e},""),this._check_and_start_session_recording()},Qp.prototype.get_distinct_id=function(){return this.get_property("distinct_id")},Qp.prototype.alias=function(e,t){if(e===this.get_property(Lp))return this.report_error("Attempting to create alias for existing People user - aborting."),-2;var r=this;return $u.isUndefined(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(Up,e),this.track("$create_alias",{alias:e,distinct_id:t},{skip_hooks:!0},function(){r.identify(e)})):(this.report_error("alias matches current distinct_id - skipping api call."),this.identify(e),-1)},Qp.prototype.name_tag=function(e){this._register_single("mp_name_tag",e)},Qp.prototype.set_config=function(e){$u.isObject(e)&&($u.extend(this.config,e),e.batch_size&&$u.each(this.request_batchers,function(e){e.resetBatchSize()}),this.get_config("persistence_name")||(this.config.persistence_name=this.config.cookie_name),this.get_config("disable_persistence")||(this.config.disable_persistence=this.config.disable_cookie),this.persistence&&this.persistence.update_config(this.config),_u.DEBUG=_u.DEBUG||this.get_config("debug"),("autocapture"in e||"record_heatmap_data"in e)&&this.autocapture&&this.autocapture.init())},Qp.prototype.get_config=function(e){return this.config[e]},Qp.prototype._run_hook=function(e){var t=(this.config.hooks[e]||Wp).apply(this,Mu.call(arguments,1));return void 0===t&&(this.report_error(e+" hook did not return a value"),t=null),t},Qp.prototype.get_property=function(e){return this.persistence.load_prop([e])},Qp.prototype.get_api_host=function(e){return this.get_config("api_hosts")[e]||this.get_config("api_host")},Qp.prototype.toString=function(){var e=this.get_config("name");return e!==$p&&(e=$p+"."+e),e},Qp.prototype._event_is_disabled=function(e){return $u.isBlockedUA(Uu)||this._flags.disable_all_events||$u.include(this.__disabled_events,e)},Qp.prototype._gdpr_init=function(){"localStorage"===this.get_config("opt_out_tracking_persistence_type")&&$u.localStorage.is_supported()&&(!this.has_opted_in_tracking()&&this.has_opted_in_tracking({persistence_type:"cookie"})&&this.opt_in_tracking({enable_persistence:!1}),!this.has_opted_out_tracking()&&this.has_opted_out_tracking({persistence_type:"cookie"})&&this.opt_out_tracking({clear_persistence:!1}),this.clear_opt_in_out_tracking({persistence_type:"cookie",enable_persistence:!1})),this.has_opted_out_tracking()?this._gdpr_update_persistence({clear_persistence:!0}):this.has_opted_in_tracking()||!this.get_config("opt_out_tracking_by_default")&&!$u.cookie.get("mp_optout")||($u.cookie.remove("mp_optout"),this.opt_out_tracking({clear_persistence:this.get_config("opt_out_persistence_by_default")}))},Qp.prototype._gdpr_update_persistence=function(e){var t;if(e&&e.clear_persistence)t=!0;else{if(!e||!e.enable_persistence)return;t=!1}this.get_config("disable_persistence")||this.persistence.disabled===t||this.persistence.set_disabled(t),t?(this.stop_batch_senders(),this.stop_session_recording()):this._batchers_were_started&&this.start_batch_senders()},Qp.prototype._gdpr_call_func=function(e,t){return t=$u.extend({track:$u.bind(this.track,this),persistence_type:this.get_config("opt_out_tracking_persistence_type"),cookie_prefix:this.get_config("opt_out_tracking_cookie_prefix"),cookie_expiration:this.get_config("cookie_expiration"),cross_site_cookie:this.get_config("cross_site_cookie"),cross_subdomain_cookie:this.get_config("cross_subdomain_cookie"),cookie_domain:this.get_config("cookie_domain"),secure_cookie:this.get_config("secure_cookie"),ignore_dnt:this.get_config("ignore_dnt")},t),$u.localStorage.is_supported()||(t.persistence_type="cookie"),e(this.get_config("token"),{track:t.track,trackEventName:t.track_event_name,trackProperties:t.track_properties,persistenceType:t.persistence_type,persistencePrefix:t.cookie_prefix,cookieDomain:t.cookie_domain,cookieExpiration:t.cookie_expiration,crossSiteCookie:t.cross_site_cookie,crossSubdomainCookie:t.cross_subdomain_cookie,secureCookie:t.secure_cookie,ignoreDnt:t.ignore_dnt})},Qp.prototype.opt_in_tracking=function(e){e=$u.extend({enable_persistence:!0},e),this._gdpr_call_func(gh,e),this._gdpr_update_persistence(e)},Qp.prototype.opt_out_tracking=function(e){(e=$u.extend({clear_persistence:!0,delete_user:!0},e)).delete_user&&this.people&&this.people._identify_called()&&(this.people.delete_user(),this.people.clear_charges()),this._gdpr_call_func(yh,e),this._gdpr_update_persistence(e)},Qp.prototype.has_opted_in_tracking=function(e){return this._gdpr_call_func(vh,e)},Qp.prototype.has_opted_out_tracking=function(e){return this._gdpr_call_func(bh,e)},Qp.prototype.clear_opt_in_out_tracking=function(e){e=$u.extend({enable_persistence:!0},e),this._gdpr_call_func(_h,e),this._gdpr_update_persistence(e)},Qp.prototype.report_error=function(e,t){Gu.error.apply(Gu.error,arguments);try{t||e instanceof Error||(e=new Error(e)),this.get_config("error_reporter")(e,t)}catch(r){Gu.error(r)}},Qp.prototype.init=Qp.prototype.init,Qp.prototype.reset=Qp.prototype.reset,Qp.prototype.disable=Qp.prototype.disable,Qp.prototype.time_event=Qp.prototype.time_event,Qp.prototype.track=Qp.prototype.track,Qp.prototype.track_links=Qp.prototype.track_links,Qp.prototype.track_forms=Qp.prototype.track_forms,Qp.prototype.track_pageview=Qp.prototype.track_pageview,Qp.prototype.register=Qp.prototype.register,Qp.prototype.register_once=Qp.prototype.register_once,Qp.prototype.unregister=Qp.prototype.unregister,Qp.prototype.identify=Qp.prototype.identify,Qp.prototype.alias=Qp.prototype.alias,Qp.prototype.name_tag=Qp.prototype.name_tag,Qp.prototype.set_config=Qp.prototype.set_config,Qp.prototype.get_config=Qp.prototype.get_config,Qp.prototype.get_api_host=Qp.prototype.get_api_host,Qp.prototype.get_property=Qp.prototype.get_property,Qp.prototype.get_distinct_id=Qp.prototype.get_distinct_id,Qp.prototype.toString=Qp.prototype.toString,Qp.prototype.opt_out_tracking=Qp.prototype.opt_out_tracking,Qp.prototype.opt_in_tracking=Qp.prototype.opt_in_tracking,Qp.prototype.has_opted_out_tracking=Qp.prototype.has_opted_out_tracking,Qp.prototype.has_opted_in_tracking=Qp.prototype.has_opted_in_tracking,Qp.prototype.clear_opt_in_out_tracking=Qp.prototype.clear_opt_in_out_tracking,Qp.prototype.get_group=Qp.prototype.get_group,Qp.prototype.set_group=Qp.prototype.set_group,Qp.prototype.add_group=Qp.prototype.add_group,Qp.prototype.remove_group=Qp.prototype.remove_group,Qp.prototype.track_with_groups=Qp.prototype.track_with_groups,Qp.prototype.start_batch_senders=Qp.prototype.start_batch_senders,Qp.prototype.stop_batch_senders=Qp.prototype.stop_batch_senders,Qp.prototype.start_session_recording=Qp.prototype.start_session_recording,Qp.prototype.stop_session_recording=Qp.prototype.stop_session_recording,Qp.prototype.pause_session_recording=Qp.prototype.pause_session_recording,Qp.prototype.resume_session_recording=Qp.prototype.resume_session_recording,Qp.prototype.get_session_recording_properties=Qp.prototype.get_session_recording_properties,Qp.prototype.get_session_replay_url=Qp.prototype.get_session_replay_url,Qp.prototype.get_tab_id=Qp.prototype.get_tab_id,Qp.prototype.DEFAULT_API_ROUTES=Yp,Qp.prototype.__get_recorder=Qp.prototype.__get_recorder,Fp.prototype.properties=Fp.prototype.properties,Fp.prototype.update_search_keyword=Fp.prototype.update_search_keyword,Fp.prototype.update_referrer_info=Fp.prototype.update_referrer_info,Fp.prototype.get_cross_subdomain=Fp.prototype.get_cross_subdomain,Fp.prototype.clear=Fp.prototype.clear;var nf={},of=function(){zp.init=function(e,t,r){if(r)return zp[r]||(zp[r]=nf[r]=ef(e,t,r),zp[r]._loaded()),zp[r];var n=zp;nf[$p]?n=nf[$p]:e&&((n=ef(e,t,$p))._loaded(),nf[$p]=n),zp=n,1===Ap&&(p[$p]=zp),$u.each(nf,function(e,t){t!==$p&&(zp[t]=e)}),zp._=$u}};var sf=(qp=function(e,t){t()},Ap=0,zp=new Qp,of(),zp.init(),function(){function e(){e.done||(e.done=!0,Xp=!0,Kp=!1,$u.each(nf,function(e){e._dom_loaded()}))}if(Ou.addEventListener)"complete"===Ou.readyState?e():Ou.addEventListener("DOMContentLoaded",e,!1);else if(Ou.attachEvent){Ou.attachEvent("onreadystatechange",e);var t=!1;try{t=null===p.frameElement}catch(r){}Ou.documentElement.doScroll&&t&&function t(){try{Ou.documentElement.doScroll("left")}catch(r){return void setTimeout(t,1)}e()}()}$u.register_event(p,"load",e,!0)}(),zp);let af=!1;const cf=()=>{af||(sf.init("c9fdb235976ef567b15bcb07bad264f3",{debug:!1,track_pageview:!1,persistence:"localStorage"}),af=!0)},lf={init:()=>{cf()},track:(e,t={})=>{af||cf(),sf.track(e,{source:"coinley-sdk",...t,timestamp:(new Date).toISOString()})},trackModalOpened:(e,t)=>{lf.track("SDK Modal Opened",{merchant_name:e,amount:t})},trackModalClosed:(e="user_closed")=>{lf.track("SDK Modal Closed",{reason:e})},trackNetworkSelected:(e,t)=>{lf.track("Network Selected",{network:e,merchant_name:t})},trackTokenSelected:(e,t,r)=>{lf.track("Token Selected",{token:e,network:t,merchant_name:r})},trackWalletConnectStarted:e=>{lf.track("Wallet Connect Started",{wallet_type:e})},trackWalletConnected:(e,t,r)=>{lf.track("Wallet Connected",{wallet_type:e,wallet_address:(null==t?void 0:t.slice(0,10))+"...",network:r})},trackWalletConnectionFailed:(e,t)=>{lf.track("Wallet Connection Failed",{wallet_type:e,error:(null==t?void 0:t.message)||t})},trackWalletDisconnected:()=>{lf.track("Wallet Disconnected")},trackPaymentCreated:(e,t,r,n)=>{lf.track("Payment Created",{payment_id:e,amount:t,network:r,token:n})},trackPaymentApprovalStarted:(e,t)=>{lf.track("Payment Approval Started",{payment_id:e,amount:t})},trackPaymentApproved:(e,t)=>{lf.track("Payment Approved",{payment_id:e,amount:t})},trackPaymentExecutionStarted:(e,t)=>{lf.track("Payment Execution Started",{payment_id:e,amount:t})},trackPaymentSuccess:(e,t,r,n,i)=>{lf.track("Payment Success",{payment_id:e,amount:t,network:r,token:n,transaction_hash:i})},trackPaymentFailed:(e,t,r,n,i)=>{lf.track("Payment Failed",{payment_id:e,amount:t,network:r,token:n,error:(null==i?void 0:i.message)||i})},trackPaymentCancelled:(e,t)=>{lf.track("Payment Cancelled",{payment_id:e,stage:t})},trackError:(e,t,r={})=>{lf.track("SDK Error",{error_type:e,error_message:t,...r})},trackNetworkSwitchRequested:(e,t)=>{lf.track("Network Switch Requested",{from_network:e,to_network:t})},trackNetworkSwitchSuccess:e=>{lf.track("Network Switch Success",{network:e})},trackNetworkSwitchFailed:(e,t)=>{lf.track("Network Switch Failed",{network:e,error:(null==t?void 0:t.message)||t})}},uf="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABxCAYAAAAj+QZ8AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAzrSURBVHgB7V3dcRs5Em4MtXWPq41gZ1+v7mwrgh3rArAUgagITNcFYDmAK9ERSBuBfQGsxY3Aku26V/MiOO7j1nqAQwMgRQ4xQONnhqOfr8q2TA4H1HzoRqO70c1g4JhUH/dhNKqgrhfT2cEMOoQaqxidyx+P5J8F8PpYjnkNPYLBgPGq+vxSFOJM/rhvXpp39ZAkGaUk40r+WK69jKT8JMdbQE8oYKDAByTJmMItGQj10OR7zyA3itFr2CQD1NhFMYYeMVhCHA8C1co7pV4yYXL4aSz/GVvfFFBBjxguIcCeOt4szYxOhiG2/V7M+T2yY7iEMOaTgIl8mBWkoth7Cduqah2u97JjuIQIUXqvYWlSohZyUEaDE/88/M+P0BMGrLIIYFAZ/R+HTGovJ+42IRqvYxZ485kKBob7QEgZZZoWoyMgrg//+vDX/0JPuA+ESLCXEApG/kxvm0LEkK2secDVZYjFpRZzIWibSyHm0COGSwjnYWoiyOIqjujXskcJUWCBqgItLuriPipOgAombqBH7EEGTKovUvz/xIdxnc8Rx8IdiHpxn7ouCVJXGnPIBD1h9p5BIU6kS6ZkBXt//uvf365fk0SIcvJJv5LUL6Wcdvq1w09z+c9MeknfSHLmEAteX8t7B30EBHsBHkLkPSsI+h482bOs3froERAT+UdLMcPlSch91M0P0w9Pz5bXpqksRcaW6Yj/H8v3vkpyLvRuOBzGxd6F2voZwpBEyKT6XMln8dF4BCzfjW2oz2hCjAu89FxmiPkctyNmMWprdOS5J11dSQsrVgXjxJAT8lyqp2aMpTnGxv1TJCRgdyzO5Jf7Giwtgv8GwWhfH5T0hK0fUQu6UeUf8UfvxY1Jl0LIHMJQBksL5zMIhXCqpLDAFpNrYSAwymnIKEkf4PUv6/+NJsQs2BHirKTlHUVaTAw9cB1xqaQijJDACYGTzUQ5adAqcbb+UuI+RPwCcTgyodjSe6UQ/4ZAtLrLi4DYhn5Y5DVscvjlguLK3xyDvWm+lEYI5+8hHiWJFMEvIRA1/3ZgfYMV9OgfYzPKZWrxfv5JLtx8DCFQhD+5bL6cRIgSN+IXb4GXlCi1VbQEt0IWdA40yRztXaG5DaEQ/Nj2crrrpP72BtJAkJRg1bhlAZr9Cc0y1LPXK/1KTYVZbcsB3rapw2RC1AwW0WvJEktS7A8sWDWyH61jkD/ul3q1xwhVUwj0HnN+1vZ2Huei4Ghvp/qwSumxfWd7I4NqRND3TdLt43rbmO7+PYYNgj93bTazEKIG4PUppELHyM+t76WrRhoEzFw+uMk/Ph0FW1O3N3/l8+9lc7/Lgd6jboR0TF5VNyeW++eQEj8EtKpf7SmGC4i78VvpRPTuUfLGQ1A3CpHkjEOIgk2ti3zXUtJiiq6gc38DXEar+15LMkgqLishSnWhOZce9tyX68mF5f4pUjL3XmHZqC1hVGkJocBnIdcN6uXZI4ZKR2obO22Rx/VE6esG6m+n/nsLW/jX/Rnp5GuTDpP7Fb6IGzJCPMadhHCVjc1rnBVppAg4b5rCinBeHzs/x7fd9uqhuNz59TfrPY3qDA8f3JIxD/lYZzH1TKRgztXEcu8ZWiztH6vtD17wlt23w/qxH1NwI5IMNRx0iDyk2POntMUiLDpftIeOOZ9ufxd5fYv1Y6RjDCFIIAPRywkq9YuxQvp8WAkxkKS2HWdT+VgFpvWw7zG24Dv2Jq8/kv6nl3rH7L4eQ9AQQojcw4BQJ7yiJ2AvhCAMKe+CQqgrKBs+bmecAIxyAlldKUk7g0R4s070ovpdadJ8DL6TM+DPoHizEeGDyeHNmZwHYYukiDA3E0HMGUAsD4fOIAP2LF/EnKtjGAqtQG2EOCzTfDT0/+UM0jFhte8QN+rnur526U+cRXIMuZ8oLgJUWG/nM9bg3wBqFXWalO7UwEplbeYORexGN+6qSLp26Wijws7ktf4sQvQvXT0hb65ywOw92twk0oSG0+mvfhd9KBQhLUeCc2EOjsQ5EjFc/vIul0YHUBOUFR8bUrxQ/jpprXV1VFoTcvgJ3d5H0D0uncRgEvSoeCGlqzIvL1xmaddYfScFft114QIEM9LxFfrFZXKq6T0FbgzT1os4YEbjR2lx9W7KDh3M1Pf4H+wKHVgqdxmFdpknx8TjgRkb1BytBwDtyxIq6N6J1UBEKd0Z7+ARmhDj0k53l6dAiGd6F/+wsfL2rjyzPR9y3ARhk3jPseF+V6RguHF3a0rZZxmLIaLV26uca9o7W0Kf4PUP0x4Lhg0NXve78ukI8boXYnbgsxoayPEQRQz6m27dGnmRGGm7LwgOUK38OwxO4oJNFjxuDldIihiazdwzGT+p1NkLnQlOdcUsVFY75+/7cNrdFWQP4Zq0nRI0MeiW2SSIq4yQxaM0POJOoCsJ0VJSjMqtC3g9x5j8dPa35Bzg+4hkQnSlAv7MxOCpiQGIOeQowXHPEEWIJkFgXZEx5ImnPAasDOj7kJxJEHagg/PgIe/SEbS8rGYlm26Aaw5meRzDA4ZTQizF8LvHA/dlWSVEp+aMLgTryE3iwKj4y/ew22DZTmHJXFQLNkbvdpH8ADX/43d4wNiIh7yqvpyY+k47IUPi8qEv6itCMP4hivC6IlnhOR/+EKAIMalAO04y8J/hfgjQEhJQdrsb7C5ddGjQi7oOPMFuICXjkYwVstTtjYKOEGJQarY6FKR8YsvSSgx37rOHpsZM9vvNNKqgfRxWKf2mqDCOW0G7ZTedfnjyCnYAU8zyRE6Mt31NDL2GpFWGo0IdLcA2dMCLmar8o01sXL9cZvaktSBN1xjt4bgTU4P4nFATOBnLzMWZ/YhxFqwRIc1q9FchEWFV2CZ9PIwtbJapnaiM/Rx9rxy4zVzUJ0hPM2UuGrVUP5fqRpXSZrB3Ysqnxh0M6rmfoML2uXZdaC22MDQBVueiOV+H8Y4K/Lv2hfkjg03YSYDPmuXrjMqZQBouJbnpNbkCoc612/Zo6oDrt+Pca4s/UW4zaWEdc/zLWexL9bHdu4qrS7gFJyE4VojbBR2o1IfpMHqyt4LtrHBABwdJrYTcdmhQ43iDXJbrvQ+05QDoGvLtpTqpddLNqV7xe8s46x0arMVqNrB1vf+w0KoOWGtYgJ3nWleyE2LUlK2NRRpsprmNdKHWvrbvZkvCsBZLa0JLkcsSxRLq6aTklxAsZ5RnzbiFpUa6+eXLrWtdSeGjkf29tmJpDZgKRI66kumkZCUkqXyqC42yfqZlats47VahcL5H2vipIjjOMoOq2UBkocyMhFD7ykahGSfRRcVaH177oR9nf13/+rMEVp9zF/scx5KST0K0Ps+PRh3dqKJiZLCXJCmhFfscx6ivLIS06vMcEFbp6Ar7VCkxxT49ZzLD15RkQjz6PA1aOmabY/mlo713LaV7KE1KEF2Qki4hHn2eBNEoX95Pu+39EL8ZlRRbtW4bkggxMzbOWeiFtZhl5f+YY7FVmfeUodkLCACFFFOt27sdSO1jWEEX0oH7jkb9QrNPKP0fdvaunQMFuh9iBQEgkLJP8QqkEcI6OOjfVprbsQPfgLt3Ldn5qI7pBSKAlNZJnEZI7h25uidvO/xJU428fdNmnI5zICEupL1GSpvqbO2Tgkjt9JlXXalSftsHQI36II7lXSeorvL92OjgihSA99YLVJ8Uu+XVU6dPAlx1FQty//OFNzbBxW9ARYTaWgKlUYYLjtsdkuLMRng8IUWLoy4UusL0gbPIJSt+Btq9CA87oPuzYLRxHdDGSUudep1EsYF4QqgmpAuqYICq3tD6kIL619JapdIJoXWf9kJ5iTHJo7nYW0pSpaislLDlQkXZrp74S2mMlGlNA6FVqmlb4b1uDVkMl7XFvlFpadMzkNILN/QX0xDq5O0BOeRJlY6QVqkhXaiLIgshCCRlevV0DJvZPUjGaow0sxe73VDThjQRz0lSsQ7q+hEyOYKaDjN6u1Yi5GJ/KScFtoc9bVqWGc6pOytTL1Lrmci4AlZM9etxDseU7pzB98WGXldPD6AnJCdbm9k+lsScgSpEY2qb6JomQR0Umghqlwr1DEKAXagpnoY+6oStIVv2uyFmDnlB1d/hR+GwCzUbUVw/+6E5XynotOVROogLKrWz8yZQgkkP2ZwM7gXDJoTSkJ7Y2bkJPeNpxT5r/sdP0BMGLiHMX6FUQHy7V+oxjFxeCcpQMGQwRljQ48+29NZfNwADlxAvLpOzz/vqQk3E3SYkw7n2oUnJsAkRwmEFiXzn/gYkJQOXEGFP51Eue07zhREwJCkZupVldxYWLH/VB1cXat5fdaJhE8JriwUl3nTRrk4T3Bbdq1NCDUEYNCFm87Z8SAtzUukMOoK94bHo7Yw6orMjbTmxDOD05U/SBz2l2wab3ncgjS78H0eagrHjdQciAAAAAElFTkSuQmCC",hf="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",df="qtIcCe_-8t4rIWktnWJm0",pf=o.createConfig({chains:[s.mainnet,s.bsc,s.polygon,s.arbitrum,s.optimism,s.avalanche,s.celo,s.base],connectors:[a.injected(),a.metaMask({dappMetadata:{name:"Coinley Payment",icon:uf}}),a.coinbaseWallet({appName:"Coinley Payment",appLogoUrl:uf})],transports:{[s.mainnet.id]:o.fallback([o.http(`https://eth-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://eth-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://cloudflare-eth.com",{timeout:1e4,retryCount:1}),o.http("https://eth.llamarpc.com",{timeout:1e4,retryCount:1}),o.http("https://ethereum.publicnode.com",{timeout:1e4,retryCount:1})]),[s.bsc.id]:o.fallback([o.http(`https://bnb-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://bnb-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://bsc-dataseed.bnbchain.org",{timeout:1e4,retryCount:1}),o.http("https://bsc-dataseed-public.bnbchain.org",{timeout:1e4,retryCount:1}),o.http("https://bsc.nodereal.io",{timeout:1e4,retryCount:1})]),[s.polygon.id]:o.fallback([o.http(`https://polygon-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://polygon-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://polygon.llamarpc.com",{timeout:1e4,retryCount:1}),o.http("https://polygon-rpc.com",{timeout:1e4,retryCount:1}),o.http("https://polygon.drpc.org",{timeout:1e4,retryCount:1})]),[s.arbitrum.id]:o.fallback([o.http(`https://arb-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://arb-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://arb1.arbitrum.io/rpc",{timeout:1e4,retryCount:1}),o.http("https://arbitrum.llamarpc.com",{timeout:1e4,retryCount:1})]),[s.optimism.id]:o.fallback([o.http(`https://opt-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://opt-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://mainnet.optimism.io",{timeout:1e4,retryCount:1}),o.http("https://optimism.llamarpc.com",{timeout:1e4,retryCount:1})]),[s.avalanche.id]:o.fallback([o.http(`https://avax-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://avax-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://api.avax.network/ext/bc/C/rpc",{timeout:1e4,retryCount:1}),o.http("https://avalanche.public-rpc.com",{timeout:1e4,retryCount:1})]),[s.celo.id]:o.fallback([o.http(`https://celo-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://celo-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://forno.celo.org",{timeout:1e4,retryCount:1}),o.http("https://celo.drpc.org",{timeout:1e4,retryCount:1})]),[s.base.id]:o.fallback([o.http(`https://base-mainnet.g.alchemy.com/v2/${hf}`,{timeout:1e4,retryCount:1}),o.http(`https://base-mainnet.g.alchemy.com/v2/${df}`,{timeout:1e4,retryCount:1}),o.http("https://mainnet.base.org",{timeout:1e4,retryCount:1}),o.http("https://base.llamarpc.com",{timeout:1e4,retryCount:1}),o.http("https://base.meowrpc.com",{timeout:1e4,retryCount:1})])}});let ff=class{constructor(e,t,r=null){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=r)}async request(e,t={}){const r=`${this.baseURL}${e}`,n={"Content-Type":"application/json",...t.headers};this.publicKey?n["X-Public-Key"]=this.publicKey:(n["X-API-Key"]=this.apiKey,n["X-API-Secret"]=this.apiSecret);const i=t.timeout||6e4,o=new AbortController,s=setTimeout(()=>o.abort(),i);try{const e=await fetch(r,{...t,headers:n,signal:o.signal});if(clearTimeout(s),!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`HTTP ${e.status}`)}return e.json()}catch(vu){if(clearTimeout(s),"AbortError"===vu.name)throw new Error(`Request timeout after ${i/1e3}s: ${e}`);throw vu}}async getNetworks(){try{return await this.request("/api/networks")}catch(vu){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(vu){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Tether USD",symbol:"USDT",contractAddress:"0x55d398326f99059fF775485246999027B3197955",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87c6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"USD Coin",symbol:"USDC",contractAddress:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async verifyQRPayment(e){return await this.request("/api/payments/verify-qr",{method:"POST",body:JSON.stringify({paymentId:e})})}async checkPaymentStatus(e){return await this.request(`/api/payments/status/${e}`)}async getContractInfo(e){try{const t=await this.request(`/api/payments/contract/${e}`);if(!t.success)throw new Error("Contract not supported on this network");return t.contractInfo}catch(vu){throw new Error(vu.message||"Failed to get contract information")}}async processPayment(e,t,r,n){try{return await this.request("/api/payments/process",{method:"POST",body:JSON.stringify({paymentId:e,transactionHash:t,network:r,senderAddress:n}),timeout:9e4})}catch(vu){throw vu}}async failPayment(e,t="Payment cancelled by user"){return await this.request("/api/payments/fail",{method:"POST",body:JSON.stringify({paymentId:e,reason:t,status:"failed"})})}};const mf="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",gf="qtIcCe_-8t4rIWktnWJm0",yf={MAINNET:[`https://solana-mainnet.g.alchemy.com/v2/${mf}`,`https://solana-mainnet.g.alchemy.com/v2/${gf}`,"https://api.mainnet-beta.solana.com","https://solana-api.projectserum.com","https://rpc.ankr.com/solana"],DEVNET:[`https://solana-devnet.g.alchemy.com/v2/${mf}`,`https://solana-devnet.g.alchemy.com/v2/${gf}`,"https://api.devnet.solana.com","https://rpc.ankr.com/solana_devnet"]},vf={MAINNET:{id:"solana-mainnet",name:"Solana Mainnet",shortName:"Solana",rpcUrl:yf.MAINNET[0],rpcEndpoints:yf.MAINNET,chainType:"solana",isTestnet:!1,blockExplorer:"https://explorer.solana.com",logo:"solana"},DEVNET:{id:"solana-devnet",name:"Solana Devnet",shortName:"Solana Devnet",rpcUrl:yf.DEVNET[0],rpcEndpoints:yf.DEVNET,chainType:"solana",isTestnet:!0,blockExplorer:"https://explorer.solana.com/?cluster=devnet",logo:"solana"}},bf={SOL:{symbol:"SOL",name:"Solana",decimals:9,isNative:!0,address:null,logo:"sol",isStablecoin:!1},USDC:{symbol:"USDC",name:"USD Coin",decimals:6,isNative:!1,address:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",logo:"usdc",isStablecoin:!0},USDT:{symbol:"USDT",name:"Tether USD",decimals:6,isNative:!1,address:"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",logo:"usdt",isStablecoin:!0},EURC:{symbol:"EURC",name:"Euro Coin",decimals:6,isNative:!1,address:"HzwqbKZw8HxMN6bF2yFZNrht3c2iXXzpKcFu7uBEDKtr",logo:"eurc",isStablecoin:!0}},wf={SOL:{symbol:"SOL",name:"Solana (Devnet)",decimals:9,isNative:!0,address:null,logo:"sol",isStablecoin:!1},USDC:{symbol:"USDC",name:"USD Coin (Devnet)",decimals:6,isNative:!1,address:"Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr",logo:"usdc",isStablecoin:!0}},xf={PHANTOM:{name:"Phantom",id:"phantom",icon:"phantom",downloadUrl:"https://phantom.app/",deepLink:"https://phantom.app/ul/browse/",installUrl:{chrome:"https://chrome.google.com/webstore/detail/phantom/bfnaelmomeimhlpmgjnjophhpkkoljpa",firefox:"https://addons.mozilla.org/en-US/firefox/addon/phantom-app/",ios:"https://apps.apple.com/us/app/phantom-solana-wallet/id1598432977",android:"https://play.google.com/store/apps/details?id=app.phantom"}},SOLFLARE:{name:"Solflare",id:"solflare",icon:"solflare",downloadUrl:"https://solflare.com/",deepLink:"https://solflare.com/ul/",installUrl:{chrome:"https://chrome.google.com/webstore/detail/solflare-wallet/bhhhlbepdkbapadjdnnojkbgioiodbic",firefox:"https://addons.mozilla.org/en-US/firefox/addon/solflare-wallet/",ios:"https://apps.apple.com/us/app/solflare/id1580902717",android:"https://play.google.com/store/apps/details?id=com.solflare.mobile"}},BACKPACK:{name:"Backpack",id:"backpack",icon:"backpack",downloadUrl:"https://backpack.app/",deepLink:"https://backpack.app/",installUrl:{chrome:"https://chrome.google.com/webstore/detail/backpack/aflkmfhebedbjioipglgcbcmnbpgliof",ios:"https://apps.apple.com/us/app/backpack-crypto-wallet/id6448811949"}},TRUST_WALLET:{name:"Trust Wallet",id:"trust",icon:"trust",downloadUrl:"https://trustwallet.com/",deepLink:"https://link.trustwallet.com/",installUrl:{chrome:"https://chrome.google.com/webstore/detail/trust-wallet/egjidjbpglichdcondbcbdnbeeppgdph",ios:"https://apps.apple.com/app/trust-crypto-bitcoin-wallet/id1288339409",android:"https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp"}},MAGIC_EDEN:{name:"Magic Eden",id:"magiceden",icon:"magiceden",downloadUrl:"https://wallet.magiceden.io/",deepLink:"https://wallet.magiceden.io/",installUrl:{chrome:"https://chrome.google.com/webstore/detail/magic-eden-wallet/mkpegjkblkkefacfnmkajcjmabijhclg",ios:"https://apps.apple.com/app/magic-eden-wallet/id6449729293",android:"https://play.google.com/store/apps/details?id=io.magiceden.wallet"}}},kf=e=>{const t=(e=>Object.values(vf).find(t=>t.id===e))(e);return(null==t?void 0:t.rpcEndpoints)||[null==t?void 0:t.rpcUrl]},_f="Crz57kC6npUiFHx7xg1sE2oMDXLFHeqKhDgXJXcuDT3B",Sf="Crz57kC6npUiFHx7xg1sE2oMDXLFHeqKhDgXJXcuDT3B",Cf=(e=!1)=>e?Sf:_f,If="evm",Ef="solana",Af={ethereum:1,bsc:56,polygon:137,arbitrum:42161,optimism:10,avalanche:43114,celo:42220,base:8453},Mf=e=>"number"==typeof e?e:"string"==typeof e?e.startsWith("0x")?parseInt(e,16):parseInt(e,10):1,Nf=e=>Af[e]||1,Pf=e=>(e=>{if(!e)return!1;const t=e.toString().toLowerCase();return Object.values(vf).some(r=>{var n;return r.id===e||(null==(n=r.shortName)?void 0:n.toLowerCase())===t})||["solana","solana-mainnet","solana-devnet","103"].includes(t)})(e)?Ef:If;function Bf(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const Tf="2.41.2";let Of={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Tf}`};class Rf extends Error{constructor(e,t={}){var r;const n=t.cause instanceof Rf?t.cause.details:(null==(i=t.cause)?void 0:i.message)?t.cause.message:t.details;var i;const o=t.cause instanceof Rf&&t.cause.docsPath||t.docsPath,s=null==(r=Of.getDocsUrl)?void 0:r.call(Of,{...t,docsPath:o});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Of.version?[`Version: ${Of.version}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=o,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=Tf}walk(e){return Lf(this,e)}}function Lf(e,t){return(null==t?void 0:t(e))?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?Lf(e.cause,t):t?null:e}class Uf extends Rf{constructor({max:e,min:t,signed:r,size:n,value:i}){super(`Number "${i}" is not in safe ${n?`${8*n}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class jf extends Rf{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Df(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function Ff(e){return Df(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function zf(e,{dir:t="left"}={}){let r="string"==typeof e?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&"0"===r["left"===t?i:r.length-i-1].toString();i++)n++;return r="left"===t?r.slice(n):r.slice(0,r.length-n),"string"==typeof e?(1===r.length&&"right"===t&&(r=`${r}0`),`0x${r.length%2==1?`0${r}`:r}`):r}class qf extends Rf{constructor({offset:e,position:t,size:r}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${r}).`,{name:"SliceOffsetOutOfBoundsError"})}}class Wf extends Rf{constructor({size:e,targetSize:t,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function $f(e,{dir:t,size:r=32}={}){return"string"==typeof e?function(e,{dir:t,size:r=32}={}){if(null===r)return e;const n=e.replace("0x","");if(n.length>2*r)throw new Wf({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n["right"===t?"padEnd":"padStart"](2*r,"0")}`}(e,{dir:t,size:r}):function(e,{dir:t,size:r=32}={}){if(null===r)return e;if(e.length>r)throw new Wf({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const o="right"===t;n[o?i:r-i-1]=e[o?i:e.length-i-1]}return n}(e,{dir:t,size:r})}const Gf=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Vf(e,t={}){return"number"==typeof e||"bigint"==typeof e?Kf(e,t):"string"==typeof e?function(e,t={}){const r=Zf.encode(e);return Hf(r,t)}(e,t):"boolean"==typeof e?function(e,t={}){const r=`0x${Number(e)}`;if("number"==typeof t.size)return rm(r,{size:t.size}),$f(r,{size:t.size});return r}(e,t):Hf(e,t)}function Hf(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=Gf[e[i]];const n=`0x${r}`;return"number"==typeof t.size?(rm(n,{size:t.size}),$f(n,{dir:"right",size:t.size})):n}function Kf(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let o;n?o=r?(1n<<8n*BigInt(n)-1n)-1n:2n**(8n*BigInt(n))-1n:"number"==typeof e&&(o=BigInt(Number.MAX_SAFE_INTEGER));const s="bigint"==typeof o&&r?-o-1n:0;if(o&&i>o||i<s){const t="bigint"==typeof e?"n":"";throw new Uf({max:o?`${o}${t}`:void 0,min:`${s}${t}`,signed:r,size:n,value:`${e}${t}`})}const a=`0x${(r&&i<0?(1n<<BigInt(8*n))+BigInt(i):i).toString(16)}`;return n?$f(a,{size:n}):a}const Zf=new TextEncoder;const Yf=new TextEncoder;function Jf(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){const r=Kf(e,t);return em(r)}(e,t):"boolean"==typeof e?function(e,t={}){const r=new Uint8Array(1);if(r[0]=Number(e),"number"==typeof t.size)return rm(r,{size:t.size}),$f(r,{size:t.size});return r}(e,t):Df(e)?em(e,t):tm(e,t)}const Xf={zero:48,nine:57,A:65,F:70,a:97,f:102};function Qf(e){return e>=Xf.zero&&e<=Xf.nine?e-Xf.zero:e>=Xf.A&&e<=Xf.F?e-(Xf.A-10):e>=Xf.a&&e<=Xf.f?e-(Xf.a-10):void 0}function em(e,t={}){let r=e;t.size&&(rm(r,{size:t.size}),r=$f(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,o=new Uint8Array(i);for(let s=0,a=0;s<i;s++){const e=Qf(n.charCodeAt(a++)),t=Qf(n.charCodeAt(a++));if(void 0===e||void 0===t)throw new Rf(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);o[s]=16*e+t}return o}function tm(e,t={}){const r=Yf.encode(e);return"number"==typeof t.size?(rm(r,{size:t.size}),$f(r,{dir:"right",size:t.size})):r}function rm(e,{size:t}){if(Ff(e)>t)throw new jf({givenSize:Ff(e),maxSize:t})}function nm(e,t={}){const{signed:r}=t;t.size&&rm(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2;return n<=(1n<<8n*BigInt(i)-1n)-1n?n:n-BigInt(`0x${"f".padStart(2*i,"f")}`)-1n}function im(e,t={}){return Number(nm(e,t))}function om(e,t){return({exclude:r,format:n})=>({exclude:r,format:(e,i)=>{const o=t(e,i);if(r)for(const t of r)delete o[t];return{...o,...n(e,i)}},type:e})}const sm={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function am(e,t){const r={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?im(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?im(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?sm[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(r.authorizationList=e.authorizationList.map(e=>({address:e.address,chainId:Number(e.chainId),nonce:Number(e.nonce),r:e.r,s:e.s,yParity:Number(e.yParity)}))),r.yParity=(()=>{if(e.yParity)return Number(e.yParity);if("bigint"==typeof r.v){if(0n===r.v||27n===r.v)return 0;if(1n===r.v||28n===r.v)return 1;if(r.v>=35n)return r.v%2n==0n?1:0}})(),"legacy"===r.type&&(delete r.accessList,delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas,delete r.yParity),"eip2930"===r.type&&(delete r.maxFeePerBlobGas,delete r.maxFeePerGas,delete r.maxPriorityFeePerGas),"eip1559"===r.type&&delete r.maxFeePerBlobGas,r}const cm=om("transaction",am);function lm(e,t){const r=(e.transactions??[]).map(e=>"string"==typeof e?e:am(e));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:r,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const um=om("block",lm);const hm={"0x0":"reverted","0x1":"success"};function dm(e,t){const r={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(e=>function(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}(e)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?im(e.transactionIndex):null,status:e.status?hm[e.status]:null,type:e.type?sm[e.type]||e.type:null};return e.blobGasPrice&&(r.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(r.blobGasUsed=BigInt(e.blobGasUsed)),r}const pm=om("transactionReceipt",dm),fm={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function mm(e,t){const r={};return void 0!==e.authorizationList&&(r.authorizationList=e.authorizationList.map(e=>({address:e.address,r:e.r?Kf(BigInt(e.r)):e.r,s:e.s?Kf(BigInt(e.s)):e.s,chainId:Kf(e.chainId),nonce:Kf(e.nonce),...void 0!==e.yParity?{yParity:Kf(e.yParity)}:{},...void 0!==e.v&&void 0===e.yParity?{v:Kf(e.v)}:{}}))),void 0!==e.accessList&&(r.accessList=e.accessList),void 0!==e.blobVersionedHashes&&(r.blobVersionedHashes=e.blobVersionedHashes),void 0!==e.blobs&&("string"!=typeof e.blobs[0]?r.blobs=e.blobs.map(e=>Hf(e)):r.blobs=e.blobs),void 0!==e.data&&(r.data=e.data),e.account&&(r.from=e.account.address),void 0!==e.from&&(r.from=e.from),void 0!==e.gas&&(r.gas=Kf(e.gas)),void 0!==e.gasPrice&&(r.gasPrice=Kf(e.gasPrice)),void 0!==e.maxFeePerBlobGas&&(r.maxFeePerBlobGas=Kf(e.maxFeePerBlobGas)),void 0!==e.maxFeePerGas&&(r.maxFeePerGas=Kf(e.maxFeePerGas)),void 0!==e.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=Kf(e.maxPriorityFeePerGas)),void 0!==e.nonce&&(r.nonce=Kf(e.nonce)),void 0!==e.to&&(r.to=e.to),void 0!==e.type&&(r.type=fm[e.type]),void 0!==e.value&&(r.value=Kf(e.value)),r}const gm=om("transactionRequest",mm);const ym=2n**256n-1n;function vm(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}class bm extends Rf{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class wm extends Rf{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class xm extends Rf{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const km={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new xm({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new wm({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new bm({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new bm({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function _m(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(km);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function Sm(e,t="hex"){const r=Cm(e),n=_m(new Uint8Array(r.length));return r.encode(n),"hex"===t?Hf(n.bytes):n.bytes}function Cm(e){return Array.isArray(e)?function(e){const t=e.reduce((e,t)=>e+t.length,0),r=Im(t);return{length:t<=55?1+t:1+r+t,encode(n){t<=55?n.pushByte(192+t):(n.pushByte(247+r),1===r?n.pushUint8(t):2===r?n.pushUint16(t):3===r?n.pushUint24(t):n.pushUint32(t));for(const{encode:t}of e)t(n)}}}(e.map(e=>Cm(e))):function(e){const t="string"==typeof e?em(e):e,r=Im(t.length),n=1===t.length&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length;return{length:n,encode(e){1===t.length&&t[0]<128?e.pushBytes(t):t.length<=55?(e.pushByte(128+t.length),e.pushBytes(t)):(e.pushByte(183+r),1===r?e.pushUint8(t.length):2===r?e.pushUint16(t.length):3===r?e.pushUint24(t.length):e.pushUint32(t.length),e.pushBytes(t))}}}(e)}function Im(e){if(e<256)return 1;if(e<65536)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new Rf("Length is too large.")}const Em={ether:-9,wei:9};function Am(e,t="wei"){return function(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,o]=[r.slice(0,r.length-t),r.slice(r.length-t)];return o=o.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${o?`.${o}`:""}`}(e,Em[t])}function Mm(e){const t=Object.entries(e).map(([e,t])=>void 0===t||!1===t?null:[e,t]).filter(Boolean),r=t.reduce((e,[t])=>Math.max(e,t.length),0);return t.map(([e,t])=>` ${`${e}:`.padEnd(r+1)} ${t}`).join("\n")}class Nm extends Rf{constructor({v:e}){super(`Invalid \`v\` value "${e}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class Pm extends Rf{constructor({transaction:e}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",Mm(e),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class Bm extends Rf{constructor({storageKey:e}){super(`Size for storage key "${e}" is invalid. Expected 32 bytes. Got ${Math.floor((e.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}function Tm(e){const{kzg:t}=e,r=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),n="string"==typeof e.blobs[0]?e.blobs.map(e=>em(e)):e.blobs,i=[];for(const o of n)i.push(Uint8Array.from(t.blobToKzgCommitment(o)));return"bytes"===r?i:i.map(e=>Hf(e))}function Om(e){const{kzg:t}=e,r=e.to??("string"==typeof e.blobs[0]?"hex":"bytes"),n="string"==typeof e.blobs[0]?e.blobs.map(e=>em(e)):e.blobs,i="string"==typeof e.commitments[0]?e.commitments.map(e=>em(e)):e.commitments,o=[];for(let s=0;s<n.length;s++){const e=n[s],r=i[s];o.push(Uint8Array.from(t.computeBlobKzgProof(e,r)))}return"bytes"===r?o:o.map(e=>Hf(e))}const Rm="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;
|
|
2
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lm(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Um(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function jm(e,...t){if(!Lm(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Dm(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");Um(e.outputLen),Um(e.blockLen)}function Fm(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function zm(e,t){jm(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function qm(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Wm(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function $m(e,t){return e<<32-t|e>>>t}function Gm(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Vm=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=Gm(e[t]);return e},Hm=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Km=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Zm(e){if(jm(e),Hm)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Km[e[r]];return t}const Ym=48,Jm=57,Xm=65,Qm=70,eg=97,tg=102;function rg(e){return e>=Ym&&e<=Jm?e-Ym:e>=Xm&&e<=Qm?e-(Xm-10):e>=eg&&e<=tg?e-(eg-10):void 0}function ng(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Hm)return Uint8Array.fromHex(e);const t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){const t=rg(e.charCodeAt(o)),r=rg(e.charCodeAt(o+1));if(void 0===t||void 0===r){const t=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+o)}n[i]=16*t+r}return n}function ig(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),jm(e),e}function og(...e){let t=0;for(let n=0;n<e.length;n++){const r=e[n];jm(r),t+=r.length}const r=new Uint8Array(t);for(let n=0,i=0;n<e.length;n++){const t=e[n];r.set(t,i),i+=t.length}return r}class sg{}function ag(e){const t=t=>e().update(ig(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function cg(e=32){if(Rm&&"function"==typeof Rm.getRandomValues)return Rm.getRandomValues(new Uint8Array(e));if(Rm&&"function"==typeof Rm.randomBytes)return Uint8Array.from(Rm.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function lg(e,t,r){return e&t^~e&r}function ug(e,t,r){return e&t^e&r^t&r}class hg extends sg{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Wm(this.buffer)}update(e){Fm(this),jm(e=ig(e));const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const s=Math.min(n-this.pos,i-o);if(s===n){const t=Wm(e);for(;n<=i-o;o+=n)this.process(t,o);continue}r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fm(this),zm(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:i}=this;let{pos:o}=this;t[o++]=128,qm(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let u=o;u<n;u++)t[u]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),a=Number(r&o),c=n?4:0,l=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);const s=Wm(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<c;u++)s.setUint32(4*u,l[u],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=s,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const dg=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pg=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),fg=BigInt(2**32-1),mg=BigInt(32);function gg(e,t=!1){return t?{h:Number(e&fg),l:Number(e>>mg&fg)}:{h:0|Number(e>>mg&fg),l:0|Number(e&fg)}}function yg(e,t=!1){const r=e.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){const{h:r,l:s}=gg(e[o],t);[n[o],i[o]]=[r,s]}return[n,i]}const vg=(e,t,r)=>e>>>r,bg=(e,t,r)=>e<<32-r|t>>>r,wg=(e,t,r)=>e>>>r|t<<32-r,xg=(e,t,r)=>e<<32-r|t>>>r,kg=(e,t,r)=>e<<64-r|t>>>r-32,_g=(e,t,r)=>e>>>r-32|t<<64-r;function Sg(e,t,r,n){const i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}const Cg=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Ig=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,Eg=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Ag=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Mg=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Ng=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Pg=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]),Bg=new Uint32Array(64);class Tg extends hg{constructor(e=32){super(64,e,8,!1),this.A=0|dg[0],this.B=0|dg[1],this.C=0|dg[2],this.D=0|dg[3],this.E=0|dg[4],this.F=0|dg[5],this.G=0|dg[6],this.H=0|dg[7]}get(){const{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|a}process(e,t){for(let u=0;u<16;u++,t+=4)Bg[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=Bg[u-15],t=Bg[u-2],r=$m(e,7)^$m(e,18)^e>>>3,n=$m(t,17)^$m(t,19)^t>>>10;Bg[u]=n+Bg[u-7]+r+Bg[u-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:l}=this;for(let u=0;u<64;u++){const e=l+($m(s,6)^$m(s,11)^$m(s,25))+lg(s,a,c)+Pg[u]+Bg[u]|0,t=($m(r,2)^$m(r,13)^$m(r,22))+ug(r,n,i)|0;l=c,c=a,a=s,s=o+e|0,o=i,i=n,n=r,r=e+t|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,i,o,s,a,c,l)}roundClean(){qm(Bg)}destroy(){this.set(0,0,0,0,0,0,0,0),qm(this.buffer)}}const Og=(()=>yg(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))))(),Rg=(()=>Og[0])(),Lg=(()=>Og[1])(),Ug=new Uint32Array(80),jg=new Uint32Array(80);class Dg extends hg{constructor(e=64){super(128,e,16,!1),this.Ah=0|pg[0],this.Al=0|pg[1],this.Bh=0|pg[2],this.Bl=0|pg[3],this.Ch=0|pg[4],this.Cl=0|pg[5],this.Dh=0|pg[6],this.Dl=0|pg[7],this.Eh=0|pg[8],this.El=0|pg[9],this.Fh=0|pg[10],this.Fl=0|pg[11],this.Gh=0|pg[12],this.Gl=0|pg[13],this.Hh=0|pg[14],this.Hl=0|pg[15]}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:m}=this;return[e,t,r,n,i,o,s,a,c,l,u,h,d,p,f,m]}set(e,t,r,n,i,o,s,a,c,l,u,h,d,p,f,m){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|m}process(e,t){for(let v=0;v<16;v++,t+=4)Ug[v]=e.getUint32(t),jg[v]=e.getUint32(t+=4);for(let v=16;v<80;v++){const e=0|Ug[v-15],t=0|jg[v-15],r=wg(e,t,1)^wg(e,t,8)^vg(e,0,7),n=xg(e,t,1)^xg(e,t,8)^bg(e,t,7),i=0|Ug[v-2],o=0|jg[v-2],s=wg(i,o,19)^kg(i,o,61)^vg(i,0,6),a=xg(i,o,19)^_g(i,o,61)^bg(i,o,6),c=Eg(n,a,jg[v-7],jg[v-16]),l=Ag(c,r,s,Ug[v-7],Ug[v-16]);Ug[v]=0|l,jg[v]=0|c}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:m,Hh:g,Hl:y}=this;for(let v=0;v<80;v++){const e=wg(u,h,14)^wg(u,h,18)^kg(u,h,41),t=xg(u,h,14)^xg(u,h,18)^_g(u,h,41),b=u&d^~u&f,w=Mg(y,t,h&p^~h&m,Lg[v],jg[v]),x=Ng(w,g,e,b,Rg[v],Ug[v]),k=0|w,_=wg(r,n,28)^kg(r,n,34)^kg(r,n,39),S=xg(r,n,28)^_g(r,n,34)^_g(r,n,39),C=r&i^r&s^i&s,I=n&o^n&a^o&a;g=0|f,y=0|m,f=0|d,m=0|p,d=0|u,p=0|h,({h:u,l:h}=Sg(0|c,0|l,0|x,0|k)),c=0|s,l=0|a,s=0|i,a=0|o,i=0|r,o=0|n;const E=Cg(k,S,I);r=Ig(E,x,_,C),n=0|E}({h:r,l:n}=Sg(0|this.Ah,0|this.Al,0|r,0|n)),({h:i,l:o}=Sg(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:a}=Sg(0|this.Ch,0|this.Cl,0|s,0|a)),({h:c,l:l}=Sg(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=Sg(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=Sg(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:m}=Sg(0|this.Gh,0|this.Gl,0|f,0|m)),({h:g,l:y}=Sg(0|this.Hh,0|this.Hl,0|g,0|y)),this.set(r,n,i,o,s,a,c,l,u,h,d,p,f,m,g,y)}roundClean(){qm(Ug,jg)}destroy(){qm(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Fg=ag(()=>new Tg),zg=ag(()=>new Dg),qg=Fg;function Wg(e){const{commitment:t,version:r=1}=e,n=e.to??("string"==typeof t?"hex":"bytes"),i=function(e){return qg(Df(e,{strict:!1})?Jf(e):e)}(t);return i.set([r],0),"bytes"===n?i:Hf(i)}const $g=4096,Gg=131072,Vg=761855;class Hg extends Rf{constructor({maxSize:e,size:t}){super("Blob size is too large.",{metaMessages:[`Max: ${e} bytes`,`Given: ${t} bytes`],name:"BlobSizeTooLargeError"})}}class Kg extends Rf{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class Zg extends Rf{constructor({hash:e,size:t}){super(`Versioned hash "${e}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${t}`],name:"InvalidVersionedHashSizeError"})}}class Yg extends Rf{constructor({hash:e,version:t}){super(`Versioned hash "${e}" version is invalid.`,{metaMessages:["Expected: 1",`Received: ${t}`],name:"InvalidVersionedHashVersionError"})}}function Jg(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??function(e){const t=e.to??("string"==typeof e.data?"hex":"bytes"),r="string"==typeof e.data?em(e.data):e.data,n=Ff(r);if(!n)throw new Kg;if(n>Vg)throw new Hg({maxSize:Vg,size:n});const i=[];let o=!0,s=0;for(;o;){const e=_m(new Uint8Array(Gg));let t=0;for(;t<$g;){const n=r.slice(s,s+31);if(e.pushByte(0),e.pushBytes(n),n.length<31){e.pushByte(128),o=!1;break}t++,s+=31}i.push(e)}return"bytes"===t?i.map(e=>e.bytes):i.map(e=>Hf(e.bytes))}({data:t,to:n}),o=e.commitments??Tm({blobs:i,kzg:r,to:n}),s=e.proofs??Om({blobs:i,commitments:o,kzg:r,to:n}),a=[];for(let c=0;c<i.length;c++)a.push({blob:i[c],commitment:o[c],proof:s[c]});return a}class Xg extends Rf{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Qg extends Rf{constructor({chainId:e}){super("number"==typeof e?`Chain ID "${e}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}class ey extends Rf{constructor({cause:e,maxFeePerGas:t}={}){super(`The fee cap (\`maxFeePerGas\`${t?` = ${Am(t)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:e,name:"FeeCapTooHighError"})}}Object.defineProperty(ey,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class ty extends Rf{constructor({cause:e,maxPriorityFeePerGas:t,maxFeePerGas:r}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${t?` = ${Am(t)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${r?` = ${Am(r)} gwei`:""}).`].join("\n"),{cause:e,name:"TipAboveFeeCapError"})}}Object.defineProperty(ty,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class ry extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const ny=BigInt(0),iy=BigInt(1),oy=BigInt(2),sy=BigInt(7),ay=BigInt(256),cy=BigInt(113),ly=[],uy=[],hy=[];for(let AE=0,ME=iy,NE=1,PE=0;AE<24;AE++){[NE,PE]=[PE,(2*NE+3*PE)%5],ly.push(2*(5*PE+NE)),uy.push((AE+1)*(AE+2)/2%64);let e=ny;for(let t=0;t<7;t++)ME=(ME<<iy^(ME>>sy)*cy)%ay,ME&oy&&(e^=iy<<(iy<<BigInt(t))-iy);hy.push(e)}const dy=yg(hy,!0),py=dy[0],fy=dy[1],my=(e,t,r)=>r>32?((e,t,r)=>t<<r-32|e>>>64-r)(e,t,r):((e,t,r)=>e<<r|t>>>32-r)(e,t,r),gy=(e,t,r)=>r>32?((e,t,r)=>e<<r-32|t>>>64-r)(e,t,r):((e,t,r)=>t<<r|e>>>32-r)(e,t,r);class yy extends sg{constructor(e,t,r,n=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,Um(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var o;this.state=new Uint8Array(200),this.state32=(o=this.state,new Uint32Array(o.buffer,o.byteOffset,Math.floor(o.byteLength/4)))}clone(){return this._cloneInto()}keccak(){Vm(this.state32),function(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let n=0;n<10;n++)r[n]=e[n]^e[n+10]^e[n+20]^e[n+30]^e[n+40];for(let n=0;n<10;n+=2){const t=(n+8)%10,i=(n+2)%10,o=r[i],s=r[i+1],a=my(o,s,1)^r[t],c=gy(o,s,1)^r[t+1];for(let r=0;r<50;r+=10)e[n+r]^=a,e[n+r+1]^=c}let t=e[2],i=e[3];for(let r=0;r<24;r++){const n=uy[r],o=my(t,i,n),s=gy(t,i,n),a=ly[r];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}for(let n=0;n<50;n+=10){for(let t=0;t<10;t++)r[t]=e[n+t];for(let t=0;t<10;t++)e[n+t]^=~r[(t+2)%10]&r[(t+4)%10]}e[0]^=py[n],e[1]^=fy[n]}qm(r)}(this.state32,this.rounds),Vm(this.state32),this.posOut=0,this.pos=0}update(e){Fm(this),jm(e=ig(e));const{blockLen:t,state:r}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(t-this.pos,n-i);for(let t=0;t<o;t++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,128&t&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Fm(this,!1),jm(e),this.finish();const t=this.state,{blockLen:r}=this;for(let n=0,i=e.length;n<i;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Um(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(zm(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,qm(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new yy(t,r,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const vy=(()=>{return e=1,t=136,r=32,ag(()=>new yy(t,e,r));var e,t,r})();const by=new ry(8192);function wy(e,t){if(by.has(`${e}.${t}`))return by.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=function(e){return vy(Df(e,{strict:!1})?Jf(e):e)}(tm(r)),i=r.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&i[s]&&(i[s]=i[s].toUpperCase()),(15&n[s>>1])>=8&&i[s+1]&&(i[s+1]=i[s+1].toUpperCase());const o=`0x${i.join("")}`;return by.set(`${e}.${t}`,o),o}const xy=/^0x[a-fA-F0-9]{40}$/,ky=new ry(8192);function _y(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(ky.has(n))return ky.get(n);const i=!(!xy.test(e)||e.toLowerCase()!==e&&r&&wy(e)!==e);return ky.set(n,i),i}function Sy(e,t,r,{strict:n}={}){return Df(e,{strict:!1})?function(e,t,r,{strict:n}={}){const i=`0x${e.replace("0x","").slice(2*t,2*r)}`;n&&Cy(i,t,r);return i}(e,t,r,{strict:n}):function(e,t,r,{strict:n}={}){const i=e.slice(t,r);n&&Cy(i,t,r);return i}(e,t,r,{strict:n})}function Cy(e,t,r){if(Ff(e)!==r-t)throw new qf({offset:r,position:"end",size:Ff(e)})}function Iy(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new Qg({chainId:t});if(i&&!_y(i))throw new Xg({address:i});if(n&&n>ym)throw new ey({maxFeePerGas:n});if(r&&n&&r>n)throw new ty({maxFeePerGas:n,maxPriorityFeePerGas:r})}function Ey(e){if(!e||0===e.length)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let e=0;e<i.length;e++)if(i[e].length-2!=64)throw new Bm({storageKey:i[e]});if(!_y(n,{strict:!1}))throw new Xg({address:n});t.push([n,i])}return t}function Ay(e,t){const r=function(e){if(e.type)return e.type;if(void 0!==e.authorizationList)return"eip7702";if(void 0!==e.blobs||void 0!==e.blobVersionedHashes||void 0!==e.maxFeePerBlobGas||void 0!==e.sidecars)return"eip4844";if(void 0!==e.maxFeePerGas||void 0!==e.maxPriorityFeePerGas)return"eip1559";if(void 0!==e.gasPrice)return void 0!==e.accessList?"eip2930":"legacy";throw new Pm({transaction:e})}(e);return"eip1559"===r?function(e,t){const{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,data:u}=e;Iy(e);const h=Ey(l),d=[Kf(r),i?Kf(i):"0x",c?Kf(c):"0x",a?Kf(a):"0x",n?Kf(n):"0x",o??"0x",s?Kf(s):"0x",u??"0x",h,...My(e,t)];return vm(["0x02",Sm(d)])}(e,t):"eip2930"===r?function(e,t){const{chainId:r,gas:n,data:i,nonce:o,to:s,value:a,accessList:c,gasPrice:l}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o}=e;if(t<=0)throw new Qg({chainId:t});if(o&&!_y(o))throw new Xg({address:o});if(r||i)throw new Rf("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>ym)throw new ey({maxFeePerGas:n})}(e);const u=Ey(c),h=[Kf(r),o?Kf(o):"0x",l?Kf(l):"0x",n?Kf(n):"0x",s??"0x",a?Kf(a):"0x",i??"0x",u,...My(e,t)];return vm(["0x01",Sm(h)])}(e,t):"eip4844"===r?function(e,t){const{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:h}=e;!function(e){const{blobVersionedHashes:t}=e;if(t){if(0===t.length)throw new Kg;for(const e of t){const t=Ff(e),r=im(Sy(e,0,1));if(32!==t)throw new Zg({hash:e,size:t});if(1!==r)throw new Yg({hash:e,version:r})}}Iy(e)}(e);let d=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(void 0===d||void 0===p)){const t="string"==typeof e.blobs[0]?e.blobs:e.blobs.map(e=>Hf(e)),r=e.kzg,n=Tm({blobs:t,kzg:r});if(void 0===d&&(d=function(e){const{commitments:t,version:r}=e,n=e.to??("string"==typeof t[0]?"hex":"bytes"),i=[];for(const o of t)i.push(Wg({commitment:o,to:n,version:r}));return i}({commitments:n})),void 0===p){p=Jg({blobs:t,commitments:n,proofs:Om({blobs:t,commitments:n,kzg:r})})}}const f=Ey(u),m=[Kf(r),i?Kf(i):"0x",l?Kf(l):"0x",c?Kf(c):"0x",n?Kf(n):"0x",o??"0x",s?Kf(s):"0x",h??"0x",f,a?Kf(a):"0x",d??[],...My(e,t)],g=[],y=[],v=[];if(p)for(let b=0;b<p.length;b++){const{blob:e,commitment:t,proof:r}=p[b];g.push(e),y.push(t),v.push(r)}return vm(["0x03",Sm(p?[m,g,y,v]:m)])}(e,t):"eip7702"===r?function(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:o,to:s,value:a,maxFeePerGas:c,maxPriorityFeePerGas:l,accessList:u,data:h}=e;!function(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:e}=r,t=r.address;if(!_y(t))throw new Xg({address:t});if(e<0)throw new Qg({chainId:e})}Iy(e)}(e);const d=Ey(u),p=function(e){if(!e||0===e.length)return[];const t=[];for(const r of e){const{chainId:e,nonce:n,...i}=r,o=r.address;t.push([e?Vf(e):"0x",o,n?Vf(n):"0x",...My({},i)])}return t}(r);return vm(["0x04",Sm([Kf(n),o?Kf(o):"0x",l?Kf(l):"0x",c?Kf(c):"0x",i?Kf(i):"0x",s??"0x",a?Kf(a):"0x",h??"0x",d,p,...My(e,t)])])}(e,t):function(e,t){const{chainId:r=0,gas:n,data:i,nonce:o,to:s,value:a,gasPrice:c}=e;!function(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o}=e;if(o&&!_y(o))throw new Xg({address:o});if(void 0!==t&&t<=0)throw new Qg({chainId:t});if(r||i)throw new Rf("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>ym)throw new ey({maxFeePerGas:n})}(e);let l=[o?Kf(o):"0x",c?Kf(c):"0x",n?Kf(n):"0x",s??"0x",a?Kf(a):"0x",i??"0x"];if(t){const e=(()=>{if(t.v>=35n){return(t.v-35n)/2n>0?t.v:27n+(35n===t.v?0n:1n)}if(r>0)return BigInt(2*r)+BigInt(35n+t.v-27n);const e=27n+(27n===t.v?0n:1n);if(t.v!==e)throw new Nm({v:t.v});return e})(),n=zf(t.r),i=zf(t.s);l=[...l,Kf(e),"0x00"===n?"0x":n,"0x00"===i?"0x":i]}else r>0&&(l=[...l,Kf(r),"0x","0x"]);return Sm(l)}(e,t)}function My(e,t){const r=t??e,{v:n,yParity:i}=r;if(void 0===r.r)return[];if(void 0===r.s)return[];if(void 0===n&&void 0===i)return[];const o=zf(r.r),s=zf(r.s);return["number"==typeof i?i?Kf(1):"0x":0n===n?"0x":1n===n?Kf(1):27n===n?"0x":Kf(1),"0x00"===o?"0x":o,"0x00"===s?"0x":s]}const Ny={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}};function Py(e,t){return function(e){return"deposit"===e.type||void 0!==e.sourceHash}(e)?function(e){!function(e){const{from:t,to:r}=e;if(t&&!_y(t))throw new Xg({address:t});if(r&&!_y(r))throw new Xg({address:r})}(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:o,mint:s,to:a,value:c}=e,l=[t,n,a??"0x",s?Vf(s):"0x",c?Vf(c):"0x",i?Vf(i):"0x",o?"0x1":"0x",r??"0x"];return vm(["0x7e",Sm(l)])}(e):Ay(e,t)}const By={blockTime:2e3,contracts:Ny,formatters:{block:um({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;const t=am(e);return"0x7e"===t.typeHex&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?nm(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}),stateRoot:e.stateRoot}}}),transaction:cm({format(e){const t={};return"0x7e"===e.type&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?nm(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:pm({format:e=>({l1GasPrice:e.l1GasPrice?nm(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?nm(e.l1GasUsed):null,l1Fee:e.l1Fee?nm(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null})})},serializers:{transaction:Py}},Ty=Bf({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:250,rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Oy=Bf({id:43114,name:"Avalanche",blockTime:1700,nativeCurrency:{decimals:18,name:"Avalanche",symbol:"AVAX"},rpcUrls:{default:{http:["https://api.avax.network/ext/bc/C/rpc"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io",apiUrl:"https://api.snowtrace.io"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:11907934}}}),Ry=1,Ly=Bf({...By,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...By.contracts,disputeGameFactory:{[Ry]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[Ry]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[Ry]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[Ry]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:1}),Uy=Bf({id:56,name:"BNB Smart Chain",blockTime:750,nativeCurrency:{decimals:18,name:"BNB",symbol:"BNB"},rpcUrls:{default:{http:["https://56.rpc.thirdweb.com"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com",apiUrl:"https://api.bscscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:15921452}}}),jy={estimateFeesPerGas:async e=>{var t;if(!(null==(t=e.request)?void 0:t.feeCurrency))return null;const[r,n]=await Promise.all([Dy(e.client,e.request.feeCurrency),Fy(e.client,e.request.feeCurrency)]);return{maxFeePerGas:e.multiply(r-n)+n,maxPriorityFeePerGas:n}}};async function Dy(e,t){const r=await e.request({method:"eth_gasPrice",params:[t]});return BigInt(r)}async function Fy(e,t){const r=await e.request({method:"eth_maxPriorityFeePerGas",params:[t]});return BigInt(r)}function zy(e){return 0===e||0n===e||null==e||"0"===e||""===e||"string"==typeof e&&("0x"===zf(e).toLowerCase()||"0x00"===zf(e).toLowerCase())}function qy(e){return!zy(e)}function Wy(e){return"cip64"===e.type||function(e){return void 0!==e.maxFeePerGas&&void 0!==e.maxPriorityFeePerGas}(e)&&qy(e.feeCurrency)}const $y={transaction:function(e,t){return Wy(e)?function(e,t){!function(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:o,feeCurrency:s}=e;if(t<=0)throw new Qg({chainId:t});if(o&&!_y(o))throw new Xg({address:o});if(n)throw new Rf("`gasPrice` is not a valid CIP-64 Transaction attribute.");if(qy(i)&&i>Gy)throw new ey({maxFeePerGas:i});if(qy(r)&&qy(i)&&r>i)throw new ty({maxFeePerGas:i,maxPriorityFeePerGas:r});if(qy(s)&&!_y(s))throw new Rf("`feeCurrency` MUST be a token address for CIP-64 transactions.");if(zy(s))throw new Rf("`feeCurrency` must be provided for CIP-64 transactions.")}(e);const{chainId:r,gas:n,nonce:i,to:o,value:s,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:l,feeCurrency:u,data:h}=e,d=[Vf(r),i?Vf(i):"0x",c?Vf(c):"0x",a?Vf(a):"0x",n?Vf(n):"0x",o??"0x",s?Vf(s):"0x",h??"0x",Ey(l),u,...My(e,t)];return vm(["0x7b",Sm(d)])}(e,t):Py(e,t)}};const Gy=ym;const Vy=Bf({...{blockTime:1e3,contracts:Ny,formatters:{block:um({format(e){var t;return{transactions:null==(t=e.transactions)?void 0:t.map(e=>{if("string"==typeof e)return e;return{...am(e),...e.gatewayFee?{gatewayFee:nm(e.gatewayFee),gatewayFeeRecipient:e.gatewayFeeRecipient}:{},feeCurrency:e.feeCurrency}})}}}),transaction:cm({format(e){if("0x7e"===e.type)return{isSystemTx:e.isSystemTx,mint:e.mint?nm(e.mint):void 0,sourceHash:e.sourceHash,type:"deposit"};const t={feeCurrency:e.feeCurrency};return"0x7b"===e.type?t.type="cip64":("0x7c"===e.type&&(t.type="cip42"),t.gatewayFee=e.gatewayFee?nm(e.gatewayFee):null,t.gatewayFeeRecipient=e.gatewayFeeRecipient),t}}),transactionRequest:gm({format(e){const t={};return e.feeCurrency&&(t.feeCurrency=e.feeCurrency),Wy(e)&&(t.type="0x7b"),t}})},serializers:$y,fees:jy},id:42220,name:"Celo",nativeCurrency:{decimals:18,name:"CELO",symbol:"CELO"},rpcUrls:{default:{http:["https://forno.celo.org"]}},blockExplorers:{default:{name:"Celo Explorer",url:"https://celoscan.io",apiUrl:"https://api.celoscan.io/api"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:13112599}},testnet:!1}),Hy=Bf({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},blockTime:12e3,rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensUniversalResolver:{address:"0xeeeeeeee14d718c2b47d9923deab1335e144eeee",blockCreated:23085558},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Ky=1,Zy=Bf({...By,id:10,name:"OP Mainnet",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io"]}},blockExplorers:{default:{name:"Optimism Explorer",url:"https://optimistic.etherscan.io",apiUrl:"https://api-optimistic.etherscan.io/api"}},contracts:{...By.contracts,disputeGameFactory:{[Ky]:{address:"0xe5965Ab5962eDc7477C8520243A95517CD252fA9"}},l2OutputOracle:{[Ky]:{address:"0xdfe97868233d1aa22e815a266982f2cf17685a27"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:4286263},portal:{[Ky]:{address:"0xbEb5Fc579115071764c7423A4f12eDde41f106Ed"}},l1StandardBridge:{[Ky]:{address:"0x99C9fc46f92E8a1c0deC1b1747d010903E884bE1"}}},sourceId:1}),Yy=Bf({id:137,name:"Polygon",blockTime:2e3,nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-rpc.com"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com",apiUrl:"https://api.polygonscan.com/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:25770160}}}),Jy=(e,t,r=!1)=>{if(!e||"string"!=typeof e)throw new Error(`Missing ${t} address`);if(!e.startsWith("0x"))throw new Error(`Invalid ${t} address format: must start with 0x`);if(42!==e.length)throw new Error(`Invalid ${t} address length: expected 42 characters, got ${e.length}`);if("0x0000000000000000000000000000000000000000"===e&&!r)throw new Error(`Invalid ${t} address: cannot be zero address`)},Xy=e=>{const t=(e=>{Jy(e.token,"token"),Jy(e.recipient1,"recipient1"),Jy(e.recipient2,"recipient2");const t=0n===BigInt(e.recipient3Percentage||0);if(Jy(e.recipient3,"recipient3",t),!e.paymentId||"string"!=typeof e.paymentId||0===e.paymentId.length)throw new Error("Invalid payment ID: must be a non-empty string");let r,n,i,o;try{r=BigInt(e.amount||0),n=BigInt(e.recipient1Percentage||0),i=BigInt(e.recipient2Percentage||0),o=BigInt(e.recipient3Percentage||0)}catch(a){throw new Error("Invalid numeric values: cannot convert to BigInt")}if(r<=0n)throw new Error(`Invalid amount: ${e.amount} (must be greater than 0)`);const s=n+i+o;if(10000n!==s)throw new Error(`Invalid percentages: total is ${s} but must equal 10000 basis points (100%). Individual: ${n}, ${i}, ${o}`);return{amount:r,percentage1:n,percentage2:i,percentage3:o}})(e);return{token:e.token,amount:t.amount,paymentId:e.paymentId,recipient1:e.recipient1,recipient2:e.recipient2,recipient3:e.recipient3,recipient1Percentage:t.percentage1,recipient2Percentage:t.percentage2,recipient3Percentage:t.percentage3}},Qy=[{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"}],ev=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"}],tv=e=>{var t,r;const n=(null==(t=null==e?void 0:e.message)?void 0:t.toLowerCase())||(null==(r=null==e?void 0:e.toString())?void 0:r.toLowerCase())||"",i=(null==e?void 0:e.code)||(null==e?void 0:e.reason)||"";return n.includes("user rejected")||n.includes("user denied")||n.includes("user cancelled")||n.includes("rejected by user")||4001===i||"ACTION_REJECTED"===i?{type:"user_rejected",title:"Transaction Cancelled",message:"You cancelled the transaction. No charges were made.",suggestion:'Click "Pay Now" to try again when you\'re ready.'}:n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("insufficient eth")||n.includes("insufficient matic")||n.includes("insufficient bnb")||-32e3===i?{type:"insufficient_funds",title:"Insufficient Funds",message:"You don't have enough tokens or gas fees in your wallet.",suggestion:"Add more funds to your wallet and try again."}:n.includes("network error")||n.includes("rpc error")||n.includes("connection failed")||n.includes("timeout")||n.includes("request failed")?{type:"network_error",title:"Network Error",message:"Unable to connect to the blockchain network.",suggestion:"Check your internet connection and try again."}:n.includes("wrong network")||n.includes("unsupported network")||n.includes("chain mismatch")||4902===i?{type:"wrong_network",title:"Wrong Network",message:"Please switch to the correct network in your wallet.",suggestion:"Your wallet should prompt you to switch networks."}:n.includes("wallet not connected")||n.includes("no provider")||n.includes("wallet disconnected")||4900===i?{type:"wallet_disconnected",title:"Wallet Disconnected",message:"Your wallet is not connected.",suggestion:"Please reconnect your wallet and try again."}:n.includes("gas estimation failed")||n.includes("execution reverted")||n.includes("out of gas")?{type:"gas_error",title:"Transaction Failed",message:"The transaction couldn't be processed.",suggestion:"This might be a temporary issue. Please try again."}:n.includes("approve")&&n.includes("failed")?{type:"approval_failed",title:"Token Approval Failed",message:"Failed to approve token spending.",suggestion:"Please try the approval step again."}:n.includes("transaction failed")||n.includes("revert")||n.includes("contract call failed")?{type:"transaction_failed",title:"Transaction Failed",message:"The blockchain transaction was unsuccessful.",suggestion:"Please check your wallet and try again."}:n.includes("popup")||n.includes("blocked")?{type:"popup_blocked",title:"Wallet Popup Blocked",message:"Your browser blocked the wallet popup.",suggestion:"Please allow popups for this site and try again."}:n.includes("rate limit")||n.includes("too many requests")?{type:"rate_limited",title:"Too Many Requests",message:"Please wait a moment before trying again.",suggestion:"Wait 30 seconds and retry your transaction."}:n.includes("payment not yet confirmed")||n.includes("not yet confirmed on-chain")||n.includes("payment not found on-chain")||n.includes("please complete the payment")?{type:"payment_pending",title:"Payment Pending",message:"Your payment is still being confirmed on the blockchain.",suggestion:"Please wait a moment and try again, or check if your transaction completed successfully."}:n.includes("deep link")||n.includes("app not installed")||n.includes("wallet app")?{type:"mobile_wallet_error",title:"Wallet App Issue",message:"Unable to open or connect to your wallet app.",suggestion:"Make sure your wallet app is installed and try again."}:{type:"unknown_error",title:"Something Went Wrong",message:"An unexpected error occurred.",suggestion:"Please try again or contact support if the problem persists."}},rv=(e,t="")=>({timestamp:(new Date).toISOString(),context:t,userFriendly:tv(e),technical:{message:(null==e?void 0:e.message)||"Unknown error",code:null==e?void 0:e.code,reason:null==e?void 0:e.reason,stack:null==e?void 0:e.stack,name:null==e?void 0:e.name}}),nv=async(e,t)=>{try{const r=await o.estimateFeesPerGas(e,{chainId:t}),n=120n,i=100n;return{maxFeePerGas:r.maxFeePerGas?r.maxFeePerGas*n/i:void 0,maxPriorityFeePerGas:r.maxPriorityFeePerGas?r.maxPriorityFeePerGas*n/i:void 0}}catch(vu){return{}}},iv="YWG990wOlIikc1tU7-WWTepfU8d1f4dp",ov=(e,t,i,s,a,l)=>{const[u,h]=r.useState("idle"),[d,p]=r.useState(""),[f,m]=r.useState(null),{data:g,isPending:y,error:v,sendTransaction:b}=n.useSendTransaction(),{isLoading:w,isSuccess:x}=n.useWaitForTransactionReceipt({hash:g}),k=async()=>{var e,t,r,n,i,s,c;try{h("splitPayment");const d=window.coinleyPendingSplitPayment;if(!d)throw new Error("Missing split payment data");const{contractCall:p,selectedToken:f,paymentData:g,selectedNetwork:y}=d,v=y.chainId||10,b=await a.getContractInfo(v),{abi:w}=b,x=Xy(p.params),k=Mf(v),_=1===k,S=_||43114===k;try{const{request:e}=await o.simulateContract(pf,{address:p.contractAddress,abi:w,functionName:"splitPayment",args:[x]})}catch(l){const i=l.data||(null==(e=l.cause)?void 0:e.data);i&&("string"==typeof i&&i.startsWith("0x08c379a0")||"string"==typeof i&&i.startsWith("0x4e487b71"));l.reason||(null==(t=l.cause)?void 0:t.reason)||(null==(r=l.cause)?void 0:r.shortMessage)||(null==(n=l.data)||n.message);if(!S){const{userFriendlyMessage:e}=(e=>{if(!e.message)return{revertReason:"Transaction will revert",userFriendlyMessage:"Transaction simulation failed"};const t=e.message.toLowerCase();return t.includes("abi encoding params/values length mismatch")?{revertReason:"Smart contract parameter mismatch. This is likely a technical issue.",userFriendlyMessage:"Technical error: Contract parameters mismatch. Please try again or contact support."}:t.includes("payment id already used")?{revertReason:"This payment ID has already been used.",userFriendlyMessage:"This payment has already been processed. Please check your transaction history."}:t.includes("percentages must equal 100")?{revertReason:"Payment split percentages are incorrect.",userFriendlyMessage:"Internal error: Payment split configuration is invalid. Please contact support."}:t.includes("token transfer failed")||t.includes("transfer amount exceeds")?{revertReason:"Insufficient token balance or approval.",userFriendlyMessage:"Insufficient balance or token approval. Please check your wallet balance."}:t.includes("amount must be greater than 0")?{revertReason:"Payment amount is invalid.",userFriendlyMessage:"Invalid payment amount. Please try again."}:t.includes("invalid recipient")||t.includes("zero address")?{revertReason:"One of the payment recipients has an invalid address.",userFriendlyMessage:"Payment configuration error: Invalid recipient address. Please contact support."}:t.includes("insufficient gas")||t.includes("out of gas")?{revertReason:"Insufficient gas for transaction.",userFriendlyMessage:"Not enough gas to process transaction. Please increase gas limit or check ETH balance."}:t.includes("nonce")?{revertReason:"Transaction nonce conflict.",userFriendlyMessage:"Transaction ordering conflict. Please try again in a moment."}:{revertReason:e.message,userFriendlyMessage:`Transaction simulation failed: ${e.message.substring(0,100)}${e.message.length>100?"...":""}`}})(l);throw new Error(e)}}const C=await nv(pf,v),I="arbitrum"===y.shortName,E=I?2:0;let A;for(let e=0;e<=E;e++)try{if(e>0){const t=2e3*e;await new Promise(e=>setTimeout(e,t))}A=await o.writeContract(pf,{address:p.contractAddress,abi:w,functionName:"splitPayment",args:[x],...C});break}catch(u){const t=(null==(i=u.message)?void 0:i.includes("Internal JSON-RPC error"))||(null==(s=u.message)?void 0:s.includes("-32603"))||(null==(c=u.message)?void 0:c.includes("nonce"));if(e===E||!t&&!I)throw u}return m(A),h("processing"),window.coinleyPendingSplitPayment=null,A}catch(vu){rv(vu,"split_payment_transaction");const t=tv(vu);throw p(t),h("error"),vu}},_=async r=>{try{if(h("processing"),!a||!a.processPayment)throw new Error("API instance not available or missing processPayment method");await new Promise(e=>setTimeout(e,8e3));const n=await a.processPayment(e.id,r,i.shortName,s);return h("success"),lf.trackPaymentSuccess(e.id,e.amount,null==i?void 0:i.shortName,null==t?void 0:t.symbol,r),n}catch(vu){rv(vu,"final_payment_processing");const n=tv(vu);throw p(n),h("error"),lf.trackPaymentFailed(null==e?void 0:e.id,null==e?void 0:e.amount,null==i?void 0:i.shortName,null==t?void 0:t.symbol,n),vu}};return{transactionStep:u,transactionError:d,currentTransactionHash:f,txPending:y,isConfirming:w,isConfirmed:x,executePaymentTransaction:async()=>{var r,n;if(!s||!(null==e?void 0:e.contractCall))throw new Error("Missing wallet connection or payment data");const a=e.contractCall;if(!a.contractAddress)throw new Error("PaymentSplitter contract data missing from payment response");if((null==l?void 0:l.ensureCorrectNetwork)&&i){if(!(await l.ensureCorrectNetwork(i)))throw new Error("Network verification failed. Please ensure you are on the correct network.")}if(!t.contractAddress)throw new Error("Native token transactions not yet supported with PaymentSplitter. Please use ERC-20 tokens.");{const l=t.decimals||6,b=a.approvalAmount||Math.floor(e.totalAmount*Math.pow(10,l));try{let e,r="unknown";try{e=await o.readContract(pf,{address:a.tokenAddress,abi:ev,functionName:"balanceOf",args:[s]}),r="wallet-rpc"}catch(u){const t=(null==i?void 0:i.chainId)||(null==i?void 0:i.id);if(!t)throw u;{const n=(e=>{const t={1:Hy,56:Uy,137:Yy,42161:Ty,10:Zy,43114:Oy,42220:Vy,8453:Ly}[e],r={1:[`https://eth-mainnet.g.alchemy.com/v2/${iv}`,"https://cloudflare-eth.com","https://eth.llamarpc.com","https://ethereum.publicnode.com"],56:[`https://bnb-mainnet.g.alchemy.com/v2/${iv}`,"https://bsc-dataseed.bnbchain.org","https://bsc-dataseed-public.bnbchain.org","https://bsc.nodereal.io"],137:[`https://polygon-mainnet.g.alchemy.com/v2/${iv}`,"https://polygon.llamarpc.com","https://polygon-rpc.com","https://polygon.drpc.org"],42161:[`https://arb-mainnet.g.alchemy.com/v2/${iv}`,"https://arb1.arbitrum.io/rpc","https://arbitrum.llamarpc.com"],10:[`https://opt-mainnet.g.alchemy.com/v2/${iv}`,"https://mainnet.optimism.io","https://optimism.llamarpc.com"],43114:[`https://avax-mainnet.g.alchemy.com/v2/${iv}`,"https://api.avax.network/ext/bc/C/rpc","https://avalanche.public-rpc.com"],42220:[`https://celo-mainnet.g.alchemy.com/v2/${iv}`,"https://forno.celo.org","https://celo.drpc.org"],8453:[`https://base-mainnet.g.alchemy.com/v2/${iv}`,"https://mainnet.base.org","https://base.llamarpc.com","https://base.meowrpc.com"]}[e];if(!t||!r)return null;const n=r.map(e=>c.http(e,{timeout:1e4,retryCount:1}));return c.createPublicClient({chain:t,transport:c.fallback(n)})})(Mf(t));if(!n)throw u;try{e=await n.readContract({address:a.tokenAddress,abi:ev,functionName:"balanceOf",args:[s]}),r="fallback-rpc"}catch(d){throw u}}}const n=BigInt(b);if(e<n){const r=`Insufficient ${t.symbol} balance. You have ${(Number(e)/Math.pow(10,l)).toFixed(6)} ${t.symbol} but need ${(Number(n)/Math.pow(10,l)).toFixed(6)} ${t.symbol}`;throw new Error(r)}}catch(f){if(f.message.includes("Insufficient"))throw f}h("approve"),window.coinleyPendingSplitPayment={contractCall:a,selectedToken:t,paymentData:e,selectedNetwork:i};try{const e="0xdac17f958d2ee523a2206206994597c13d831ec7"===a.tokenAddress.toLowerCase()||"USDT"===t.symbol.toUpperCase();let r,n=c.erc20Abi;e&&(n=Qy);try{r=BigInt(b)}catch(g){throw new Error(`Invalid amount value: ${b}`)}let l=0n,u=0;const d=3;for(;u<d;)try{l=await o.readContract(pf,{address:a.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[s,a.contractAddress]});break}catch(y){u++,u<d?await new Promise(e=>setTimeout(e,2e3)):l=0n}if(l>=r){h("splitPayment");const e=await k();return e&&await _(e),e}if(e&&l>0n){const e=await nv(pf,i.chainId),t=await o.writeContract(pf,{address:a.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[a.contractAddress,0n],...e});await o.waitForTransactionReceipt(pf,{hash:t,confirmations:1,timeout:12e4})}const p=await nv(pf,i.chainId),f=await o.writeContract(pf,{address:a.tokenAddress,abi:c.erc20Abi,functionName:"approve",args:[a.contractAddress,r],...p});m(f);await o.waitForTransactionReceipt(pf,{hash:f,confirmations:1,timeout:12e4});await new Promise(e=>setTimeout(e,3e3));let w=0;const x=3;let S=!1;for(;w<x&&!S;){try{if(await o.readContract(pf,{address:a.tokenAddress,abi:c.erc20Abi,functionName:"allowance",args:[s,a.contractAddress]})>=r){S=!0;break}w<x-1&&await new Promise(e=>setTimeout(e,2e3))}catch(v){w<x-1&&await new Promise(e=>setTimeout(e,2e3))}w++}const C=await k();return C&&await _(C),C}catch(vu){rv(vu,"approve_transaction");const t=tv(vu);if(p(t),h("idle"),(null==(r=vu.message)?void 0:r.includes("User rejected"))||(null==(n=vu.message)?void 0:n.includes("User denied"))||4001===vu.code)throw new Error("Transaction was cancelled by user");throw new Error(`Approve failed: ${vu.message}`)}}},executeSplitPayment:k,processFinalPayment:_,resetTransaction:()=>{h("idle"),p(""),m(null),window.coinleyPendingSplitPayment=null},setTransactionError:p,setTransactionStep:h}};var sv="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};function av(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function cv(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}for(var lv={},uv={byteLength:function(e){var t=gv(e),r=t[0],n=t[1];return 3*(r+n)/4-n},toByteArray:function(e){var t,r,n=gv(e),i=n[0],o=n[1],s=new pv(function(e,t,r){return 3*(t+r)/4-r}(0,i,o)),a=0,c=o>0?i-4:i;for(r=0;r<c;r+=4)t=dv[e.charCodeAt(r)]<<18|dv[e.charCodeAt(r+1)]<<12|dv[e.charCodeAt(r+2)]<<6|dv[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===o&&(t=dv[e.charCodeAt(r)]<<2|dv[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===o&&(t=dv[e.charCodeAt(r)]<<10|dv[e.charCodeAt(r+1)]<<4|dv[e.charCodeAt(r+2)]>>2,s[a++]=t>>8&255,s[a++]=255&t);return s},fromByteArray:function(e){for(var t,r=e.length,n=r%3,i=[],o=16383,s=0,a=r-n;s<a;s+=o)i.push(vv(e,s,s+o>a?a:s+o));1===n?(t=e[r-1],i.push(hv[t>>2]+hv[t<<4&63]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],i.push(hv[t>>10]+hv[t>>4&63]+hv[t<<2&63]+"="));return i.join("")}},hv=[],dv=[],pv="undefined"!=typeof Uint8Array?Uint8Array:Array,fv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",mv=0;mv<64;++mv)hv[mv]=fv[mv],dv[fv.charCodeAt(mv)]=mv;function gv(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function yv(e){return hv[e>>18&63]+hv[e>>12&63]+hv[e>>6&63]+hv[63&e]}function vv(e,t,r){for(var n,i=[],o=t;o<r;o+=3)n=(e[o]<<16&16711680)+(e[o+1]<<8&65280)+(255&e[o+2]),i.push(yv(n));return i.join("")}dv["-".charCodeAt(0)]=62,dv["_".charCodeAt(0)]=63;var bv={
|
|
3
|
+
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
4
|
+
read:function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<<a)-1,l=c>>1,u=-7,h=r?i-1:0,d=r?-1:1,p=e[t+h];for(h+=d,o=p&(1<<-u)-1,p>>=-u,u+=a;u>0;o=256*o+e[t+h],h+=d,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+h],h+=d,u-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=l}return(p?-1:1)*s*Math.pow(2,o-n)},write:function(e,t,r,n,i,o){var s,a,c,l=8*o-i-1,u=(1<<l)-1,h=u>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,f=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+h>=1?d/c:d*Math.pow(2,1-h))*c>=2&&(s++,c/=2),s+h>=u?(a=0,s=u):s+h>=1?(a=(t*c-1)*Math.pow(2,i),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;e[r+p]=255&a,p+=f,a/=256,i-=8);for(s=s<<i|a,l+=i;l>0;e[r+p]=255&s,p+=f,s/=256,l-=8);e[r+p-f]|=128*m}};!function(e){
|
|
5
|
+
/*!
|
|
6
|
+
* The buffer module from node.js, for the browser.
|
|
7
|
+
*
|
|
8
|
+
* @author Feross Aboukhadijeh <https://feross.org>
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
const t=uv,r=bv,n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=s,e.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,s.prototype),t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return a(e,t,r)}function a(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|p(e,t);let n=o(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if(H(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return u(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(H(e,ArrayBuffer)||e&&H(e.buffer,ArrayBuffer))return h(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(H(e,SharedArrayBuffer)||e&&H(e.buffer,SharedArrayBuffer)))return h(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,r);const i=function(e){if(s.isBuffer(e)){const t=0|d(e.length),r=o(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||K(e.length)?o(0):u(e);if("Buffer"===e.type&&Array.isArray(e.data))return u(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function c(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e){return c(e),o(e<0?0:0|d(e))}function u(e){const t=e.length<0?0:0|d(e.length),r=o(t);for(let n=0;n<t;n+=1)r[n]=255&e[n];return r}function h(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,s.prototype),n}function d(e){if(e>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function p(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||H(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return $(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(i)return n?-1:$(e).length;t=(""+t).toLowerCase(),i=!0}}function f(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,r);case"utf8":case"utf-8":return S(this,t,r);case"ascii":return I(this,t,r);case"latin1":case"binary":return E(this,t,r);case"base64":return _(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function m(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function g(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),K(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:y(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):y(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function y(e,t,r,n,i){let o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){let n=-1;for(o=r;o<a;o++)if(l(e,o)===l(t,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===c)return n*s}else-1!==n&&(o-=o-n),n=-1}else for(r+c>a&&(r=a-c),o=r;o>=0;o--){let r=!0;for(let n=0;n<c;n++)if(l(e,o+n)!==l(t,n)){r=!1;break}if(r)return o}return-1}function v(e,t,r,n){r=Number(r)||0;const i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=t.length;let s;for(n>o/2&&(n=o/2),s=0;s<n;++s){const n=parseInt(t.substr(2*s,2),16);if(K(n))return s;e[r+s]=n}return s}function b(e,t,r,n){return V($(t,e.length-r),e,r,n)}function w(e,t,r,n){return V(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function x(e,t,r,n){return V(G(t),e,r,n)}function k(e,t,r,n){return V(function(e,t){let r,n,i;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function _(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function S(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i<r;){const t=e[i];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(i+s<=r){let r,n,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(c=(15&t)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[i+1],n=e[i+2],a=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(e){const t=e.length;if(t<=C)return String.fromCharCode.apply(String,e);let r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=C));return r}(n)}e.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(e,t,r){return a(e,t,r)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(e,t,r){return function(e,t,r){return c(e),e<=0?o(e):void 0!==t?"string"==typeof r?o(e).fill(t,r):o(e).fill(t):o(e)}(e,t,r)},s.allocUnsafe=function(e){return l(e)},s.allocUnsafeSlow=function(e){return l(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),H(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,n=t.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},s.isEncoding=function(e){switch(String(e).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}},s.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return s.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const n=s.allocUnsafe(t);let i=0;for(r=0;r<e.length;++r){let t=e[r];if(H(t,Uint8Array))i+t.length>n.length?(s.isBuffer(t)||(t=s.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!s.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},s.byteLength=p,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)m(this,t,t+1);return this},s.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)m(this,t,t+3),m(this,t+1,t+2);return this},s.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)m(this,t,t+7),m(this,t+1,t+6),m(this,t+2,t+5),m(this,t+3,t+4);return this},s.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?S(this,0,e):f.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(e){if(!s.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===s.compare(this,e)},s.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(e,t,r,n,i){if(H(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(o,a),l=this.slice(n,i),u=e.slice(t,r);for(let s=0;s<c;++s)if(l[s]!==u[s]){o=l[s],a=u[s];break}return o<a?-1:a<o?1:0},s.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},s.prototype.indexOf=function(e,t,r){return g(this,e,t,r,!0)},s.prototype.lastIndexOf=function(e,t,r){return g(this,e,t,r,!1)},s.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return v(this,e,t,r);case"utf8":case"utf-8":return b(this,e,t,r);case"ascii":case"latin1":case"binary":return w(this,e,t,r);case"base64":return x(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return k(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const C=4096;function I(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function E(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function A(e,t,r){const n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let o=t;o<r;++o)i+=Z[e[o]];return i}function M(e,t,r){const n=e.slice(t,r);let i="";for(let o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function N(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,r,n,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function B(e,t,r,n,i){F(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function T(e,t,r,n,i){F(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function O(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function R(e,t,n,i,o){return t=+t,n>>>=0,o||O(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function L(e,t,n,i,o){return t=+t,n>>>=0,o||O(e,0,n,8),r.write(e,t,n,i,52,8),n+8}s.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const n=this.subarray(e,t);return Object.setPrototypeOf(n,s.prototype),n},s.prototype.readUintLE=s.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return n},s.prototype.readUintBE=s.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUint8=s.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readBigUInt64LE=Y(function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||q(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Y(function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||q(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=this[e],i=1,o=0;for(;++o<t&&(i*=256);)n+=this[e+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readBigInt64LE=Y(function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||q(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),s.prototype.readBigInt64BE=Y(function(e){z(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||q(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),s.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){P(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){P(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigUInt64LE=Y(function(e,t=0){return B(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Y(function(e,t=0){return T(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let i=0,o=1,s=0;for(this[t]=255&e;++i<r&&(o*=256);)e<0&&0===s&&0!==this[t+i-1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);P(this,e,t,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/o|0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeBigInt64LE=Y(function(e,t=0){return B(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Y(function(e,t=0){return T(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(e,t,r){return R(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return R(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);const i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},s.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){const t=e.charCodeAt(0);("utf8"===n&&t<128||"latin1"===n)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{const o=s.isBuffer(e)?e:s.from(e,n),a=o.length;if(0===a)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%a]}return this};const U={};function j(e,t,r){U[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function D(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function F(e,t,r,n,i,o){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let n;throw n=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new U.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,r){z(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||q(t,e.length-(r+1))}(n,i,o)}function z(e,t){if("number"!=typeof e)throw new U.ERR_INVALID_ARG_TYPE(t,"number",e)}function q(e,t,r){if(Math.floor(e)!==e)throw z(e,r),new U.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new U.ERR_BUFFER_OUT_OF_BOUNDS;throw new U.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}j("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),j("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),j("ERR_OUT_OF_RANGE",function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function $(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let s=0;s<n;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,r,n){let i;for(i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function H(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function K(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function Y(e){return"undefined"==typeof BigInt?J:e}function J(){throw new Error("BigInt not supported")}}(lv);
|
|
12
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
13
|
+
const wv=BigInt(0),xv=BigInt(1);function kv(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function _v(e,t,r=""){const n=Lm(e),i=null==e?void 0:e.length,o=void 0!==t;if(!n||o&&i!==t){throw new Error((r&&`"${r}" `)+"expected Uint8Array"+(o?` of length ${t}`:"")+", got "+(n?`length=${i}`:"type="+typeof e))}return e}function Sv(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function Cv(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?wv:BigInt("0x"+e)}function Iv(e){return Cv(Zm(e))}function Ev(e){return jm(e),Cv(Zm(Uint8Array.from(e).reverse()))}function Av(e,t){return ng(e.toString(16).padStart(2*t,"0"))}function Mv(e,t){return Av(e,t).reverse()}function Nv(e,t,r){let n;if("string"==typeof t)try{n=ng(t)}catch(o){throw new Error(e+" must be hex string or Uint8Array, cause: "+o)}else{if(!Lm(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}const i=n.length;if("number"==typeof r&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}function Pv(e){return Uint8Array.from(e)}const Bv=e=>"bigint"==typeof e&&wv<=e;function Tv(e,t,r,n){if(!function(e,t,r){return Bv(e)&&Bv(t)&&Bv(r)&&t<=e&&e<r}(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Ov(e){let t;for(t=0;e>wv;e>>=xv,t+=1);return t}const Rv=e=>(xv<<BigInt(e))-xv;function Lv(e,t,r={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function n(t,r,n){const i=e[t];if(n&&void 0===i)return;const o=typeof i;if(o!==r||null===i)throw new Error(`param "${t}" is invalid: expected ${r}, got ${o}`)}Object.entries(t).forEach(([e,t])=>n(e,t,!1)),Object.entries(r).forEach(([e,t])=>n(e,t,!0))}function Uv(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(void 0!==i)return i;const o=e(r,...n);return t.set(r,o),o}}
|
|
14
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jv=BigInt(0),Dv=BigInt(1),Fv=BigInt(2),zv=BigInt(3),qv=BigInt(4),Wv=BigInt(5),$v=BigInt(7),Gv=BigInt(8),Vv=BigInt(9),Hv=BigInt(16);function Kv(e,t){const r=e%t;return r>=jv?r:t+r}function Zv(e,t,r){let n=e;for(;t-- >jv;)n*=n,n%=r;return n}function Yv(e,t){if(e===jv)throw new Error("invert: expected non-zero number");if(t<=jv)throw new Error("invert: expected positive modulus, got "+t);let r=Kv(e,t),n=t,i=jv,o=Dv;for(;r!==jv;){const e=n%r,t=i-o*(n/r);n=r,r=e,i=o,o=t}if(n!==Dv)throw new Error("invert: does not exist");return Kv(i,t)}function Jv(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Xv(e,t){const r=(e.ORDER+Dv)/qv,n=e.pow(t,r);return Jv(e,n,t),n}function Qv(e,t){const r=(e.ORDER-Wv)/Gv,n=e.mul(t,Fv),i=e.pow(n,r),o=e.mul(t,i),s=e.mul(e.mul(o,Fv),i),a=e.mul(o,e.sub(s,e.ONE));return Jv(e,a,t),a}function eb(e){if(e<zv)throw new Error("sqrt is not defined for small field");let t=e-Dv,r=0;for(;t%Fv===jv;)t/=Fv,r++;let n=Fv;const i=sb(e);for(;1===ib(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return Xv;let o=i.pow(n,t);const s=(t+Dv)/Fv;return function(e,n){if(e.is0(n))return n;if(1!==ib(e,n))throw new Error("Cannot find square root");let i=r,a=e.mul(e.ONE,o),c=e.pow(n,t),l=e.pow(n,s);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,r=e.sqr(c);for(;!e.eql(r,e.ONE);)if(t++,r=e.sqr(r),t===i)throw new Error("Cannot find square root");const n=Dv<<BigInt(i-t-1),o=e.pow(a,n);i=t,a=e.sqr(o),c=e.mul(c,a),l=e.mul(l,o)}return l}}function tb(e){return e%qv===zv?Xv:e%Gv===Wv?Qv:e%Hv===Vv?function(e){const t=sb(e),r=eb(e),n=r(t,t.neg(t.ONE)),i=r(t,n),o=r(t,t.neg(n)),s=(e+$v)/Hv;return(e,t)=>{let r=e.pow(t,s),a=e.mul(r,n);const c=e.mul(r,i),l=e.mul(r,o),u=e.eql(e.sqr(a),t),h=e.eql(e.sqr(c),t);r=e.cmov(r,a,u),a=e.cmov(l,c,h);const d=e.eql(e.sqr(a),t),p=e.cmov(r,a,d);return Jv(e,p,t),p}}(e):eb(e)}const rb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nb(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r)),e.ONE),o=e.inv(i);return t.reduceRight((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r)),o),n}function ib(e,t){const r=(e.ORDER-Dv)/Fv,n=e.pow(t,r),i=e.eql(n,e.ONE),o=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function ob(e,t){void 0!==t&&Um(t);const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function sb(e,t,r=!1,n={}){if(e<=jv)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,o,s,a=!1;if("object"==typeof t&&null!=t){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(i=e.BITS),e.sqrt&&(o=e.sqrt),"boolean"==typeof e.isLE&&(r=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),s=e.allowedLengths}else"number"==typeof t&&(i=t),n.sqrt&&(o=n.sqrt);const{nBitLength:c,nByteLength:l}=ob(e,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:Rv(c),ZERO:jv,ONE:Dv,allowedLengths:s,create:t=>Kv(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return jv<=t&&t<e},is0:e=>e===jv,isValidNot0:e=>!h.is0(e)&&h.isValid(e),isOdd:e=>(e&Dv)===Dv,neg:t=>Kv(-t,e),eql:(e,t)=>e===t,sqr:t=>Kv(t*t,e),add:(t,r)=>Kv(t+r,e),sub:(t,r)=>Kv(t-r,e),mul:(t,r)=>Kv(t*r,e),pow:(e,t)=>function(e,t,r){if(r<jv)throw new Error("invalid exponent, negatives unsupported");if(r===jv)return e.ONE;if(r===Dv)return t;let n=e.ONE,i=t;for(;r>jv;)r&Dv&&(n=e.mul(n,i)),i=e.sqr(i),r>>=Dv;return n}(h,e,t),div:(t,r)=>Kv(t*Yv(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Yv(t,e),sqrt:o||(t=>(u||(u=tb(e)),u(h,t))),toBytes:e=>r?Mv(e,l):Av(e,l),fromBytes:(t,n=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,r?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let i=r?Ev(t):Iv(t);if(a&&(i=Kv(i,e)),!n&&!h.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:e=>nb(h,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(h)}function ab(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function cb(e){const t=ab(e);return t+Math.ceil(t/2)}
|
|
15
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
16
|
+
const lb=BigInt(0),ub=BigInt(1);function hb(e,t){const r=t.negate();return e?r:t}function db(e,t){const r=nb(e.Fp,t.map(e=>e.Z));return t.map((t,n)=>e.fromAffine(t.toAffine(r[n])))}function pb(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function fb(e,t){pb(e,t);const r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Rv(e),maxNumber:r,shiftBy:BigInt(e)}}function mb(e,t,r){const{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r;let a=Number(e&i),c=e>>s;a>n&&(a-=o,c+=ub);const l=t*n;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}const gb=new WeakMap,yb=new WeakMap;function vb(e){return yb.get(e)||1}function bb(e){if(e!==lb)throw new Error("invalid wNAF")}class wb{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>lb;)t&ub&&(r=r.add(n)),n=n.double(),t>>=ub;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=fb(t,this.bits),i=[];let o=e,s=o;for(let a=0;a<r;a++){s=o,i.push(s);for(let e=1;e<n;e++)s=s.add(o),i.push(s);o=s.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=fb(e,this.bits);for(let s=0;s<o.windows;s++){const{nextN:e,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:h}=mb(r,s,o);r=e,c?i=i.add(hb(u,t[h])):n=n.add(hb(l,t[a]))}return bb(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){const i=fb(e,this.bits);for(let o=0;o<i.windows&&r!==lb;o++){const{nextN:e,offset:s,isZero:a,isNeg:c}=mb(r,o,i);if(r=e,!a){const e=t[s];n=n.add(c?e.negate():e)}}return bb(r),n}getPrecomputes(e,t,r){let n=gb.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&("function"==typeof r&&(n=r(n)),gb.set(t,n))),n}cached(e,t,r){const n=vb(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const i=vb(e);return 1===i?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){pb(t,this.bits),yb.set(e,t),gb.delete(e)}hasCache(e){return 1!==vb(e)}}function xb(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)})}(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)})}(n,t);const i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=e.ZERO,a=Ov(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Rv(c),u=new Array(Number(l)+1).fill(s);let h=s;for(let d=Math.floor((t.BITS-1)/c)*c;d>=0;d-=c){u.fill(s);for(let t=0;t<o;t++){const e=n[t],i=Number(e>>BigInt(d)&l);u[i]=u[i].add(r[t])}let e=s;for(let t=u.length-1,r=s;t>0;t--)r=r.add(u[t]),e=e.add(r);if(h=h.add(e),0!==d)for(let t=0;t<c;t++)h=h.double()}return h}function kb(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(e){Lv(e,rb.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(t),t}return sb(e,{isLE:r})}function _b(e,t,r={},n){if(void 0===n&&(n="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const e=t[a];if(!("bigint"==typeof e&&e>lb))throw new Error(`CURVE.${a} must be positive bigint`)}const i=kb(t.p,r.Fp,n),o=kb(t.n,r.Fn,n),s=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const a of s)if(!i.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:i,Fn:o}}
|
|
17
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sb=BigInt(0),Cb=BigInt(1),Ib=BigInt(2),Eb=BigInt(8);function Ab(e,t,r={}){if("function"!=typeof t)throw new Error('"hash" function param is required');Lv(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:n}=r,{BASE:i,Fp:o,Fn:s}=e,a=r.randomBytes||cg,c=r.adjustScalarBytes||(e=>e),l=r.domain||((e,t,r)=>{if(kv(r,"phflag"),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function u(e){return s.create(Ev(e))}function h(e){const{head:r,prefix:n,scalar:o}=function(e){const r=g.secretKey;e=Nv("private key",e,r);const n=Nv("hashed private key",t(e),2*r),i=c(n.slice(0,r));return{head:i,prefix:n.slice(r,2*r),scalar:u(i)}}(e),s=i.multiply(o),a=s.toBytes();return{head:r,prefix:n,scalar:o,point:s,pointBytes:a}}function d(e){return h(e).pointBytes}function p(e=Uint8Array.of(),...r){const i=og(...r);return u(t(l(i,Nv("context",e),!!n)))}const f={zip215:!0};const m=o.BYTES,g={secretKey:m,publicKey:m,signature:2*m,seed:m};function y(e=a(g.seed)){return _v(e,g.seed,"seed")}const v={getExtendedPublicKey:h,randomSecretKey:y,isValidSecretKey:function(e){return Lm(e)&&e.length===s.BYTES},isValidPublicKey:function(t,r){try{return!!e.fromBytes(t,r)}catch(vu){return!1}},toMontgomery(t){const{y:r}=e.fromBytes(t),n=g.publicKey,i=32===n;if(!i&&57!==n)throw new Error("only defined for 25519 and 448");const s=i?o.div(Cb+r,Cb-r):o.div(r-Cb,r+Cb);return o.toBytes(s)},toMontgomerySecret(e){const r=g.secretKey;_v(e,r);const n=t(e.subarray(0,r));return c(n).subarray(0,r)},randomPrivateKey:y,precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({keygen:function(e){const t=v.randomSecretKey(e);return{secretKey:t,publicKey:d(t)}},getPublicKey:d,sign:function(e,t,r={}){e=Nv("message",e),n&&(e=n(e));const{prefix:o,scalar:a,pointBytes:c}=h(t),l=p(r.context,o,e),u=i.multiply(l).toBytes(),d=p(r.context,u,c,e),f=s.create(l+d*a);if(!s.isValid(f))throw new Error("sign failed: invalid s");return _v(og(u,s.toBytes(f)),g.signature,"result")},verify:function(t,r,o,s=f){const{context:a,zip215:c}=s,l=g.signature;t=Nv("signature",t,l),r=Nv("message",r),o=Nv("publicKey",o,g.publicKey),void 0!==c&&kv(c,"zip215"),n&&(r=n(r));const u=l/2,h=t.subarray(0,u),d=Ev(t.subarray(u,l));let m,y,v;try{m=e.fromBytes(o,c),y=e.fromBytes(h,c),v=i.multiplyUnsafe(d)}catch(vu){return!1}if(!c&&m.isSmallOrder())return!1;const b=p(a,y.toBytes(),m.toBytes(),r);return y.add(m.multiplyUnsafe(b)).subtract(v).clearCofactor().is0()},utils:v,Point:e,lengths:g})}function Mb(e){const{CURVE:t,curveOpts:r,hash:n,eddsaOpts:i}=function(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r={Fp:e.Fp,Fn:sb(t.n,e.nBitLength,!0),uvRatio:e.uvRatio},n={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:r,hash:e.hash,eddsaOpts:n}}(e),o=function(e,t={}){const r=_b("edwards",e,t,t.FpFnLE),{Fp:n,Fn:i}=r;let o=r.CURVE;const{h:s}=o;Lv(t,{},{uvRatio:"function"});const a=Ib<<BigInt(8*i.BYTES)-Cb,c=e=>n.create(e),l=t.uvRatio||((e,t)=>{try{return{isValid:!0,value:n.sqrt(n.div(e,t))}}catch(r){return{isValid:!1,value:Sb}}});if(!function(e,t,r,n){const i=e.sqr(r),o=e.sqr(n),s=e.add(e.mul(t.a,i),o),a=e.add(e.ONE,e.mul(t.d,e.mul(i,o)));return e.eql(s,a)}(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(e,t,r=!1){return Tv("coordinate "+e,t,r?Cb:Sb,a),t}function h(e){if(!(e instanceof f))throw new Error("ExtendedPoint expected")}const d=Uv((e,t)=>{const{X:r,Y:i,Z:o}=e,s=e.is0();null==t&&(t=s?Eb:n.inv(o));const a=c(r*t),l=c(i*t),u=n.mul(o,t);if(s)return{x:Sb,y:Cb};if(u!==Cb)throw new Error("invZ was invalid");return{x:a,y:l}}),p=Uv(e=>{const{a:t,d:r}=o;if(e.is0())throw new Error("bad point: ZERO");const{X:n,Y:i,Z:s,T:a}=e,l=c(n*n),u=c(i*i),h=c(s*s),d=c(h*h),p=c(l*t);if(c(h*c(p+u))!==c(d+c(r*c(l*u))))throw new Error("bad point: equation left != right (1)");if(c(n*i)!==c(s*a))throw new Error("bad point: equation left != right (2)");return!0});class f{constructor(e,t,r,n){this.X=u("x",e),this.Y=u("y",t),this.Z=u("z",r,!0),this.T=u("t",n),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof f)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return u("x",t),u("y",r),new f(t,r,Cb,c(t*r))}static fromBytes(e,t=!1){const r=n.BYTES,{a:i,d:s}=o;e=Pv(_v(e,r,"point")),kv(t,"zip215");const u=Pv(e),h=e[r-1];u[r-1]=-129&h;const d=Ev(u),p=t?a:n.ORDER;Tv("point.y",d,Sb,p);const m=c(d*d),g=c(m-Cb),y=c(s*m-i);let{isValid:v,value:b}=l(g,y);if(!v)throw new Error("bad point: invalid y coordinate");const w=(b&Cb)===Cb,x=!!(128&h);if(!t&&b===Sb&&x)throw new Error("bad point: x=0 and x_0=1");return x!==w&&(b=c(-b)),f.fromAffine({x:b,y:d})}static fromHex(e,t=!1){return f.fromBytes(Nv("point",e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return m.createCache(this,e),t||this.multiply(Ib),this}assertValidity(){p(this)}equals(e){h(e);const{X:t,Y:r,Z:n}=this,{X:i,Y:o,Z:s}=e,a=c(t*s),l=c(i*n),u=c(r*s),d=c(o*n);return a===l&&u===d}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){const{a:e}=o,{X:t,Y:r,Z:n}=this,i=c(t*t),s=c(r*r),a=c(Ib*c(n*n)),l=c(e*i),u=t+r,h=c(c(u*u)-i-s),d=l+s,p=d-a,m=l-s,g=c(h*p),y=c(d*m),v=c(h*m),b=c(p*d);return new f(g,y,b,v)}add(e){h(e);const{a:t,d:r}=o,{X:n,Y:i,Z:s,T:a}=this,{X:l,Y:u,Z:d,T:p}=e,m=c(n*l),g=c(i*u),y=c(a*r*p),v=c(s*d),b=c((n+i)*(l+u)-m-g),w=v-y,x=v+y,k=c(g-t*m),_=c(b*w),S=c(x*k),C=c(b*k),I=c(w*x);return new f(_,S,I,C)}subtract(e){return this.add(e.negate())}multiply(e){if(!i.isValidNot0(e))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:t,f:r}=m.cached(this,e,e=>db(f,e));return db(f,[t,r])[0]}multiplyUnsafe(e,t=f.ZERO){if(!i.isValid(e))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return e===Sb?f.ZERO:this.is0()||e===Cb?this:m.unsafe(this,e,e=>db(f,e),t)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return m.unsafe(this,o.n).is0()}toAffine(e){return d(this,e)}clearCofactor(){return s===Cb?this:this.multiplyUnsafe(s)}toBytes(){const{x:e,y:t}=this.toAffine(),r=n.toBytes(t);return r[r.length-1]|=e&Cb?128:0,r}toHex(){return Zm(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(e){return db(f,e)}static msm(e,t){return xb(f,i,e,t)}_setWindowSize(e){this.precompute(e)}toRawBytes(){return this.toBytes()}}f.BASE=new f(o.Gx,o.Gy,Cb,c(o.Gx*o.Gy)),f.ZERO=new f(Sb,Cb,Cb,Sb),f.Fp=n,f.Fn=i;const m=new wb(f,i.BITS);return f.BASE.precompute(8),f}(t,r);return function(e,t){const r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}(e,Ab(o,n,i))}
|
|
18
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Nb=BigInt(1),Pb=BigInt(2);BigInt(3);const Bb=BigInt(5),Tb=BigInt(8),Ob=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Rb=(()=>({p:Ob,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Tb,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function Lb(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const Ub=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function jb(e,t){const r=Ob,n=Kv(t*t*t,r),i=function(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),o=Ob,s=e*e%o*e%o,a=Zv(s,Pb,o)*s%o,c=Zv(a,Nb,o)*e%o,l=Zv(c,Bb,o)*c%o,u=Zv(l,t,o)*l%o,h=Zv(u,r,o)*u%o,d=Zv(h,n,o)*h%o,p=Zv(d,i,o)*d%o,f=Zv(p,i,o)*d%o,m=Zv(f,t,o)*l%o;return{pow_p_5_8:Zv(m,Pb,o)*e%o,b2:s}}(e*Kv(n*n*t,r)).pow_p_5_8;let o=Kv(e*n*i,r);const s=Kv(t*o*o,r),a=o,c=Kv(o*Ub,r),l=s===e,u=s===Kv(-e,r),h=s===Kv(-e*Ub,r);return l&&(o=a),(u||h)&&(o=c),(Kv(o,r)&Dv)===Dv&&(o=Kv(-o,r)),{isValid:l||u,value:o}}const Db=(()=>sb(Rb.p,{isLE:!0}))(),Fb=(()=>({...Rb,Fp:Db,hash:zg,adjustScalarBytes:Lb,uvRatio:jb}))(),zb=(()=>Mb(Fb))();var qb={exports:{}};const Wb=cv(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));(function(e,t){function r(e,t){if(!e)throw new Error(t||"Assertion failed")}function n(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function i(e,t,r){if(i.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var o;"object"==typeof e?e.exports=i:t.BN=i,i.BN=i,i.wordSize=26;try{o="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:Wb.Buffer}catch(I){}function s(e,t){var n=e.charCodeAt(t);return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void r(!1,"Invalid character in "+e)}function a(e,t,r){var n=s(e,r);return r-1>=t&&(n|=s(e,r-1)<<4),n}function c(e,t,n,i){for(var o=0,s=0,a=Math.min(e.length,n),c=t;c<a;c++){var l=e.charCodeAt(c)-48;o*=i,s=l>=49?l-49+10:l>=17?l-17+10:l,r(l>=0&&s<i,"Invalid character"),o+=s}return o}function l(e,t){e.words=t.words,e.length=t.length,e.negative=t.negative,e.red=t.red}if(i.isBN=function(e){return e instanceof i||null!==e&&"object"==typeof e&&e.constructor.wordSize===i.wordSize&&Array.isArray(e.words)},i.max=function(e,t){return e.cmp(t)>0?e:t},i.min=function(e,t){return e.cmp(t)<0?e:t},i.prototype._init=function(e,t,n){if("number"==typeof e)return this._initNumber(e,t,n);if("object"==typeof e)return this._initArray(e,t,n);"hex"===t&&(t=16),r(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(i++,this.negative=1),i<e.length&&(16===t?this._parseHex(e,i,n):(this._parseBase(e,t,i),"le"===n&&this._initArray(this.toArray(),t,n)))},i.prototype._initNumber=function(e,t,n){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(r(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),t,n)},i.prototype._initArray=function(e,t,n){if(r("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var o,s,a=0;if("be"===n)for(i=e.length-1,o=0;i>=0;i-=3)s=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===n)for(i=0,o=0;i<e.length;i+=3)s=e[i]|e[i+1]<<8|e[i+2]<<16,this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},i.prototype._parseHex=function(e,t,r){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n<this.length;n++)this.words[n]=0;var i,o=0,s=0;if("be"===r)for(n=e.length-1;n>=t;n-=2)i=a(e,t,n)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n<e.length;n+=2)i=a(e,t,n)<<o,this.words[s]|=67108863&i,o>=18?(o-=18,s+=1,this.words[s]|=i>>>26):o+=8;this._strip()},i.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,s=o%n,a=Math.min(o,o-s)+r,l=0,u=r;u<a;u+=n)l=c(e,u,u+n,t),this.imuln(i),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l);if(0!==s){var h=1;for(l=c(e,u,e.length,t),u=0;u<s;u++)h*=t;this.imuln(h),this.words[0]+l<67108864?this.words[0]+=l:this._iaddn(l)}this._strip()},i.prototype.copy=function(e){e.words=new Array(this.length);for(var t=0;t<this.length;t++)e.words[t]=this.words[t];e.length=this.length,e.negative=this.negative,e.red=this.red},i.prototype._move=function(e){l(e,this)},i.prototype.clone=function(){var e=new i(null);return this.copy(e),e},i.prototype._expand=function(e){for(;this.length<e;)this.words[this.length++]=0;return this},i.prototype._strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{i.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(I){i.prototype.inspect=u}else i.prototype.inspect=u;function u(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"}var h=["","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"],d=[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],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],s=i*o,a=67108863&s,c=s/67108864|0;r.words[0]=a;for(var l=1;l<n;l++){for(var u=c>>>26,h=67108863&c,d=Math.min(l,t.length-1),p=Math.max(0,l-e.length+1);p<=d;p++){var f=l-p|0;u+=(s=(i=0|e.words[f])*(o=0|t.words[p])+h)/67108864|0,h=67108863&s}r.words[l]=0|h,c=0|u}return 0!==c?r.words[l]=0|c:r.length--,r._strip()}i.prototype.toString=function(e,t){var n;if(t=0|t||1,16===(e=e||10)||"hex"===e){n="";for(var i=0,o=0,s=0;s<this.length;s++){var a=this.words[s],c=(16777215&(a<<i|o)).toString(16);o=a>>>24-i&16777215,(i+=2)>=26&&(i-=26,s--),n=0!==o||s!==this.length-1?h[6-c.length]+c+n:c+n}for(0!==o&&(n=o.toString(16)+n);n.length%t!==0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}if(e===(0|e)&&e>=2&&e<=36){var l=d[e],u=p[e];n="";var f=this.clone();for(f.negative=0;!f.isZero();){var m=f.modrn(u).toString(e);n=(f=f.idivn(u)).isZero()?m+n:h[l-m.length]+m+n}for(this.isZero()&&(n="0"+n);n.length%t!==0;)n="0"+n;return 0!==this.negative&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&r(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},i.prototype.toJSON=function(){return this.toString(16,2)},o&&(i.prototype.toBuffer=function(e,t){return this.toArrayLike(o,e,t)}),i.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},i.prototype.toArrayLike=function(e,t,n){this._strip();var i=this.byteLength(),o=n||Math.max(1,i);r(i<=o,"byte array longer than desired length"),r(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,i),s},i.prototype._toArrayLikeLE=function(e,t){for(var r=0,n=0,i=0,o=0;i<this.length;i++){var s=this.words[i]<<o|n;e[r++]=255&s,r<e.length&&(e[r++]=s>>8&255),r<e.length&&(e[r++]=s>>16&255),6===o?(r<e.length&&(e[r++]=s>>24&255),n=0,o=0):(n=s>>>24,o+=2)}if(r<e.length)for(e[r++]=n;r<e.length;)e[r++]=0},i.prototype._toArrayLikeBE=function(e,t){for(var r=e.length-1,n=0,i=0,o=0;i<this.length;i++){var s=this.words[i]<<o|n;e[r--]=255&s,r>=0&&(e[r--]=s>>8&255),r>=0&&(e[r--]=s>>16&255),6===o?(r>=0&&(e[r--]=s>>24&255),n=0,o=0):(n=s>>>24,o+=2)}if(r>=0)for(e[r--]=n;r>=0;)e[r--]=0},Math.clz32?i.prototype._countBits=function(e){return 32-Math.clz32(e)}:i.prototype._countBits=function(e){var t=e,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},i.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 8191&t||(r+=13,t>>>=13),127&t||(r+=7,t>>>=7),15&t||(r+=4,t>>>=4),3&t||(r+=2,t>>>=2),1&t||r++,r},i.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;t<this.length;t++){var r=this._zeroBits(this.words[t]);if(e+=r,26!==r)break}return e},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(e){return 0!==this.negative?this.abs().inotn(e).iaddn(1):this.clone()},i.prototype.fromTwos=function(e){return this.testn(e-1)?this.notn(e).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return 0!==this.negative},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(e){for(;this.length<e.length;)this.words[this.length++]=0;for(var t=0;t<e.length;t++)this.words[t]=this.words[t]|e.words[t];return this._strip()},i.prototype.ior=function(e){return r(0===(this.negative|e.negative)),this.iuor(e)},i.prototype.or=function(e){return this.length>e.length?this.clone().ior(e):e.clone().ior(this)},i.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},i.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;r<t.length;r++)this.words[r]=this.words[r]&e.words[r];return this.length=t.length,this._strip()},i.prototype.iand=function(e){return r(0===(this.negative|e.negative)),this.iuand(e)},i.prototype.and=function(e){return this.length>e.length?this.clone().iand(e):e.clone().iand(this)},i.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},i.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;n<r.length;n++)this.words[n]=t.words[n]^r.words[n];if(this!==t)for(;n<t.length;n++)this.words[n]=t.words[n];return this.length=t.length,this._strip()},i.prototype.ixor=function(e){return r(0===(this.negative|e.negative)),this.iuxor(e)},i.prototype.xor=function(e){return this.length>e.length?this.clone().ixor(e):e.clone().ixor(this)},i.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},i.prototype.inotn=function(e){r("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),n=e%26;this._expand(t),n>0&&t--;for(var i=0;i<t;i++)this.words[i]=67108863&~this.words[i];return n>0&&(this.words[i]=~this.words[i]&67108863>>26-n),this._strip()},i.prototype.notn=function(e){return this.clone().inotn(e)},i.prototype.setn=function(e,t){r("number"==typeof e&&e>=0);var n=e/26|0,i=e%26;return this._expand(n+1),this.words[n]=t?this.words[n]|1<<i:this.words[n]&~(1<<i),this._strip()},i.prototype.iadd=function(e){var t,r,n;if(0!==this.negative&&0===e.negative)return this.negative=0,t=this.isub(e),this.negative^=1,this._normSign();if(0===this.negative&&0!==e.negative)return e.negative=0,t=this.isub(e),e.negative=1,t._normSign();this.length>e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o<n.length;o++)t=(0|r.words[o])+(0|n.words[o])+i,this.words[o]=67108863&t,i=t>>>26;for(;0!==i&&o<r.length;o++)t=(0|r.words[o])+i,this.words[o]=67108863&t,i=t>>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;o<r.length;o++)this.words[o]=r.words[o];return this},i.prototype.add=function(e){var t;return 0!==e.negative&&0===this.negative?(e.negative=0,t=this.sub(e),e.negative^=1,t):0===e.negative&&0!==this.negative?(this.negative=0,t=e.sub(this),this.negative=1,t):this.length>e.length?this.clone().iadd(e):e.clone().iadd(this)},i.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,s=0;s<n.length;s++)o=(t=(0|r.words[s])-(0|n.words[s])+o)>>26,this.words[s]=67108863&t;for(;0!==o&&s<r.length;s++)o=(t=(0|r.words[s])+o)>>26,this.words[s]=67108863&t;if(0===o&&s<r.length&&r!==this)for(;s<r.length;s++)this.words[s]=r.words[s];return this.length=Math.max(this.length,s),r!==this&&(this.negative=1),this._strip()},i.prototype.sub=function(e){return this.clone().isub(e)};var m=function(e,t,r){var n,i,o,s=e.words,a=t.words,c=r.words,l=0,u=0|s[0],h=8191&u,d=u>>>13,p=0|s[1],f=8191&p,m=p>>>13,g=0|s[2],y=8191&g,v=g>>>13,b=0|s[3],w=8191&b,x=b>>>13,k=0|s[4],_=8191&k,S=k>>>13,C=0|s[5],I=8191&C,E=C>>>13,A=0|s[6],M=8191&A,N=A>>>13,P=0|s[7],B=8191&P,T=P>>>13,O=0|s[8],R=8191&O,L=O>>>13,U=0|s[9],j=8191&U,D=U>>>13,F=0|a[0],z=8191&F,q=F>>>13,W=0|a[1],$=8191&W,G=W>>>13,V=0|a[2],H=8191&V,K=V>>>13,Z=0|a[3],Y=8191&Z,J=Z>>>13,X=0|a[4],Q=8191&X,ee=X>>>13,te=0|a[5],re=8191&te,ne=te>>>13,ie=0|a[6],oe=8191&ie,se=ie>>>13,ae=0|a[7],ce=8191&ae,le=ae>>>13,ue=0|a[8],he=8191&ue,de=ue>>>13,pe=0|a[9],fe=8191&pe,me=pe>>>13;r.negative=e.negative^t.negative,r.length=19;var ge=(l+(n=Math.imul(h,z))|0)+((8191&(i=(i=Math.imul(h,q))+Math.imul(d,z)|0))<<13)|0;l=((o=Math.imul(d,q))+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(f,z),i=(i=Math.imul(f,q))+Math.imul(m,z)|0,o=Math.imul(m,q);var ye=(l+(n=n+Math.imul(h,$)|0)|0)+((8191&(i=(i=i+Math.imul(h,G)|0)+Math.imul(d,$)|0))<<13)|0;l=((o=o+Math.imul(d,G)|0)+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(y,z),i=(i=Math.imul(y,q))+Math.imul(v,z)|0,o=Math.imul(v,q),n=n+Math.imul(f,$)|0,i=(i=i+Math.imul(f,G)|0)+Math.imul(m,$)|0,o=o+Math.imul(m,G)|0;var ve=(l+(n=n+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,K)|0)+Math.imul(d,H)|0))<<13)|0;l=((o=o+Math.imul(d,K)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,z),i=(i=Math.imul(w,q))+Math.imul(x,z)|0,o=Math.imul(x,q),n=n+Math.imul(y,$)|0,i=(i=i+Math.imul(y,G)|0)+Math.imul(v,$)|0,o=o+Math.imul(v,G)|0,n=n+Math.imul(f,H)|0,i=(i=i+Math.imul(f,K)|0)+Math.imul(m,H)|0,o=o+Math.imul(m,K)|0;var be=(l+(n=n+Math.imul(h,Y)|0)|0)+((8191&(i=(i=i+Math.imul(h,J)|0)+Math.imul(d,Y)|0))<<13)|0;l=((o=o+Math.imul(d,J)|0)+(i>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(_,z),i=(i=Math.imul(_,q))+Math.imul(S,z)|0,o=Math.imul(S,q),n=n+Math.imul(w,$)|0,i=(i=i+Math.imul(w,G)|0)+Math.imul(x,$)|0,o=o+Math.imul(x,G)|0,n=n+Math.imul(y,H)|0,i=(i=i+Math.imul(y,K)|0)+Math.imul(v,H)|0,o=o+Math.imul(v,K)|0,n=n+Math.imul(f,Y)|0,i=(i=i+Math.imul(f,J)|0)+Math.imul(m,Y)|0,o=o+Math.imul(m,J)|0;var we=(l+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(d,Q)|0))<<13)|0;l=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(I,z),i=(i=Math.imul(I,q))+Math.imul(E,z)|0,o=Math.imul(E,q),n=n+Math.imul(_,$)|0,i=(i=i+Math.imul(_,G)|0)+Math.imul(S,$)|0,o=o+Math.imul(S,G)|0,n=n+Math.imul(w,H)|0,i=(i=i+Math.imul(w,K)|0)+Math.imul(x,H)|0,o=o+Math.imul(x,K)|0,n=n+Math.imul(y,Y)|0,i=(i=i+Math.imul(y,J)|0)+Math.imul(v,Y)|0,o=o+Math.imul(v,J)|0,n=n+Math.imul(f,Q)|0,i=(i=i+Math.imul(f,ee)|0)+Math.imul(m,Q)|0,o=o+Math.imul(m,ee)|0;var xe=(l+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(d,re)|0))<<13)|0;l=((o=o+Math.imul(d,ne)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(M,z),i=(i=Math.imul(M,q))+Math.imul(N,z)|0,o=Math.imul(N,q),n=n+Math.imul(I,$)|0,i=(i=i+Math.imul(I,G)|0)+Math.imul(E,$)|0,o=o+Math.imul(E,G)|0,n=n+Math.imul(_,H)|0,i=(i=i+Math.imul(_,K)|0)+Math.imul(S,H)|0,o=o+Math.imul(S,K)|0,n=n+Math.imul(w,Y)|0,i=(i=i+Math.imul(w,J)|0)+Math.imul(x,Y)|0,o=o+Math.imul(x,J)|0,n=n+Math.imul(y,Q)|0,i=(i=i+Math.imul(y,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(f,re)|0,i=(i=i+Math.imul(f,ne)|0)+Math.imul(m,re)|0,o=o+Math.imul(m,ne)|0;var ke=(l+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,se)|0)+Math.imul(d,oe)|0))<<13)|0;l=((o=o+Math.imul(d,se)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(B,z),i=(i=Math.imul(B,q))+Math.imul(T,z)|0,o=Math.imul(T,q),n=n+Math.imul(M,$)|0,i=(i=i+Math.imul(M,G)|0)+Math.imul(N,$)|0,o=o+Math.imul(N,G)|0,n=n+Math.imul(I,H)|0,i=(i=i+Math.imul(I,K)|0)+Math.imul(E,H)|0,o=o+Math.imul(E,K)|0,n=n+Math.imul(_,Y)|0,i=(i=i+Math.imul(_,J)|0)+Math.imul(S,Y)|0,o=o+Math.imul(S,J)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(x,Q)|0,o=o+Math.imul(x,ee)|0,n=n+Math.imul(y,re)|0,i=(i=i+Math.imul(y,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(f,oe)|0,i=(i=i+Math.imul(f,se)|0)+Math.imul(m,oe)|0,o=o+Math.imul(m,se)|0;var _e=(l+(n=n+Math.imul(h,ce)|0)|0)+((8191&(i=(i=i+Math.imul(h,le)|0)+Math.imul(d,ce)|0))<<13)|0;l=((o=o+Math.imul(d,le)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(R,z),i=(i=Math.imul(R,q))+Math.imul(L,z)|0,o=Math.imul(L,q),n=n+Math.imul(B,$)|0,i=(i=i+Math.imul(B,G)|0)+Math.imul(T,$)|0,o=o+Math.imul(T,G)|0,n=n+Math.imul(M,H)|0,i=(i=i+Math.imul(M,K)|0)+Math.imul(N,H)|0,o=o+Math.imul(N,K)|0,n=n+Math.imul(I,Y)|0,i=(i=i+Math.imul(I,J)|0)+Math.imul(E,Y)|0,o=o+Math.imul(E,J)|0,n=n+Math.imul(_,Q)|0,i=(i=i+Math.imul(_,ee)|0)+Math.imul(S,Q)|0,o=o+Math.imul(S,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(x,re)|0,o=o+Math.imul(x,ne)|0,n=n+Math.imul(y,oe)|0,i=(i=i+Math.imul(y,se)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,se)|0,n=n+Math.imul(f,ce)|0,i=(i=i+Math.imul(f,le)|0)+Math.imul(m,ce)|0,o=o+Math.imul(m,le)|0;var Se=(l+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;l=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(j,z),i=(i=Math.imul(j,q))+Math.imul(D,z)|0,o=Math.imul(D,q),n=n+Math.imul(R,$)|0,i=(i=i+Math.imul(R,G)|0)+Math.imul(L,$)|0,o=o+Math.imul(L,G)|0,n=n+Math.imul(B,H)|0,i=(i=i+Math.imul(B,K)|0)+Math.imul(T,H)|0,o=o+Math.imul(T,K)|0,n=n+Math.imul(M,Y)|0,i=(i=i+Math.imul(M,J)|0)+Math.imul(N,Y)|0,o=o+Math.imul(N,J)|0,n=n+Math.imul(I,Q)|0,i=(i=i+Math.imul(I,ee)|0)+Math.imul(E,Q)|0,o=o+Math.imul(E,ee)|0,n=n+Math.imul(_,re)|0,i=(i=i+Math.imul(_,ne)|0)+Math.imul(S,re)|0,o=o+Math.imul(S,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,se)|0)+Math.imul(x,oe)|0,o=o+Math.imul(x,se)|0,n=n+Math.imul(y,ce)|0,i=(i=i+Math.imul(y,le)|0)+Math.imul(v,ce)|0,o=o+Math.imul(v,le)|0,n=n+Math.imul(f,he)|0,i=(i=i+Math.imul(f,de)|0)+Math.imul(m,he)|0,o=o+Math.imul(m,de)|0;var Ce=(l+(n=n+Math.imul(h,fe)|0)|0)+((8191&(i=(i=i+Math.imul(h,me)|0)+Math.imul(d,fe)|0))<<13)|0;l=((o=o+Math.imul(d,me)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(j,$),i=(i=Math.imul(j,G))+Math.imul(D,$)|0,o=Math.imul(D,G),n=n+Math.imul(R,H)|0,i=(i=i+Math.imul(R,K)|0)+Math.imul(L,H)|0,o=o+Math.imul(L,K)|0,n=n+Math.imul(B,Y)|0,i=(i=i+Math.imul(B,J)|0)+Math.imul(T,Y)|0,o=o+Math.imul(T,J)|0,n=n+Math.imul(M,Q)|0,i=(i=i+Math.imul(M,ee)|0)+Math.imul(N,Q)|0,o=o+Math.imul(N,ee)|0,n=n+Math.imul(I,re)|0,i=(i=i+Math.imul(I,ne)|0)+Math.imul(E,re)|0,o=o+Math.imul(E,ne)|0,n=n+Math.imul(_,oe)|0,i=(i=i+Math.imul(_,se)|0)+Math.imul(S,oe)|0,o=o+Math.imul(S,se)|0,n=n+Math.imul(w,ce)|0,i=(i=i+Math.imul(w,le)|0)+Math.imul(x,ce)|0,o=o+Math.imul(x,le)|0,n=n+Math.imul(y,he)|0,i=(i=i+Math.imul(y,de)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,de)|0;var Ie=(l+(n=n+Math.imul(f,fe)|0)|0)+((8191&(i=(i=i+Math.imul(f,me)|0)+Math.imul(m,fe)|0))<<13)|0;l=((o=o+Math.imul(m,me)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(j,H),i=(i=Math.imul(j,K))+Math.imul(D,H)|0,o=Math.imul(D,K),n=n+Math.imul(R,Y)|0,i=(i=i+Math.imul(R,J)|0)+Math.imul(L,Y)|0,o=o+Math.imul(L,J)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(T,Q)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(M,re)|0,i=(i=i+Math.imul(M,ne)|0)+Math.imul(N,re)|0,o=o+Math.imul(N,ne)|0,n=n+Math.imul(I,oe)|0,i=(i=i+Math.imul(I,se)|0)+Math.imul(E,oe)|0,o=o+Math.imul(E,se)|0,n=n+Math.imul(_,ce)|0,i=(i=i+Math.imul(_,le)|0)+Math.imul(S,ce)|0,o=o+Math.imul(S,le)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,de)|0)+Math.imul(x,he)|0,o=o+Math.imul(x,de)|0;var Ee=(l+(n=n+Math.imul(y,fe)|0)|0)+((8191&(i=(i=i+Math.imul(y,me)|0)+Math.imul(v,fe)|0))<<13)|0;l=((o=o+Math.imul(v,me)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(j,Y),i=(i=Math.imul(j,J))+Math.imul(D,Y)|0,o=Math.imul(D,J),n=n+Math.imul(R,Q)|0,i=(i=i+Math.imul(R,ee)|0)+Math.imul(L,Q)|0,o=o+Math.imul(L,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(T,re)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(M,oe)|0,i=(i=i+Math.imul(M,se)|0)+Math.imul(N,oe)|0,o=o+Math.imul(N,se)|0,n=n+Math.imul(I,ce)|0,i=(i=i+Math.imul(I,le)|0)+Math.imul(E,ce)|0,o=o+Math.imul(E,le)|0,n=n+Math.imul(_,he)|0,i=(i=i+Math.imul(_,de)|0)+Math.imul(S,he)|0,o=o+Math.imul(S,de)|0;var Ae=(l+(n=n+Math.imul(w,fe)|0)|0)+((8191&(i=(i=i+Math.imul(w,me)|0)+Math.imul(x,fe)|0))<<13)|0;l=((o=o+Math.imul(x,me)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(j,Q),i=(i=Math.imul(j,ee))+Math.imul(D,Q)|0,o=Math.imul(D,ee),n=n+Math.imul(R,re)|0,i=(i=i+Math.imul(R,ne)|0)+Math.imul(L,re)|0,o=o+Math.imul(L,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,n=n+Math.imul(M,ce)|0,i=(i=i+Math.imul(M,le)|0)+Math.imul(N,ce)|0,o=o+Math.imul(N,le)|0,n=n+Math.imul(I,he)|0,i=(i=i+Math.imul(I,de)|0)+Math.imul(E,he)|0,o=o+Math.imul(E,de)|0;var Me=(l+(n=n+Math.imul(_,fe)|0)|0)+((8191&(i=(i=i+Math.imul(_,me)|0)+Math.imul(S,fe)|0))<<13)|0;l=((o=o+Math.imul(S,me)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(j,re),i=(i=Math.imul(j,ne))+Math.imul(D,re)|0,o=Math.imul(D,ne),n=n+Math.imul(R,oe)|0,i=(i=i+Math.imul(R,se)|0)+Math.imul(L,oe)|0,o=o+Math.imul(L,se)|0,n=n+Math.imul(B,ce)|0,i=(i=i+Math.imul(B,le)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,le)|0,n=n+Math.imul(M,he)|0,i=(i=i+Math.imul(M,de)|0)+Math.imul(N,he)|0,o=o+Math.imul(N,de)|0;var Ne=(l+(n=n+Math.imul(I,fe)|0)|0)+((8191&(i=(i=i+Math.imul(I,me)|0)+Math.imul(E,fe)|0))<<13)|0;l=((o=o+Math.imul(E,me)|0)+(i>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,n=Math.imul(j,oe),i=(i=Math.imul(j,se))+Math.imul(D,oe)|0,o=Math.imul(D,se),n=n+Math.imul(R,ce)|0,i=(i=i+Math.imul(R,le)|0)+Math.imul(L,ce)|0,o=o+Math.imul(L,le)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,de)|0)+Math.imul(T,he)|0,o=o+Math.imul(T,de)|0;var Pe=(l+(n=n+Math.imul(M,fe)|0)|0)+((8191&(i=(i=i+Math.imul(M,me)|0)+Math.imul(N,fe)|0))<<13)|0;l=((o=o+Math.imul(N,me)|0)+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(j,ce),i=(i=Math.imul(j,le))+Math.imul(D,ce)|0,o=Math.imul(D,le),n=n+Math.imul(R,he)|0,i=(i=i+Math.imul(R,de)|0)+Math.imul(L,he)|0,o=o+Math.imul(L,de)|0;var Be=(l+(n=n+Math.imul(B,fe)|0)|0)+((8191&(i=(i=i+Math.imul(B,me)|0)+Math.imul(T,fe)|0))<<13)|0;l=((o=o+Math.imul(T,me)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(j,he),i=(i=Math.imul(j,de))+Math.imul(D,he)|0,o=Math.imul(D,de);var Te=(l+(n=n+Math.imul(R,fe)|0)|0)+((8191&(i=(i=i+Math.imul(R,me)|0)+Math.imul(L,fe)|0))<<13)|0;l=((o=o+Math.imul(L,me)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863;var Oe=(l+(n=Math.imul(j,fe))|0)+((8191&(i=(i=Math.imul(j,me))+Math.imul(D,fe)|0))<<13)|0;return l=((o=Math.imul(D,me))+(i>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,c[0]=ge,c[1]=ye,c[2]=ve,c[3]=be,c[4]=we,c[5]=xe,c[6]=ke,c[7]=_e,c[8]=Se,c[9]=Ce,c[10]=Ie,c[11]=Ee,c[12]=Ae,c[13]=Me,c[14]=Ne,c[15]=Pe,c[16]=Be,c[17]=Te,c[18]=Oe,0!==l&&(c[19]=l,r.length++),r};function g(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o<r.length-1;o++){var s=i;i=0;for(var a=67108863&n,c=Math.min(o,t.length-1),l=Math.max(0,o-e.length+1);l<=c;l++){var u=o-l,h=(0|e.words[u])*(0|t.words[l]),d=67108863&h;a=67108863&(d=d+a|0),i+=(s=(s=s+(h/67108864|0)|0)+(d>>>26)|0)>>>26,s&=67108863}r.words[o]=a,n=s,s=i}return 0!==n?r.words[o]=n:r.length--,r._strip()}function y(e,t,r){return g(e,t,r)}Math.imul||(m=f),i.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?m(this,e,t):r<63?f(this,e,t):r<1024?g(this,e,t):y(this,e,t)},i.prototype.mul=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),this.mulTo(e,t)},i.prototype.mulf=function(e){var t=new i(null);return t.words=new Array(this.length+e.length),y(this,e,t)},i.prototype.imul=function(e){return this.clone().mulTo(e,this)},i.prototype.imuln=function(e){var t=e<0;t&&(e=-e),r("number"==typeof e),r(e<67108864);for(var n=0,i=0;i<this.length;i++){var o=(0|this.words[i])*e,s=(67108863&o)+(67108863&n);n>>=26,n+=o/67108864|0,n+=s>>>26,this.words[i]=67108863&s}return 0!==n&&(this.words[i]=n,this.length++),this.length=0===e?1:this.length,t?this.ineg():this},i.prototype.muln=function(e){return this.clone().imuln(e)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r<t.length;r++){var n=r/26|0,i=r%26;t[r]=e.words[n]>>>i&1}return t}(e);if(0===t.length)return new i(1);for(var r=this,n=0;n<t.length&&0===t[n];n++,r=r.sqr());if(++n<t.length)for(var o=r.sqr();n<t.length;n++,o=o.sqr())0!==t[n]&&(r=r.mul(o));return r},i.prototype.iushln=function(e){r("number"==typeof e&&e>=0);var t,n=e%26,i=(e-n)/26,o=67108863>>>26-n<<26-n;if(0!==n){var s=0;for(t=0;t<this.length;t++){var a=this.words[t]&o,c=(0|this.words[t])-a<<n;this.words[t]=c|s,s=a>>>26-n}s&&(this.words[t]=s,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t<i;t++)this.words[t]=0;this.length+=i}return this._strip()},i.prototype.ishln=function(e){return r(0===this.negative),this.iushln(e)},i.prototype.iushrn=function(e,t,n){var i;r("number"==typeof e&&e>=0),i=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<<o,c=n;if(i-=s,i=Math.max(0,i),c){for(var l=0;l<s;l++)c.words[l]=this.words[l];c.length=s}if(0===s);else if(this.length>s)for(this.length-=s,l=0;l<this.length;l++)this.words[l]=this.words[l+s];else this.words[0]=0,this.length=1;var u=0;for(l=this.length-1;l>=0&&(0!==u||l>=i);l--){var h=0|this.words[l];this.words[l]=u<<26-o|h>>>o,u=h&a}return c&&0!==u&&(c.words[c.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},i.prototype.ishrn=function(e,t,n){return r(0===this.negative),this.iushrn(e,t,n)},i.prototype.shln=function(e){return this.clone().ishln(e)},i.prototype.ushln=function(e){return this.clone().iushln(e)},i.prototype.shrn=function(e){return this.clone().ishrn(e)},i.prototype.ushrn=function(e){return this.clone().iushrn(e)},i.prototype.testn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26,i=1<<t;return!(this.length<=n||!(this.words[n]&i))},i.prototype.imaskn=function(e){r("number"==typeof e&&e>=0);var t=e%26,n=(e-t)/26;if(r(0===this.negative,"imaskn works only with positive numbers"),this.length<=n)return this;if(0!==t&&n++,this.length=Math.min(n,this.length),0!==t){var i=67108863^67108863>>>t<<t;this.words[this.length-1]&=i}return this._strip()},i.prototype.maskn=function(e){return this.clone().imaskn(e)},i.prototype.iaddn=function(e){return r("number"==typeof e),r(e<67108864),e<0?this.isubn(-e):0!==this.negative?1===this.length&&(0|this.words[0])<=e?(this.words[0]=e-(0|this.words[0]),this.negative=0,this):(this.negative=0,this.isubn(e),this.negative=1,this):this._iaddn(e)},i.prototype._iaddn=function(e){this.words[0]+=e;for(var t=0;t<this.length&&this.words[t]>=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},i.prototype.isubn=function(e){if(r("number"==typeof e),r(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t<this.length&&this.words[t]<0;t++)this.words[t]+=67108864,this.words[t+1]-=1;return this._strip()},i.prototype.addn=function(e){return this.clone().iaddn(e)},i.prototype.subn=function(e){return this.clone().isubn(e)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(e,t,n){var i,o,s=e.length+n;this._expand(s);var a=0;for(i=0;i<e.length;i++){o=(0|this.words[i+n])+a;var c=(0|e.words[i])*t;a=((o-=67108863&c)>>26)-(c/67108864|0),this.words[i+n]=67108863&o}for(;i<this.length-n;i++)a=(o=(0|this.words[i+n])+a)>>26,this.words[i+n]=67108863&o;if(0===a)return this._strip();for(r(-1===a),a=0,i=0;i<this.length;i++)a=(o=-(0|this.words[i])+a)>>26,this.words[i]=67108863&o;return this.negative=1,this._strip()},i.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),o=e,s=0|o.words[o.length-1];0!=(r=26-this._countBits(s))&&(o=o.ushln(r),n.iushln(r),s=0|o.words[o.length-1]);var a,c=n.length-o.length;if("mod"!==t){(a=new i(null)).length=c+1,a.words=new Array(a.length);for(var l=0;l<a.length;l++)a.words[l]=0}var u=n.clone()._ishlnsubmul(o,1,c);0===u.negative&&(n=u,a&&(a.words[c]=1));for(var h=c-1;h>=0;h--){var d=67108864*(0|n.words[o.length+h])+(0|n.words[o.length+h-1]);for(d=Math.min(d/s|0,67108863),n._ishlnsubmul(o,d,h);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(o,1,h),n.isZero()||(n.negative^=1);a&&(a.words[h]=d)}return a&&a._strip(),n._strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:a||null,mod:n}},i.prototype.divmod=function(e,t,n){return r(!e.isZero()),this.isZero()?{div:new i(0),mod:new i(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(o=a.div.neg()),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.iadd(e)),{div:o,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(o=a.div.neg()),{div:o,mod:a.mod}):0!==(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),n&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new i(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new i(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new i(this.modrn(e.words[0]))}:this._wordDiv(e,t);var o,s,a},i.prototype.div=function(e){return this.divmod(e,"div",!1).div},i.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},i.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},i.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},i.prototype.modrn=function(e){var t=e<0;t&&(e=-e),r(e<=67108863);for(var n=(1<<26)%e,i=0,o=this.length-1;o>=0;o--)i=(n*i+(0|this.words[o]))%e;return t?-i:i},i.prototype.modn=function(e){return this.modrn(e)},i.prototype.idivn=function(e){var t=e<0;t&&(e=-e),r(e<=67108863);for(var n=0,i=this.length-1;i>=0;i--){var o=(0|this.words[i])+67108864*n;this.words[i]=o/e|0,n=o%e}return this._strip(),t?this.ineg():this},i.prototype.divn=function(e){return this.clone().idivn(e)},i.prototype.egcd=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o=new i(1),s=new i(0),a=new i(0),c=new i(1),l=0;t.isEven()&&n.isEven();)t.iushrn(1),n.iushrn(1),++l;for(var u=n.clone(),h=t.clone();!t.isZero();){for(var d=0,p=1;0===(t.words[0]&p)&&d<26;++d,p<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(o.isOdd()||s.isOdd())&&(o.iadd(u),s.isub(h)),o.iushrn(1),s.iushrn(1);for(var f=0,m=1;0===(n.words[0]&m)&&f<26;++f,m<<=1);if(f>0)for(n.iushrn(f);f-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(u),c.isub(h)),a.iushrn(1),c.iushrn(1);t.cmp(n)>=0?(t.isub(n),o.isub(a),s.isub(c)):(n.isub(t),a.isub(o),c.isub(s))}return{a:a,b:c,gcd:n.iushln(l)}},i.prototype._invmp=function(e){r(0===e.negative),r(!e.isZero());var t=this,n=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var o,s=new i(1),a=new i(0),c=n.clone();t.cmpn(1)>0&&n.cmpn(1)>0;){for(var l=0,u=1;0===(t.words[0]&u)&&l<26;++l,u<<=1);if(l>0)for(t.iushrn(l);l-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var h=0,d=1;0===(n.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(n.iushrn(h);h-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(n)>=0?(t.isub(n),s.isub(a)):(n.isub(t),a.isub(s))}return(o=0===t.cmpn(1)?s:a).cmpn(0)<0&&o.iadd(e),o},i.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},i.prototype.invm=function(e){return this.egcd(e).a.umod(e)},i.prototype.isEven=function(){return!(1&this.words[0])},i.prototype.isOdd=function(){return!(1&~this.words[0])},i.prototype.andln=function(e){return this.words[0]&e},i.prototype.bincn=function(e){r("number"==typeof e);var t=e%26,n=(e-t)/26,i=1<<t;if(this.length<=n)return this._expand(n+1),this.words[n]|=i,this;for(var o=i,s=n;0!==o&&s<this.length;s++){var a=0|this.words[s];o=(a+=o)>>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},i.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},i.prototype.cmpn=function(e){var t,n=e<0;if(0!==this.negative&&!n)return-1;if(0===this.negative&&n)return 1;if(this._strip(),this.length>1)t=1;else{n&&(e=-e),r(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:i<e?-1:1}return 0!==this.negative?0|-t:t},i.prototype.cmp=function(e){if(0!==this.negative&&0===e.negative)return-1;if(0===this.negative&&0!==e.negative)return 1;var t=this.ucmp(e);return 0!==this.negative?0|-t:t},i.prototype.ucmp=function(e){if(this.length>e.length)return 1;if(this.length<e.length)return-1;for(var t=0,r=this.length-1;r>=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){n<i?t=-1:n>i&&(t=1);break}}return t},i.prototype.gtn=function(e){return 1===this.cmpn(e)},i.prototype.gt=function(e){return 1===this.cmp(e)},i.prototype.gten=function(e){return this.cmpn(e)>=0},i.prototype.gte=function(e){return this.cmp(e)>=0},i.prototype.ltn=function(e){return-1===this.cmpn(e)},i.prototype.lt=function(e){return-1===this.cmp(e)},i.prototype.lten=function(e){return this.cmpn(e)<=0},i.prototype.lte=function(e){return this.cmp(e)<=0},i.prototype.eqn=function(e){return 0===this.cmpn(e)},i.prototype.eq=function(e){return 0===this.cmp(e)},i.red=function(e){return new S(e)},i.prototype.toRed=function(e){return r(!this.red,"Already a number in reduction context"),r(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(e){return this.red=e,this},i.prototype.forceRed=function(e){return r(!this.red,"Already a number in reduction context"),this._forceRed(e)},i.prototype.redAdd=function(e){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},i.prototype.redIAdd=function(e){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},i.prototype.redSub=function(e){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},i.prototype.redISub=function(e){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},i.prototype.redShl=function(e){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},i.prototype.redMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},i.prototype.redIMul=function(e){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(e){return r(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var v={k256:null,p224:null,p192:null,p25519:null};function b(e,t){this.name=e,this.p=new i(t,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function w(){b.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function x(){b.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function k(){b.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){b.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=i._prime(e);this.m=t.p,this.prime=t}else r(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function C(e){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new i(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)}b.prototype._tmp=function(){var e=new i(null);return e.words=new Array(Math.ceil(this.n/13)),e},b.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t<this.n?-1:r.ucmp(this.p);return 0===n?(r.words[0]=0,r.length=1):n>0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},b.prototype.split=function(e,t){e.iushrn(this.n,0,t)},b.prototype.imulK=function(e){return e.imul(this.k)},n(w,b),w.prototype.split=function(e,t){for(var r=4194303,n=Math.min(e.length,9),i=0;i<n;i++)t.words[i]=e.words[i];if(t.length=n,e.length<=9)return e.words[0]=0,void(e.length=1);var o=e.words[9];for(t.words[t.length++]=o&r,i=10;i<e.length;i++){var s=0|e.words[i];e.words[i-10]=(s&r)<<4|o>>>22,o=s}o>>>=22,e.words[i-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},w.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r<e.length;r++){var n=0|e.words[r];t+=977*n,e.words[r]=67108863&t,t=64*n+(t/67108864|0)}return 0===e.words[e.length-1]&&(e.length--,0===e.words[e.length-1]&&e.length--),e},n(x,b),n(k,b),n(_,b),_.prototype.imulK=function(e){for(var t=0,r=0;r<e.length;r++){var n=19*(0|e.words[r])+t,i=67108863&n;n>>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},i._prime=function(e){if(v[e])return v[e];var t;if("k256"===e)t=new w;else if("p224"===e)t=new x;else if("p192"===e)t=new k;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return v[e]=t,t},S.prototype._verify1=function(e){r(0===e.negative,"red works only with positives"),r(e.red,"red works only with red numbers")},S.prototype._verify2=function(e,t){r(0===(e.negative|t.negative),"red works only with positives"),r(e.red&&e.red===t.red,"red works only with red numbers")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},S.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},S.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},S.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(r(t%2==1),3===t){var n=this.m.add(new i(1)).iushrn(2);return this.pow(e,n)}for(var o=this.m.subn(1),s=0;!o.isZero()&&0===o.andln(1);)s++,o.iushrn(1);r(!o.isZero());var a=new i(1).toRed(this),c=a.redNeg(),l=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new i(2*u*u).toRed(this);0!==this.pow(u,l).cmp(c);)u.redIAdd(c);for(var h=this.pow(u,o),d=this.pow(e,o.addn(1).iushrn(1)),p=this.pow(e,o),f=s;0!==p.cmp(a);){for(var m=p,g=0;0!==m.cmp(a);g++)m=m.redSqr();r(g<f);var y=this.pow(h,new i(1).iushln(f-g-1));d=d.redMul(y),h=y.redSqr(),p=p.redMul(h),f=g}return d},S.prototype.invm=function(e){var t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)},S.prototype.pow=function(e,t){if(t.isZero())return new i(1).toRed(this);if(0===t.cmpn(1))return e.clone();var r=new Array(16);r[0]=new i(1).toRed(this),r[1]=e;for(var n=2;n<r.length;n++)r[n]=this.mul(r[n-1],e);var o=r[0],s=0,a=0,c=t.bitLength()%26;for(0===c&&(c=26),n=t.length-1;n>=0;n--){for(var l=t.words[n],u=c-1;u>=0;u--){var h=l>>u&1;o!==r[0]&&(o=this.sqr(o)),0!==h||0!==s?(s<<=1,s|=h,(4===++a||0===n&&0===u)&&(o=this.mul(o,r[s]),a=0,s=0)):a=0}c=26}return o},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},i.mont=function(e){return new C(e)},n(C,S),C.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},C.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},C.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},C.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new i(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),o=r.isub(n).iushrn(this.shift),s=o;return o.cmp(this.m)>=0?s=o.isub(this.m):o.cmpn(0)<0&&(s=o.iadd(this.m)),s._forceRed(this)},C.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}})(qb,sv);var $b=qb.exports;const Gb=av($b);var Vb={exports:{}};
|
|
19
|
+
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */!function(e,t){var r=lv,n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(Vb,Vb.exports);var Hb=Vb.exports.Buffer;var Kb=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),o=i.charCodeAt(0);if(255!==t[o])throw new TypeError(i+" is ambiguous");t[o]=n}var s=e.length,a=e.charAt(0),c=Math.log(s)/Math.log(256),l=Math.log(256)/Math.log(s);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return Hb.alloc(0);for(var r=0,n=0,i=0;e[r]===a;)n++,r++;for(var o=(e.length-r)*c+1>>>0,l=new Uint8Array(o);r<e.length;){var u=e.charCodeAt(r);if(u>255)return;var h=t[u];if(255===h)return;for(var d=0,p=o-1;(0!==h||d<i)&&-1!==p;p--,d++)h+=s*l[p]>>>0,l[p]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");i=d,r++}for(var f=o-i;f!==o&&0===l[f];)f++;var m=Hb.allocUnsafe(n+(o-f));m.fill(0,0,n);for(var g=n;f!==o;)m[g++]=l[f++];return m}return{encode:function(t){if((Array.isArray(t)||t instanceof Uint8Array)&&(t=Hb.from(t)),!Hb.isBuffer(t))throw new TypeError("Expected Buffer");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var c=(o-i)*l+1>>>0,u=new Uint8Array(c);i!==o;){for(var h=t[i],d=0,p=c-1;(0!==h||d<n)&&-1!==p;p--,d++)h+=256*u[p]>>>0,u[p]=h%s>>>0,h=h/s>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,i++}for(var f=c-n;f!==c&&0===u[f];)f++;for(var m=a.repeat(r);f<c;++f)m+=e.charAt(u[f]);return m},decodeUnsafe:u,decode:function(e){var t=u(e);if(t)return t;throw new Error("Non-base"+s+" character")}}},Zb=Kb("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");const Yb=av(Zb);var Jb={};function Xb(e,t,r){return t<=e&&e<=r}function Qb(e){if(void 0===e)return{};if(e===Object(e))return e;throw TypeError("Could not convert argument to dictionary")}function ew(e){this.tokens=[].slice.call(e)}ew.prototype={endOfStream:function(){return!this.tokens.length},read:function(){return this.tokens.length?this.tokens.shift():-1},prepend:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.unshift(t.pop());else this.tokens.unshift(e)},push:function(e){if(Array.isArray(e))for(var t=e;t.length;)this.tokens.push(t.shift());else this.tokens.push(e)}};var tw=-1;function rw(e,t){if(e)throw TypeError("Decoder error");return t||65533}var nw="utf-8";function iw(e,t){if(!(this instanceof iw))return new iw(e,t);if((e=void 0!==e?String(e).toLowerCase():nw)!==nw)throw new Error("Encoding not supported. Only utf-8 is supported");t=Qb(t),this._streaming=!1,this._BOMseen=!1,this._decoder=null,this._fatal=Boolean(t.fatal),this._ignoreBOM=Boolean(t.ignoreBOM),Object.defineProperty(this,"encoding",{value:"utf-8"}),Object.defineProperty(this,"fatal",{value:this._fatal}),Object.defineProperty(this,"ignoreBOM",{value:this._ignoreBOM})}function ow(e,t){if(!(this instanceof ow))return new ow(e,t);if((e=void 0!==e?String(e).toLowerCase():nw)!==nw)throw new Error("Encoding not supported. Only utf-8 is supported");t=Qb(t),this._streaming=!1,this._encoder=null,this._options={fatal:Boolean(t.fatal)},Object.defineProperty(this,"encoding",{value:"utf-8"})}function sw(e){var t=e.fatal,r=0,n=0,i=0,o=128,s=191;this.handler=function(e,a){if(-1===a&&0!==i)return i=0,rw(t);if(-1===a)return tw;if(0===i){if(Xb(a,0,127))return a;if(Xb(a,194,223))i=1,r=a-192;else if(Xb(a,224,239))224===a&&(o=160),237===a&&(s=159),i=2,r=a-224;else{if(!Xb(a,240,244))return rw(t);240===a&&(o=144),244===a&&(s=143),i=3,r=a-240}return r<<=6*i,null}if(!Xb(a,o,s))return r=i=n=0,o=128,s=191,e.prepend(a),rw(t);if(o=128,s=191,r+=a-128<<6*(i-(n+=1)),n!==i)return null;var c=r;return r=i=n=0,c}}function aw(e){e.fatal,this.handler=function(e,t){if(-1===t)return tw;if(Xb(t,0,127))return t;var r,n;Xb(t,128,2047)?(r=1,n=192):Xb(t,2048,65535)?(r=2,n=224):Xb(t,65536,1114111)&&(r=3,n=240);for(var i=[(t>>6*r)+n];r>0;){var o=t>>6*(r-1);i.push(128|63&o),r-=1}return i}}iw.prototype={decode:function(e,t){var r;r="object"==typeof e&&e instanceof ArrayBuffer?new Uint8Array(e):"object"==typeof e&&"buffer"in e&&e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(0),t=Qb(t),this._streaming||(this._decoder=new sw({fatal:this._fatal}),this._BOMseen=!1),this._streaming=Boolean(t.stream);for(var n,i=new ew(r),o=[];!i.endOfStream()&&(n=this._decoder.handler(i,i.read()))!==tw;)null!==n&&(Array.isArray(n)?o.push.apply(o,n):o.push(n));if(!this._streaming){do{if((n=this._decoder.handler(i,i.read()))===tw)break;null!==n&&(Array.isArray(n)?o.push.apply(o,n):o.push(n))}while(!i.endOfStream());this._decoder=null}return o.length&&(-1===["utf-8"].indexOf(this.encoding)||this._ignoreBOM||this._BOMseen||(65279===o[0]?(this._BOMseen=!0,o.shift()):this._BOMseen=!0)),function(e){for(var t="",r=0;r<e.length;++r){var n=e[r];n<=65535?t+=String.fromCharCode(n):(n-=65536,t+=String.fromCharCode(55296+(n>>10),56320+(1023&n)))}return t}(o)}},ow.prototype={encode:function(e,t){e=e?String(e):"",t=Qb(t),this._streaming||(this._encoder=new aw(this._options)),this._streaming=Boolean(t.stream);for(var r,n=[],i=new ew(function(e){for(var t=String(e),r=t.length,n=0,i=[];n<r;){var o=t.charCodeAt(n);if(o<55296||o>57343)i.push(o);else if(56320<=o&&o<=57343)i.push(65533);else if(55296<=o&&o<=56319)if(n===r-1)i.push(65533);else{var s=e.charCodeAt(n+1);if(56320<=s&&s<=57343){var a=1023&o,c=1023&s;i.push(65536+(a<<10)+c),n+=1}else i.push(65533)}n+=1}return i}(e));!i.endOfStream()&&(r=this._encoder.handler(i,i.read()))!==tw;)Array.isArray(r)?n.push.apply(n,r):n.push(r);if(!this._streaming){for(;(r=this._encoder.handler(i,i.read()))!==tw;)Array.isArray(r)?n.push.apply(n,r):n.push(r);this._encoder=null}return new Uint8Array(n)}};const cw=cv(Object.freeze(Object.defineProperty({__proto__:null,TextDecoder:iw,TextEncoder:ow},Symbol.toStringTag,{value:"Module"})));var lw=["buffer","Buffer"],uw=sv&&sv.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),hw=sv&&sv.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),dw=sv&&sv.__decorate||function(e,t,r,n){var i,o=arguments.length,s=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,n);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(o<3?i(s):o>3?i(t,r,s):i(t,r))||s);return o>3&&s&&Object.defineProperty(t,r,s),s},pw=sv&&sv.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.hasOwnProperty.call(e,r)&&uw(t,e,r);return hw(t,e),t},fw=sv&&sv.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Jb,"__esModule",{value:!0});var mw=Jb.deserializeUnchecked=Pw=Jb.deserialize=Aw=Jb.serialize=Jb.BinaryReader=Jb.BinaryWriter=Jb.BorshError=Jb.baseDecode=Jb.baseEncode=void 0;const gw=fw($b),yw=fw(Zb),vw=pw(cw),bw=new("function"!=typeof TextDecoder?vw.TextDecoder:TextDecoder)("utf-8",{fatal:!0});Jb.baseEncode=function(e){return"string"==typeof e&&(e=lw.from(e,"utf8")),yw.default.encode(lw.from(e))},Jb.baseDecode=function(e){return lw.from(yw.default.decode(e))};const ww=1024;class xw extends Error{constructor(e){super(e),this.fieldPath=[],this.originalMessage=e}addToFieldPath(e){this.fieldPath.splice(0,0,e),this.message=this.originalMessage+": "+this.fieldPath.join(".")}}Jb.BorshError=xw;class kw{constructor(){this.buf=lw.alloc(ww),this.length=0}maybeResize(){this.buf.length<16+this.length&&(this.buf=lw.concat([this.buf,lw.alloc(ww)]))}writeU8(e){this.maybeResize(),this.buf.writeUInt8(e,this.length),this.length+=1}writeU16(e){this.maybeResize(),this.buf.writeUInt16LE(e,this.length),this.length+=2}writeU32(e){this.maybeResize(),this.buf.writeUInt32LE(e,this.length),this.length+=4}writeU64(e){this.maybeResize(),this.writeBuffer(lw.from(new gw.default(e).toArray("le",8)))}writeU128(e){this.maybeResize(),this.writeBuffer(lw.from(new gw.default(e).toArray("le",16)))}writeU256(e){this.maybeResize(),this.writeBuffer(lw.from(new gw.default(e).toArray("le",32)))}writeU512(e){this.maybeResize(),this.writeBuffer(lw.from(new gw.default(e).toArray("le",64)))}writeBuffer(e){this.buf=lw.concat([lw.from(this.buf.subarray(0,this.length)),e,lw.alloc(ww)]),this.length+=e.length}writeString(e){this.maybeResize();const t=lw.from(e,"utf8");this.writeU32(t.length),this.writeBuffer(t)}writeFixedArray(e){this.writeBuffer(lw.from(e))}writeArray(e,t){this.maybeResize(),this.writeU32(e.length);for(const r of e)this.maybeResize(),t(r)}toArray(){return this.buf.subarray(0,this.length)}}function _w(e,t,r){const n=r.value;r.value=function(...e){try{return n.apply(this,e)}catch(t){if(t instanceof RangeError){const e=t.code;if(["ERR_BUFFER_OUT_OF_BOUNDS","ERR_OUT_OF_RANGE"].indexOf(e)>=0)throw new xw("Reached the end of buffer when deserializing")}throw t}}}Jb.BinaryWriter=kw;class Sw{constructor(e){this.buf=e,this.offset=0}readU8(){const e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readU16(){const e=this.buf.readUInt16LE(this.offset);return this.offset+=2,e}readU32(){const e=this.buf.readUInt32LE(this.offset);return this.offset+=4,e}readU64(){const e=this.readBuffer(8);return new gw.default(e,"le")}readU128(){const e=this.readBuffer(16);return new gw.default(e,"le")}readU256(){const e=this.readBuffer(32);return new gw.default(e,"le")}readU512(){const e=this.readBuffer(64);return new gw.default(e,"le")}readBuffer(e){if(this.offset+e>this.buf.length)throw new xw(`Expected buffer length ${e} isn't within bounds`);const t=this.buf.slice(this.offset,this.offset+e);return this.offset+=e,t}readString(){const e=this.readU32(),t=this.readBuffer(e);try{return bw.decode(t)}catch(r){throw new xw(`Error decoding UTF-8 string: ${r}`)}}readFixedArray(e){return new Uint8Array(this.readBuffer(e))}readArray(e){const t=this.readU32(),r=Array();for(let n=0;n<t;++n)r.push(e());return r}}function Cw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Iw(e,t,r,n,i){try{if("string"==typeof n)i[`write${Cw(n)}`](r);else if(n instanceof Array)if("number"==typeof n[0]){if(r.length!==n[0])throw new xw(`Expecting byte array of length ${n[0]}, but got ${r.length} bytes`);i.writeFixedArray(r)}else if(2===n.length&&"number"==typeof n[1]){if(r.length!==n[1])throw new xw(`Expecting byte array of length ${n[1]}, but got ${r.length} bytes`);for(let t=0;t<n[1];t++)Iw(e,null,r[t],n[0],i)}else i.writeArray(r,r=>{Iw(e,t,r,n[0],i)});else if(void 0!==n.kind)switch(n.kind){case"option":null==r?i.writeU8(0):(i.writeU8(1),Iw(e,t,r,n.type,i));break;case"map":i.writeU32(r.size),r.forEach((r,o)=>{Iw(e,t,o,n.key,i),Iw(e,t,r,n.value,i)});break;default:throw new xw(`FieldType ${n} unrecognized`)}else Ew(e,r,i)}catch(vu){throw vu instanceof xw&&vu.addToFieldPath(t),vu}}function Ew(e,t,r){if("function"==typeof t.borshSerialize)return void t.borshSerialize(r);const n=e.get(t.constructor);if(!n)throw new xw(`Class ${t.constructor.name} is missing in schema`);if("struct"===n.kind)n.fields.map(([n,i])=>{Iw(e,n,t[n],i,r)});else{if("enum"!==n.kind)throw new xw(`Unexpected schema kind: ${n.kind} for ${t.constructor.name}`);{const i=t[n.field];for(let o=0;o<n.values.length;++o){const[s,a]=n.values[o];if(s===i){r.writeU8(o),Iw(e,s,t[s],a,r);break}}}}}dw([_w],Sw.prototype,"readU8",null),dw([_w],Sw.prototype,"readU16",null),dw([_w],Sw.prototype,"readU32",null),dw([_w],Sw.prototype,"readU64",null),dw([_w],Sw.prototype,"readU128",null),dw([_w],Sw.prototype,"readU256",null),dw([_w],Sw.prototype,"readU512",null),dw([_w],Sw.prototype,"readString",null),dw([_w],Sw.prototype,"readFixedArray",null),dw([_w],Sw.prototype,"readArray",null),Jb.BinaryReader=Sw;var Aw=Jb.serialize=function(e,t,r=kw){const n=new r;return Ew(e,t,n),n.toArray()};function Mw(e,t,r,n){try{if("string"==typeof r)return n[`read${Cw(r)}`]();if(r instanceof Array){if("number"==typeof r[0])return n.readFixedArray(r[0]);if("number"==typeof r[1]){const t=[];for(let i=0;i<r[1];i++)t.push(Mw(e,null,r[0],n));return t}return n.readArray(()=>Mw(e,t,r[0],n))}if("option"===r.kind){return n.readU8()?Mw(e,t,r.type,n):void 0}if("map"===r.kind){let i=new Map;const o=n.readU32();for(let s=0;s<o;s++){const o=Mw(e,t,r.key,n),s=Mw(e,t,r.value,n);i.set(o,s)}return i}return Nw(e,r,n)}catch(vu){throw vu instanceof xw&&vu.addToFieldPath(t),vu}}function Nw(e,t,r){if("function"==typeof t.borshDeserialize)return t.borshDeserialize(r);const n=e.get(t);if(!n)throw new xw(`Class ${t.name} is missing in schema`);if("struct"===n.kind){const n={};for(const[i,o]of e.get(t).fields)n[i]=Mw(e,i,o,r);return new t(n)}if("enum"===n.kind){const i=r.readU8();if(i>=n.values.length)throw new xw(`Enum index: ${i} is out of range`);const[o,s]=n.values[i],a=Mw(e,o,s,r);return new t({[o]:a})}throw new xw(`Unexpected schema kind: ${n.kind} for ${t.constructor.name}`)}var Pw=Jb.deserialize=function(e,t,r,n=Sw){const i=new n(r),o=Nw(e,t,i);if(i.offset<r.length)throw new xw(`Unexpected ${r.length-i.offset} bytes after deserialized data`);return o};mw=Jb.deserializeUnchecked=function(e,t,r,n=Sw){return Nw(e,t,new n(r))};var Bw={};
|
|
20
|
+
/**
|
|
21
|
+
* Support for translating between Uint8Array instances and JavaScript
|
|
22
|
+
* native types.
|
|
23
|
+
*
|
|
24
|
+
* {@link module:Layout~Layout|Layout} is the basis of a class
|
|
25
|
+
* hierarchy that associates property names with sequences of encoded
|
|
26
|
+
* bytes.
|
|
27
|
+
*
|
|
28
|
+
* Layouts are supported for these scalar (numeric) types:
|
|
29
|
+
* * {@link module:Layout~UInt|Unsigned integers in little-endian
|
|
30
|
+
* format} with {@link module:Layout.u8|8-bit}, {@link
|
|
31
|
+
* module:Layout.u16|16-bit}, {@link module:Layout.u24|24-bit},
|
|
32
|
+
* {@link module:Layout.u32|32-bit}, {@link
|
|
33
|
+
* module:Layout.u40|40-bit}, and {@link module:Layout.u48|48-bit}
|
|
34
|
+
* representation ranges;
|
|
35
|
+
* * {@link module:Layout~UIntBE|Unsigned integers in big-endian
|
|
36
|
+
* format} with {@link module:Layout.u16be|16-bit}, {@link
|
|
37
|
+
* module:Layout.u24be|24-bit}, {@link module:Layout.u32be|32-bit},
|
|
38
|
+
* {@link module:Layout.u40be|40-bit}, and {@link
|
|
39
|
+
* module:Layout.u48be|48-bit} representation ranges;
|
|
40
|
+
* * {@link module:Layout~Int|Signed integers in little-endian
|
|
41
|
+
* format} with {@link module:Layout.s8|8-bit}, {@link
|
|
42
|
+
* module:Layout.s16|16-bit}, {@link module:Layout.s24|24-bit},
|
|
43
|
+
* {@link module:Layout.s32|32-bit}, {@link
|
|
44
|
+
* module:Layout.s40|40-bit}, and {@link module:Layout.s48|48-bit}
|
|
45
|
+
* representation ranges;
|
|
46
|
+
* * {@link module:Layout~IntBE|Signed integers in big-endian format}
|
|
47
|
+
* with {@link module:Layout.s16be|16-bit}, {@link
|
|
48
|
+
* module:Layout.s24be|24-bit}, {@link module:Layout.s32be|32-bit},
|
|
49
|
+
* {@link module:Layout.s40be|40-bit}, and {@link
|
|
50
|
+
* module:Layout.s48be|48-bit} representation ranges;
|
|
51
|
+
* * 64-bit integral values that decode to an exact (if magnitude is
|
|
52
|
+
* less than 2^53) or nearby integral Number in {@link
|
|
53
|
+
* module:Layout.nu64|unsigned little-endian}, {@link
|
|
54
|
+
* module:Layout.nu64be|unsigned big-endian}, {@link
|
|
55
|
+
* module:Layout.ns64|signed little-endian}, and {@link
|
|
56
|
+
* module:Layout.ns64be|unsigned big-endian} encodings;
|
|
57
|
+
* * 32-bit floating point values with {@link
|
|
58
|
+
* module:Layout.f32|little-endian} and {@link
|
|
59
|
+
* module:Layout.f32be|big-endian} representations;
|
|
60
|
+
* * 64-bit floating point values with {@link
|
|
61
|
+
* module:Layout.f64|little-endian} and {@link
|
|
62
|
+
* module:Layout.f64be|big-endian} representations;
|
|
63
|
+
* * {@link module:Layout.const|Constants} that take no space in the
|
|
64
|
+
* encoded expression.
|
|
65
|
+
*
|
|
66
|
+
* and for these aggregate types:
|
|
67
|
+
* * {@link module:Layout.seq|Sequence}s of instances of a {@link
|
|
68
|
+
* module:Layout~Layout|Layout}, with JavaScript representation as
|
|
69
|
+
* an Array and constant or data-dependent {@link
|
|
70
|
+
* module:Layout~Sequence#count|length};
|
|
71
|
+
* * {@link module:Layout.struct|Structure}s that aggregate a
|
|
72
|
+
* heterogeneous sequence of {@link module:Layout~Layout|Layout}
|
|
73
|
+
* instances, with JavaScript representation as an Object;
|
|
74
|
+
* * {@link module:Layout.union|Union}s that support multiple {@link
|
|
75
|
+
* module:Layout~VariantLayout|variant layouts} over a fixed
|
|
76
|
+
* (padded) or variable (not padded) span of bytes, using an
|
|
77
|
+
* unsigned integer at the start of the data or a separate {@link
|
|
78
|
+
* module:Layout.unionLayoutDiscriminator|layout element} to
|
|
79
|
+
* determine which layout to use when interpreting the buffer
|
|
80
|
+
* contents;
|
|
81
|
+
* * {@link module:Layout.bits|BitStructure}s that contain a sequence
|
|
82
|
+
* of individual {@link
|
|
83
|
+
* module:Layout~BitStructure#addField|BitField}s packed into an 8,
|
|
84
|
+
* 16, 24, or 32-bit unsigned integer starting at the least- or
|
|
85
|
+
* most-significant bit;
|
|
86
|
+
* * {@link module:Layout.cstr|C strings} of varying length;
|
|
87
|
+
* * {@link module:Layout.blob|Blobs} of fixed- or variable-{@link
|
|
88
|
+
* module:Layout~Blob#length|length} raw data.
|
|
89
|
+
*
|
|
90
|
+
* All {@link module:Layout~Layout|Layout} instances are immutable
|
|
91
|
+
* after construction, to prevent internal state from becoming
|
|
92
|
+
* inconsistent.
|
|
93
|
+
*
|
|
94
|
+
* @local Layout
|
|
95
|
+
* @local ExternalLayout
|
|
96
|
+
* @local GreedyCount
|
|
97
|
+
* @local OffsetLayout
|
|
98
|
+
* @local UInt
|
|
99
|
+
* @local UIntBE
|
|
100
|
+
* @local Int
|
|
101
|
+
* @local IntBE
|
|
102
|
+
* @local NearUInt64
|
|
103
|
+
* @local NearUInt64BE
|
|
104
|
+
* @local NearInt64
|
|
105
|
+
* @local NearInt64BE
|
|
106
|
+
* @local Float
|
|
107
|
+
* @local FloatBE
|
|
108
|
+
* @local Double
|
|
109
|
+
* @local DoubleBE
|
|
110
|
+
* @local Sequence
|
|
111
|
+
* @local Structure
|
|
112
|
+
* @local UnionDiscriminator
|
|
113
|
+
* @local UnionLayoutDiscriminator
|
|
114
|
+
* @local Union
|
|
115
|
+
* @local VariantLayout
|
|
116
|
+
* @local BitStructure
|
|
117
|
+
* @local BitField
|
|
118
|
+
* @local Boolean
|
|
119
|
+
* @local Blob
|
|
120
|
+
* @local CString
|
|
121
|
+
* @local Constant
|
|
122
|
+
* @local bindConstructorLayout
|
|
123
|
+
* @module Layout
|
|
124
|
+
* @license MIT
|
|
125
|
+
* @author Peter A. Bigot
|
|
126
|
+
* @see {@link https://github.com/pabigot/buffer-layout|buffer-layout on GitHub}
|
|
127
|
+
*/Object.defineProperty(Bw,"__esModule",{value:!0}),Bw.s16=Bw.s8=Bw.nu64be=Bw.u48be=Bw.u40be=Bw.u32be=Bw.u24be=Bw.u16be=wx=Bw.nu64=Bw.u48=Bw.u40=bx=Bw.u32=Bw.u24=vx=Bw.u16=yx=Bw.u8=gx=Bw.offset=Bw.greedy=Bw.Constant=Bw.UTF8=Bw.CString=Bw.Blob=Bw.Boolean=Bw.BitField=Bw.BitStructure=Bw.VariantLayout=Bw.Union=Bw.UnionLayoutDiscriminator=Bw.UnionDiscriminator=Bw.Structure=Bw.Sequence=Bw.DoubleBE=Bw.Double=Bw.FloatBE=Bw.Float=Bw.NearInt64BE=Bw.NearInt64=Bw.NearUInt64BE=Bw.NearUInt64=Bw.IntBE=Bw.Int=Bw.UIntBE=Bw.UInt=Bw.OffsetLayout=Bw.GreedyCount=Bw.ExternalLayout=Bw.bindConstructorLayout=Bw.nameWithProperty=Bw.Layout=Bw.uint8ArrayToBuffer=Bw.checkUint8Array=void 0,Bw.constant=Bw.utf8=Bw.cstr=Sx=Bw.blob=Bw.unionLayoutDiscriminator=Bw.union=_x=Bw.seq=Bw.bits=kx=Bw.struct=Bw.f64be=Bw.f64=Bw.f32be=Bw.f32=Bw.ns64be=Bw.s48be=Bw.s40be=Bw.s32be=Bw.s24be=Bw.s16be=xx=Bw.ns64=Bw.s48=Bw.s40=Bw.s32=Bw.s24=void 0;const Tw=lv;function Ow(e){if(!(e instanceof Uint8Array))throw new TypeError("b must be a Uint8Array")}function Rw(e){return Ow(e),Tw.Buffer.from(e.buffer,e.byteOffset,e.length)}Bw.checkUint8Array=Ow,Bw.uint8ArrayToBuffer=Rw;class Lw{constructor(e,t){if(!Number.isInteger(e))throw new TypeError("span must be an integer");this.span=e,this.property=t}makeDestinationObject(){return{}}getSpan(e,t){if(0>this.span)throw new RangeError("indeterminate span");return this.span}replicate(e){const t=Object.create(this.constructor.prototype);return Object.assign(t,this),t.property=e,t}fromArray(e){}}function Uw(e,t){return t.property?e+"["+t.property+"]":e}Bw.Layout=Lw,Bw.nameWithProperty=Uw,Bw.bindConstructorLayout=function(e,t){if("function"!=typeof e)throw new TypeError("Class must be constructor");if(Object.prototype.hasOwnProperty.call(e,"layout_"))throw new Error("Class is already bound to a layout");if(!(t&&t instanceof Lw))throw new TypeError("layout must be a Layout");if(Object.prototype.hasOwnProperty.call(t,"boundConstructor_"))throw new Error("layout is already bound to a constructor");e.layout_=t,t.boundConstructor_=e,t.makeDestinationObject=()=>new e,Object.defineProperty(e.prototype,"encode",{value(e,r){return t.encode(this,e,r)},writable:!0}),Object.defineProperty(e,"decode",{value:(e,r)=>t.decode(e,r),writable:!0})};class jw extends Lw{isCount(){throw new Error("ExternalLayout is abstract")}}Bw.ExternalLayout=jw;class Dw extends jw{constructor(e=1,t){if(!Number.isInteger(e)||0>=e)throw new TypeError("elementSpan must be a (positive) integer");super(-1,t),this.elementSpan=e}isCount(){return!0}decode(e,t=0){Ow(e);const r=e.length-t;return Math.floor(r/this.elementSpan)}encode(e,t,r){return 0}}Bw.GreedyCount=Dw;class Fw extends jw{constructor(e,t=0,r){if(!(e instanceof Lw))throw new TypeError("layout must be a Layout");if(!Number.isInteger(t))throw new TypeError("offset must be integer or undefined");super(e.span,r||e.property),this.layout=e,this.offset=t}isCount(){return this.layout instanceof zw||this.layout instanceof qw}decode(e,t=0){return this.layout.decode(e,t+this.offset)}encode(e,t,r=0){return this.layout.encode(e,t,r+this.offset)}}Bw.OffsetLayout=Fw;class zw extends Lw{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return Rw(e).readUIntLE(t,this.span)}encode(e,t,r=0){return Rw(t).writeUIntLE(e,r,this.span),this.span}}Bw.UInt=zw;class qw extends Lw{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return Rw(e).readUIntBE(t,this.span)}encode(e,t,r=0){return Rw(t).writeUIntBE(e,r,this.span),this.span}}Bw.UIntBE=qw;class Ww extends Lw{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return Rw(e).readIntLE(t,this.span)}encode(e,t,r=0){return Rw(t).writeIntLE(e,r,this.span),this.span}}Bw.Int=Ww;class $w extends Lw{constructor(e,t){if(super(e,t),6<this.span)throw new RangeError("span must not exceed 6 bytes")}decode(e,t=0){return Rw(e).readIntBE(t,this.span)}encode(e,t,r=0){return Rw(t).writeIntBE(e,r,this.span),this.span}}Bw.IntBE=$w;const Gw=Math.pow(2,32);function Vw(e){const t=Math.floor(e/Gw);return{hi32:t,lo32:e-t*Gw}}function Hw(e,t){return e*Gw+t}class Kw extends Lw{constructor(e){super(8,e)}decode(e,t=0){const r=Rw(e),n=r.readUInt32LE(t);return Hw(r.readUInt32LE(t+4),n)}encode(e,t,r=0){const n=Vw(e),i=Rw(t);return i.writeUInt32LE(n.lo32,r),i.writeUInt32LE(n.hi32,r+4),8}}Bw.NearUInt64=Kw;class Zw extends Lw{constructor(e){super(8,e)}decode(e,t=0){const r=Rw(e);return Hw(r.readUInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const n=Vw(e),i=Rw(t);return i.writeUInt32BE(n.hi32,r),i.writeUInt32BE(n.lo32,r+4),8}}Bw.NearUInt64BE=Zw;class Yw extends Lw{constructor(e){super(8,e)}decode(e,t=0){const r=Rw(e),n=r.readUInt32LE(t);return Hw(r.readInt32LE(t+4),n)}encode(e,t,r=0){const n=Vw(e),i=Rw(t);return i.writeUInt32LE(n.lo32,r),i.writeInt32LE(n.hi32,r+4),8}}Bw.NearInt64=Yw;class Jw extends Lw{constructor(e){super(8,e)}decode(e,t=0){const r=Rw(e);return Hw(r.readInt32BE(t),r.readUInt32BE(t+4))}encode(e,t,r=0){const n=Vw(e),i=Rw(t);return i.writeInt32BE(n.hi32,r),i.writeUInt32BE(n.lo32,r+4),8}}Bw.NearInt64BE=Jw;class Xw extends Lw{constructor(e){super(4,e)}decode(e,t=0){return Rw(e).readFloatLE(t)}encode(e,t,r=0){return Rw(t).writeFloatLE(e,r),4}}Bw.Float=Xw;class Qw extends Lw{constructor(e){super(4,e)}decode(e,t=0){return Rw(e).readFloatBE(t)}encode(e,t,r=0){return Rw(t).writeFloatBE(e,r),4}}Bw.FloatBE=Qw;class ex extends Lw{constructor(e){super(8,e)}decode(e,t=0){return Rw(e).readDoubleLE(t)}encode(e,t,r=0){return Rw(t).writeDoubleLE(e,r),8}}Bw.Double=ex;class tx extends Lw{constructor(e){super(8,e)}decode(e,t=0){return Rw(e).readDoubleBE(t)}encode(e,t,r=0){return Rw(t).writeDoubleBE(e,r),8}}Bw.DoubleBE=tx;class rx extends Lw{constructor(e,t,r){if(!(e instanceof Lw))throw new TypeError("elementLayout must be a Layout");if(!(t instanceof jw&&t.isCount()||Number.isInteger(t)&&0<=t))throw new TypeError("count must be non-negative integer or an unsigned integer ExternalLayout");let n=-1;!(t instanceof jw)&&0<e.span&&(n=t*e.span),super(n,r),this.elementLayout=e,this.count=t}getSpan(e,t=0){if(0<=this.span)return this.span;let r=0,n=this.count;if(n instanceof jw&&(n=n.decode(e,t)),0<this.elementLayout.span)r=n*this.elementLayout.span;else{let i=0;for(;i<n;)r+=this.elementLayout.getSpan(e,t+r),++i}return r}decode(e,t=0){const r=[];let n=0,i=this.count;for(i instanceof jw&&(i=i.decode(e,t));n<i;)r.push(this.elementLayout.decode(e,t)),t+=this.elementLayout.getSpan(e,t),n+=1;return r}encode(e,t,r=0){const n=this.elementLayout,i=e.reduce((e,i)=>e+n.encode(i,t,r+e),0);return this.count instanceof jw&&this.count.encode(e.length,t,r),i}}Bw.Sequence=rx;class nx extends Lw{constructor(e,t,r){if(!Array.isArray(e)||!e.reduce((e,t)=>e&&t instanceof Lw,!0))throw new TypeError("fields must be array of Layout instances");"boolean"==typeof t&&void 0===r&&(r=t,t=void 0);for(const o of e)if(0>o.span&&void 0===o.property)throw new Error("fields cannot contain unnamed variable-length layout");let n=-1;try{n=e.reduce((e,t)=>e+t.getSpan(),0)}catch(i){}super(n,t),this.fields=e,this.decodePrefixes=!!r}getSpan(e,t=0){if(0<=this.span)return this.span;let r=0;try{r=this.fields.reduce((r,n)=>{const i=n.getSpan(e,t);return t+=i,r+i},0)}catch(n){throw new RangeError("indeterminate span")}return r}decode(e,t=0){Ow(e);const r=this.makeDestinationObject();for(const n of this.fields)if(void 0!==n.property&&(r[n.property]=n.decode(e,t)),t+=n.getSpan(e,t),this.decodePrefixes&&e.length===t)break;return r}encode(e,t,r=0){const n=r;let i=0,o=0;for(const s of this.fields){let n=s.span;if(o=0<n?n:0,void 0!==s.property){const i=e[s.property];void 0!==i&&(o=s.encode(i,t,r),0>n&&(n=s.getSpan(t,r)))}i=r,r+=n}return i+o-n}fromArray(e){const t=this.makeDestinationObject();for(const r of this.fields)void 0!==r.property&&0<e.length&&(t[r.property]=e.shift());return t}layoutFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}offsetOf(e){if("string"!=typeof e)throw new TypeError("property must be string");let t=0;for(const r of this.fields){if(r.property===e)return t;0>r.span?t=-1:0<=t&&(t+=r.span)}}}Bw.Structure=nx;class ix{constructor(e){this.property=e}decode(e,t){throw new Error("UnionDiscriminator is abstract")}encode(e,t,r){throw new Error("UnionDiscriminator is abstract")}}Bw.UnionDiscriminator=ix;class ox extends ix{constructor(e,t){if(!(e instanceof jw&&e.isCount()))throw new TypeError("layout must be an unsigned integer ExternalLayout");super(t||e.property||"variant"),this.layout=e}decode(e,t){return this.layout.decode(e,t)}encode(e,t,r){return this.layout.encode(e,t,r)}}Bw.UnionLayoutDiscriminator=ox;class sx extends Lw{constructor(e,t,r){let n;if(e instanceof zw||e instanceof qw)n=new ox(new Fw(e));else if(e instanceof jw&&e.isCount())n=new ox(e);else{if(!(e instanceof ix))throw new TypeError("discr must be a UnionDiscriminator or an unsigned integer layout");n=e}if(void 0===t&&(t=null),!(null===t||t instanceof Lw))throw new TypeError("defaultLayout must be null or a Layout");if(null!==t){if(0>t.span)throw new Error("defaultLayout must have constant span");void 0===t.property&&(t=t.replicate("content"))}let i=-1;t&&(i=t.span,0<=i&&(e instanceof zw||e instanceof qw)&&(i+=n.layout.span)),super(i,r),this.discriminator=n,this.usesPrefixDiscriminator=e instanceof zw||e instanceof qw,this.defaultLayout=t,this.registry={};let o=this.defaultGetSourceVariant.bind(this);this.getSourceVariant=function(e){return o(e)},this.configGetSourceVariant=function(e){o=e.bind(this)}}getSpan(e,t=0){if(0<=this.span)return this.span;const r=this.getVariant(e,t);if(!r)throw new Error("unable to determine span for unrecognized variant");return r.getSpan(e,t)}defaultGetSourceVariant(e){if(Object.prototype.hasOwnProperty.call(e,this.discriminator.property)){if(this.defaultLayout&&this.defaultLayout.property&&Object.prototype.hasOwnProperty.call(e,this.defaultLayout.property))return;const t=this.registry[e[this.discriminator.property]];if(t&&(!t.layout||t.property&&Object.prototype.hasOwnProperty.call(e,t.property)))return t}else for(const t in this.registry){const r=this.registry[t];if(r.property&&Object.prototype.hasOwnProperty.call(e,r.property))return r}throw new Error("unable to infer src variant")}decode(e,t=0){let r;const n=this.discriminator,i=n.decode(e,t),o=this.registry[i];if(void 0===o){const o=this.defaultLayout;let s=0;this.usesPrefixDiscriminator&&(s=n.layout.span),r=this.makeDestinationObject(),r[n.property]=i,r[o.property]=o.decode(e,t+s)}else r=o.decode(e,t);return r}encode(e,t,r=0){const n=this.getSourceVariant(e);if(void 0===n){const n=this.discriminator,i=this.defaultLayout;let o=0;return this.usesPrefixDiscriminator&&(o=n.layout.span),n.encode(e[n.property],t,r),o+i.encode(e[i.property],t,r+o)}return n.encode(e,t,r)}addVariant(e,t,r){const n=new ax(this,e,t,r);return this.registry[e]=n,n}getVariant(e,t=0){let r;return r=e instanceof Uint8Array?this.discriminator.decode(e,t):e,this.registry[r]}}Bw.Union=sx;class ax extends Lw{constructor(e,t,r,n){if(!(e instanceof sx))throw new TypeError("union must be a Union");if(!Number.isInteger(t)||0>t)throw new TypeError("variant must be a (non-negative) integer");if("string"==typeof r&&void 0===n&&(n=r,r=null),r){if(!(r instanceof Lw))throw new TypeError("layout must be a Layout");if(null!==e.defaultLayout&&0<=r.span&&r.span>e.defaultLayout.span)throw new Error("variant span exceeds span of containing union");if("string"!=typeof n)throw new TypeError("variant must have a String property")}let i=e.span;0>e.span&&(i=r?r.span:0,0<=i&&e.usesPrefixDiscriminator&&(i+=e.discriminator.layout.span)),super(i,n),this.union=e,this.variant=t,this.layout=r||null}getSpan(e,t=0){if(0<=this.span)return this.span;let r=0;this.union.usesPrefixDiscriminator&&(r=this.union.discriminator.layout.span);let n=0;return this.layout&&(n=this.layout.getSpan(e,t+r)),r+n}decode(e,t=0){const r=this.makeDestinationObject();if(this!==this.union.getVariant(e,t))throw new Error("variant mismatch");let n=0;return this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span),this.layout?r[this.property]=this.layout.decode(e,t+n):this.property?r[this.property]=!0:this.union.usesPrefixDiscriminator&&(r[this.union.discriminator.property]=this.variant),r}encode(e,t,r=0){let n=0;if(this.union.usesPrefixDiscriminator&&(n=this.union.discriminator.layout.span),this.layout&&!Object.prototype.hasOwnProperty.call(e,this.property))throw new TypeError("variant lacks property "+this.property);this.union.discriminator.encode(this.variant,t,r);let i=n;if(this.layout&&(this.layout.encode(e[this.property],t,r+n),i+=this.layout.getSpan(t,r+n),0<=this.union.span&&i>this.union.span))throw new Error("encoded variant overruns containing union");return i}fromArray(e){if(this.layout)return this.layout.fromArray(e)}}function cx(e){return 0>e&&(e+=4294967296),e}Bw.VariantLayout=ax;class lx extends Lw{constructor(e,t,r){if(!(e instanceof zw||e instanceof qw))throw new TypeError("word must be a UInt or UIntBE layout");if("string"==typeof t&&void 0===r&&(r=t,t=!1),4<e.span)throw new RangeError("word cannot exceed 32 bits");super(e.span,r),this.word=e,this.msb=!!t,this.fields=[];let n=0;this._packedSetValue=function(e){return n=cx(e),this},this._packedGetValue=function(){return n}}decode(e,t=0){const r=this.makeDestinationObject(),n=this.word.decode(e,t);this._packedSetValue(n);for(const i of this.fields)void 0!==i.property&&(r[i.property]=i.decode(e));return r}encode(e,t,r=0){const n=this.word.decode(t,r);this._packedSetValue(n);for(const i of this.fields)if(void 0!==i.property){const t=e[i.property];void 0!==t&&i.encode(t)}return this.word.encode(this._packedGetValue(),t,r)}addField(e,t){const r=new ux(this,e,t);return this.fields.push(r),r}addBoolean(e){const t=new hx(this,e);return this.fields.push(t),t}fieldFor(e){if("string"!=typeof e)throw new TypeError("property must be string");for(const t of this.fields)if(t.property===e)return t}}Bw.BitStructure=lx;class ux{constructor(e,t,r){if(!(e instanceof lx))throw new TypeError("container must be a BitStructure");if(!Number.isInteger(t)||0>=t)throw new TypeError("bits must be positive integer");const n=8*e.span,i=e.fields.reduce((e,t)=>e+t.bits,0);if(t+i>n)throw new Error("bits too long for span remainder ("+(n-i)+" of "+n+" remain)");this.container=e,this.bits=t,this.valueMask=(1<<t)-1,32===t&&(this.valueMask=4294967295),this.start=i,this.container.msb&&(this.start=n-i-t),this.wordMask=cx(this.valueMask<<this.start),this.property=r}decode(e,t){return cx(this.container._packedGetValue()&this.wordMask)>>>this.start}encode(e){if("number"!=typeof e||!Number.isInteger(e)||e!==cx(e&this.valueMask))throw new TypeError(Uw("BitField.encode",this)+" value must be integer not exceeding "+this.valueMask);const t=this.container._packedGetValue(),r=cx(e<<this.start);this.container._packedSetValue(cx(t&~this.wordMask)|r)}}Bw.BitField=ux;let hx=class extends ux{constructor(e,t){super(e,1,t)}decode(e,t){return!!super.decode(e,t)}encode(e){"boolean"==typeof e&&(e=+e),super.encode(e)}};Bw.Boolean=hx;let dx=class extends Lw{constructor(e,t){if(!(e instanceof jw&&e.isCount()||Number.isInteger(e)&&0<=e))throw new TypeError("length must be positive integer or an unsigned integer ExternalLayout");let r=-1;e instanceof jw||(r=e),super(r,t),this.length=e}getSpan(e,t){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),r}decode(e,t=0){let r=this.span;return 0>r&&(r=this.length.decode(e,t)),Rw(e).slice(t,t+r)}encode(e,t,r){let n=this.length;if(this.length instanceof jw&&(n=e.length),!(e instanceof Uint8Array&&n===e.length))throw new TypeError(Uw("Blob.encode",this)+" requires (length "+n+") Uint8Array as src");if(r+n>t.length)throw new RangeError("encoding overruns Uint8Array");const i=Rw(e);return Rw(t).write(i.toString("hex"),r,n,"hex"),this.length instanceof jw&&this.length.encode(n,t,r),n}};Bw.Blob=dx;class px extends Lw{constructor(e){super(-1,e)}getSpan(e,t=0){Ow(e);let r=t;for(;r<e.length&&0!==e[r];)r+=1;return 1+r-t}decode(e,t=0){const r=this.getSpan(e,t);return Rw(e).slice(t,t+r-1).toString("utf-8")}encode(e,t,r=0){"string"!=typeof e&&(e=String(e));const n=Tw.Buffer.from(e,"utf8"),i=n.length;if(r+i>t.length)throw new RangeError("encoding overruns Buffer");const o=Rw(t);return n.copy(o,r),o[r+i]=0,i+1}}Bw.CString=px;class fx extends Lw{constructor(e,t){if("string"==typeof e&&void 0===t&&(t=e,e=void 0),void 0===e)e=-1;else if(!Number.isInteger(e))throw new TypeError("maxSpan must be an integer");super(-1,t),this.maxSpan=e}getSpan(e,t=0){return Ow(e),e.length-t}decode(e,t=0){const r=this.getSpan(e,t);if(0<=this.maxSpan&&this.maxSpan<r)throw new RangeError("text length exceeds maxSpan");return Rw(e).slice(t,t+r).toString("utf-8")}encode(e,t,r=0){"string"!=typeof e&&(e=String(e));const n=Tw.Buffer.from(e,"utf8"),i=n.length;if(0<=this.maxSpan&&this.maxSpan<i)throw new RangeError("text length exceeds maxSpan");if(r+i>t.length)throw new RangeError("encoding overruns Buffer");return n.copy(Rw(t),r),i}}Bw.UTF8=fx;class mx extends Lw{constructor(e,t){super(0,t),this.value=e}decode(e,t){return this.value}encode(e,t,r){return 0}}Bw.Constant=mx,Bw.greedy=(e,t)=>new Dw(e,t);var gx=Bw.offset=(e,t,r)=>new Fw(e,t,r),yx=Bw.u8=e=>new zw(1,e),vx=Bw.u16=e=>new zw(2,e);Bw.u24=e=>new zw(3,e);var bx=Bw.u32=e=>new zw(4,e);Bw.u40=e=>new zw(5,e),Bw.u48=e=>new zw(6,e);var wx=Bw.nu64=e=>new Kw(e);Bw.u16be=e=>new qw(2,e),Bw.u24be=e=>new qw(3,e),Bw.u32be=e=>new qw(4,e),Bw.u40be=e=>new qw(5,e),Bw.u48be=e=>new qw(6,e),Bw.nu64be=e=>new Zw(e),Bw.s8=e=>new Ww(1,e),Bw.s16=e=>new Ww(2,e),Bw.s24=e=>new Ww(3,e),Bw.s32=e=>new Ww(4,e),Bw.s40=e=>new Ww(5,e),Bw.s48=e=>new Ww(6,e);var xx=Bw.ns64=e=>new Yw(e);Bw.s16be=e=>new $w(2,e),Bw.s24be=e=>new $w(3,e),Bw.s32be=e=>new $w(4,e),Bw.s40be=e=>new $w(5,e),Bw.s48be=e=>new $w(6,e),Bw.ns64be=e=>new Jw(e),Bw.f32=e=>new Xw(e),Bw.f32be=e=>new Qw(e),Bw.f64=e=>new ex(e),Bw.f64be=e=>new tx(e);var kx=Bw.struct=(e,t,r)=>new nx(e,t,r);Bw.bits=(e,t,r)=>new lx(e,t,r);var _x=Bw.seq=(e,t,r)=>new rx(e,t,r);Bw.union=(e,t,r)=>new sx(e,t,r),Bw.unionLayoutDiscriminator=(e,t)=>new ox(e,t);var Sx=Bw.blob=(e,t)=>new dx(e,t);Bw.cstr=e=>new px(e),Bw.utf8=(e,t)=>new fx(e,t),Bw.constant=(e,t)=>new mx(e,t);function Cx(e){if(Array.isArray(e)){return"%5B"+e.map(Cx).join("%2C%20")+"%5D"}return"bigint"==typeof e?`${e}n`:encodeURIComponent(String(null!=e&&null===Object.getPrototypeOf(e)?{...e}:e))}function Ix([e,t]){return`${e}=${Cx(t)}`}function Ex(e,t={}){{let r=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(r+=` '${function(e){const t=Object.entries(e).map(Ix).join("&");return btoa(t)}(t)}'`),`${r}\``}}var Ax=class extends Error{constructor(...[e,t]){let r,n;if(t){const{cause:e,...i}=t;e&&(n={cause:e}),Object.keys(i).length>0&&(r=i)}super(Ex(e,r),n),m(this,"cause",this.cause),m(this,"context"),this.context={__code:e,...r},this.name="SolanaError"}};function Mx(e){return"fixedSize"in e&&"number"==typeof e.fixedSize}function Nx(e){return 1!==(null==e?void 0:e.endian)}function Px(e){return t={fixedSize:e.size,write(t,r,n){e.range&&function(e,t,r,n){if(n<t||n>r)throw new Ax(8078011,{codecDescription:e,max:r,min:t,value:n})}(e.name,e.range[0],e.range[1],t);const i=new ArrayBuffer(e.size);return e.set(new DataView(i),t,Nx(e.config)),r.set(new Uint8Array(i),n),n+e.size}},Object.freeze({...t,encode:e=>{const r=new Uint8Array(function(e,t){return"fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}(e,t));return t.write(e,r,0),r}});var t}function Bx(e){return t={fixedSize:e.size,read(t,r=0){!function(e,t,r=0){if(t.length-r<=0)throw new Ax(8078e3,{codecDescription:e})}(e.name,t,r),function(e,t,r,n=0){const i=r.length-n;if(i<t)throw new Ax(8078001,{bytesLength:i,codecDescription:e,expected:t})}(e.name,e.size,t,r);const n=new DataView(function(e,t,r){const n=e.byteOffset+(t??0),i=r??e.byteLength;return e.buffer.slice(n,n+i)}(t,r,e.size));return[e.get(n,Nx(e.config)),r+e.size]}},Object.freeze({...t,decode:(e,r=0)=>t.read(e,r)[0]});var t}var Tx=(e={})=>function(e,t){if(Mx(e)!==Mx(t))throw new Ax(8078004);if(Mx(e)&&Mx(t)&&e.fixedSize!==t.fixedSize)throw new Ax(8078005,{decoderFixedSize:t.fixedSize,encoderFixedSize:e.fixedSize});if(!Mx(e)&&!Mx(t)&&e.maxSize!==t.maxSize)throw new Ax(8078006,{decoderMaxSize:t.maxSize,encoderMaxSize:e.maxSize});return{...t,...e,decode:t.decode,encode:e.encode,read:t.read,write:e.write}}(((e={})=>Px({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,t,r)=>e.setBigUint64(0,BigInt(t),r),size:8}))(e),((e={})=>Bx({config:e,get:(e,t)=>e.getBigUint64(0,t),name:"u64",size:8}))(e));class Ox extends TypeError{constructor(e,t){let r;const{message:n,explanation:i,...o}=e,{path:s}=e,a=0===s.length?n:`At path: ${s.join(".")} -- ${n}`;super(i??a),null!=i&&(this.cause=a),Object.assign(this,o),this.name=this.constructor.name,this.failures=()=>r??(r=[e,...t()])}}function Rx(e){return"object"==typeof e&&null!=e}function Lx(e){return Rx(e)&&!Array.isArray(e)}function Ux(e){return"symbol"==typeof e?e.toString():"string"==typeof e?JSON.stringify(e):`${e}`}function jx(e,t,r,n){if(!0===e)return;!1===e?e={}:"string"==typeof e&&(e={message:e});const{path:i,branch:o}=t,{type:s}=r,{refinement:a,message:c=`Expected a value of type \`${s}\`${a?` with refinement \`${a}\``:""}, but received: \`${Ux(n)}\``}=e;return{value:n,type:s,refinement:a,key:i[i.length-1],path:i,branch:o,...e,message:c}}function*Dx(e,t,r,n){var i;Rx(i=e)&&"function"==typeof i[Symbol.iterator]||(e=[e]);for(const o of e){const e=jx(o,t,r,n);e&&(yield e)}}function*Fx(e,t,r={}){const{path:n=[],branch:i=[e],coerce:o=!1,mask:s=!1}=r,a={path:n,branch:i,mask:s};o&&(e=t.coercer(e,a));let c="valid";for(const l of t.validator(e,a))l.explanation=r.message,c="not_valid",yield[l,void 0];for(let[l,u,h]of t.entries(e,a)){const t=Fx(u,h,{path:void 0===l?n:[...n,l],branch:void 0===l?i:[...i,u],coerce:o,mask:s,message:r.message});for(const r of t)r[0]?(c=null!=r[0].refinement?"not_refined":"not_valid",yield[r[0],void 0]):o&&(u=r[1],void 0===l?e=u:e instanceof Map?e.set(l,u):e instanceof Set?e.add(u):Rx(e)&&(void 0!==u||l in e)&&(e[l]=u))}if("not_valid"!==c)for(const l of t.refiner(e,a))l.explanation=r.message,c="not_refined",yield[l,void 0];"valid"===c&&(yield[void 0,e])}let zx=class{constructor(e){const{type:t,schema:r,validator:n,refiner:i,coercer:o=e=>e,entries:s=function*(){}}=e;this.type=t,this.schema=r,this.entries=s,this.coercer=o,this.validator=n?(e,t)=>Dx(n(e,t),t,this,e):()=>[],this.refiner=i?(e,t)=>Dx(i(e,t),t,this,e):()=>[]}assert(e,t){return function(e,t,r){const n=$x(e,t,{message:r});if(n[0])throw n[0]}(e,this,t)}create(e,t){return qx(e,this,t)}is(e){return Wx(e,this)}mask(e,t){return function(e,t,r){const n=$x(e,t,{coerce:!0,mask:!0,message:r});if(n[0])throw n[0];return n[1]}(e,this,t)}validate(e,t={}){return $x(e,this,t)}};function qx(e,t,r){const n=$x(e,t,{coerce:!0,message:r});if(n[0])throw n[0];return n[1]}function Wx(e,t){return!$x(e,t)[0]}function $x(e,t,r={}){const n=Fx(e,t,r),i=function(e){const{done:t,value:r}=e.next();return t?void 0:r}(n);if(i[0]){return[new Ox(i[0],function*(){for(const e of n)e[0]&&(yield e[0])}),void 0]}return[void 0,i[1]]}function Gx(e,t){return new zx({type:e,schema:null,validator:t})}function Vx(e){return new zx({type:"array",schema:e,*entries(t){if(e&&Array.isArray(t))for(const[r,n]of t.entries())yield[r,n,e]},coercer:e=>Array.isArray(e)?e.slice():e,validator:e=>Array.isArray(e)||`Expected an array value, but received: ${Ux(e)}`})}function Hx(){return Gx("boolean",e=>"boolean"==typeof e)}function Kx(e){return Gx("instance",t=>t instanceof e||`Expected a \`${e.name}\` instance, but received: ${Ux(t)}`)}function Zx(e){const t=Ux(e),r=typeof e;return new zx({type:"literal",schema:"string"===r||"number"===r||"boolean"===r?e:null,validator:r=>r===e||`Expected the literal \`${t}\`, but received: ${Ux(r)}`})}function Yx(e){return new zx({...e,validator:(t,r)=>null===t||e.validator(t,r),refiner:(t,r)=>null===t||e.refiner(t,r)})}function Jx(){return Gx("number",e=>"number"==typeof e&&!isNaN(e)||`Expected a number, but received: ${Ux(e)}`)}function Xx(e){return new zx({...e,validator:(t,r)=>void 0===t||e.validator(t,r),refiner:(t,r)=>void 0===t||e.refiner(t,r)})}function Qx(e,t){return new zx({type:"record",schema:null,*entries(r){if(Rx(r))for(const n in r){const i=r[n];yield[n,n,e],yield[n,i,t]}},validator:e=>Lx(e)||`Expected an object, but received: ${Ux(e)}`,coercer:e=>Lx(e)?{...e}:e})}function ek(){return Gx("string",e=>"string"==typeof e||`Expected a string, but received: ${Ux(e)}`)}function tk(e){const t=Gx("never",()=>!1);return new zx({type:"tuple",schema:null,*entries(r){if(Array.isArray(r)){const n=Math.max(e.length,r.length);for(let i=0;i<n;i++)yield[i,r[i],e[i]||t]}},validator:e=>Array.isArray(e)||`Expected an array, but received: ${Ux(e)}`,coercer:e=>Array.isArray(e)?e.slice():e})}function rk(e){const t=Object.keys(e);return new zx({type:"type",schema:e,*entries(r){if(Rx(r))for(const n of t)yield[n,r[n],e[n]]},validator:e=>Lx(e)||`Expected an object, but received: ${Ux(e)}`,coercer:e=>Lx(e)?{...e}:e})}function nk(e){const t=e.map(e=>e.type).join(" | ");return new zx({type:"union",schema:null,coercer(t,r){for(const n of e){const[e,i]=n.validate(t,{coerce:!0,mask:r.mask});if(!e)return i}return t},validator(r,n){const i=[];for(const t of e){const[...e]=Fx(r,t,n),[o]=e;if(!o[0])return[];for(const[t]of e)t&&i.push(t)}return[`Expected the value to satisfy a union of \`${t}\`, but received: ${Ux(r)}`,...i]}})}function ik(){return Gx("unknown",()=>!0)}function ok(e,t,r){return new zx({...e,coercer:(n,i)=>Wx(n,t)?e.coercer(r(n,i),i):e.coercer(n,i)})}var sk,ak=new Uint8Array(16);function ck(){if(!sk&&!(sk="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return sk(ak)}const lk=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function uk(e){return"string"==typeof e&&lk.test(e)}for(var hk,dk,pk=[],fk=0;fk<256;++fk)pk.push((fk+256).toString(16).substr(1));function mk(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=(pk[e[t+0]]+pk[e[t+1]]+pk[e[t+2]]+pk[e[t+3]]+"-"+pk[e[t+4]]+pk[e[t+5]]+"-"+pk[e[t+6]]+pk[e[t+7]]+"-"+pk[e[t+8]]+pk[e[t+9]]+"-"+pk[e[t+10]]+pk[e[t+11]]+pk[e[t+12]]+pk[e[t+13]]+pk[e[t+14]]+pk[e[t+15]]).toLowerCase();if(!uk(r))throw TypeError("Stringified UUID is invalid");return r}var gk=0,yk=0;function vk(e){if(!uk(e))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,r[11]=t/4294967296&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r}function bk(e,t,r){function n(e,n,i,o){if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(e)),"string"==typeof n&&(n=vk(n)),16!==n.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var s=new Uint8Array(16+e.length);if(s.set(n),s.set(e,n.length),(s=r(s))[6]=15&s[6]|t,s[8]=63&s[8]|128,i){o=o||0;for(var a=0;a<16;++a)i[o+a]=s[a];return i}return mk(s)}try{n.name=e}catch(EE){}return n.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",n.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",n}function wk(e){return 14+(e+64>>>9<<4)+1}function xk(e,t){var r=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(r>>16)<<16|65535&r}function kk(e,t,r,n,i,o){return xk((s=xk(xk(t,e),xk(n,o)))<<(a=i)|s>>>32-a,r);var s,a}function _k(e,t,r,n,i,o,s){return kk(t&r|~t&n,e,t,i,o,s)}function Sk(e,t,r,n,i,o,s){return kk(t&n|r&~n,e,t,i,o,s)}function Ck(e,t,r,n,i,o,s){return kk(t^r^n,e,t,i,o,s)}function Ik(e,t,r,n,i,o,s){return kk(r^(t|~n),e,t,i,o,s)}var Ek=bk("v3",48,function(e){if("string"==typeof e){var t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(var r=0;r<t.length;++r)e[r]=t.charCodeAt(r)}return function(e){for(var t=[],r=32*e.length,n="0123456789abcdef",i=0;i<r;i+=8){var o=e[i>>5]>>>i%32&255,s=parseInt(n.charAt(o>>>4&15)+n.charAt(15&o),16);t.push(s)}return t}(function(e,t){e[t>>5]|=128<<t%32,e[wk(t)-1]=t;for(var r=1732584193,n=-271733879,i=-1732584194,o=271733878,s=0;s<e.length;s+=16){var a=r,c=n,l=i,u=o;r=_k(r,n,i,o,e[s],7,-680876936),o=_k(o,r,n,i,e[s+1],12,-389564586),i=_k(i,o,r,n,e[s+2],17,606105819),n=_k(n,i,o,r,e[s+3],22,-1044525330),r=_k(r,n,i,o,e[s+4],7,-176418897),o=_k(o,r,n,i,e[s+5],12,1200080426),i=_k(i,o,r,n,e[s+6],17,-1473231341),n=_k(n,i,o,r,e[s+7],22,-45705983),r=_k(r,n,i,o,e[s+8],7,1770035416),o=_k(o,r,n,i,e[s+9],12,-1958414417),i=_k(i,o,r,n,e[s+10],17,-42063),n=_k(n,i,o,r,e[s+11],22,-1990404162),r=_k(r,n,i,o,e[s+12],7,1804603682),o=_k(o,r,n,i,e[s+13],12,-40341101),i=_k(i,o,r,n,e[s+14],17,-1502002290),r=Sk(r,n=_k(n,i,o,r,e[s+15],22,1236535329),i,o,e[s+1],5,-165796510),o=Sk(o,r,n,i,e[s+6],9,-1069501632),i=Sk(i,o,r,n,e[s+11],14,643717713),n=Sk(n,i,o,r,e[s],20,-373897302),r=Sk(r,n,i,o,e[s+5],5,-701558691),o=Sk(o,r,n,i,e[s+10],9,38016083),i=Sk(i,o,r,n,e[s+15],14,-660478335),n=Sk(n,i,o,r,e[s+4],20,-405537848),r=Sk(r,n,i,o,e[s+9],5,568446438),o=Sk(o,r,n,i,e[s+14],9,-1019803690),i=Sk(i,o,r,n,e[s+3],14,-187363961),n=Sk(n,i,o,r,e[s+8],20,1163531501),r=Sk(r,n,i,o,e[s+13],5,-1444681467),o=Sk(o,r,n,i,e[s+2],9,-51403784),i=Sk(i,o,r,n,e[s+7],14,1735328473),r=Ck(r,n=Sk(n,i,o,r,e[s+12],20,-1926607734),i,o,e[s+5],4,-378558),o=Ck(o,r,n,i,e[s+8],11,-2022574463),i=Ck(i,o,r,n,e[s+11],16,1839030562),n=Ck(n,i,o,r,e[s+14],23,-35309556),r=Ck(r,n,i,o,e[s+1],4,-1530992060),o=Ck(o,r,n,i,e[s+4],11,1272893353),i=Ck(i,o,r,n,e[s+7],16,-155497632),n=Ck(n,i,o,r,e[s+10],23,-1094730640),r=Ck(r,n,i,o,e[s+13],4,681279174),o=Ck(o,r,n,i,e[s],11,-358537222),i=Ck(i,o,r,n,e[s+3],16,-722521979),n=Ck(n,i,o,r,e[s+6],23,76029189),r=Ck(r,n,i,o,e[s+9],4,-640364487),o=Ck(o,r,n,i,e[s+12],11,-421815835),i=Ck(i,o,r,n,e[s+15],16,530742520),r=Ik(r,n=Ck(n,i,o,r,e[s+2],23,-995338651),i,o,e[s],6,-198630844),o=Ik(o,r,n,i,e[s+7],10,1126891415),i=Ik(i,o,r,n,e[s+14],15,-1416354905),n=Ik(n,i,o,r,e[s+5],21,-57434055),r=Ik(r,n,i,o,e[s+12],6,1700485571),o=Ik(o,r,n,i,e[s+3],10,-1894986606),i=Ik(i,o,r,n,e[s+10],15,-1051523),n=Ik(n,i,o,r,e[s+1],21,-2054922799),r=Ik(r,n,i,o,e[s+8],6,1873313359),o=Ik(o,r,n,i,e[s+15],10,-30611744),i=Ik(i,o,r,n,e[s+6],15,-1560198380),n=Ik(n,i,o,r,e[s+13],21,1309151649),r=Ik(r,n,i,o,e[s+4],6,-145523070),o=Ik(o,r,n,i,e[s+11],10,-1120210379),i=Ik(i,o,r,n,e[s+2],15,718787259),n=Ik(n,i,o,r,e[s+9],21,-343485551),r=xk(r,a),n=xk(n,c),i=xk(i,l),o=xk(o,u)}return[r,n,i,o]}(function(e){if(0===e.length)return[];for(var t=8*e.length,r=new Uint32Array(wk(t)),n=0;n<t;n+=8)r[n>>5]|=(255&e[n/8])<<n%32;return r}(e),8*e.length))});function Ak(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}function Mk(e,t){return e<<t|e>>>32-t}var Nk=bk("v5",80,function(e){var t=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i<n.length;++i)e.push(n.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var o=e.length/4+2,s=Math.ceil(o/16),a=new Array(s),c=0;c<s;++c){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=e[64*c+4*u]<<24|e[64*c+4*u+1]<<16|e[64*c+4*u+2]<<8|e[64*c+4*u+3];a[c]=l}a[s-1][14]=8*(e.length-1)/Math.pow(2,32),a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=8*(e.length-1)&4294967295;for(var h=0;h<s;++h){for(var d=new Uint32Array(80),p=0;p<16;++p)d[p]=a[h][p];for(var f=16;f<80;++f)d[f]=Mk(d[f-3]^d[f-8]^d[f-14]^d[f-16],1);for(var m=r[0],g=r[1],y=r[2],v=r[3],b=r[4],w=0;w<80;++w){var x=Math.floor(w/20),k=Mk(m,5)+Ak(x,g,y,v)+b+t[x]+d[w]>>>0;b=v,v=y,y=Mk(g,30)>>>0,g=m,m=k}r[0]=r[0]+m>>>0,r[1]=r[1]+g>>>0,r[2]=r[2]+y>>>0,r[3]=r[3]+v>>>0,r[4]=r[4]+b>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]});const Pk=cv(Object.freeze(Object.defineProperty({__proto__:null,NIL:"00000000-0000-0000-0000-000000000000",parse:vk,stringify:mk,v1:function(e,t,r){var n=t&&r||0,i=t||new Array(16),o=(e=e||{}).node||hk,s=void 0!==e.clockseq?e.clockseq:dk;if(null==o||null==s){var a=e.random||(e.rng||ck)();null==o&&(o=hk=[1|a[0],a[1],a[2],a[3],a[4],a[5]]),null==s&&(s=dk=16383&(a[6]<<8|a[7]))}var c=void 0!==e.msecs?e.msecs:Date.now(),l=void 0!==e.nsecs?e.nsecs:yk+1,u=c-gk+(l-yk)/1e4;if(u<0&&void 0===e.clockseq&&(s=s+1&16383),(u<0||c>gk)&&void 0===e.nsecs&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");gk=c,yk=l,dk=s;var h=(1e4*(268435455&(c+=122192928e5))+l)%4294967296;i[n++]=h>>>24&255,i[n++]=h>>>16&255,i[n++]=h>>>8&255,i[n++]=255&h;var d=c/4294967296*1e4&268435455;i[n++]=d>>>8&255,i[n++]=255&d,i[n++]=d>>>24&15|16,i[n++]=d>>>16&255,i[n++]=s>>>8|128,i[n++]=255&s;for(var p=0;p<6;++p)i[n+p]=o[p];return t||mk(i)},v3:Ek,v4:function(e,t,r){var n=(e=e||{}).random||(e.rng||ck)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,t){r=r||0;for(var i=0;i<16;++i)t[r+i]=n[i];return t}return mk(n)},v5:Nk,validate:uk,version:function(e){if(!uk(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)}},Symbol.toStringTag,{value:"Module"}))),Bk=Pk.v4;var Tk=function(e,t,r,n){if("string"!=typeof e)throw new TypeError(e+" must be a string");const i="number"==typeof(n=n||{}).version?n.version:2;if(1!==i&&2!==i)throw new TypeError(i+" must be 1 or 2");const o={method:e};if(2===i&&(o.jsonrpc="2.0"),t){if("object"!=typeof t&&!Array.isArray(t))throw new TypeError(t+" must be an object, array or omitted");o.params=t}if(void 0===r){const e="function"==typeof n.generator?n.generator:function(){return Bk()};o.id=e(o,n)}else 2===i&&null===r?n.notificationIdNull&&(o.id=null):o.id=r;return o};const Ok=Pk.v4,Rk=Tk,Lk=function(e,t){if(!(this instanceof Lk))return new Lk(e,t);t||(t={}),this.options={reviver:void 0!==t.reviver?t.reviver:null,replacer:void 0!==t.replacer?t.replacer:null,generator:void 0!==t.generator?t.generator:function(){return Ok()},version:void 0!==t.version?t.version:2,notificationIdNull:"boolean"==typeof t.notificationIdNull&&t.notificationIdNull},this.callServer=e};var Uk=Lk;Lk.prototype.request=function(e,t,r,n){const i=this;let o=null;const s=Array.isArray(e)&&"function"==typeof t;if(1===this.options.version&&s)throw new TypeError("JSON-RPC 1.0 does not support batching");if(s||!s&&e&&"object"==typeof e&&"function"==typeof t)n=t,o=e;else{"function"==typeof r&&(n=r,r=void 0);const i="function"==typeof n;try{o=Rk(e,t,r,{generator:this.options.generator,version:this.options.version,notificationIdNull:this.options.notificationIdNull})}catch(EE){if(i)return n(EE);throw EE}if(!i)return o}let a;try{a=JSON.stringify(o,this.options.replacer)}catch(EE){return n(EE)}return this.callServer(a,function(e,t){i._parseResponse(e,t,n)}),o},Lk.prototype._parseResponse=function(e,t,r){if(e)return void r(e);if(!t)return r();let n;try{n=JSON.parse(t,this.options.reviver)}catch(i){return r(i)}if(3===r.length){if(Array.isArray(n)){const e=function(e){return void 0!==e.error},t=function(t){return!e(t)};return r(null,n.filter(e),n.filter(t))}return r(null,n.error,n.result)}r(null,n)};const jk=av(Uk);var Dk={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,s){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new i(n,o||e,s),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s},a.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},a.prototype.emit=function(e,t,n,i,o,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,l,u=this._events[a],h=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),h){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,i),!0;case 5:return u.fn.call(u.context,t,n,i,o),!0;case 6:return u.fn.call(u.context,t,n,i,o,s),!0}for(l=1,c=new Array(h-1);l<h;l++)c[l-1]=arguments[l];u.fn.apply(u.context,c)}else{var d,p=u.length;for(l=0;l<p;l++)switch(u[l].once&&this.removeListener(e,u[l].fn,void 0,!0),h){case 1:u[l].fn.call(u[l].context);break;case 2:u[l].fn.call(u[l].context,t);break;case 3:u[l].fn.call(u[l].context,t,n);break;case 4:u[l].fn.call(u[l].context,t,n,i);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];u[l].fn.apply(u[l].context,c)}}return!0},a.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,i){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return s(this,o),this;var a=this._events[o];if(a.fn)a.fn!==t||i&&!a.once||n&&a.context!==n||s(this,o);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==t||i&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[o]=1===l.length?l[0]:l:s(this,o)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(Dk);const Fk=av(Dk.exports);var zk=class extends Fk{constructor(e,t,r){super(),m(this,"socket"),this.socket=new window.WebSocket(e,r),this.socket.onopen=()=>this.emit("open"),this.socket.onmessage=e=>this.emit("message",e.data),this.socket.onerror=e=>this.emit("error",e),this.socket.onclose=e=>{this.emit("close",e.code,e.reason)}}send(e,t,r){const n=r||t;try{this.socket.send(e),n()}catch(vu){n(vu)}}close(e,t){this.socket.close(e,t)}addEventListener(e,t,r){this.socket.addEventListener(e,t,r)}};var qk=class{encode(e){return JSON.stringify(e)}decode(e){return JSON.parse(e)}},Wk=class extends Fk{constructor(e,t="ws://localhost:8080",{autoconnect:r=!0,reconnect:n=!0,reconnect_interval:i=1e3,max_reconnects:o=5,...s}={},a,c){super(),m(this,"address"),m(this,"rpc_id"),m(this,"queue"),m(this,"options"),m(this,"autoconnect"),m(this,"ready"),m(this,"reconnect"),m(this,"reconnect_timer_id"),m(this,"reconnect_interval"),m(this,"max_reconnects"),m(this,"rest_options"),m(this,"current_reconnects"),m(this,"generate_request_id"),m(this,"socket"),m(this,"webSocketFactory"),m(this,"dataPack"),this.webSocketFactory=e,this.queue={},this.rpc_id=0,this.address=t,this.autoconnect=r,this.ready=!1,this.reconnect=n,this.reconnect_timer_id=void 0,this.reconnect_interval=i,this.max_reconnects=o,this.rest_options=s,this.current_reconnects=0,this.generate_request_id=a||(()=>"number"==typeof this.rpc_id?++this.rpc_id:Number(this.rpc_id)+1),this.dataPack=c||new qk,this.autoconnect&&this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}connect(){this.socket||this._connect(this.address,{autoconnect:this.autoconnect,reconnect:this.reconnect,reconnect_interval:this.reconnect_interval,max_reconnects:this.max_reconnects,...this.rest_options})}call(e,t,r,n){return n||"object"!=typeof r||(n=r,r=null),new Promise((i,o)=>{if(!this.ready)return o(new Error("socket not ready"));const s=this.generate_request_id(e,t),a={jsonrpc:"2.0",method:e,params:t||void 0,id:s};this.socket.send(this.dataPack.encode(a),n,e=>{if(e)return o(e);this.queue[s]={promise:[i,o]},r&&(this.queue[s].timeout=setTimeout(()=>{delete this.queue[s],o(new Error("reply timeout"))},r))})})}async login(e){const t=await this.call("rpc.login",e);if(!t)throw new Error("authentication failed");return t}async listMethods(){return await this.call("__listMethods")}notify(e,t){return new Promise((r,n)=>{if(!this.ready)return n(new Error("socket not ready"));const i={jsonrpc:"2.0",method:e,params:t};this.socket.send(this.dataPack.encode(i),e=>{if(e)return n(e);r()})})}async subscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.on",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed subscribing to an event '"+e+"' with: "+t[e]);return t}async unsubscribe(e){"string"==typeof e&&(e=[e]);const t=await this.call("rpc.off",e);if("string"==typeof e&&"ok"!==t[e])throw new Error("Failed unsubscribing from an event with: "+t);return t}close(e,t){this.socket.close(e||1e3,t)}setAutoReconnect(e){this.reconnect=e}setReconnectInterval(e){this.reconnect_interval=e}setMaxReconnects(e){this.max_reconnects=e}_connect(e,t){clearTimeout(this.reconnect_timer_id),this.socket=this.webSocketFactory(e,t),this.socket.addEventListener("open",()=>{this.ready=!0,this.emit("open"),this.current_reconnects=0}),this.socket.addEventListener("message",({data:e})=>{e instanceof ArrayBuffer&&(e=lv.Buffer.from(e).toString());try{e=this.dataPack.decode(e)}catch(vu){return}if(e.notification&&this.listeners(e.notification).length){if(!Object.keys(e.params).length)return this.emit(e.notification);const t=[e.notification];if(e.params.constructor===Object)t.push(e.params);else for(let r=0;r<e.params.length;r++)t.push(e.params[r]);return Promise.resolve().then(()=>{this.emit.apply(this,t)})}if(!this.queue[e.id])return e.method?Promise.resolve().then(()=>{this.emit(e.method,null==e?void 0:e.params)}):void 0;"error"in e=="result"in e&&this.queue[e.id].promise[1](new Error('Server response malformed. Response must include either "result" or "error", but not both.')),this.queue[e.id].timeout&&clearTimeout(this.queue[e.id].timeout),e.error?this.queue[e.id].promise[1](e.error):this.queue[e.id].promise[0](e.result),delete this.queue[e.id]}),this.socket.addEventListener("error",e=>this.emit("error",e)),this.socket.addEventListener("close",({code:r,reason:n})=>{this.ready&&setTimeout(()=>this.emit("close",r,n),0),this.ready=!1,this.socket=void 0,1e3!==r&&(this.current_reconnects++,this.reconnect&&(this.max_reconnects>this.current_reconnects||0===this.max_reconnects)&&(this.reconnect_timer_id=setTimeout(()=>this._connect(e,t),this.reconnect_interval)))})}};class $k extends sg{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Dm(e);const r=ig(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),qm(i)}update(e){return Fm(this),this.iHash.update(e),this}digestInto(e){Fm(this),jm(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:s}=this;return e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=s,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gk=(e,t,r)=>new $k(e,t).update(r).digest();Gk.create=(e,t)=>new $k(e,t);
|
|
128
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
129
|
+
const Vk=(e,t)=>(e+(e>=0?t:-t)/Qk)/t;function Hk(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function Kk(e,t){const r={};for(let n of Object.keys(t))r[n]=void 0===e[n]?t[n]:e[n];return kv(r.lowS,"lowS"),kv(r.prehash,"prehash"),void 0!==r.format&&Hk(r.format),r}class Zk extends Error{constructor(e=""){super(e)}}const Yk={Err:Zk,_tlv:{encode:(e,t)=>{const{Err:r}=Yk;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=Sv(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const o=n>127?Sv(i.length/2|128):"";return Sv(e)+o+i+t},decode(e,t){const{Err:r}=Yk;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++];let o=0;if(!!(128&i)){const e=127&i;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const s=t.subarray(n,n+e);if(s.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===s[0])throw new r("tlv.decode(long): zero leftmost byte");for(const t of s)o=o<<8|t;if(n+=e,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=i;const s=t.subarray(n,n+o);if(s.length!==o)throw new r("tlv.decode: wrong value length");return{v:s,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=Yk;if(e<Jk)throw new t("integer: negative integers are not allowed");let r=Sv(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=Yk;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Iv(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=Yk,i=Nv("signature",e),{v:o,l:s}=n.decode(48,i);if(s.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=Yk,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},Jk=BigInt(0),Xk=BigInt(1),Qk=BigInt(2),e_=BigInt(3),t_=BigInt(4);function r_(e,t){const{BYTES:r}=e;let n;if("bigint"==typeof t)n=t;else{let i=Nv("private key",t);try{n=e.fromBytes(i)}catch(vu){throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function n_(e,t={}){const r=_b("weierstrass",e,t),{Fp:n,Fn:i}=r;let o=r.CURVE;const{h:s,n:a}=o;Lv(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!n.is0(o.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=o_(n,i);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const h=t.toBytes||function(e,t,r){const{x:i,y:o}=t.toAffine(),s=n.toBytes(i);if(kv(r,"isCompressed"),r){u();return og(i_(!n.isOdd(o)),s)}return og(Uint8Array.of(4),s,n.toBytes(o))},d=t.fromBytes||function(e){_v(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:r}=l,i=e.length,o=e[0],s=e.subarray(1);if(i!==t||2!==o&&3!==o){if(i===r&&4===o){const e=n.BYTES,t=n.fromBytes(s.subarray(0,e)),r=n.fromBytes(s.subarray(e,2*e));if(!f(t,r))throw new Error("bad point: is not on curve");return{x:t,y:r}}throw new Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${r}`)}{const e=n.fromBytes(s);if(!n.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=p(e);let r;try{r=n.sqrt(t)}catch(a){const e=a instanceof Error?": "+a.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}u();return!(1&~o)!==n.isOdd(r)&&(r=n.neg(r)),{x:e,y:r}}};function p(e){const t=n.sqr(e),r=n.mul(t,e);return n.add(n.add(r,n.mul(e,o.a)),o.b)}function f(e,t){const r=n.sqr(t),i=p(e);return n.eql(r,i)}if(!f(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const m=n.mul(n.pow(o.a,e_),t_),g=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(m,g)))throw new Error("bad curve params: a or b");function y(e,t,r=!1){if(!n.isValid(t)||r&&n.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function v(e){if(!(e instanceof _))throw new Error("ProjectivePoint expected")}function b(e){if(!c||!c.basises)throw new Error("no endo");return function(e,t,r){const[[n,i],[o,s]]=t,a=Vk(s*e,r),c=Vk(-i*e,r);let l=e-a*n-c*o,u=-a*i-c*s;const h=l<Jk,d=u<Jk;h&&(l=-l),d&&(u=-u);const p=Rv(Math.ceil(Ov(r)/2))+Xk;if(l<Jk||l>=p||u<Jk||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}(e,c.basises,i.ORDER)}const w=Uv((e,t)=>{const{X:r,Y:i,Z:o}=e;if(n.eql(o,n.ONE))return{x:r,y:i};const s=e.is0();null==t&&(t=s?n.ONE:n.inv(o));const a=n.mul(r,t),c=n.mul(i,t),l=n.mul(o,t);if(s)return{x:n.ZERO,y:n.ZERO};if(!n.eql(l,n.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),x=Uv(e=>{if(e.is0()){if(t.allowInfinityPoint&&!n.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:r,y:i}=e.toAffine();if(!n.isValid(r)||!n.isValid(i))throw new Error("bad point: x or y not field elements");if(!f(r,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(e,t,r,i,o){return r=new _(n.mul(r.X,e),r.Y,r.Z),t=hb(i,t),r=hb(o,r),t.add(r)}class _{constructor(e,t,r){this.X=y("x",e),this.Y=y("y",t,!0),this.Z=y("z",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof _)throw new Error("projective point not allowed");return n.is0(t)&&n.is0(r)?_.ZERO:new _(t,r,n.ONE)}static fromBytes(e){const t=_.fromAffine(d(_v(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return _.fromBytes(Nv("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return C.createCache(this,e),t||this.multiply(e_),this}assertValidity(){x(this)}hasEvenY(){const{y:e}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(e)}equals(e){v(e);const{X:t,Y:r,Z:i}=this,{X:o,Y:s,Z:a}=e,c=n.eql(n.mul(t,a),n.mul(o,i)),l=n.eql(n.mul(r,a),n.mul(s,i));return c&&l}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){const{a:e,b:t}=o,r=n.mul(t,e_),{X:i,Y:s,Z:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,h=n.mul(i,i),d=n.mul(s,s),p=n.mul(a,a),f=n.mul(i,s);return f=n.add(f,f),u=n.mul(i,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,p),l=n.add(c,l),c=n.sub(d,l),l=n.add(d,l),l=n.mul(c,l),c=n.mul(f,c),u=n.mul(r,u),p=n.mul(e,p),f=n.sub(h,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(h,h),h=n.add(u,h),h=n.add(h,p),h=n.mul(h,f),l=n.add(l,h),p=n.mul(s,a),p=n.add(p,p),h=n.mul(p,f),c=n.sub(c,h),u=n.mul(p,d),u=n.add(u,u),u=n.add(u,u),new _(c,l,u)}add(e){v(e);const{X:t,Y:r,Z:i}=this,{X:s,Y:a,Z:c}=e;let l=n.ZERO,u=n.ZERO,h=n.ZERO;const d=o.a,p=n.mul(o.b,e_);let f=n.mul(t,s),m=n.mul(r,a),g=n.mul(i,c),y=n.add(t,r),b=n.add(s,a);y=n.mul(y,b),b=n.add(f,m),y=n.sub(y,b),b=n.add(t,i);let w=n.add(s,c);return b=n.mul(b,w),w=n.add(f,g),b=n.sub(b,w),w=n.add(r,i),l=n.add(a,c),w=n.mul(w,l),l=n.add(m,g),w=n.sub(w,l),h=n.mul(d,b),l=n.mul(p,g),h=n.add(l,h),l=n.sub(m,h),h=n.add(m,h),u=n.mul(l,h),m=n.add(f,f),m=n.add(m,f),g=n.mul(d,g),b=n.mul(p,b),m=n.add(m,g),g=n.sub(f,g),g=n.mul(d,g),b=n.add(b,g),f=n.mul(m,b),u=n.add(u,f),f=n.mul(w,b),l=n.mul(y,l),l=n.sub(l,f),f=n.mul(y,m),h=n.mul(w,h),h=n.add(h,f),new _(l,u,h)}subtract(e){return this.add(e.negate())}is0(){return this.equals(_.ZERO)}multiply(e){const{endo:r}=t;if(!i.isValidNot0(e))throw new Error("invalid scalar: out of range");let n,o;const s=e=>C.cached(this,e,e=>db(_,e));if(r){const{k1neg:t,k1:i,k2neg:a,k2:c}=b(e),{p:l,f:u}=s(i),{p:h,f:d}=s(c);o=u.add(d),n=k(r.beta,l,h,t,a)}else{const{p:t,f:r}=s(e);n=t,o=r}return db(_,[n,o])[0]}multiplyUnsafe(e){const{endo:r}=t,n=this;if(!i.isValid(e))throw new Error("invalid scalar: out of range");if(e===Jk||n.is0())return _.ZERO;if(e===Xk)return n;if(C.hasCache(this))return this.multiply(e);if(r){const{k1neg:t,k1:i,k2neg:o,k2:s}=b(e),{p1:a,p2:c}=function(e,t,r,n){let i=t,o=e.ZERO,s=e.ZERO;for(;r>lb||n>lb;)r&ub&&(o=o.add(i)),n&ub&&(s=s.add(i)),i=i.double(),r>>=ub,n>>=ub;return{p1:o,p2:s}}(_,n,i,s);return k(r.beta,a,c,t,o)}return C.unsafe(n,e)}multiplyAndAddUnsafe(e,t,r){const n=this.multiplyUnsafe(t).add(e.multiplyUnsafe(r));return n.is0()?void 0:n}toAffine(e){return w(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return s===Xk||(e?e(_,this):C.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return s===Xk?this:e?e(_,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(e=!0){return kv(e,"isCompressed"),this.assertValidity(),h(_,this,e)}toHex(e=!0){return Zm(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return db(_,e)}static msm(e,t){return xb(_,i,e,t)}static fromPrivateKey(e){return _.BASE.multiply(r_(i,e))}}_.BASE=new _(o.Gx,o.Gy,n.ONE),_.ZERO=new _(n.ZERO,n.ONE,n.ZERO),_.Fp=n,_.Fn=i;const S=i.BITS,C=new wb(_,t.endo?Math.ceil(S/2):S);return _.BASE.precompute(8),_}function i_(e){return Uint8Array.of(e?2:3)}function o_(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function s_(e,t={}){const{Fn:r}=e,n=t.randomBytes||cg,i=Object.assign(o_(e.Fp,r),{seed:cb(r.ORDER)});function o(e){try{return!!r_(r,e)}catch(vu){return!1}}function s(e=n(i.seed)){return function(e,t,r=!1){const n=e.length,i=ab(t),o=cb(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);const s=Kv(r?Ev(e):Iv(e),t-Dv)+Dv;return r?Mv(s,i):Av(s,i)}(_v(e,i.seed,"seed"),r.ORDER)}function a(t,n=!0){return e.BASE.multiply(r_(r,t)).toBytes(n)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:n,publicKey:o,publicKeyUncompressed:s}=i;if(r.allowedLengths||n===o)return;const a=Nv("key",t).length;return a===o||a===s}const l={isValidSecretKey:o,isValidPublicKey:function(t,r){const{publicKey:n,publicKeyUncompressed:o}=i;try{const i=t.length;return(!0!==r||i===n)&&((!1!==r||i===o)&&!!e.fromBytes(t))}catch(vu){return!1}},randomSecretKey:s,isValidPrivateKey:o,randomPrivateKey:s,normPrivateKeyToScalar:e=>r_(r,e),precompute:(t=8,r=e.BASE)=>r.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,n,i=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(n))throw new Error("second arg must be public key");const o=r_(r,t);return e.fromHex(n).multiply(o).toBytes(i)},keygen:function(e){const t=s(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:i})}function a_(e,t,r={}){Dm(t),Lv(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||cg,i=r.hmac||((e,...r)=>Gk(t,e,og(...r))),{Fp:o,Fn:s}=e,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p}=s_(e,r),f={prehash:!1,lowS:"boolean"==typeof r.lowS&&r.lowS,format:void 0,extraEntropy:!1},m="compact";function g(e){return e>a>>Xk}function y(e,t){if(!s.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class v{constructor(e,t,r){this.r=y("r",e),this.s=y("s",t),null!=r&&(this.recovery=r),Object.freeze(this)}static fromBytes(e,t=m){let r;if(function(e,t){Hk(t);const r=p.signature;_v(e,"compact"===t?r:"recovered"===t?r+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:r}=Yk.toSig(_v(e));return new v(t,r)}"recovered"===t&&(r=e[0],t="compact",e=e.subarray(1));const n=s.BYTES,i=e.subarray(0,n),o=e.subarray(n,2*n);return new v(s.fromBytes(i),s.fromBytes(o),r)}static fromHex(e,t){return this.fromBytes(ng(e),t)}addRecoveryBit(e){return new v(this.r,this.s,e)}recoverPublicKey(t){const r=o.ORDER,{r:n,s:i,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*Qk<r&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?n+a:n;if(!o.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=o.toBytes(l),h=e.fromBytes(og(i_(!(1&c)),u)),d=s.inv(l),p=w(Nv("msgHash",t)),f=s.create(-p*d),m=s.create(i*d),g=e.BASE.multiplyUnsafe(f).add(h.multiplyUnsafe(m));if(g.is0())throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=m){if(Hk(e),"der"===e)return ng(Yk.hexFromSig(this));const t=s.toBytes(this.r),r=s.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return og(Uint8Array.of(this.recovery),t,r)}return og(t,r)}toHex(e){return Zm(this.toBytes(e))}assertValidity(){}static fromCompact(e){return v.fromBytes(Nv("sig",e),"compact")}static fromDER(e){return v.fromBytes(Nv("sig",e),"der")}normalizeS(){return this.hasHighS()?new v(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Zm(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Zm(this.toBytes("compact"))}}const b=r.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=Iv(e),r=8*e.length-c;return r>0?t>>BigInt(r):t},w=r.bits2int_modN||function(e){return s.create(b(e))},x=Rv(c);function k(e){return Tv("num < 2^"+c,e,Jk,x),s.toBytes(e)}function _(e,r){return _v(e,void 0,"message"),r?_v(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:d,lengths:p,Point:e,sign:function(r,o,a={}){r=Nv("message",r);const{seed:c,k2sig:l}=function(t,r,i){if(["recovered","canonical"].some(e=>e in i))throw new Error("sign() legacy options not supported");const{lowS:o,prehash:a,extraEntropy:c}=Kk(i,f);t=_(t,a);const l=w(t),u=r_(s,r),h=[k(u),k(l)];if(null!=c&&!1!==c){const e=!0===c?n(p.secretKey):c;h.push(Nv("extraEntropy",e))}const d=og(...h),m=l;return{seed:d,k2sig:function(t){const r=b(t);if(!s.isValidNot0(r))return;const n=s.inv(r),i=e.BASE.multiply(r).toAffine(),a=s.create(i.x);if(a===Jk)return;const c=s.create(n*s.create(m+a*u));if(c===Jk)return;let l=(i.x===a?0:2)|Number(i.y&Xk),h=c;return o&&g(c)&&(h=s.neg(c),l^=1),new v(a,h,l)}}}(r,o,a);return function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");const n=e=>new Uint8Array(e),i=e=>Uint8Array.of(e);let o=n(e),s=n(e),a=0;const c=()=>{o.fill(1),s.fill(0),a=0},l=(...e)=>r(s,o,...e),u=(e=n(0))=>{s=l(i(0),e),o=l(),0!==e.length&&(s=l(i(1),e),o=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e<t;){o=l();const t=o.slice();r.push(t),e+=o.length}return og(...r)};return(e,t)=>{let r;for(c(),u(e);!(r=t(h()));)u();return c(),r}}(t.outputLen,s.BYTES,i)(c,l)},verify:function(t,r,n,i={}){const{lowS:o,prehash:a,format:c}=Kk(i,f);if(n=Nv("publicKey",n),r=_(Nv("message",r),a),"strict"in i)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const r="string"==typeof e||Lm(e),n=!r&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!r&&!n)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(n)t=new v(e.r,e.s);else if(r){try{t=v.fromBytes(Nv("sig",e),"der")}catch(i){if(!(i instanceof Yk.Err))throw i}if(!t)try{t=v.fromBytes(Nv("sig",e),"compact")}catch(vu){return!1}}return t||!1}(t):v.fromBytes(Nv("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(n);if(o&&l.hasHighS())return!1;const{r:i,s:a}=l,c=w(r),u=s.inv(a),h=s.create(c*u),d=s.create(i*u),p=e.BASE.multiplyUnsafe(h).add(t.multiplyUnsafe(d));if(p.is0())return!1;return s.create(p.x)===i}catch(u){return!1}},recoverPublicKey:function(e,t,r={}){const{prehash:n}=Kk(r,f);return t=_(t,n),v.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:v,hash:t})}function c_(e){const{CURVE:t,curveOpts:r}=function(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp;let n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:r,Fn:sb(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}(e),n={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,hash:e.hash,ecdsaOpts:n}}function l_(e){const{CURVE:t,curveOpts:r,hash:n,ecdsaOpts:i}=c_(e);return function(e,t){const r=t.Point;return Object.assign({},t,{ProjectivePoint:r,CURVE:Object.assign({},e,ob(r.Fn.ORDER,r.Fn.BITS))})}(e,a_(n_(t,r),n,i))}
|
|
130
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
131
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
132
|
+
const u_={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},h_={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},d_=BigInt(2);const p_=sb(u_.p,{sqrt:function(e){const t=u_.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=Zv(u,r,t)*u%t,d=Zv(h,r,t)*u%t,p=Zv(d,d_,t)*l%t,f=Zv(p,i,t)*p%t,m=Zv(f,o,t)*f%t,g=Zv(m,a,t)*m%t,y=Zv(g,c,t)*g%t,v=Zv(y,a,t)*m%t,b=Zv(v,r,t)*u%t,w=Zv(b,s,t)*f%t,x=Zv(w,n,t)*l%t,k=Zv(x,d_,t);if(!p_.eql(p_.sqr(k),e))throw new Error("Cannot find square root");return k}}),f_=function(e,t){const r=t=>l_({...e,hash:t});return{...r(t),create:r}}({...u_,Fp:p_,lowS:!0,endo:h_},Fg);function m_(e){try{return zb.ExtendedPoint.fromHex(e),!0}catch{return!1}}zb.utils.randomPrivateKey,zb.getPublicKey;const g_=zb.verify,y_=e=>lv.Buffer.isBuffer(e)?e:e instanceof Uint8Array?lv.Buffer.from(e.buffer,e.byteOffset,e.byteLength):lv.Buffer.from(e);class v_{constructor(e){Object.assign(this,e)}encode(){return lv.Buffer.from(Aw(b_,this))}static decode(e){return Pw(b_,this,e)}static decodeUnchecked(e){return mw(b_,this,e)}}const b_=new Map;var w_;const x_=32;let k_=1;class __ extends v_{constructor(e){if(super({}),this._bn=void 0,function(e){return void 0!==e._bn}(e))this._bn=e._bn;else{if("string"==typeof e){const t=Yb.decode(e);if(t.length!=x_)throw new Error("Invalid public key input");this._bn=new Gb(t)}else this._bn=new Gb(e);if(this._bn.byteLength()>x_)throw new Error("Invalid public key input")}}static unique(){const e=new __(k_);return k_+=1,new __(e.toBuffer())}equals(e){return this._bn.eq(e._bn)}toBase58(){return Yb.encode(this.toBytes())}toJSON(){return this.toBase58()}toBytes(){const e=this.toBuffer();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}toBuffer(){const e=this._bn.toArrayLike(lv.Buffer);if(e.length===x_)return e;const t=lv.Buffer.alloc(32);return e.copy(t,32-e.length),t}get[Symbol.toStringTag](){return`PublicKey(${this.toString()})`}toString(){return this.toBase58()}static async createWithSeed(e,t,r){const n=lv.Buffer.concat([e.toBuffer(),lv.Buffer.from(t),r.toBuffer()]),i=qg(n);return new __(i)}static createProgramAddressSync(e,t){let r=lv.Buffer.alloc(0);e.forEach(function(e){if(e.length>32)throw new TypeError("Max seed length exceeded");r=lv.Buffer.concat([r,y_(e)])}),r=lv.Buffer.concat([r,t.toBuffer(),lv.Buffer.from("ProgramDerivedAddress")]);const n=qg(r);if(m_(n))throw new Error("Invalid seeds, address must fall off the curve");return new __(n)}static async createProgramAddress(e,t){return this.createProgramAddressSync(e,t)}static findProgramAddressSync(e,t){let r,n=255;for(;0!=n;){try{const i=e.concat(lv.Buffer.from([n]));r=this.createProgramAddressSync(i,t)}catch(EE){if(EE instanceof TypeError)throw EE;n--;continue}return[r,n]}throw new Error("Unable to find a viable program address nonce")}static async findProgramAddress(e,t){return this.findProgramAddressSync(e,t)}static isOnCurve(e){return m_(new __(e).toBytes())}}w_=__,__.default=new w_("11111111111111111111111111111111"),b_.set(__,{kind:"struct",fields:[["_bn","u256"]]}),new __("BPFLoader1111111111111111111111111111111111");const S_=1232;class C_ extends Error{constructor(e){super(`Signature ${e} has expired: block height exceeded.`),this.signature=void 0,this.signature=e}}Object.defineProperty(C_.prototype,"name",{value:"TransactionExpiredBlockheightExceededError"});class I_ extends Error{constructor(e,t){super(`Transaction was not confirmed in ${t.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${e} using the Solana Explorer or CLI tools.`),this.signature=void 0,this.signature=e}}Object.defineProperty(I_.prototype,"name",{value:"TransactionExpiredTimeoutError"});class E_ extends Error{constructor(e){super(`Signature ${e} has expired: the nonce is no longer valid.`),this.signature=void 0,this.signature=e}}Object.defineProperty(E_.prototype,"name",{value:"TransactionExpiredNonceInvalidError"});class A_{constructor(e,t){this.staticAccountKeys=void 0,this.accountKeysFromLookups=void 0,this.staticAccountKeys=e,this.accountKeysFromLookups=t}keySegments(){const e=[this.staticAccountKeys];return this.accountKeysFromLookups&&(e.push(this.accountKeysFromLookups.writable),e.push(this.accountKeysFromLookups.readonly)),e}get(e){for(const t of this.keySegments()){if(e<t.length)return t[e];e-=t.length}}get length(){return this.keySegments().flat().length}compileInstructions(e){if(this.length>256)throw new Error("Account index overflow encountered during compilation");const t=new Map;this.keySegments().flat().forEach((e,r)=>{t.set(e.toBase58(),r)});const r=e=>{const r=t.get(e.toBase58());if(void 0===r)throw new Error("Encountered an unknown instruction account key during compilation");return r};return e.map(e=>({programIdIndex:r(e.programId),accountKeyIndexes:e.keys.map(e=>r(e.pubkey)),data:e.data}))}}const M_=(e="publicKey")=>Sx(32,e),N_=(e="string")=>{const t=kx([bx("length"),bx("lengthPadding"),Sx(gx(bx(),-8),"chars")],e),r=t.decode.bind(t),n=t.encode.bind(t),i=t;return i.decode=(e,t)=>r(e,t).chars.toString(),i.encode=(e,t,r)=>{const i={chars:lv.Buffer.from(e,"utf8")};return n(i,t,r)},i.alloc=e=>bx().span+bx().span+lv.Buffer.from(e,"utf8").length,i};function P_(e,t){const r=e=>{if(e.span>=0)return e.span;if("function"==typeof e.alloc)return e.alloc(t[e.property]);if("count"in e&&"elementLayout"in e){const n=t[e.property];if(Array.isArray(n))return n.length*r(e.elementLayout)}else if("fields"in e)return P_({layout:e},t[e.property]);return 0};let n=0;return e.layout.fields.forEach(e=>{n+=r(e)}),n}function B_(e){let t=0,r=0;for(;;){let n=e.shift();if(t|=(127&n)<<7*r,r+=1,!(128&n))break}return t}function T_(e,t){let r=t;for(;;){let t=127&r;if(r>>=7,0==r){e.push(t);break}t|=128,e.push(t)}}function O_(e,t){if(!e)throw new Error(t||"Assertion failed")}class R_{constructor(e,t){this.payer=void 0,this.keyMetaMap=void 0,this.payer=e,this.keyMetaMap=t}static compile(e,t){const r=new Map,n=e=>{const t=e.toBase58();let n=r.get(t);return void 0===n&&(n={isSigner:!1,isWritable:!1,isInvoked:!1},r.set(t,n)),n},i=n(t);i.isSigner=!0,i.isWritable=!0;for(const o of e){n(o.programId).isInvoked=!0;for(const e of o.keys){const t=n(e.pubkey);t.isSigner||(t.isSigner=e.isSigner),t.isWritable||(t.isWritable=e.isWritable)}}return new R_(t,r)}getMessageComponents(){const e=[...this.keyMetaMap.entries()];O_(e.length<=256,"Max static account keys length exceeded");const t=e.filter(([,e])=>e.isSigner&&e.isWritable),r=e.filter(([,e])=>e.isSigner&&!e.isWritable),n=e.filter(([,e])=>!e.isSigner&&e.isWritable),i=e.filter(([,e])=>!e.isSigner&&!e.isWritable),o={numRequiredSignatures:t.length+r.length,numReadonlySignedAccounts:r.length,numReadonlyUnsignedAccounts:i.length};{O_(t.length>0,"Expected at least one writable signer key");const[e]=t[0];O_(e===this.payer.toBase58(),"Expected first writable signer key to be the fee payer")}return[o,[...t.map(([e])=>new __(e)),...r.map(([e])=>new __(e)),...n.map(([e])=>new __(e)),...i.map(([e])=>new __(e))]]}extractTableLookup(e){const[t,r]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&e.isWritable),[n,i]=this.drainKeysFoundInLookupTable(e.state.addresses,e=>!e.isSigner&&!e.isInvoked&&!e.isWritable);if(0!==t.length||0!==n.length)return[{accountKey:e.key,writableIndexes:t,readonlyIndexes:n},{writable:r,readonly:i}]}drainKeysFoundInLookupTable(e,t){const r=new Array,n=new Array;for(const[i,o]of this.keyMetaMap.entries())if(t(o)){const t=new __(i),o=e.findIndex(e=>e.equals(t));o>=0&&(O_(o<256,"Max lookup table index exceeded"),r.push(o),n.push(t),this.keyMetaMap.delete(i))}return[r,n]}}const L_="Reached end of buffer unexpectedly";function U_(e){if(0===e.length)throw new Error(L_);return e.shift()}function j_(e,...t){const[r]=t;if(2===t.length?r+(t[1]??0)>e.length:r>=e.length)throw new Error(L_);return e.splice(...t)}class D_{constructor(e){this.header=void 0,this.accountKeys=void 0,this.recentBlockhash=void 0,this.instructions=void 0,this.indexToProgramIds=new Map,this.header=e.header,this.accountKeys=e.accountKeys.map(e=>new __(e)),this.recentBlockhash=e.recentBlockhash,this.instructions=e.instructions,this.instructions.forEach(e=>this.indexToProgramIds.set(e.programIdIndex,this.accountKeys[e.programIdIndex]))}get version(){return"legacy"}get staticAccountKeys(){return this.accountKeys}get compiledInstructions(){return this.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Yb.decode(e.data)}))}get addressTableLookups(){return[]}getAccountKeys(){return new A_(this.staticAccountKeys)}static compile(e){const t=R_.compile(e.instructions,e.payerKey),[r,n]=t.getMessageComponents(),i=new A_(n).compileInstructions(e.instructions).map(e=>({programIdIndex:e.programIdIndex,accounts:e.accountKeyIndexes,data:Yb.encode(e.data)}));return new D_({header:r,accountKeys:n,recentBlockhash:e.recentBlockhash,instructions:i})}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures;if(e>=this.header.numRequiredSignatures){return e-t<this.accountKeys.length-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}isProgramId(e){return this.indexToProgramIds.has(e)}programIds(){return[...this.indexToProgramIds.values()]}nonProgramIds(){return this.accountKeys.filter((e,t)=>!this.isProgramId(t))}serialize(){const e=this.accountKeys.length;let t=[];T_(t,e);const r=this.instructions.map(e=>{const{accounts:t,programIdIndex:r}=e,n=Array.from(Yb.decode(e.data));let i=[];T_(i,t.length);let o=[];return T_(o,n.length),{programIdIndex:r,keyIndicesCount:lv.Buffer.from(i),keyIndices:t,dataLength:lv.Buffer.from(o),data:n}});let n=[];T_(n,r.length);let i=lv.Buffer.alloc(S_);lv.Buffer.from(n).copy(i);let o=n.length;r.forEach(e=>{const t=kx([yx("programIdIndex"),Sx(e.keyIndicesCount.length,"keyIndicesCount"),_x(yx("keyIndex"),e.keyIndices.length,"keyIndices"),Sx(e.dataLength.length,"dataLength"),_x(yx("userdatum"),e.data.length,"data")]).encode(e,i,o);o+=t}),i=i.slice(0,o);const s=kx([Sx(1,"numRequiredSignatures"),Sx(1,"numReadonlySignedAccounts"),Sx(1,"numReadonlyUnsignedAccounts"),Sx(t.length,"keyCount"),_x(M_("key"),e,"keys"),M_("recentBlockhash")]),a={numRequiredSignatures:lv.Buffer.from([this.header.numRequiredSignatures]),numReadonlySignedAccounts:lv.Buffer.from([this.header.numReadonlySignedAccounts]),numReadonlyUnsignedAccounts:lv.Buffer.from([this.header.numReadonlyUnsignedAccounts]),keyCount:lv.Buffer.from(t),keys:this.accountKeys.map(e=>y_(e.toBytes())),recentBlockhash:Yb.decode(this.recentBlockhash)};let c=lv.Buffer.alloc(2048);const l=s.encode(a,c);return i.copy(c,l),c.slice(0,l+i.length)}static from(e){let t=[...e];const r=U_(t);if(r!==(127&r))throw new Error("Versioned messages must be deserialized with VersionedMessage.deserialize()");const n=U_(t),i=U_(t),o=B_(t);let s=[];for(let h=0;h<o;h++){const e=j_(t,0,x_);s.push(new __(lv.Buffer.from(e)))}const a=j_(t,0,x_),c=B_(t);let l=[];for(let h=0;h<c;h++){const e=U_(t),r=j_(t,0,B_(t)),n=j_(t,0,B_(t)),i=Yb.encode(lv.Buffer.from(n));l.push({programIdIndex:e,accounts:r,data:i})}const u={header:{numRequiredSignatures:r,numReadonlySignedAccounts:n,numReadonlyUnsignedAccounts:i},recentBlockhash:Yb.encode(lv.Buffer.from(a)),accountKeys:s,instructions:l};return new D_(u)}}class F_{constructor(e){this.header=void 0,this.staticAccountKeys=void 0,this.recentBlockhash=void 0,this.compiledInstructions=void 0,this.addressTableLookups=void 0,this.header=e.header,this.staticAccountKeys=e.staticAccountKeys,this.recentBlockhash=e.recentBlockhash,this.compiledInstructions=e.compiledInstructions,this.addressTableLookups=e.addressTableLookups}get version(){return 0}get numAccountKeysFromLookups(){let e=0;for(const t of this.addressTableLookups)e+=t.readonlyIndexes.length+t.writableIndexes.length;return e}getAccountKeys(e){let t;if(e&&"accountKeysFromLookups"in e&&e.accountKeysFromLookups){if(this.numAccountKeysFromLookups!=e.accountKeysFromLookups.writable.length+e.accountKeysFromLookups.readonly.length)throw new Error("Failed to get account keys because of a mismatch in the number of account keys from lookups");t=e.accountKeysFromLookups}else if(e&&"addressLookupTableAccounts"in e&&e.addressLookupTableAccounts)t=this.resolveAddressTableLookups(e.addressLookupTableAccounts);else if(this.addressTableLookups.length>0)throw new Error("Failed to get account keys because address table lookups were not resolved");return new A_(this.staticAccountKeys,t)}isAccountSigner(e){return e<this.header.numRequiredSignatures}isAccountWritable(e){const t=this.header.numRequiredSignatures,r=this.staticAccountKeys.length;if(e>=r){return e-r<this.addressTableLookups.reduce((e,t)=>e+t.writableIndexes.length,0)}if(e>=this.header.numRequiredSignatures){return e-t<r-t-this.header.numReadonlyUnsignedAccounts}return e<t-this.header.numReadonlySignedAccounts}resolveAddressTableLookups(e){const t={writable:[],readonly:[]};for(const r of this.addressTableLookups){const n=e.find(e=>e.key.equals(r.accountKey));if(!n)throw new Error(`Failed to find address lookup table account for table key ${r.accountKey.toBase58()}`);for(const e of r.writableIndexes){if(!(e<n.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${r.accountKey.toBase58()}`);t.writable.push(n.state.addresses[e])}for(const e of r.readonlyIndexes){if(!(e<n.state.addresses.length))throw new Error(`Failed to find address for index ${e} in address lookup table ${r.accountKey.toBase58()}`);t.readonly.push(n.state.addresses[e])}}return t}static compile(e){const t=R_.compile(e.instructions,e.payerKey),r=new Array,n={writable:new Array,readonly:new Array},i=e.addressLookupTableAccounts||[];for(const c of i){const e=t.extractTableLookup(c);if(void 0!==e){const[t,{writable:i,readonly:o}]=e;r.push(t),n.writable.push(...i),n.readonly.push(...o)}}const[o,s]=t.getMessageComponents(),a=new A_(s,n).compileInstructions(e.instructions);return new F_({header:o,staticAccountKeys:s,recentBlockhash:e.recentBlockhash,compiledInstructions:a,addressTableLookups:r})}serialize(){const e=Array();T_(e,this.staticAccountKeys.length);const t=this.serializeInstructions(),r=Array();T_(r,this.compiledInstructions.length);const n=this.serializeAddressTableLookups(),i=Array();T_(i,this.addressTableLookups.length);const o=kx([yx("prefix"),kx([yx("numRequiredSignatures"),yx("numReadonlySignedAccounts"),yx("numReadonlyUnsignedAccounts")],"header"),Sx(e.length,"staticAccountKeysLength"),_x(M_(),this.staticAccountKeys.length,"staticAccountKeys"),M_("recentBlockhash"),Sx(r.length,"instructionsLength"),Sx(t.length,"serializedInstructions"),Sx(i.length,"addressTableLookupsLength"),Sx(n.length,"serializedAddressTableLookups")]),s=new Uint8Array(S_),a=o.encode({prefix:128,header:this.header,staticAccountKeysLength:new Uint8Array(e),staticAccountKeys:this.staticAccountKeys.map(e=>e.toBytes()),recentBlockhash:Yb.decode(this.recentBlockhash),instructionsLength:new Uint8Array(r),serializedInstructions:t,addressTableLookupsLength:new Uint8Array(i),serializedAddressTableLookups:n},s);return s.slice(0,a)}serializeInstructions(){let e=0;const t=new Uint8Array(S_);for(const r of this.compiledInstructions){const n=Array();T_(n,r.accountKeyIndexes.length);const i=Array();T_(i,r.data.length);e+=kx([yx("programIdIndex"),Sx(n.length,"encodedAccountKeyIndexesLength"),_x(yx(),r.accountKeyIndexes.length,"accountKeyIndexes"),Sx(i.length,"encodedDataLength"),Sx(r.data.length,"data")]).encode({programIdIndex:r.programIdIndex,encodedAccountKeyIndexesLength:new Uint8Array(n),accountKeyIndexes:r.accountKeyIndexes,encodedDataLength:new Uint8Array(i),data:r.data},t,e)}return t.slice(0,e)}serializeAddressTableLookups(){let e=0;const t=new Uint8Array(S_);for(const r of this.addressTableLookups){const n=Array();T_(n,r.writableIndexes.length);const i=Array();T_(i,r.readonlyIndexes.length);e+=kx([M_("accountKey"),Sx(n.length,"encodedWritableIndexesLength"),_x(yx(),r.writableIndexes.length,"writableIndexes"),Sx(i.length,"encodedReadonlyIndexesLength"),_x(yx(),r.readonlyIndexes.length,"readonlyIndexes")]).encode({accountKey:r.accountKey.toBytes(),encodedWritableIndexesLength:new Uint8Array(n),writableIndexes:r.writableIndexes,encodedReadonlyIndexesLength:new Uint8Array(i),readonlyIndexes:r.readonlyIndexes},t,e)}return t.slice(0,e)}static deserialize(e){let t=[...e];const r=U_(t),n=127&r;O_(r!==n,"Expected versioned message but received legacy message");O_(0===n,`Expected versioned message with version 0 but found version ${n}`);const i={numRequiredSignatures:U_(t),numReadonlySignedAccounts:U_(t),numReadonlyUnsignedAccounts:U_(t)},o=[],s=B_(t);for(let d=0;d<s;d++)o.push(new __(j_(t,0,x_)));const a=Yb.encode(j_(t,0,x_)),c=B_(t),l=[];for(let d=0;d<c;d++){const e=U_(t),r=j_(t,0,B_(t)),n=B_(t),i=new Uint8Array(j_(t,0,n));l.push({programIdIndex:e,accountKeyIndexes:r,data:i})}const u=B_(t),h=[];for(let d=0;d<u;d++){const e=new __(j_(t,0,x_)),r=j_(t,0,B_(t)),n=j_(t,0,B_(t));h.push({accountKey:e,writableIndexes:r,readonlyIndexes:n})}return new F_({header:i,staticAccountKeys:o,recentBlockhash:a,compiledInstructions:l,addressTableLookups:h})}}let z_=function(e){return e[e.BLOCKHEIGHT_EXCEEDED=0]="BLOCKHEIGHT_EXCEEDED",e[e.PROCESSED=1]="PROCESSED",e[e.TIMED_OUT=2]="TIMED_OUT",e[e.NONCE_INVALID=3]="NONCE_INVALID",e}({});const q_=lv.Buffer.alloc(64).fill(0);class W_{constructor(e){this.keys=void 0,this.programId=void 0,this.data=lv.Buffer.alloc(0),this.programId=e.programId,this.keys=e.keys,e.data&&(this.data=e.data)}toJSON(){return{keys:this.keys.map(({pubkey:e,isSigner:t,isWritable:r})=>({pubkey:e.toJSON(),isSigner:t,isWritable:r})),programId:this.programId.toJSON(),data:[...this.data]}}}class $_{get signature(){return this.signatures.length>0?this.signatures[0].signature:null}constructor(e){if(this.signatures=[],this.feePayer=void 0,this.instructions=[],this.recentBlockhash=void 0,this.lastValidBlockHeight=void 0,this.nonceInfo=void 0,this.minNonceContextSlot=void 0,this._message=void 0,this._json=void 0,e)if(e.feePayer&&(this.feePayer=e.feePayer),e.signatures&&(this.signatures=e.signatures),Object.prototype.hasOwnProperty.call(e,"nonceInfo")){const{minContextSlot:t,nonceInfo:r}=e;this.minNonceContextSlot=t,this.nonceInfo=r}else if(Object.prototype.hasOwnProperty.call(e,"lastValidBlockHeight")){const{blockhash:t,lastValidBlockHeight:r}=e;this.recentBlockhash=t,this.lastValidBlockHeight=r}else{const{recentBlockhash:t,nonceInfo:r}=e;r&&(this.nonceInfo=r),this.recentBlockhash=t}}toJSON(){return{recentBlockhash:this.recentBlockhash||null,feePayer:this.feePayer?this.feePayer.toJSON():null,nonceInfo:this.nonceInfo?{nonce:this.nonceInfo.nonce,nonceInstruction:this.nonceInfo.nonceInstruction.toJSON()}:null,instructions:this.instructions.map(e=>e.toJSON()),signers:this.signatures.map(({publicKey:e})=>e.toJSON())}}add(...e){if(0===e.length)throw new Error("No instructions");return e.forEach(e=>{"instructions"in e?this.instructions=this.instructions.concat(e.instructions):"data"in e&&"programId"in e&&"keys"in e?this.instructions.push(e):this.instructions.push(new W_(e))}),this}compileMessage(){if(this._message&&JSON.stringify(this.toJSON())===JSON.stringify(this._json))return this._message;let e,t,r;if(this.nonceInfo?(e=this.nonceInfo.nonce,t=this.instructions[0]!=this.nonceInfo.nonceInstruction?[this.nonceInfo.nonceInstruction,...this.instructions]:this.instructions):(e=this.recentBlockhash,t=this.instructions),!e)throw new Error("Transaction recentBlockhash required");if(t.length<1&&console.warn("No instructions provided"),this.feePayer)r=this.feePayer;else{if(!(this.signatures.length>0&&this.signatures[0].publicKey))throw new Error("Transaction fee payer required");r=this.signatures[0].publicKey}for(let f=0;f<t.length;f++)if(void 0===t[f].programId)throw new Error(`Transaction instruction index ${f} has undefined program id`);const n=[],i=[];t.forEach(e=>{e.keys.forEach(e=>{i.push({...e})});const t=e.programId.toString();n.includes(t)||n.push(t)}),n.forEach(e=>{i.push({pubkey:new __(e),isSigner:!1,isWritable:!1})});const o=[];i.forEach(e=>{const t=e.pubkey.toString(),r=o.findIndex(e=>e.pubkey.toString()===t);r>-1?(o[r].isWritable=o[r].isWritable||e.isWritable,o[r].isSigner=o[r].isSigner||e.isSigner):o.push(e)}),o.sort(function(e,t){if(e.isSigner!==t.isSigner)return e.isSigner?-1:1;if(e.isWritable!==t.isWritable)return e.isWritable?-1:1;return e.pubkey.toBase58().localeCompare(t.pubkey.toBase58(),"en",{localeMatcher:"best fit",usage:"sort",sensitivity:"variant",ignorePunctuation:!1,numeric:!1,caseFirst:"lower"})});const s=o.findIndex(e=>e.pubkey.equals(r));if(s>-1){const[e]=o.splice(s,1);e.isSigner=!0,e.isWritable=!0,o.unshift(e)}else o.unshift({pubkey:r,isSigner:!0,isWritable:!0});for(const f of this.signatures){const e=o.findIndex(e=>e.pubkey.equals(f.publicKey));if(!(e>-1))throw new Error(`unknown signer: ${f.publicKey.toString()}`);o[e].isSigner||(o[e].isSigner=!0,console.warn("Transaction references a signature that is unnecessary, only the fee payer and instruction signer accounts should sign a transaction. This behavior is deprecated and will throw an error in the next major version release."))}let a=0,c=0,l=0;const u=[],h=[];o.forEach(({pubkey:e,isSigner:t,isWritable:r})=>{t?(u.push(e.toString()),a+=1,r||(c+=1)):(h.push(e.toString()),r||(l+=1))});const d=u.concat(h),p=t.map(e=>{const{data:t,programId:r}=e;return{programIdIndex:d.indexOf(r.toString()),accounts:e.keys.map(e=>d.indexOf(e.pubkey.toString())),data:Yb.encode(t)}});return p.forEach(e=>{O_(e.programIdIndex>=0),e.accounts.forEach(e=>O_(e>=0))}),new D_({header:{numRequiredSignatures:a,numReadonlySignedAccounts:c,numReadonlyUnsignedAccounts:l},accountKeys:d,recentBlockhash:e,instructions:p})}_compile(){const e=this.compileMessage(),t=e.accountKeys.slice(0,e.header.numRequiredSignatures);if(this.signatures.length===t.length){if(this.signatures.every((e,r)=>t[r].equals(e.publicKey)))return e}return this.signatures=t.map(e=>({signature:null,publicKey:e})),e}serializeMessage(){return this._compile().serialize()}async getEstimatedFee(e){return(await e.getFeeForMessage(this.compileMessage())).value}setSigners(...e){if(0===e.length)throw new Error("No signers");const t=new Set;this.signatures=e.filter(e=>{const r=e.toString();return!t.has(r)&&(t.add(r),!0)}).map(e=>({signature:null,publicKey:e}))}sign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,r=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),r.push(i))}this.signatures=r.map(e=>({signature:null,publicKey:e.publicKey}));const n=this._compile();this._partialSign(n,...r)}partialSign(...e){if(0===e.length)throw new Error("No signers");const t=new Set,r=[];for(const i of e){const e=i.publicKey.toString();t.has(e)||(t.add(e),r.push(i))}const n=this._compile();this._partialSign(n,...r)}_partialSign(e,...t){const r=e.serialize();t.forEach(e=>{const t=((e,t)=>zb.sign(e,t.slice(0,32)))(r,e.secretKey);this._addSignature(e.publicKey,y_(t))})}addSignature(e,t){this._compile(),this._addSignature(e,t)}_addSignature(e,t){O_(64===t.length);const r=this.signatures.findIndex(t=>e.equals(t.publicKey));if(r<0)throw new Error(`unknown signer: ${e.toString()}`);this.signatures[r].signature=lv.Buffer.from(t)}verifySignatures(e=!0){return!this._getMessageSignednessErrors(this.serializeMessage(),e)}_getMessageSignednessErrors(e,t){const r={};for(const{signature:n,publicKey:i}of this.signatures)null===n?t&&(r.missing||(r.missing=[])).push(i):g_(n,e,i.toBytes())||(r.invalid||(r.invalid=[])).push(i);return r.invalid||r.missing?r:void 0}serialize(e){const{requireAllSignatures:t,verifySignatures:r}=Object.assign({requireAllSignatures:!0,verifySignatures:!0},e),n=this.serializeMessage();if(r){const e=this._getMessageSignednessErrors(n,t);if(e){let t="Signature verification failed.";throw e.invalid&&(t+=`\nInvalid signature for public key${1===e.invalid.length?"":"(s)"} [\`${e.invalid.map(e=>e.toBase58()).join("`, `")}\`].`),e.missing&&(t+=`\nMissing signature for public key${1===e.missing.length?"":"(s)"} [\`${e.missing.map(e=>e.toBase58()).join("`, `")}\`].`),new Error(t)}}return this._serialize(n)}_serialize(e){const{signatures:t}=this,r=[];T_(r,t.length);const n=r.length+64*t.length+e.length,i=lv.Buffer.alloc(n);return O_(t.length<256),lv.Buffer.from(r).copy(i,0),t.forEach(({signature:e},t)=>{null!==e&&(O_(64===e.length,"signature has invalid length"),lv.Buffer.from(e).copy(i,r.length+64*t))}),e.copy(i,r.length+64*t.length),O_(i.length<=S_,`Transaction too large: ${i.length} > 1232`),i}get keys(){return O_(1===this.instructions.length),this.instructions[0].keys.map(e=>e.pubkey)}get programId(){return O_(1===this.instructions.length),this.instructions[0].programId}get data(){return O_(1===this.instructions.length),this.instructions[0].data}static from(e){let t=[...e];const r=B_(t);let n=[];for(let i=0;i<r;i++){const e=j_(t,0,64);n.push(Yb.encode(lv.Buffer.from(e)))}return $_.populate(D_.from(t),n)}static populate(e,t=[]){const r=new $_;return r.recentBlockhash=e.recentBlockhash,e.header.numRequiredSignatures>0&&(r.feePayer=e.accountKeys[0]),t.forEach((t,n)=>{const i={signature:t==Yb.encode(q_)?null:Yb.decode(t),publicKey:e.accountKeys[n]};r.signatures.push(i)}),e.instructions.forEach(t=>{const n=t.accounts.map(t=>{const n=e.accountKeys[t];return{pubkey:n,isSigner:r.signatures.some(e=>e.publicKey.toString()===n.toString())||e.isAccountSigner(t),isWritable:e.isAccountWritable(t)}});r.instructions.push(new W_({keys:n,programId:e.accountKeys[t.programIdIndex],data:Yb.decode(t.data)}))}),r._message=e,r._json=r.toJSON(),r}}new __("SysvarC1ock11111111111111111111111111111111"),new __("SysvarEpochSchedu1e111111111111111111111111"),new __("Sysvar1nstructions1111111111111111111111111");const G_=new __("SysvarRecentB1ockHashes11111111111111111111"),V_=new __("SysvarRent111111111111111111111111111111111");new __("SysvarRewards111111111111111111111111111111"),new __("SysvarS1otHashes111111111111111111111111111"),new __("SysvarS1otHistory11111111111111111111111111"),new __("SysvarStakeHistory1111111111111111111111111");class H_ extends Error{constructor({action:e,signature:t,transactionMessage:r,logs:n}){const i=n?`Logs: \n${JSON.stringify(n.slice(-10),null,2)}. `:"",o="\nCatch the `SendTransactionError` and call `getLogs()` on it for full details.";let s;switch(e){case"send":s=`Transaction ${t} resulted in an error. \n${r}. `+i+o;break;case"simulate":s=`Simulation failed. \nMessage: ${r}. \n`+i+o;break;default:s=`Unknown action '${(e=>e)(e)}'`}super(s),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=t,this.transactionMessage=r,this.transactionLogs=n||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(null==e||"object"!=typeof e||!("then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((t,r)=>{e.getTransaction(this.signature).then(e=>{if(e&&e.meta&&e.meta.logMessages){const r=e.meta.logMessages;this.transactionLogs=r,t(r)}else r(new Error("Log messages not found"))}).catch(r)})),await this.transactionLogs}}class K_ extends Error{constructor({code:e,message:t,data:r},n){super(null!=n?`${n}: ${t}`:t),this.code=void 0,this.data=void 0,this.code=e,this.data=r,this.name="SolanaJSONRPCError"}}function Z_(e){return new Promise(t=>setTimeout(t,e))}function Y_(e,t){const r=e.layout.span>=0?e.layout.span:P_(e,t),n=lv.Buffer.alloc(r),i=Object.assign({instruction:e.index},t);return e.layout.encode(i,n),n}const J_=wx("lamportsPerSignature"),X_=kx([bx("version"),bx("state"),M_("authorizedPubkey"),M_("nonce"),kx([J_],"feeCalculator")]),Q_=X_.span;class eS{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const t=X_.decode(y_(e),0);return new eS({authorizedPubkey:new __(t.authorizedPubkey),nonce:new __(t.nonce).toString(),feeCalculator:t.feeCalculator})}}function tS(e){const t=Sx(8,e),r=t.decode.bind(t),n=t.encode.bind(t),i=t,o=Tx();return i.decode=(e,t)=>{const n=r(e,t);return o.decode(n)},i.encode=(e,t,r)=>{const i=o.encode(e);return n(i,t,r)},i}const rS=Object.freeze({Create:{index:0,layout:kx([bx("instruction"),xx("lamports"),xx("space"),M_("programId")])},Assign:{index:1,layout:kx([bx("instruction"),M_("programId")])},Transfer:{index:2,layout:kx([bx("instruction"),tS("lamports")])},CreateWithSeed:{index:3,layout:kx([bx("instruction"),M_("base"),N_("seed"),xx("lamports"),xx("space"),M_("programId")])},AdvanceNonceAccount:{index:4,layout:kx([bx("instruction")])},WithdrawNonceAccount:{index:5,layout:kx([bx("instruction"),xx("lamports")])},InitializeNonceAccount:{index:6,layout:kx([bx("instruction"),M_("authorized")])},AuthorizeNonceAccount:{index:7,layout:kx([bx("instruction"),M_("authorized")])},Allocate:{index:8,layout:kx([bx("instruction"),xx("space")])},AllocateWithSeed:{index:9,layout:kx([bx("instruction"),M_("base"),N_("seed"),xx("space"),M_("programId")])},AssignWithSeed:{index:10,layout:kx([bx("instruction"),M_("base"),N_("seed"),M_("programId")])},TransferWithSeed:{index:11,layout:kx([bx("instruction"),tS("lamports"),N_("seed"),M_("programId")])},UpgradeNonceAccount:{index:12,layout:kx([bx("instruction")])}});class nS{constructor(){}static createAccount(e){const t=Y_(rS.Create,{lamports:e.lamports,space:e.space,programId:y_(e.programId.toBuffer())});return new W_({keys:[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!0,isWritable:!0}],programId:this.programId,data:t})}static transfer(e){let t,r;if("basePubkey"in e){t=Y_(rS.TransferWithSeed,{lamports:BigInt(e.lamports),seed:e.seed,programId:y_(e.programId.toBuffer())}),r=[{pubkey:e.fromPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}else{t=Y_(rS.Transfer,{lamports:BigInt(e.lamports)}),r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0}]}return new W_({keys:r,programId:this.programId,data:t})}static assign(e){let t,r;if("basePubkey"in e){t=Y_(rS.AssignWithSeed,{base:y_(e.basePubkey.toBuffer()),seed:e.seed,programId:y_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Y_(rS.Assign,{programId:y_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new W_({keys:r,programId:this.programId,data:t})}static createAccountWithSeed(e){const t=Y_(rS.CreateWithSeed,{base:y_(e.basePubkey.toBuffer()),seed:e.seed,lamports:e.lamports,space:e.space,programId:y_(e.programId.toBuffer())});let r=[{pubkey:e.fromPubkey,isSigner:!0,isWritable:!0},{pubkey:e.newAccountPubkey,isSigner:!1,isWritable:!0}];return e.basePubkey.equals(e.fromPubkey)||r.push({pubkey:e.basePubkey,isSigner:!0,isWritable:!1}),new W_({keys:r,programId:this.programId,data:t})}static createNonceAccount(e){const t=new $_;"basePubkey"in e&&"seed"in e?t.add(nS.createAccountWithSeed({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,basePubkey:e.basePubkey,seed:e.seed,lamports:e.lamports,space:Q_,programId:this.programId})):t.add(nS.createAccount({fromPubkey:e.fromPubkey,newAccountPubkey:e.noncePubkey,lamports:e.lamports,space:Q_,programId:this.programId}));const r={noncePubkey:e.noncePubkey,authorizedPubkey:e.authorizedPubkey};return t.add(this.nonceInitialize(r)),t}static nonceInitialize(e){const t=Y_(rS.InitializeNonceAccount,{authorized:y_(e.authorizedPubkey.toBuffer())}),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:G_,isSigner:!1,isWritable:!1},{pubkey:V_,isSigner:!1,isWritable:!1}],programId:this.programId,data:t};return new W_(r)}static nonceAdvance(e){const t=Y_(rS.AdvanceNonceAccount),r={keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:G_,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t};return new W_(r)}static nonceWithdraw(e){const t=Y_(rS.WithdrawNonceAccount,{lamports:e.lamports});return new W_({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.toPubkey,isSigner:!1,isWritable:!0},{pubkey:G_,isSigner:!1,isWritable:!1},{pubkey:V_,isSigner:!1,isWritable:!1},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static nonceAuthorize(e){const t=Y_(rS.AuthorizeNonceAccount,{authorized:y_(e.newAuthorizedPubkey.toBuffer())});return new W_({keys:[{pubkey:e.noncePubkey,isSigner:!1,isWritable:!0},{pubkey:e.authorizedPubkey,isSigner:!0,isWritable:!1}],programId:this.programId,data:t})}static allocate(e){let t,r;if("basePubkey"in e){t=Y_(rS.AllocateWithSeed,{base:y_(e.basePubkey.toBuffer()),seed:e.seed,space:e.space,programId:y_(e.programId.toBuffer())}),r=[{pubkey:e.accountPubkey,isSigner:!1,isWritable:!0},{pubkey:e.basePubkey,isSigner:!0,isWritable:!1}]}else{t=Y_(rS.Allocate,{space:e.space}),r=[{pubkey:e.accountPubkey,isSigner:!0,isWritable:!0}]}return new W_({keys:r,programId:this.programId,data:t})}}function iS(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oS,sS;function aS(){if(sS)return oS;sS=1;var e=Object.prototype.toString,t=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};function r(n,i){var o,s,a,c,l,u,h;if(!0===n)return"true";if(!1===n)return"false";switch(typeof n){case"object":if(null===n)return null;if(n.toJSON&&"function"==typeof n.toJSON)return r(n.toJSON(),i);if("[object Array]"===(h=e.call(n))){for(a="[",s=n.length-1,o=0;o<s;o++)a+=r(n[o],!0)+",";return s>-1&&(a+=r(n[o],!0)),a+"]"}if("[object Object]"===h){for(s=(c=t(n).sort()).length,a="",o=0;o<s;)void 0!==(u=r(n[l=c[o]],!1))&&(a&&(a+=","),a+=JSON.stringify(l)+":"+u),o++;return"{"+a+"}"}return JSON.stringify(n);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(n);default:return isFinite(n)?n:null}}return oS=function(e){var t=r(e,!1);if(void 0!==t)return""+t}}nS.programId=new __("11111111111111111111111111111111"),new __("BPFLoader2111111111111111111111111111111111");var cS=iS(aS());function lS(e){let t=0;for(;e>1;)e/=2,t++;return t}class uS{constructor(e,t,r,n,i){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=t,this.warmup=r,this.firstNormalEpoch=n,this.firstNormalSlot=i}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const r=lS(0===(t=e+32+1)?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,1+(t|=t>>32)))-lS(32)-1;return[r,e-(this.getSlotsInEpoch(r)-32)]}{const t=e-this.firstNormalSlot,r=Math.floor(t/this.slotsPerEpoch);return[this.firstNormalEpoch+r,t%this.slotsPerEpoch]}var t}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?32*(Math.pow(2,e)-1):(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+lS(32)):this.slotsPerEpoch}}var hS=globalThis.fetch;class dS extends Wk{constructor(e,t,r){super(e=>{const r=function(e,t){return new zk(e,t)}(e,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...t});return this.underlyingSocket="socket"in r?r.socket:r,r},e,t,r),this.underlyingSocket=void 0}call(...e){var t;const r=null==(t=this.underlyingSocket)?void 0:t.readyState;return 1===r?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+r+")"))}notify(...e){var t;const r=null==(t=this.underlyingSocket)?void 0:t.readyState;return 1===r?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+r+")"))}}class pS{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const t=function(e,t){let r;try{r=e.layout.decode(t)}catch(EE){throw new Error("invalid instruction; "+EE)}if(r.typeIndex!==e.index)throw new Error(`invalid account data; account type mismatch ${r.typeIndex} != ${e.index}`);return r}(fS,e),r=e.length-56;O_(r>=0,"lookup table is invalid"),O_(r%32==0,"lookup table is invalid");const n=r/32,{addresses:i}=kx([_x(M_(),n,"addresses")]).decode(e.slice(56));return{deactivationSlot:t.deactivationSlot,lastExtendedSlot:t.lastExtendedSlot,lastExtendedSlotStartIndex:t.lastExtendedStartIndex,authority:0!==t.authority.length?new __(t.authority[0]):void 0,addresses:i.map(e=>new __(e))}}}const fS={index:1,layout:kx([bx("typeIndex"),tS("deactivationSlot"),wx("lastExtendedSlot"),yx("lastExtendedStartIndex"),yx(),_x(M_(),gx(yx(),-1),"authority")])},mS=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;const gS=ok(Kx(__),ek(),e=>new __(e)),yS=tk([ek(),Zx("base64")]),vS=ok(Kx(lv.Buffer),yS,e=>lv.Buffer.from(e[0],"base64"));function bS(e){let t,r;if("string"==typeof e)t=e;else if(e){const{commitment:n,...i}=e;t=n,r=i}return{commitment:t,config:r}}function wS(e){return e.map(e=>"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:e.memcmp.encoding??"base58"}}:e)}function xS(e){return nk([rk({jsonrpc:Zx("2.0"),id:ek(),result:e}),rk({jsonrpc:Zx("2.0"),id:ek(),error:rk({code:ik(),message:ek(),data:Xx(Gx("any",()=>!0))})})])}const kS=xS(ik());function _S(e){return ok(xS(e),kS,t=>"error"in t?t:{...t,result:qx(t.result,e)})}function SS(e){return _S(rk({context:rk({slot:Jx()}),value:e}))}function CS(e){return rk({context:rk({slot:Jx()}),value:e})}function IS(e,t){return 0===e?new F_({header:t.header,staticAccountKeys:t.accountKeys.map(e=>new __(e)),recentBlockhash:t.recentBlockhash,compiledInstructions:t.instructions.map(e=>({programIdIndex:e.programIdIndex,accountKeyIndexes:e.accounts,data:Yb.decode(e.data)})),addressTableLookups:t.addressTableLookups}):new D_(t)}const ES=rk({foundation:Jx(),foundationTerm:Jx(),initial:Jx(),taper:Jx(),terminal:Jx()}),AS=_S(Vx(Yx(rk({epoch:Jx(),effectiveSlot:Jx(),amount:Jx(),postBalance:Jx(),commission:Xx(Yx(Jx()))})))),MS=Vx(rk({slot:Jx(),prioritizationFee:Jx()})),NS=rk({total:Jx(),validator:Jx(),foundation:Jx(),epoch:Jx()}),PS=rk({epoch:Jx(),slotIndex:Jx(),slotsInEpoch:Jx(),absoluteSlot:Jx(),blockHeight:Xx(Jx()),transactionCount:Xx(Jx())}),BS=rk({slotsPerEpoch:Jx(),leaderScheduleSlotOffset:Jx(),warmup:Hx(),firstNormalEpoch:Jx(),firstNormalSlot:Jx()}),TS=Qx(ek(),Vx(Jx())),OS=Yx(nk([rk({}),ek()])),RS=rk({err:OS}),LS=Zx("receivedSignature"),US=rk({"solana-core":ek(),"feature-set":Xx(Jx())}),jS=rk({program:ek(),programId:gS,parsed:ik()}),DS=rk({programId:gS,accounts:Vx(gS),data:ek()}),FS=SS(rk({err:Yx(nk([rk({}),ek()])),logs:Yx(Vx(ek())),accounts:Xx(Yx(Vx(Yx(rk({executable:Hx(),owner:ek(),lamports:Jx(),data:Vx(ek()),rentEpoch:Xx(Jx())}))))),unitsConsumed:Xx(Jx()),returnData:Xx(Yx(rk({programId:ek(),data:tk([ek(),Zx("base64")])}))),innerInstructions:Xx(Yx(Vx(rk({index:Jx(),instructions:Vx(nk([jS,DS]))}))))})),zS=SS(rk({byIdentity:Qx(ek(),Vx(Jx())),range:rk({firstSlot:Jx(),lastSlot:Jx()})}));const qS=_S(ES),WS=_S(NS),$S=_S(MS),GS=_S(PS),VS=_S(BS),HS=_S(TS),KS=_S(Jx()),ZS=SS(rk({total:Jx(),circulating:Jx(),nonCirculating:Jx(),nonCirculatingAccounts:Vx(gS)})),YS=rk({amount:ek(),uiAmount:Yx(Jx()),decimals:Jx(),uiAmountString:Xx(ek())}),JS=SS(Vx(rk({address:gS,amount:ek(),uiAmount:Yx(Jx()),decimals:Jx(),uiAmountString:Xx(ek())}))),XS=SS(Vx(rk({pubkey:gS,account:rk({executable:Hx(),owner:gS,lamports:Jx(),data:vS,rentEpoch:Jx()})}))),QS=rk({program:ek(),parsed:ik(),space:Jx()}),eC=SS(Vx(rk({pubkey:gS,account:rk({executable:Hx(),owner:gS,lamports:Jx(),data:QS,rentEpoch:Jx()})}))),tC=SS(Vx(rk({lamports:Jx(),address:gS}))),rC=rk({executable:Hx(),owner:gS,lamports:Jx(),data:vS,rentEpoch:Jx()}),nC=rk({pubkey:gS,account:rC}),iC=ok(nk([Kx(lv.Buffer),QS]),nk([yS,QS]),e=>Array.isArray(e)?qx(e,vS):e),oC=rk({executable:Hx(),owner:gS,lamports:Jx(),data:iC,rentEpoch:Jx()}),sC=rk({pubkey:gS,account:oC}),aC=rk({state:nk([Zx("active"),Zx("inactive"),Zx("activating"),Zx("deactivating")]),active:Jx(),inactive:Jx()}),cC=_S(Vx(rk({signature:ek(),slot:Jx(),err:OS,memo:Yx(ek()),blockTime:Xx(Yx(Jx()))}))),lC=_S(Vx(rk({signature:ek(),slot:Jx(),err:OS,memo:Yx(ek()),blockTime:Xx(Yx(Jx()))}))),uC=rk({subscription:Jx(),result:CS(rC)}),hC=rk({pubkey:gS,account:rC}),dC=rk({subscription:Jx(),result:CS(hC)}),pC=rk({parent:Jx(),slot:Jx(),root:Jx()}),fC=rk({subscription:Jx(),result:pC}),mC=nk([rk({type:nk([Zx("firstShredReceived"),Zx("completed"),Zx("optimisticConfirmation"),Zx("root")]),slot:Jx(),timestamp:Jx()}),rk({type:Zx("createdBank"),parent:Jx(),slot:Jx(),timestamp:Jx()}),rk({type:Zx("frozen"),slot:Jx(),timestamp:Jx(),stats:rk({numTransactionEntries:Jx(),numSuccessfulTransactions:Jx(),numFailedTransactions:Jx(),maxTransactionsPerEntry:Jx()})}),rk({type:Zx("dead"),slot:Jx(),timestamp:Jx(),err:ek()})]),gC=rk({subscription:Jx(),result:mC}),yC=rk({subscription:Jx(),result:CS(nk([RS,LS]))}),vC=rk({subscription:Jx(),result:Jx()}),bC=rk({pubkey:ek(),gossip:Yx(ek()),tpu:Yx(ek()),rpc:Yx(ek()),version:Yx(ek())}),wC=rk({votePubkey:ek(),nodePubkey:ek(),activatedStake:Jx(),epochVoteAccount:Hx(),epochCredits:Vx(tk([Jx(),Jx(),Jx()])),commission:Jx(),lastVote:Jx(),rootSlot:Yx(Jx())}),xC=_S(rk({current:Vx(wC),delinquent:Vx(wC)})),kC=nk([Zx("processed"),Zx("confirmed"),Zx("finalized")]),_C=rk({slot:Jx(),confirmations:Yx(Jx()),err:OS,confirmationStatus:Xx(kC)}),SC=SS(Vx(Yx(_C))),CC=_S(Jx()),IC=rk({accountKey:gS,writableIndexes:Vx(Jx()),readonlyIndexes:Vx(Jx())}),EC=rk({signatures:Vx(ek()),message:rk({accountKeys:Vx(ek()),header:rk({numRequiredSignatures:Jx(),numReadonlySignedAccounts:Jx(),numReadonlyUnsignedAccounts:Jx()}),instructions:Vx(rk({accounts:Vx(Jx()),data:ek(),programIdIndex:Jx()})),recentBlockhash:ek(),addressTableLookups:Xx(Vx(IC))})}),AC=rk({pubkey:gS,signer:Hx(),writable:Hx(),source:Xx(nk([Zx("transaction"),Zx("lookupTable")]))}),MC=rk({accountKeys:Vx(AC),signatures:Vx(ek())}),NC=rk({parsed:ik(),program:ek(),programId:gS}),PC=rk({accounts:Vx(gS),data:ek(),programId:gS}),BC=ok(nk([PC,NC]),nk([rk({parsed:ik(),program:ek(),programId:ek()}),rk({accounts:Vx(ek()),data:ek(),programId:ek()})]),e=>qx(e,"accounts"in e?PC:NC)),TC=rk({signatures:Vx(ek()),message:rk({accountKeys:Vx(AC),instructions:Vx(BC),recentBlockhash:ek(),addressTableLookups:Xx(Yx(Vx(IC)))})}),OC=rk({accountIndex:Jx(),mint:ek(),owner:Xx(ek()),programId:Xx(ek()),uiTokenAmount:YS}),RC=rk({writable:Vx(gS),readonly:Vx(gS)}),LC=rk({err:OS,fee:Jx(),innerInstructions:Xx(Yx(Vx(rk({index:Jx(),instructions:Vx(rk({accounts:Vx(Jx()),data:ek(),programIdIndex:Jx()}))})))),preBalances:Vx(Jx()),postBalances:Vx(Jx()),logMessages:Xx(Yx(Vx(ek()))),preTokenBalances:Xx(Yx(Vx(OC))),postTokenBalances:Xx(Yx(Vx(OC))),loadedAddresses:Xx(RC),computeUnitsConsumed:Xx(Jx()),costUnits:Xx(Jx())}),UC=rk({err:OS,fee:Jx(),innerInstructions:Xx(Yx(Vx(rk({index:Jx(),instructions:Vx(BC)})))),preBalances:Vx(Jx()),postBalances:Vx(Jx()),logMessages:Xx(Yx(Vx(ek()))),preTokenBalances:Xx(Yx(Vx(OC))),postTokenBalances:Xx(Yx(Vx(OC))),loadedAddresses:Xx(RC),computeUnitsConsumed:Xx(Jx()),costUnits:Xx(Jx())}),jC=nk([Zx(0),Zx("legacy")]),DC=rk({pubkey:ek(),lamports:Jx(),postBalance:Yx(Jx()),rewardType:Yx(ek()),commission:Xx(Yx(Jx()))}),FC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),transactions:Vx(rk({transaction:EC,meta:Yx(LC),version:Xx(jC)})),rewards:Xx(Vx(DC)),blockTime:Yx(Jx()),blockHeight:Yx(Jx())}))),zC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),rewards:Xx(Vx(DC)),blockTime:Yx(Jx()),blockHeight:Yx(Jx())}))),qC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),transactions:Vx(rk({transaction:MC,meta:Yx(LC),version:Xx(jC)})),rewards:Xx(Vx(DC)),blockTime:Yx(Jx()),blockHeight:Yx(Jx())}))),WC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),transactions:Vx(rk({transaction:TC,meta:Yx(UC),version:Xx(jC)})),rewards:Xx(Vx(DC)),blockTime:Yx(Jx()),blockHeight:Yx(Jx())}))),$C=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),transactions:Vx(rk({transaction:MC,meta:Yx(UC),version:Xx(jC)})),rewards:Xx(Vx(DC)),blockTime:Yx(Jx()),blockHeight:Yx(Jx())}))),GC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),rewards:Xx(Vx(DC)),blockTime:Yx(Jx()),blockHeight:Yx(Jx())}))),VC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),transactions:Vx(rk({transaction:EC,meta:Yx(LC)})),rewards:Xx(Vx(DC)),blockTime:Yx(Jx())}))),HC=_S(Yx(rk({blockhash:ek(),previousBlockhash:ek(),parentSlot:Jx(),signatures:Vx(ek()),blockTime:Yx(Jx())}))),KC=_S(Yx(rk({slot:Jx(),meta:Yx(LC),blockTime:Xx(Yx(Jx())),transaction:EC,version:Xx(jC)}))),ZC=_S(Yx(rk({slot:Jx(),transaction:TC,meta:Yx(UC),blockTime:Xx(Yx(Jx())),version:Xx(jC)}))),YC=SS(rk({blockhash:ek(),lastValidBlockHeight:Jx()})),JC=SS(Hx()),XC=_S(Vx(rk({slot:Jx(),numTransactions:Jx(),numSlots:Jx(),samplePeriodSecs:Jx()}))),QC=SS(Yx(rk({feeCalculator:rk({lamportsPerSignature:Jx()})}))),eI=_S(ek()),tI=_S(ek()),rI=rk({err:OS,logs:Vx(ek()),signature:ek()}),nI=rk({result:CS(rI),subscription:Jx()}),iI={"solana-client":"js/1.0.0-maintenance"};class oI{constructor(e,t){let r,n,i,o,s,a;var c;this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const e={};return async t=>{const{commitment:r,config:n}=bS(t),i=this._buildArgs([],r,void 0,n),o=cS(i);return e[o]=e[o]??(async()=>{try{const e=qx(await this._rpcRequest("getBlockHeight",i),_S(Jx()));if("error"in e)throw new K_(e.error,"failed to get block height information");return e.result}finally{delete e[o]}})(),await e[o]}})(),t&&"string"==typeof t?this._commitment=t:t&&(this._commitment=t.commitment,this._confirmTransactionInitialTimeout=t.confirmTransactionInitialTimeout,r=t.wsEndpoint,n=t.httpHeaders,i=t.fetch,o=t.fetchMiddleware,s=t.disableRetryOnRateLimit,a=t.httpAgent),this._rpcEndpoint=function(e){if(!1===/^https?:/.test(e))throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return e}(e),this._rpcWsEndpoint=r||function(e){const t=e.match(mS);if(null==t)throw TypeError(`Failed to validate endpoint URL \`${e}\``);const[r,n,i,o]=t,s=e.startsWith("https:")?"wss:":"ws:",a=null==i?null:parseInt(i.slice(1),10);return`${s}//${n}${null==a?"":`:${a+1}`}${o}`}(e),this._rpcClient=function(e,t,r,n,i,o){const s=r||hS;let a;null!=o&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments."),n&&(a=async(e,t)=>{const r=await new Promise((r,i)=>{try{n(e,t,(e,t)=>r([e,t]))}catch(vu){i(vu)}});return await s(...r)});const c=new jk(async(r,n)=>{const o={method:"POST",body:r,agent:void 0,headers:Object.assign({"Content-Type":"application/json"},t||{},iI)};try{let t,r=5,c=500;for(;t=a?await a(e,o):await s(e,o),429===t.status&&!0!==i&&(r-=1,0!==r);)console.error(`Server responded with ${t.status} ${t.statusText}. Retrying after ${c}ms delay...`),await Z_(c),c*=2;const l=await t.text();t.ok?n(null,l):n(new Error(`${t.status} ${t.statusText}: ${l}`))}catch(EE){EE instanceof Error&&n(EE)}},{});return c}(e,n,i,o,s,a),this._rpcRequest=(c=this._rpcClient,(e,t)=>new Promise((r,n)=>{c.request(e,t,(e,t)=>{e?n(e):r(t)})})),this._rpcBatchRequest=function(e){return t=>new Promise((r,n)=>{0===t.length&&r([]);const i=t.map(t=>e.request(t.methodName,t.args));e.request(i,(e,t)=>{e?n(e):r(t)})})}(this._rpcClient),this._rpcWebSocket=new dS(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgs([e.toBase58()],r,void 0,n),o=qx(await this._rpcRequest("getBalance",i),SS(Jx()));if("error"in o)throw new K_(o.error,`failed to get balance for ${e.toBase58()}`);return o.result}async getBalance(e,t){return await this.getBalanceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+t)})}async getBlockTime(e){const t=qx(await this._rpcRequest("getBlockTime",[e]),_S(Yx(Jx())));if("error"in t)throw new K_(t.error,`failed to get block time for slot ${e}`);return t.result}async getMinimumLedgerSlot(){const e=qx(await this._rpcRequest("minimumLedgerSlot",[]),_S(Jx()));if("error"in e)throw new K_(e.error,"failed to get minimum ledger slot");return e.result}async getFirstAvailableBlock(){const e=qx(await this._rpcRequest("getFirstAvailableBlock",[]),KS);if("error"in e)throw new K_(e.error,"failed to get first available block");return e.result}async getSupply(e){let t={};t="string"==typeof e?{commitment:e}:e?{...e,commitment:e&&e.commitment||this.commitment}:{commitment:this.commitment};const r=qx(await this._rpcRequest("getSupply",[t]),ZS);if("error"in r)throw new K_(r.error,"failed to get supply");return r.result}async getTokenSupply(e,t){const r=this._buildArgs([e.toBase58()],t),n=qx(await this._rpcRequest("getTokenSupply",r),SS(YS));if("error"in n)throw new K_(n.error,"failed to get token supply");return n.result}async getTokenAccountBalance(e,t){const r=this._buildArgs([e.toBase58()],t),n=qx(await this._rpcRequest("getTokenAccountBalance",r),SS(YS));if("error"in n)throw new K_(n.error,"failed to get token account balance");return n.result}async getTokenAccountsByOwner(e,t,r){const{commitment:n,config:i}=bS(r);let o=[e.toBase58()];"mint"in t?o.push({mint:t.mint.toBase58()}):o.push({programId:t.programId.toBase58()});const s=this._buildArgs(o,n,"base64",i),a=qx(await this._rpcRequest("getTokenAccountsByOwner",s),XS);if("error"in a)throw new K_(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getParsedTokenAccountsByOwner(e,t,r){let n=[e.toBase58()];"mint"in t?n.push({mint:t.mint.toBase58()}):n.push({programId:t.programId.toBase58()});const i=this._buildArgs(n,r,"jsonParsed"),o=qx(await this._rpcRequest("getTokenAccountsByOwner",i),eC);if("error"in o)throw new K_(o.error,`failed to get token accounts owned by account ${e.toBase58()}`);return o.result}async getLargestAccounts(e){const t={...e,commitment:e&&e.commitment||this.commitment},r=t.filter||t.commitment?[t]:[],n=qx(await this._rpcRequest("getLargestAccounts",r),tC);if("error"in n)throw new K_(n.error,"failed to get largest accounts");return n.result}async getTokenLargestAccounts(e,t){const r=this._buildArgs([e.toBase58()],t),n=qx(await this._rpcRequest("getTokenLargestAccounts",r),JS);if("error"in n)throw new K_(n.error,"failed to get token largest accounts");return n.result}async getAccountInfoAndContext(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgs([e.toBase58()],r,"base64",n),o=qx(await this._rpcRequest("getAccountInfo",i),SS(Yx(rC)));if("error"in o)throw new K_(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getParsedAccountInfo(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgs([e.toBase58()],r,"jsonParsed",n),o=qx(await this._rpcRequest("getAccountInfo",i),SS(Yx(oC)));if("error"in o)throw new K_(o.error,`failed to get info about account ${e.toBase58()}`);return o.result}async getAccountInfo(e,t){try{return(await this.getAccountInfoAndContext(e,t)).value}catch(r){throw new Error("failed to get info about account "+e.toBase58()+": "+r)}}async getMultipleParsedAccounts(e,t){const{commitment:r,config:n}=bS(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],r,"jsonParsed",n),s=qx(await this._rpcRequest("getMultipleAccounts",o),SS(Vx(Yx(oC))));if("error"in s)throw new K_(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfoAndContext(e,t){const{commitment:r,config:n}=bS(t),i=e.map(e=>e.toBase58()),o=this._buildArgs([i],r,"base64",n),s=qx(await this._rpcRequest("getMultipleAccounts",o),SS(Vx(Yx(rC))));if("error"in s)throw new K_(s.error,`failed to get info for accounts ${i}`);return s.result}async getMultipleAccountsInfo(e,t){return(await this.getMultipleAccountsInfoAndContext(e,t)).value}async getStakeActivation(e,t,r){const{commitment:n,config:i}=bS(t),o=this._buildArgs([e.toBase58()],n,void 0,{...i,epoch:null!=r?r:null==i?void 0:i.epoch}),s=qx(await this._rpcRequest("getStakeActivation",o),_S(aC));if("error"in s)throw new K_(s.error,`failed to get Stake Activation ${e.toBase58()}`);return s.result}async getProgramAccounts(e,t){const{commitment:r,config:n}=bS(t),{encoding:i,...o}=n||{},s=this._buildArgs([e.toBase58()],r,i||"base64",{...o,...o.filters?{filters:wS(o.filters)}:null}),a=await this._rpcRequest("getProgramAccounts",s),c=Vx(nC),l=!0===o.withContext?qx(a,SS(c)):qx(a,_S(c));if("error"in l)throw new K_(l.error,`failed to get accounts owned by program ${e.toBase58()}`);return l.result}async getParsedProgramAccounts(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgs([e.toBase58()],r,"jsonParsed",n),o=qx(await this._rpcRequest("getProgramAccounts",i),_S(Vx(sC)));if("error"in o)throw new K_(o.error,`failed to get accounts owned by program ${e.toBase58()}`);return o.result}async confirmTransaction(e,t){var r;let n,i;if("string"==typeof e)n=e;else{const t=e;if(null==(r=t.abortSignal)?void 0:r.aborted)return Promise.reject(t.abortSignal.reason);n=t.signature}try{i=Yb.decode(n)}catch(EE){throw new Error("signature must be base58 encoded: "+n)}return O_(64===i.length,"signature has invalid length"),"string"==typeof e?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:t||this.commitment,signature:n}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:t||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:t||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((t,r)=>{null!=e&&(e.aborted?r(e.reason):e.addEventListener("abort",()=>{r(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:t}){let r,n,i=!1;const o=new Promise((o,s)=>{try{r=this.onSignature(t,(e,t)=>{r=void 0;const n={context:t,value:e};o({__type:z_.PROCESSED,response:n})},e);const a=new Promise(e=>{null==r?e():n=this._onSubscriptionStateChange(r,t=>{"subscribed"===t&&e()})});(async()=>{if(await a,i)return;const r=await this.getSignatureStatus(t);if(i)return;if(null==r)return;const{context:n,value:c}=r;if(null!=c)if(null==c?void 0:c.err)s(c.err);else{switch(e){case"confirmed":case"single":case"singleGossip":if("processed"===c.confirmationStatus)return;break;case"finalized":case"max":case"root":if("processed"===c.confirmationStatus||"confirmed"===c.confirmationStatus)return}i=!0,o({__type:z_.PROCESSED,response:{context:n,value:c}})}})()}catch(EE){s(EE)}});return{abortConfirmation:()=>{n&&(n(),n=void 0),null!=r&&(this.removeSignatureListener(r),r=void 0)},confirmationPromise:o}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:t,lastValidBlockHeight:r,signature:n}}){let i=!1;const o=new Promise(t=>{const n=async()=>{try{return await this.getBlockHeight(e)}catch(t){return-1}};(async()=>{let e=await n();if(!i){for(;e<=r;){if(await Z_(1e3),i)return;if(e=await n(),i)return}t({__type:z_.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:s,confirmationPromise:a}=this.getTransactionConfirmationPromise({commitment:e,signature:n}),c=this.getCancellationPromise(t);let l;try{const e=await Promise.race([c,a,o]);if(e.__type!==z_.PROCESSED)throw new C_(n);l=e.response}finally{i=!0,s()}return l}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:t,minContextSlot:r,nonceAccountPubkey:n,nonceValue:i,signature:o}}){let s=!1;const a=new Promise(t=>{let o=i,a=null;const c=async()=>{try{const{context:t,value:i}=await this.getNonceAndContext(n,{commitment:e,minContextSlot:r});return a=t.slot,null==i?void 0:i.nonce}catch(t){return o}};(async()=>{if(o=await c(),!s)for(;;){if(i!==o)return void t({__type:z_.NONCE_INVALID,slotInWhichNonceDidAdvance:a});if(await Z_(2e3),s)return;if(o=await c(),s)return}})()}),{abortConfirmation:c,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:o}),u=this.getCancellationPromise(t);let h;try{const t=await Promise.race([u,l,a]);if(t.__type===z_.PROCESSED)h=t.response;else{let n;for(;;){const e=await this.getSignatureStatus(o);if(null==e)break;if(!(e.context.slot<(t.slotInWhichNonceDidAdvance??r))){n=e;break}await Z_(400)}if(!(null==n?void 0:n.value))throw new E_(o);{const t=e||"finalized",{confirmationStatus:r}=n.value;switch(t){case"processed":case"recent":if("processed"!==r&&"confirmed"!==r&&"finalized"!==r)throw new E_(o);break;case"confirmed":case"single":case"singleGossip":if("confirmed"!==r&&"finalized"!==r)throw new E_(o);break;case"finalized":case"max":case"root":if("finalized"!==r)throw new E_(o)}h={context:n.context,value:{err:n.value.err}}}}}finally{s=!0,c()}return h}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:t}){let r;const n=new Promise(t=>{let n=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":n=this._confirmTransactionInitialTimeout||3e4}r=setTimeout(()=>t({__type:z_.TIMED_OUT,timeoutMs:n}),n)}),{abortConfirmation:i,confirmationPromise:o}=this.getTransactionConfirmationPromise({commitment:e,signature:t});let s;try{const e=await Promise.race([o,n]);if(e.__type!==z_.PROCESSED)throw new I_(t,e.timeoutMs/1e3);s=e.response}finally{clearTimeout(r),i()}return s}async getClusterNodes(){const e=qx(await this._rpcRequest("getClusterNodes",[]),_S(Vx(bC)));if("error"in e)throw new K_(e.error,"failed to get cluster nodes");return e.result}async getVoteAccounts(e){const t=this._buildArgs([],e),r=qx(await this._rpcRequest("getVoteAccounts",t),xC);if("error"in r)throw new K_(r.error,"failed to get vote accounts");return r.result}async getSlot(e){const{commitment:t,config:r}=bS(e),n=this._buildArgs([],t,void 0,r),i=qx(await this._rpcRequest("getSlot",n),_S(Jx()));if("error"in i)throw new K_(i.error,"failed to get slot");return i.result}async getSlotLeader(e){const{commitment:t,config:r}=bS(e),n=this._buildArgs([],t,void 0,r),i=qx(await this._rpcRequest("getSlotLeader",n),_S(ek()));if("error"in i)throw new K_(i.error,"failed to get slot leader");return i.result}async getSlotLeaders(e,t){const r=[e,t],n=qx(await this._rpcRequest("getSlotLeaders",r),_S(Vx(gS)));if("error"in n)throw new K_(n.error,"failed to get slot leaders");return n.result}async getSignatureStatus(e,t){const{context:r,value:n}=await this.getSignatureStatuses([e],t);O_(1===n.length);return{context:r,value:n[0]}}async getSignatureStatuses(e,t){const r=[e];t&&r.push(t);const n=qx(await this._rpcRequest("getSignatureStatuses",r),SC);if("error"in n)throw new K_(n.error,"failed to get signature status");return n.result}async getTransactionCount(e){const{commitment:t,config:r}=bS(e),n=this._buildArgs([],t,void 0,r),i=qx(await this._rpcRequest("getTransactionCount",n),_S(Jx()));if("error"in i)throw new K_(i.error,"failed to get transaction count");return i.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const t=this._buildArgs([],e),r=qx(await this._rpcRequest("getInflationGovernor",t),qS);if("error"in r)throw new K_(r.error,"failed to get inflation");return r.result}async getInflationReward(e,t,r){const{commitment:n,config:i}=bS(r),o=this._buildArgs([e.map(e=>e.toBase58())],n,void 0,{...i,epoch:null!=t?t:null==i?void 0:i.epoch}),s=qx(await this._rpcRequest("getInflationReward",o),AS);if("error"in s)throw new K_(s.error,"failed to get inflation reward");return s.result}async getInflationRate(){const e=qx(await this._rpcRequest("getInflationRate",[]),WS);if("error"in e)throw new K_(e.error,"failed to get inflation rate");return e.result}async getEpochInfo(e){const{commitment:t,config:r}=bS(e),n=this._buildArgs([],t,void 0,r),i=qx(await this._rpcRequest("getEpochInfo",n),GS);if("error"in i)throw new K_(i.error,"failed to get epoch info");return i.result}async getEpochSchedule(){const e=qx(await this._rpcRequest("getEpochSchedule",[]),VS);if("error"in e)throw new K_(e.error,"failed to get epoch schedule");const t=e.result;return new uS(t.slotsPerEpoch,t.leaderScheduleSlotOffset,t.warmup,t.firstNormalEpoch,t.firstNormalSlot)}async getLeaderSchedule(){const e=qx(await this._rpcRequest("getLeaderSchedule",[]),HS);if("error"in e)throw new K_(e.error,"failed to get leader schedule");return e.result}async getMinimumBalanceForRentExemption(e,t){const r=this._buildArgs([e],t),n=qx(await this._rpcRequest("getMinimumBalanceForRentExemption",r),CC);return"error"in n?(console.warn("Unable to fetch minimum balance for rent exemption"),0):n.result}async getRecentBlockhashAndContext(e){const{context:t,value:{blockhash:r}}=await this.getLatestBlockhashAndContext(e);return{context:t,value:{blockhash:r,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON:()=>({})}}}}async getRecentPerformanceSamples(e){const t=qx(await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),XC);if("error"in t)throw new K_(t.error,"failed to get recent performance samples");return t.result}async getFeeCalculatorForBlockhash(e,t){const r=this._buildArgs([e],t),n=qx(await this._rpcRequest("getFeeCalculatorForBlockhash",r),QC);if("error"in n)throw new K_(n.error,"failed to get fee calculator");const{context:i,value:o}=n.result;return{context:i,value:null!==o?o.feeCalculator:null}}async getFeeForMessage(e,t){const r=y_(e.serialize()).toString("base64"),n=this._buildArgs([r],t),i=qx(await this._rpcRequest("getFeeForMessage",n),SS(Yx(Jx())));if("error"in i)throw new K_(i.error,"failed to get fee for message");if(null===i.result)throw new Error("invalid blockhash");return i.result}async getRecentPrioritizationFees(e){var t;const r=null==(t=null==e?void 0:e.lockedWritableAccounts)?void 0:t.map(e=>e.toBase58()),n=(null==r?void 0:r.length)?[r]:[],i=qx(await this._rpcRequest("getRecentPrioritizationFees",n),$S);if("error"in i)throw new K_(i.error,"failed to get recent prioritization fees");return i.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(t){throw new Error("failed to get recent blockhash: "+t)}}async getLatestBlockhashAndContext(e){const{commitment:t,config:r}=bS(e),n=this._buildArgs([],t,void 0,r),i=qx(await this._rpcRequest("getLatestBlockhash",n),YC);if("error"in i)throw new K_(i.error,"failed to get latest blockhash");return i.result}async isBlockhashValid(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgs([e],r,void 0,n),o=qx(await this._rpcRequest("isBlockhashValid",i),JC);if("error"in o)throw new K_(o.error,"failed to determine if the blockhash `"+e+"`is valid");return o.result}async getVersion(){const e=qx(await this._rpcRequest("getVersion",[]),_S(US));if("error"in e)throw new K_(e.error,"failed to get version");return e.result}async getGenesisHash(){const e=qx(await this._rpcRequest("getGenesisHash",[]),_S(ek()));if("error"in e)throw new K_(e.error,"failed to get genesis hash");return e.result}async getBlock(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgsAtLeastConfirmed([e],r,void 0,n),o=await this._rpcRequest("getBlock",i);try{switch(null==n?void 0:n.transactionDetails){case"accounts":{const e=qx(o,qC);if("error"in e)throw e.error;return e.result}case"none":{const e=qx(o,zC);if("error"in e)throw e.error;return e.result}default:{const e=qx(o,FC);if("error"in e)throw e.error;const{result:t}=e;return t?{...t,transactions:t.transactions.map(({transaction:e,meta:t,version:r})=>({meta:t,transaction:{...e,message:IS(r,e.message)},version:r}))}:null}}}catch(s){throw new K_(s,"failed to get confirmed block")}}async getParsedBlock(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n),o=await this._rpcRequest("getBlock",i);try{switch(null==n?void 0:n.transactionDetails){case"accounts":{const e=qx(o,$C);if("error"in e)throw e.error;return e.result}case"none":{const e=qx(o,GC);if("error"in e)throw e.error;return e.result}default:{const e=qx(o,WC);if("error"in e)throw e.error;return e.result}}}catch(s){throw new K_(s,"failed to get block")}}async getBlockProduction(e){let t,r;if("string"==typeof e)r=e;else if(e){const{commitment:n,...i}=e;r=n,t=i}const n=this._buildArgs([],r,"base64",t),i=qx(await this._rpcRequest("getBlockProduction",n),zS);if("error"in i)throw new K_(i.error,"failed to get block production information");return i.result}async getTransaction(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgsAtLeastConfirmed([e],r,void 0,n),o=qx(await this._rpcRequest("getTransaction",i),KC);if("error"in o)throw new K_(o.error,"failed to get transaction");const s=o.result;return s?{...s,transaction:{...s.transaction,message:IS(s.version,s.transaction.message)}}:s}async getParsedTransaction(e,t){const{commitment:r,config:n}=bS(t),i=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n),o=qx(await this._rpcRequest("getTransaction",i),ZC);if("error"in o)throw new K_(o.error,"failed to get transaction");return o.result}async getParsedTransactions(e,t){const{commitment:r,config:n}=bS(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",n)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=qx(e,ZC);if("error"in t)throw new K_(t.error,"failed to get transactions");return t.result})}async getTransactions(e,t){const{commitment:r,config:n}=bS(t),i=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],r,void 0,n)}));return(await this._rpcBatchRequest(i)).map(e=>{const t=qx(e,KC);if("error"in t)throw new K_(t.error,"failed to get transactions");const r=t.result;return r?{...r,transaction:{...r.transaction,message:IS(r.version,r.transaction.message)}}:r})}async getConfirmedBlock(e,t){const r=this._buildArgsAtLeastConfirmed([e],t),n=qx(await this._rpcRequest("getBlock",r),VC);if("error"in n)throw new K_(n.error,"failed to get confirmed block");const i=n.result;if(!i)throw new Error("Confirmed block "+e+" not found");const o={...i,transactions:i.transactions.map(({transaction:e,meta:t})=>{const r=new D_(e.message);return{meta:t,transaction:{...e,message:r}}})};return{...o,transactions:o.transactions.map(({transaction:e,meta:t})=>({meta:t,transaction:$_.populate(e.message,e.signatures)}))}}async getBlocks(e,t,r){const n=this._buildArgsAtLeastConfirmed(void 0!==t?[e,t]:[e],r),i=qx(await this._rpcRequest("getBlocks",n),_S(Vx(Jx())));if("error"in i)throw new K_(i.error,"failed to get blocks");return i.result}async getBlockSignatures(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),n=qx(await this._rpcRequest("getBlock",r),HC);if("error"in n)throw new K_(n.error,"failed to get block");const i=n.result;if(!i)throw new Error("Block "+e+" not found");return i}async getConfirmedBlockSignatures(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,void 0,{transactionDetails:"signatures",rewards:!1}),n=qx(await this._rpcRequest("getBlock",r),HC);if("error"in n)throw new K_(n.error,"failed to get confirmed block");const i=n.result;if(!i)throw new Error("Confirmed block "+e+" not found");return i}async getConfirmedTransaction(e,t){const r=this._buildArgsAtLeastConfirmed([e],t),n=qx(await this._rpcRequest("getTransaction",r),KC);if("error"in n)throw new K_(n.error,"failed to get transaction");const i=n.result;if(!i)return i;const o=new D_(i.transaction.message),s=i.transaction.signatures;return{...i,transaction:$_.populate(o,s)}}async getParsedConfirmedTransaction(e,t){const r=this._buildArgsAtLeastConfirmed([e],t,"jsonParsed"),n=qx(await this._rpcRequest("getTransaction",r),ZC);if("error"in n)throw new K_(n.error,"failed to get confirmed transaction");return n.result}async getParsedConfirmedTransactions(e,t){const r=e.map(e=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([e],t,"jsonParsed")}));return(await this._rpcBatchRequest(r)).map(e=>{const t=qx(e,ZC);if("error"in t)throw new K_(t.error,"failed to get confirmed transactions");return t.result})}async getConfirmedSignaturesForAddress(e,t,r){let n={},i=await this.getFirstAvailableBlock();for(;!("until"in n)&&!(--t<=0||t<i);)try{const e=await this.getConfirmedBlockSignatures(t,"finalized");e.signatures.length>0&&(n.until=e.signatures[e.signatures.length-1].toString())}catch(EE){if(EE instanceof Error&&EE.message.includes("skipped"))continue;throw EE}let o=await this.getSlot("finalized");for(;!("before"in n||++r>o);)try{const e=await this.getConfirmedBlockSignatures(r);e.signatures.length>0&&(n.before=e.signatures[e.signatures.length-1].toString())}catch(EE){if(EE instanceof Error&&EE.message.includes("skipped"))continue;throw EE}return(await this.getConfirmedSignaturesForAddress2(e,n)).map(e=>e.signature)}async getConfirmedSignaturesForAddress2(e,t,r){const n=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,t),i=qx(await this._rpcRequest("getConfirmedSignaturesForAddress2",n),cC);if("error"in i)throw new K_(i.error,"failed to get confirmed signatures for address");return i.result}async getSignaturesForAddress(e,t,r){const n=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,t),i=qx(await this._rpcRequest("getSignaturesForAddress",n),lC);if("error"in i)throw new K_(i.error,"failed to get signatures for address");return i.result}async getAddressLookupTable(e,t){const{context:r,value:n}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==n&&(i=new pS({key:e,state:pS.deserialize(n.data)})),{context:r,value:i}}async getNonceAndContext(e,t){const{context:r,value:n}=await this.getAccountInfoAndContext(e,t);let i=null;return null!==n&&(i=eS.fromAccountData(n.data)),{context:r,value:i}}async getNonce(e,t){return await this.getNonceAndContext(e,t).then(e=>e.value).catch(t=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+t)})}async requestAirdrop(e,t){const r=qx(await this._rpcRequest("requestAirdrop",[e.toBase58(),t]),eI);if("error"in r)throw new K_(r.error,`airdrop to ${e.toBase58()} failed`);return r.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Z_(100);const e=Date.now()-this._blockhashInfo.lastFetch>=3e4;if(null!==this._blockhashInfo.latestBlockhash&&!e)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),t=this._blockhashInfo.latestBlockhash,r=t?t.blockhash:null;for(let n=0;n<50;n++){const e=await this.getLatestBlockhash("finalized");if(r!==e.blockhash)return this._blockhashInfo={latestBlockhash:e,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},e;await Z_(200)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:t,config:r}=bS(e),n=this._buildArgs([],t,"base64",r),i=qx(await this._rpcRequest("getStakeMinimumDelegation",n),SS(Jx()));if("error"in i)throw new K_(i.error,"failed to get stake minimum delegation");return i.result}async simulateTransaction(e,t,r){if("message"in e){const n=e.serialize(),i=lv.Buffer.from(n).toString("base64");if(Array.isArray(t)||void 0!==r)throw new Error("Invalid arguments");const o=t||{};o.encoding="base64","commitment"in o||(o.commitment=this.commitment),t&&"object"==typeof t&&"innerInstructions"in t&&(o.innerInstructions=t.innerInstructions);const s=[i,o],a=qx(await this._rpcRequest("simulateTransaction",s),FS);if("error"in a)throw new Error("failed to simulate transaction: "+a.error.message);return a.result}let n;if(e instanceof $_){let t=e;n=new $_,n.feePayer=t.feePayer,n.instructions=e.instructions,n.nonceInfo=t.nonceInfo,n.signatures=t.signatures}else n=$_.populate(e),n._message=n._json=void 0;if(void 0!==t&&!Array.isArray(t))throw new Error("Invalid arguments");const i=t;if(n.nonceInfo&&i)n.sign(...i);else{let e=this._disableBlockhashCaching;for(;;){const t=await this._blockhashWithExpiryBlockHeight(e);if(n.lastValidBlockHeight=t.lastValidBlockHeight,n.recentBlockhash=t.blockhash,!i)break;if(n.sign(...i),!n.signature)throw new Error("!signature");const r=n.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(r)&&!this._blockhashInfo.transactionSignatures.includes(r)){this._blockhashInfo.simulatedSignatures.push(r);break}e=!0}}const o=n._compile(),s=o.serialize(),a=n._serialize(s).toString("base64"),c={encoding:"base64",commitment:this.commitment};if(r){const e=(Array.isArray(r)?r:o.nonProgramIds()).map(e=>e.toBase58());c.accounts={encoding:"base64",addresses:e}}i&&(c.sigVerify=!0),t&&"object"==typeof t&&"innerInstructions"in t&&(c.innerInstructions=t.innerInstructions);const l=[a,c],u=qx(await this._rpcRequest("simulateTransaction",l),FS);if("error"in u){let e;if("data"in u.error&&(e=u.error.data.logs,e&&Array.isArray(e))){const t="\n ",r=t+e.join(t);console.error(u.error.message,r)}throw new H_({action:"simulate",signature:"",transactionMessage:u.error.message,logs:e})}return u.result}async sendTransaction(e,t,r){if("version"in e){if(t&&Array.isArray(t))throw new Error("Invalid arguments");const r=e.serialize();return await this.sendRawTransaction(r,t)}if(void 0===t||!Array.isArray(t))throw new Error("Invalid arguments");const n=t;if(e.nonceInfo)e.sign(...n);else{let t=this._disableBlockhashCaching;for(;;){const r=await this._blockhashWithExpiryBlockHeight(t);if(e.lastValidBlockHeight=r.lastValidBlockHeight,e.recentBlockhash=r.blockhash,e.sign(...n),!e.signature)throw new Error("!signature");const i=e.signature.toString("base64");if(!this._blockhashInfo.transactionSignatures.includes(i)){this._blockhashInfo.transactionSignatures.push(i);break}t=!0}}const i=e.serialize();return await this.sendRawTransaction(i,r)}async sendRawTransaction(e,t){const r=y_(e).toString("base64");return await this.sendEncodedTransaction(r,t)}async sendEncodedTransaction(e,t){const r={encoding:"base64"},n=t&&t.skipPreflight,i=!0===n?"processed":t&&t.preflightCommitment||this.commitment;t&&null!=t.maxRetries&&(r.maxRetries=t.maxRetries),t&&null!=t.minContextSlot&&(r.minContextSlot=t.minContextSlot),n&&(r.skipPreflight=n),i&&(r.preflightCommitment=i);const o=[e,r],s=qx(await this._rpcRequest("sendTransaction",o),tI);if("error"in s){let e;throw"data"in s.error&&(e=s.error.data.logs),new H_({action:n?"send":"simulate",signature:"",transactionMessage:s.error.message,logs:e})}return s.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch{}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),1e3!==e?(this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([e,t])=>{this._setSubscription(e,{...t,state:"pending"})})):this._updateSubscriptions()}_setSubscription(e,t){var r;const n=null==(r=this._subscriptionsByHash[e])?void 0:r.state;if(this._subscriptionsByHash[e]=t,n!==t.state){const r=this._subscriptionStateChangeCallbacksByHash[e];r&&r.forEach(e=>{try{e(t.state)}catch{}})}}_onSubscriptionStateChange(e,t){var r;const n=this._subscriptionHashByClientSubscriptionId[e];if(null==n)return()=>{};const i=(r=this._subscriptionStateChangeCallbacksByHash)[n]||(r[n]=new Set);return i.add(t),()=>{i.delete(t),0===i.size&&delete this._subscriptionStateChangeCallbacksByHash[n]}}async _updateSubscriptions(){if(0===Object.keys(this._subscriptionsByHash).length)return void(this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(EE){Error}},500)));if(null!==this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected)return void this._rpcWebSocket.connect();const e=this._rpcWebSocketGeneration,t=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async e=>{const r=this._subscriptionsByHash[e];if(void 0!==r)switch(r.state){case"pending":case"unsubscribed":if(0===r.callbacks.size)return delete this._subscriptionsByHash[e],"unsubscribed"===r.state&&delete this._subscriptionCallbacksByServerSubscriptionId[r.serverSubscriptionId],void(await this._updateSubscriptions());await(async()=>{const{args:n,method:i}=r;try{this._setSubscription(e,{...r,state:"subscribing"});const t=await this._rpcWebSocket.call(i,n);this._setSubscription(e,{...r,serverSubscriptionId:t,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[t]=r.callbacks,await this._updateSubscriptions()}catch(o){if(console.error(`Received ${o instanceof Error?"":"JSON-RPC "}error calling \`${i}\``,{args:n,error:o}),!t())return;this._setSubscription(e,{...r,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":0===r.callbacks.size&&await(async()=>{const{serverSubscriptionId:n,unsubscribeMethod:i}=r;if(this._subscriptionsAutoDisposedByRpc.has(n))this._subscriptionsAutoDisposedByRpc.delete(n);else{this._setSubscription(e,{...r,state:"unsubscribing"}),this._setSubscription(e,{...r,state:"unsubscribing"});try{await this._rpcWebSocket.call(i,[n])}catch(o){if(o instanceof Error&&console.error(`${i} error:`,o.message),!t())return;return this._setSubscription(e,{...r,state:"subscribed"}),void(await this._updateSubscriptions())}}this._setSubscription(e,{...r,state:"unsubscribed"}),await this._updateSubscriptions()})()}}))}_handleServerNotification(e,t){const r=this._subscriptionCallbacksByServerSubscriptionId[e];void 0!==r&&r.forEach(e=>{try{e(...t)}catch(r){console.error(r)}})}_wsOnAccountNotification(e){const{result:t,subscription:r}=qx(e,uC);this._handleServerNotification(r,[t.value,t.context])}_makeSubscription(e,t){const r=this._nextClientSubscriptionId++,n=cS([e.method,t]),i=this._subscriptionsByHash[n];return void 0===i?this._subscriptionsByHash[n]={...e,args:t,callbacks:new Set([e.callback]),state:"pending"}:i.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[r]=n,this._subscriptionDisposeFunctionsByClientSubscriptionId[r]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[r],delete this._subscriptionHashByClientSubscriptionId[r];const t=this._subscriptionsByHash[n];O_(void 0!==t,`Could not find a \`Subscription\` when tearing down client subscription #${r}`),t.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),r}onAccountChange(e,t,r){const{commitment:n,config:i}=bS(r),o=this._buildArgs([e.toBase58()],n||this._commitment||"finalized","base64",i);return this._makeSubscription({callback:t,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},o)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:t,subscription:r}=qx(e,dC);this._handleServerNotification(r,[{accountId:t.value.pubkey,accountInfo:t.value.account},t.context])}onProgramAccountChange(e,t,r,n){const{commitment:i,config:o}=bS(r),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o||(n?{filters:wS(n)}:void 0));return this._makeSubscription({callback:t,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},s)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,t,r){const n=this._buildArgs(["object"==typeof e?{mentions:[e.toString()]}:e],r||this._commitment||"finalized");return this._makeSubscription({callback:t,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},n)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:t,subscription:r}=qx(e,nI);this._handleServerNotification(r,[t.value,t.context])}_wsOnSlotNotification(e){const{result:t,subscription:r}=qx(e,fC);this._handleServerNotification(r,[t])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:t,subscription:r}=qx(e,gC);this._handleServerNotification(r,[t])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,t){const r=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];r?await r():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${t}' events could not be found.`)}_buildArgs(e,t,r,n){const i=t||this._commitment;if(i||r||n){let t={};r&&(t.encoding=r),i&&(t.commitment=i),n&&(t=Object.assign(t,n)),e.push(t)}return e}_buildArgsAtLeastConfirmed(e,t,r,n){const i=t||this._commitment;if(i&&!["confirmed","finalized"].includes(i))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,t,r,n)}_wsOnSignatureNotification(e){const{result:t,subscription:r}=qx(e,yC);"receivedSignature"!==t.value&&this._subscriptionsAutoDisposedByRpc.add(r),this._handleServerNotification(r,"receivedSignature"===t.value?[{type:"received"},t.context]:[{type:"status",result:t.value},t.context])}onSignature(e,t,r){const n=this._buildArgs([e],r||this._commitment||"finalized"),i=this._makeSubscription({callback:(e,r)=>{if("status"===e.type){t(e.result,r);try{this.removeSignatureListener(i)}catch(n){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},n);return i}onSignatureWithOptions(e,t,r){const{commitment:n,...i}={...r,commitment:r&&r.commitment||this._commitment||"finalized"},o=this._buildArgs([e],n,void 0,i),s=this._makeSubscription({callback:(e,r)=>{t(e,r);try{this.removeSignatureListener(s)}catch(n){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},o);return s}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:t,subscription:r}=qx(e,vC);this._handleServerNotification(r,[t])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}var sI;Object.freeze({CreateLookupTable:{index:0,layout:kx([bx("instruction"),tS("recentSlot"),yx("bumpSeed")])},FreezeLookupTable:{index:1,layout:kx([bx("instruction")])},ExtendLookupTable:{index:2,layout:kx([bx("instruction"),tS(),_x(M_(),gx(bx(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:kx([bx("instruction")])},CloseLookupTable:{index:4,layout:kx([bx("instruction")])}}),new __("AddressLookupTab1e1111111111111111111111111"),Object.freeze({RequestUnits:{index:0,layout:kx([yx("instruction"),bx("units"),bx("additionalFee")])},RequestHeapFrame:{index:1,layout:kx([yx("instruction"),bx("bytes")])},SetComputeUnitLimit:{index:2,layout:kx([yx("instruction"),bx("units")])},SetComputeUnitPrice:{index:3,layout:kx([yx("instruction"),tS("microLamports")])}}),new __("ComputeBudget111111111111111111111111111111"),kx([yx("numSignatures"),yx("padding"),vx("signatureOffset"),vx("signatureInstructionIndex"),vx("publicKeyOffset"),vx("publicKeyInstructionIndex"),vx("messageDataOffset"),vx("messageDataSize"),vx("messageInstructionIndex")]),new __("Ed25519SigVerify111111111111111111111111111"),f_.utils.isValidPrivateKey,kx([yx("numSignatures"),vx("signatureOffset"),yx("signatureInstructionIndex"),vx("ethAddressOffset"),yx("ethAddressInstructionIndex"),vx("messageDataOffset"),vx("messageDataSize"),yx("messageInstructionIndex"),Sx(20,"ethAddress"),Sx(64,"signature"),yx("recoveryId")]),new __("KeccakSecp256k11111111111111111111111111111"),new __("StakeConfig11111111111111111111111111111111");class aI{constructor(e,t,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=t,this.custodian=r}}sI=aI,aI.default=new sI(0,0,__.default),Object.freeze({Initialize:{index:0,layout:kx([bx("instruction"),((e="authorized")=>kx([M_("staker"),M_("withdrawer")],e))(),((e="lockup")=>kx([xx("unixTimestamp"),xx("epoch"),M_("custodian")],e))()])},Authorize:{index:1,layout:kx([bx("instruction"),M_("newAuthorized"),bx("stakeAuthorizationType")])},Delegate:{index:2,layout:kx([bx("instruction")])},Split:{index:3,layout:kx([bx("instruction"),xx("lamports")])},Withdraw:{index:4,layout:kx([bx("instruction"),xx("lamports")])},Deactivate:{index:5,layout:kx([bx("instruction")])},Merge:{index:7,layout:kx([bx("instruction")])},AuthorizeWithSeed:{index:8,layout:kx([bx("instruction"),M_("newAuthorized"),bx("stakeAuthorizationType"),N_("authoritySeed"),M_("authorityOwner")])}}),new __("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:kx([bx("instruction"),((e="voteInit")=>kx([M_("nodePubkey"),M_("authorizedVoter"),M_("authorizedWithdrawer"),yx("commission")],e))()])},Authorize:{index:1,layout:kx([bx("instruction"),M_("newAuthorized"),bx("voteAuthorizationType")])},Withdraw:{index:3,layout:kx([bx("instruction"),xx("lamports")])},UpdateValidatorIdentity:{index:4,layout:kx([bx("instruction")])},AuthorizeWithSeed:{index:10,layout:kx([bx("instruction"),((e="voteAuthorizeWithSeedArgs")=>kx([bx("voteAuthorizationType"),M_("currentAuthorityDerivedKeyOwnerPubkey"),N_("currentAuthorityDerivedKeySeed"),M_("newAuthorized")],e))()])}}),new __("Vote111111111111111111111111111111111111111"),new __("Va1idator1nfo111111111111111111111111111111"),rk({name:ek(),website:Xx(ek()),details:Xx(ek()),iconUrl:Xx(ek()),keybaseUsername:Xx(ek())}),new __("Vote111111111111111111111111111111111111111"),kx([M_("nodePubkey"),M_("authorizedWithdrawer"),yx("commission"),wx(),_x(kx([wx("slot"),bx("confirmationCount")]),gx(bx(),-8),"votes"),yx("rootSlotValid"),wx("rootSlot"),wx(),_x(kx([wx("epoch"),M_("authorizedVoter")]),gx(bx(),-8),"authorizedVoters"),kx([_x(kx([M_("authorizedPubkey"),wx("epochOfLastAuthorizedSwitch"),wx("targetEpoch")]),32,"buf"),wx("idx"),yx("isEmpty")],"priorVoters"),wx(),_x(kx([wx("epoch"),wx("credits"),wx("prevCredits")]),gx(bx(),-8),"epochCredits"),kx([wx("slot"),wx("timestamp")],"lastTimestamp")]);const cI=1e9,lI=Object.freeze(Object.defineProperty({__proto__:null,AddressLookupTableAccount:pS,BLOCKHASH_CACHE_TIMEOUT_MS:3e4,Connection:oI,EpochSchedule:uS,FeeCalculatorLayout:J_,LAMPORTS_PER_SOL:cI,Lockup:aI,MAX_SEED_LENGTH:32,Message:D_,MessageAccountKeys:A_,MessageV0:F_,NONCE_ACCOUNT_LENGTH:Q_,NonceAccount:eS,PACKET_DATA_SIZE:S_,PUBLIC_KEY_LENGTH:x_,PublicKey:__,SIGNATURE_LENGTH_IN_BYTES:64,SOLANA_SCHEMA:b_,SYSTEM_INSTRUCTION_LAYOUTS:rS,SYSVAR_RECENT_BLOCKHASHES_PUBKEY:G_,SYSVAR_RENT_PUBKEY:V_,SendTransactionError:H_,SolanaJSONRPCError:K_,Struct:v_,SystemProgram:nS,Transaction:$_,TransactionExpiredBlockheightExceededError:C_,TransactionExpiredNonceInvalidError:E_,TransactionExpiredTimeoutError:I_,TransactionInstruction:W_,TransactionStatus:z_,VERSION_PREFIX_MASK:127},Symbol.toStringTag,{value:"Module"})),uI=new __("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");new __("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");const hI=new __("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");new __("So11111111111111111111111111111111111111112"),new __("9pan9bMn5HatX4EJdBwg9VgCa7Uz5HL8N1m5D3NdXejP");const dI=e=>({decode:e.decode.bind(e),encode:e.encode.bind(e)});var pI={},fI=["buffer","Buffer"];Object.defineProperty(pI,"__esModule",{value:!0});var mI=pI.toBigIntLE=function(e){{const t=fI.from(e);t.reverse();const r=t.toString("hex");return 0===r.length?BigInt(0):BigInt(`0x${r}`)}};pI.toBigIntBE=function(e){{const t=e.toString("hex");return 0===t.length?BigInt(0):BigInt(`0x${t}`)}};var gI=pI.toBufferLE=function(e,t){{const r=e.toString(16),n=fI.from(r.padStart(2*t,"0").slice(0,2*t),"hex");return n.reverse(),n}};pI.toBufferBE=function(e,t){{const r=e.toString(16);return fI.from(r.padStart(2*t,"0").slice(0,2*t),"hex")}};var yI=["buffer","Buffer"];const vI=(bI=8,e=>{const t=Sx(bI,e),{encode:r,decode:n}=dI(t),i=t;return i.decode=(e,t)=>{const r=n(e,t);return mI(yI.from(r))},i.encode=(e,t,n)=>{const i=gI(e,bI);return r(i,t,n)},i});var bI;const wI=e=>{const t=Sx(32,e),{encode:r,decode:n}=dI(t),i=t;return i.decode=(e,t)=>{const r=n(e,t);return new __(r)},i.encode=(e,t,n)=>{const i=e.toBuffer();return r(i,t,n)},i};class xI extends Error{constructor(e){super(e)}}class kI extends xI{constructor(){super(...arguments),this.name="TokenOwnerOffCurveError"}}var _I,SI;(SI=_I||(_I={}))[SI.InitializeMint=0]="InitializeMint",SI[SI.InitializeAccount=1]="InitializeAccount",SI[SI.InitializeMultisig=2]="InitializeMultisig",SI[SI.Transfer=3]="Transfer",SI[SI.Approve=4]="Approve",SI[SI.Revoke=5]="Revoke",SI[SI.SetAuthority=6]="SetAuthority",SI[SI.MintTo=7]="MintTo",SI[SI.Burn=8]="Burn",SI[SI.CloseAccount=9]="CloseAccount",SI[SI.FreezeAccount=10]="FreezeAccount",SI[SI.ThawAccount=11]="ThawAccount",SI[SI.TransferChecked=12]="TransferChecked",SI[SI.ApproveChecked=13]="ApproveChecked",SI[SI.MintToChecked=14]="MintToChecked",SI[SI.BurnChecked=15]="BurnChecked",SI[SI.InitializeAccount2=16]="InitializeAccount2",SI[SI.SyncNative=17]="SyncNative",SI[SI.InitializeAccount3=18]="InitializeAccount3",SI[SI.InitializeMultisig2=19]="InitializeMultisig2",SI[SI.InitializeMint2=20]="InitializeMint2",SI[SI.GetAccountDataSize=21]="GetAccountDataSize",SI[SI.InitializeImmutableOwner=22]="InitializeImmutableOwner",SI[SI.AmountToUiAmount=23]="AmountToUiAmount",SI[SI.UiAmountToAmount=24]="UiAmountToAmount",SI[SI.InitializeMintCloseAuthority=25]="InitializeMintCloseAuthority",SI[SI.TransferFeeExtension=26]="TransferFeeExtension",SI[SI.ConfidentialTransferExtension=27]="ConfidentialTransferExtension",SI[SI.DefaultAccountStateExtension=28]="DefaultAccountStateExtension",SI[SI.Reallocate=29]="Reallocate",SI[SI.MemoTransferExtension=30]="MemoTransferExtension",SI[SI.CreateNativeMint=31]="CreateNativeMint",SI[SI.InitializeNonTransferableMint=32]="InitializeNonTransferableMint",SI[SI.InterestBearingMintExtension=33]="InterestBearingMintExtension",SI[SI.CpiGuardExtension=34]="CpiGuardExtension",SI[SI.InitializePermanentDelegate=35]="InitializePermanentDelegate",SI[SI.TransferHookExtension=36]="TransferHookExtension",SI[SI.MetadataPointerExtension=39]="MetadataPointerExtension";async function CI(e,t,r=!1,n=uI,i=hI){if(!r&&!__.isOnCurve(t.toBuffer()))throw new kI;const[o]=await __.findProgramAddress([t.toBuffer(),n.toBuffer(),e.toBuffer()],i);return o}kx([bx("mintAuthorityOption"),wI("mintAuthority"),vI("supply"),yx("decimals"),(e=>{const t=yx(e),{encode:r,decode:n}=dI(t),i=t;return i.decode=(e,t)=>!!n(e,t),i.encode=(e,t,n)=>{const i=Number(e);return r(i,t,n)},i})("isInitialized"),bx("freezeAuthorityOption"),wI("freezeAuthority")]).span;var II=["buffer","Buffer"];function EI(e,t,r,n,i=uI,o=hI){return function(e,t,r,n,i,o=uI,s=hI){const a=[{pubkey:e,isSigner:!0,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0},{pubkey:r,isSigner:!1,isWritable:!1},{pubkey:n,isSigner:!1,isWritable:!1},{pubkey:nS.programId,isSigner:!1,isWritable:!1},{pubkey:o,isSigner:!1,isWritable:!1}];return new W_({keys:a,programId:s,data:i})}(e,t,r,n,II.from([1]),i,o)}var AI=["buffer","Buffer"];const MI=kx([yx("instruction"),vI("amount")]);function NI(e,t,r,n,i=[],o=uI){const s=function(e,t,r){if(r.length){e.push({pubkey:t,isSigner:!1,isWritable:!1});for(const t of r)e.push({pubkey:t instanceof __?t:t.publicKey,isSigner:!0,isWritable:!1})}else e.push({pubkey:t,isSigner:!0,isWritable:!1});return e}([{pubkey:e,isSigner:!1,isWritable:!0},{pubkey:t,isSigner:!1,isWritable:!0}],r,i),a=AI.alloc(MI.span);return MI.encode({instruction:_I.Transfer,amount:BigInt(n)},a),new W_({keys:s,programId:o,data:a})}var PI=["buffer","Buffer"];let BI=null;const TI=async()=>(BI||(BI=await(async e=>{const t=`global:${e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}`,r=(new TextEncoder).encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return PI.from(i.slice(0,8))})("splitPayment")),BI),OI=e=>{const t=PI.from(e,"utf-8"),r=PI.alloc(4);return r.writeUInt32LE(t.length,0),PI.concat([r,t])},RI=e=>{const t=PI.alloc(8);return t.writeBigUInt64LE(BigInt(e),0),t},LI=e=>{const t=PI.alloc(2);return t.writeUInt16LE(e,0),t},UI=(e,t)=>{const r=(e=>{const t=e.replace(/-/g,"");return t.length>32?PI.from(t.slice(0,32),"utf-8"):PI.from(t,"utf-8")})(e),n=[PI.from("payment"),r];return __.findProgramAddressSync(n,t)},jI=(e,t,n=!0)=>{const[i,o]=r.useState(!1),[s,a]=r.useState(null),[c,l]=r.useState(null),u=r.useRef(0),h=r.useCallback(()=>{const t=Array.isArray(e)?e:[e];if(!t||0===t.length||!t[0])return null;const r=t[u.current%t.length];return new oI(r,"confirmed")},[e]);r.useCallback(()=>{const t=Array.isArray(e)?e:[e];u.current=(u.current+1)%t.length},[e]);return{isProcessing:i,txSignature:s,error:c,splitPayment:r.useCallback(async({paymentId:e,tokenMintAddress:r,amount:i,merchantWallet:s,coinleyWallet:c,merchantPercentage:u=9850,coinleyPercentage:d=150,thirdPartyWallet:p=null,thirdPartyPercentage:f=0})=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");const m=u+d+f;if(1e4!==m)throw new Error(`Percentages must sum to 10000 (100%). Got: ${m}`);o(!0),l(null),a(null);try{const l=h();if(!l)throw new Error("Solana RPC connection not available");const m=t.adapter,g=Cf(n),y=new __(g),v=new __(t.publicKey),b=new __(r),w=new __(s),x=new __(c),k=p&&f>0?new __(p):nS.programId,_=await CI(b,v,!1,uI,hI),S=await CI(b,w,!1,uI,hI),C=await CI(b,x,!1,uI,hI);let I;I=p&&f>0?await CI(b,k,!1,uI,hI):nS.programId;const E=e.replace(/-/g,""),[A]=UI(e,y),M=await(async(e,t,r,n,i)=>{const o=await TI();return PI.concat([o,OI(e),RI(t),LI(r),LI(n),LI(i)])})(E,i,u,d,f),N=new W_({programId:y,keys:[{pubkey:v,isSigner:!0,isWritable:!0},{pubkey:b,isSigner:!1,isWritable:!1},{pubkey:_,isSigner:!1,isWritable:!0},{pubkey:w,isSigner:!1,isWritable:!1},{pubkey:S,isSigner:!1,isWritable:!0},{pubkey:x,isSigner:!1,isWritable:!1},{pubkey:C,isSigner:!1,isWritable:!0},{pubkey:k,isSigner:!1,isWritable:!1},{pubkey:I,isSigner:!1,isWritable:!1},{pubkey:A,isSigner:!1,isWritable:!0},{pubkey:uI,isSigner:!1,isWritable:!1},{pubkey:nS.programId,isSigner:!1,isWritable:!1}],data:M}),P=new $_;P.add(EI(v,S,w,b)),P.add(EI(v,C,x,b)),P.add(N);const{blockhash:B,lastValidBlockHeight:T}=await l.getLatestBlockhash();P.recentBlockhash=B,P.feePayer=v;const O=await m.signTransaction(P),R=await l.sendRawTransaction(O.serialize()),L=await l.confirmTransaction({signature:R,blockhash:B,lastValidBlockHeight:T});if(L.value.err)throw new Error("Transaction failed: "+JSON.stringify(L.value.err));return a(R),o(!1),{signature:R,paymentRecordPda:A.toBase58(),success:!0}}catch(EE){console.error("Solana PaymentSplitter error:",EE);let t=EE.message||"Payment split failed";throw t.includes("insufficient")?t="Insufficient balance for payment":t.includes("User rejected")?t="Transaction was rejected by user":t.includes("already in use")?t="Payment ID already used. Please try again.":t.includes("Account not found")&&(t="Token account not found. Recipient needs to have received this token before."),l(t),o(!1),new Error(t)}},[t,h,n]),getPaymentRecord:r.useCallback(async e=>{try{const t=h();if(!t)return null;const r=Cf(n),i=new __(r),[o]=UI(e,i),s=await t.getAccountInfo(o);return s?{exists:!0,address:o.toBase58(),data:s.data}:null}catch(EE){return console.error("Error fetching payment record:",EE),null}},[h,n]),findPaymentRecordPDA:e=>{const t=Cf(n),r=new __(t),[i]=UI(e,r);return i.toBase58()}}},DI=({options:e=[],value:n,onChange:i,placeholder:o,renderOption:s,getOptionKey:a,getOptionValue:c,getSearchableText:u,disabled:h=!1})=>{const[d,p]=r.useState(!1),[f,m]=r.useState(""),[g,y]=r.useState({top:0,left:0,width:400,maxHeight:450}),v=r.useRef(null),b=r.useRef(null),w=e.filter(e=>(u?u(e):"").toLowerCase().includes(f.toLowerCase())),x=e.find(e=>c(e)===n),k=()=>{if(b.current){const e=window.innerWidth,t=window.innerHeight,r=Math.min(400,e-40),n=Math.min(450,t-100);y({top:t/2-n/2,left:e/2-r/2,width:r,maxHeight:n})}};r.useEffect(()=>{const e=e=>{v.current&&!v.current.contains(e.target)&&b.current&&!b.current.contains(e.target)&&(p(!1),m(""))},t=()=>{d&&k()};if(d){k();const r=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${r}px`,document.body.style.width="100%",document.addEventListener("mousedown",e),window.addEventListener("resize",t)}return()=>{if(d){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",window.scrollTo(0,-1*parseInt(e||"0"))}document.removeEventListener("mousedown",e),window.removeEventListener("resize",t)}},[d]);const _=d&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-30 transition-opacity",style:{zIndex:999998},onClick:()=>{p(!1),m("")}}),t.jsxs("div",{ref:v,className:"fixed bg-white border-2 border-gray-200 rounded-3xl shadow-2xl overflow-hidden",style:{top:g.top,left:g.left,width:g.width,maxHeight:g.maxHeight,zIndex:999999,transform:"translateZ(0)",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 0 0 1px rgba(0, 0, 0, 0.05)"},children:[t.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 bg-gradient-to-r from-[#7042D2]/10 to-purple-50",children:[t.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:o||"Select Option"}),t.jsx("button",{onClick:()=>{p(!1),m("")},className:"text-gray-500 hover:text-gray-700 transition-colors p-1 rounded-full hover:bg-gray-100",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),t.jsx("div",{className:"p-4 border-b border-gray-200 bg-gray-50",children:t.jsx("input",{type:"text",placeholder:"Search networks and tokens...",value:f,onChange:e=>m(e.target.value),className:"w-full p-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-[#7042D2]/20 focus:border-[#7042D2] text-sm",style:{fontFamily:"Bricolage Grotesque, sans-serif"},autoFocus:!0})}),t.jsx("div",{className:"overflow-y-auto custom-scrollbar",style:{maxHeight:(g.maxHeight||450)-180+"px",minHeight:"200px"},children:0===w.length?t.jsxs("div",{className:"p-8 text-gray-500 text-center",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"text-4xl mb-3",children:"๐"}),t.jsx("div",{className:"text-lg mb-2",children:"No options found"}),t.jsx("div",{className:"text-sm text-gray-400",children:"Try a different search term"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-100 text-sm text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("span",{className:"font-semibold",children:w.length})," option",1!==w.length?"s":""," available"]}),t.jsx("div",{className:"p-2",children:w.map(e=>t.jsx("button",{type:"button",onClick:()=>{i(c(e)),p(!1),m("")},className:"w-full p-4 text-left hover:bg-[#7042D2]/10 transition-all duration-200 rounded-xl mb-2 last:mb-0 "+(c(e)===n?"bg-[#7042D2]/20 text-[#7042D2] border-2 border-[#7042D2]/30":"text-gray-800 border-2 border-transparent hover:border-[#7042D2]/20"),style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:s(e)},a(e)))})]})}),t.jsx("div",{className:"p-3 bg-gradient-to-r from-gray-50 to-gray-100 border-t border-gray-200 text-center",children:t.jsx("div",{className:"text-xs text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:w.length>5?"โ๏ธ Scroll to see more options":"โจ Select your preferred option"})})]})]});return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"relative",children:t.jsx("button",{ref:b,type:"button",onClick:()=>{h||(d||k(),p(!d))},disabled:h,className:`w-full p-4 border-2 rounded-2xl bg-gradient-to-r from-white to-gray-50 text-left focus:outline-none focus:ring-3 focus:ring-[#7042D2]/20 focus:border-[#7042D2] transition-all duration-300 ease-out shadow-lg hover:shadow-xl ${h?"opacity-50 cursor-not-allowed":"hover:border-[#7042D2]/50 cursor-pointer"} ${d?"border-[#7042D2] ring-3 ring-[#7042D2]/20":"border-gray-200"}`,style:{minHeight:"60px",fontFamily:"Bricolage Grotesque, sans-serif",fontSize:"16px",fontWeight:"500"},children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("div",{className:"flex items-center space-x-3",children:x?s(x):t.jsx("span",{className:"text-gray-500",children:o})}),t.jsx("div",{className:"transform transition-transform duration-200 "+(d?"rotate-180":""),children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 text-[#7042D2]",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]})})}),"undefined"!=typeof document&&document.body&&l.createPortal(_,document.body),t.jsx("style",{children:"\n .custom-scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #7042D2 #f1f1f1;\n }\n .custom-scrollbar::-webkit-scrollbar {\n width: 12px;\n }\n .custom-scrollbar::-webkit-scrollbar-track {\n background: #f8f9fa;\n border-radius: 10px;\n margin: 4px;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb {\n background: linear-gradient(180deg, #7042D2 0%, #5b34b1 100%);\n border-radius: 10px;\n border: 2px solid #f8f9fa;\n }\n .custom-scrollbar::-webkit-scrollbar-thumb:hover {\n background: linear-gradient(180deg, #5b34b1 0%, #4c2a93 100%);\n }\n .custom-scrollbar::-webkit-scrollbar-corner {\n background: #f8f9fa;\n }\n "})]})},FI=({currentStep:e,targetStep:n,children:i,className:o="",duration:s=300})=>{const[a,c]=r.useState(e===n),[l,u]=r.useState(e===n);return r.useEffect(()=>{e===n?(u(!0),setTimeout(()=>c(!0),10)):(c(!1),setTimeout(()=>u(!1),s))},[e,n,s]),l?t.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${a?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${o}\n `,style:{transitionDuration:`${s}ms`},children:i}):null},zI=({status:e,message:n,theme:i="light",payment:o=null,transactionHash:s=null,selectedPaymentMethod:a=null,selectedNetwork:c=null,merchantName:l="Merchant",onClose:u=null})=>{const[h,d]=r.useState(!1),[p,f]=r.useState(0);r.useEffect(()=>{if("processing"===e){const e=setInterval(()=>{f(e=>e>=90?e:e+15*Math.random())},500);return()=>clearInterval(e)}},[e]);const m=async()=>{if(s)try{await navigator.clipboard.writeText(s),d(!0),setTimeout(()=>d(!1),2e3)}catch(EE){}},g=()=>{switch(e){case"processing":return t.jsxs("div",{className:"relative",children:[t.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-[#7042D2] border-blue-500/20"}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("div",{className:"w-6 h-6 bg-[#7042D2] rounded-full animate-pulse"})})]});case"success":return t.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center animate-bounce",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return t.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"processing"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Processing Payment"}),t.jsx("p",{className:"text-center text-gray-600 mb-6",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Your transaction has been sent to the blockchain and is being processed..."}),t.jsxs("div",{className:"w-full max-w-xs mb-4",children:[t.jsx("div",{className:"bg-gray-200 rounded-full h-3",children:t.jsx("div",{className:"bg-[#7042D2] h-3 rounded-full transition-all duration-500 ease-out",style:{width:`${p}%`}})}),t.jsxs("div",{className:"text-center mt-2 text-sm text-gray-500",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Processing... ",Math.round(p),"%"]})]}),t.jsxs("div",{className:"text-center space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Transaction submitted"})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-yellow-500 rounded-full animate-pulse"}),t.jsx("span",{className:"text-sm text-gray-600",children:"Confirming on blockchain..."})]}),t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx("div",{className:"w-2 h-2 bg-gray-300 rounded-full"}),t.jsx("span",{className:"text-sm text-gray-400",children:"Finalizing payment..."})]})]}),t.jsx("div",{className:"mt-6 p-3 bg-blue-50 rounded-lg border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-800 text-center",children:"Please don't close this window. This usually takes 10-30 seconds."})})]}):"success"===e?t.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[t.jsx("div",{className:"mb-6",children:g()}),t.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Payment Successful!"}),o&&a&&t.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Your payment of ",t.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[o.totalAmount||o.amount," ",a.currency]})," has been completed."]}),s&&t.jsxs("div",{className:"w-full mb-6 px-4",children:[t.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Transaction Details"}),t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100 mb-3",onClick:m,children:[t.jsx("span",{className:"font-mono text-sm text-gray-700",children:(y=s,y?y.length<=16?y:`${y.slice(0,8)}...${y.slice(-8)}`:"")}),t.jsxs("div",{className:"flex items-center",children:[h?t.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]}),(()=>{const e=((e,t)=>{if(!e||!t)return null;const r="string"==typeof t?t:t.shortName||t.name;return{ethereum:`https://etherscan.io/tx/${e}`,bsc:`https://bscscan.com/tx/${e}`,polygon:`https://polygonscan.com/tx/${e}`,arbitrum:`https://arbiscan.io/tx/${e}`,optimism:`https://optimistic.etherscan.io/tx/${e}`,avalanche:`https://snowtrace.io/tx/${e}`,celo:`https://celoscan.io/tx/${e}`,base:`https://basescan.org/tx/${e}`,solana:`https://explorer.solana.com/tx/${e}`,"solana-mainnet":`https://explorer.solana.com/tx/${e}`,"solana-devnet":`https://explorer.solana.com/tx/${e}?cluster=devnet`,"solana devnet":`https://explorer.solana.com/tx/${e}?cluster=devnet`}[null==r?void 0:r.toLowerCase()]||null})(s,c),r=(e=>{if(!e)return"Explorer";const t="string"==typeof e?e:e.shortName||e.name;return{ethereum:"Etherscan",bsc:"BscScan",polygon:"PolygonScan",arbitrum:"Arbiscan",optimism:"Optimistic Etherscan",avalanche:"SnowTrace",celo:"CeloScan",base:"BaseScan",solana:"Solana Explorer","solana-mainnet":"Solana Explorer","solana-devnet":"Solana Explorer (Devnet)","solana devnet":"Solana Explorer (Devnet)"}[null==t?void 0:t.toLowerCase()]||"Explorer"})(c);return c&&e&&t.jsxs("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 w-full p-3 rounded-lg border border-[#7042D2] bg-white hover:bg-purple-50 transition-colors group",children:[t.jsxs("span",{className:"text-sm font-medium text-[#7042D2]",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["View on ",r]}),t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-[#7042D2] group-hover:translate-x-1 transition-transform",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})]})})()]}),u&&t.jsx("button",{onClick:u,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-semibold rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Close"})]}):t.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[t.jsx("div",{className:"mb-4",children:g()}),t.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),t.jsx("p",{className:"text-center text-gray-600",children:n})]});var y},qI={bitcoin:1,ethereum:1027,bsc:1839,polygon:3890,cardano:2010,avalanche:5805,fantom:3513,arbitrum:11841,optimism:11840,USDT:825,USDC:3408,BUSD:4687,DAI:4943,FRAX:6952,TUSD:2563,USDP:5992,USDD:5994,FDUSD:26081,PYUSD:28295,WBTC:3717,LINK:1975,UNI:7083,AAVE:7278,COMP:5692,YFI:5864,MKR:1518,SUSHI:6758,CRV:6538,SNX:2586,UMA:5617,BAL:5728,MANA:1966,SAND:6210,APE:18876,LDO:8e3,GRT:6719,ENS:13855,RPL:2943,SHIB:5994,MATIC:3890,BNB:1839,ADA:2010,SOL:5426,DOT:6636,AVAX:5805,TRX:1958,ALGO:4030,FTM:3513,ARB:11841,OP:11840,"1INCH":8104,DYDX:11156,ICP:8916,FIL:2280,CAKE:7186,RUNE:4157,ALPHA:7232,BNT:1727,KNC:1982,ZRX:1896,REN:2539,LRC:1934,WETH:2396,WMATIC:3890,WBNB:1839,UST:7129,USTC:7129,LUSD:8115,MIM:9681,FEI:8642,TRIBE:8741,RAI:8525,SUSD:2927},WI={ethereum:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bsc:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",polygon:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arbitrum:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avalanche:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",celo:"https://s2.coinmarketcap.com/static/img/coins/64x64/5567.png",optimism:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",base:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",eth:"https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png",bnb:"https://s2.coinmarketcap.com/static/img/coins/64x64/1839.png",trx:"https://s2.coinmarketcap.com/static/img/coins/64x64/1958.png",algo:"https://s2.coinmarketcap.com/static/img/coins/64x64/4030.png",matic:"https://s2.coinmarketcap.com/static/img/coins/64x64/28321.png",arb:"https://s2.coinmarketcap.com/static/img/coins/64x64/11841.png",avax:"https://s2.coinmarketcap.com/static/img/coins/64x64/5805.png",op:"https://s2.coinmarketcap.com/static/img/coins/64x64/11840.png",sol:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png",solana:"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png","solana-mainnet":"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png","solana-devnet":"https://s2.coinmarketcap.com/static/img/coins/64x64/5426.png"},$I={metamask:"https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg",coinbase:"https://avatars.githubusercontent.com/u/18060234?s=280&v=4",rabby:"https://rabby.io/logo-128.png",zerion:"https://app.zerion.io/favicon-32x32.png",okx:"https://static.okx.com/cdn/assets/imgs/248/58E63FEA47A2B7D7.png",binance:"https://bin.bnbstatic.com/static/images/common/favicon.ico",cryptocom:"https://crypto.com/favicon.ico","1inch":"https://1inch.io/favicon.svg",hot:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiNGRjZBNkEiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmg0djhoLTR2LTJoMnYtNGgtMnYtMnptNiAwaDJ2MmgtdjdoLTJ2LTIiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg==",phantom:"https://phantom.app/img/phantom-logo.svg",solflare:"https://solflare.com/assets/logo.svg",backpack:"https://www.backpack.exchange/_next/image?url=%2Fbackpack-logo.png&w=128&q=75",trust:"https://trustwallet.com/assets/images/favicon.png",default:"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTQiIGZpbGw9IiM2MzY2RjEiIHN0cm9rZT0iI0Y5RkFGQiIgc3Ryb2tlLXdpZHRoPSIyIi8+CjxwYXRoIGQ9Ik0xMCAxMmgxMnY4SDEweiIgZmlsbD0ibm9uZSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHJ4PSIxIi8+CjxjaXJjbGUgY3g9IjE4IiBjeT0iMTYiIHI9IjEiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPg=="},GI=e=>(e=>{if(!e)return null;const t=qI[e.toUpperCase()];return t?`https://s2.coinmarketcap.com/static/img/coins/64x64/${t}.png`:null})(e),VI=(e,t)=>{const r=e.toLowerCase(),n=t.toLowerCase();for(const[i,o]of Object.entries($I))if(r.includes(i)||n.includes(i))return o;return $I.default},HI=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),KI=e=>{switch(e){case"trust":return window.ethereum&&!0===window.ethereum.isTrust;case"metaMask":return window.ethereum&&!0===window.ethereum.isMetaMask;case"injected":return window.ethereum&&!window.ethereum.isMetaMask&&!window.ethereum.isCoinbaseWallet;default:return!1}},ZI=(e,t)=>{if(!t)return[];if(!["ethereum","bsc","polygon","arbitrum","optimism","avalanche","celo","base"].includes(t.shortName))return[];return[...(e||[]).map(e=>(e=>({type:e.id,name:e.name,icon:VI(e.name,e.id),description:`Connect using ${e.name}`,isInstalled:!0,connector:e,isWagmi:!0}))(e)),...HI()?[{type:"trust",name:"Trust Wallet",icon:"๐ก๏ธ",description:"Multi-chain wallet with transaction deep links",isInstalled:!1,connector:null,isWagmi:!1,mobileOnly:!0,hasTransactionDeepLinks:!0}]:[]]},YI=(e,t,r,n,i="metamask",o=null)=>{if(!e)return null;try{const t="https://paymentscreen.vercel.app",n=new URLSearchParams,o=(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId);if(!o)return null;n.set("paymentId",o),n.set("preferredWallet",i),n.set("isMobile","true");const s=`${t}?${n.toString()}`;let a;switch(i){case"metamask":a=`https://metamask.app.link/dapp/${s.replace("https://","")}`;break;case"trust":const e=(null==r?void 0:r.chainId)||1;a=`https://link.trustwallet.com/open_url?coin_id=${(e=>{const t="string"==typeof e&&e.startsWith("0x")?parseInt(e,16):parseInt(e);return[1,56,137,42161,10,43114,42220,8453].includes(t)?60:{}[t]||60})(e)}&url=${encodeURIComponent(s)}`;break;case"coinbase":a=`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(s)}`;break;default:a=s}return a}catch(vu){return null}},JI=(e,t)=>{if(!t)return null;try{switch(e){case"metamask":return t.includes("metamask.app.link")?t:`https://metamask.app.link/dapp/${t.replace("https://","")}`;case"trust":return t.includes("link.trustwallet.com")?t:`https://link.trustwallet.com/open_url?coin_id=60&url=${encodeURIComponent(t)}`;case"coinbase":return t.includes("go.cb-w.com")?t:`https://go.cb-w.com/dapp?cb_url=${encodeURIComponent(t)}`;default:return t}}catch(vu){return t}},XI=Object.freeze(Object.defineProperty({__proto__:null,generateMobilePaymentDeepLink:JI,generateQRPaymentURI:YI},Symbol.toStringTag,{value:"Module"})),QI=({walletAddress:e,amount:n,currency:i,network:o,theme:s="light",paymentData:a=null,onPaymentDetected:c=null,config:l=null,selectedToken:h=null,selectedNetwork:d=null,preferredWallet:p="metamask",compact:f=!1})=>{const[m,g]=r.useState(""),[y,v]=r.useState(""),[b,w]=r.useState(!0),[x,k]=r.useState(!1),[_,S]=r.useState(!1),C=r.useRef(null);return r.useEffect(()=>{(async()=>{if(null==a?void 0:a.id){w(!0);try{if(!h||!h.contractAddress)throw new Error("Cannot generate QR code: Token contract address required");if(!d||!d.chainId)throw new Error("Cannot generate QR code: Network chain ID required");const e=YI(a,0,d,0,p);if(e.includes("metamask.app.link")||e.includes("link.trustwallet.com")||e.includes("go.cb-w.com"),!e)throw new Error("Failed to generate Coinley payment URL");g(e);const t=HI(),r=await u.toDataURL(e,{width:f?140:t?350:280,margin:2,errorCorrectionLevel:"M",color:{dark:"dark"===s?"#FFFFFF":"#000000",light:"dark"===s?"#000000":"#FFFFFF"}});v(r),w(!1)}catch(vu){w(!1)}}else w(!1)})()},[a,n,i,o,s,h,d,l,p]),r.useEffect(()=>()=>{C.current&&clearInterval(C.current)},[]),t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex gap-3 items-start w-full mb-2",children:[t.jsx("div",{className:"p-1.5 rounded-lg bg-white shadow-sm border flex-shrink-0",children:b?t.jsx("div",{className:"flex items-center justify-center",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-b-2 border-purple-600 mx-auto mb-1"}),t.jsx("div",{className:"text-xs text-gray-600",children:"Generating..."})]})}):y?t.jsx("img",{src:y,alt:"Payment QR Code",className:"rounded-lg",style:{width:140,height:140}}):t.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:140,height:140},children:t.jsxs("div",{className:"text-center p-2",children:[t.jsx("div",{className:"text-lg mb-1",children:"โ ๏ธ"}),t.jsx("div",{className:"text-xs text-gray-600",children:(null==a?void 0:a.id)?"QR Failed":"Payment not created"})]})})}),t.jsxs("div",{className:"flex-1 flex flex-col justify-center",children:[t.jsxs("div",{className:"p-2 bg-gray-50 rounded-lg mb-2",children:[t.jsxs("div",{className:"flex justify-between items-center mb-1",children:[t.jsx("span",{className:"text-xs font-medium text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"text-sm font-bold text-[#7042D2]",children:[n," ",i]})]}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),t.jsx("span",{className:"text-xs font-medium text-gray-700",children:o})]})]}),_?t.jsxs("div",{className:"flex items-center justify-center text-xs font-semibold text-green-600 p-1.5 bg-green-50 rounded-lg",children:[t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3.5 w-3.5 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Payment Received!"]}):t.jsx("div",{className:"p-1.5 rounded-lg bg-blue-50 border border-blue-200",children:t.jsx("p",{className:"text-xs text-blue-700 text-center leading-tight",children:"๐ฑ Scan with phone camera"})})]})]})})},eE=({selectedNetwork:e,onWalletSelect:i,onConnect:o,connectedWallet:s,loading:a,paymentData:c=null,selectedToken:l=null,api:u=null,onSolanaConnect:h=null,solanaWallet:d=null})=>{const[p,f]=r.useState(null),m=r.useMemo(()=>e?Pf(e.type||e.shortName||e.id):If,[e])===Ef,{connectors:g}=n.useConnect(),{isConnected:y,address:v}=n.useAccount(),b=r.useMemo(()=>m?d.availableWallets.map(e=>({type:e.id,name:e.name,icon:VI(e.name,e.id)||"๐",description:e.adapter?"Available":"Not installed",isSolana:!0,wallet:e})):ZI(g,e),[m,d.availableWallets,g,e]),w=async(t,r)=>{if(HI())if(c)try{const{generateQRPaymentURI:n,generateMobilePaymentDeepLink:i}=await Promise.resolve().then(()=>XI),o=n(c,l,e,(null==u?void 0:u.config)||{},r);if(!o)throw new Error("Failed to generate payment URL");const s=i(r,o);if(!s)throw new Error(`Failed to generate ${t.name} deep link`);window.location.href=s}catch(vu){alert(`Failed to open ${t.name}: ${vu.message}`)}else alert("Please create a payment first before selecting a mobile wallet.");else alert(`Please install ${t.name} mobile app or use the browser extension if available.`)};return e?0===b.length?t.jsxs("div",{className:"text-center p-4",children:[t.jsxs("p",{className:"text-gray-500 mb-4",children:["No compatible wallets found for ",e.name]}),t.jsx("div",{className:"p-3 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-sm text-amber-800",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:[t.jsx("div",{className:"font-medium mb-2",children:"Install a compatible wallet:"}),t.jsx("div",{className:"space-y-1 text-xs",children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:["โข ",t.jsx("a",{href:xf.PHANTOM.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Phantom Wallet"})]}),t.jsxs("div",{children:["โข ",t.jsx("a",{href:xf.SOLFLARE.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Solflare Wallet"})]}),t.jsxs("div",{children:["โข ",t.jsx("a",{href:xf.BACKPACK.downloadUrl,target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Backpack Wallet"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:["โข ",t.jsx("a",{href:"https://metamask.io/download/",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install MetaMask Wallet"})]}),t.jsxs("div",{children:["โข ",t.jsx("a",{href:"https://www.coinbase.com/wallet",target:"_blank",rel:"noopener noreferrer",className:"text-amber-700 underline hover:text-amber-900",children:"Install Coinbase Wallet"})]})]})})]})})]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:["Select Wallet for ",e.name]}),t.jsx(DI,{options:b,value:(null==s?void 0:s.walletType)||p||"",onChange:async e=>{f(e);const t=b.find(t=>t.type===e);if(t){if(i(e),t.isSolana){try{const t=await d.connectWallet(e);h&&await h({walletType:e,publicKey:t,wallet:d})}catch(vu){console.error("Failed to connect Solana wallet:",vu),alert(`Failed to connect: ${vu.message}`)}return}t.isWagmi&&t.connector?await o(t.connector):t.isWagmi||await w(t,e)}},placeholder:"Choose your wallet...",renderOption:e=>{var r,n,i,o,c,l,u;return t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsxs("div",{className:"w-8 h-8 flex items-center justify-center",children:[e.icon.startsWith("http")||e.icon.startsWith("data:")?t.jsx("img",{src:e.icon,alt:e.name,className:"w-6 h-6 rounded-full object-contain",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="block"}}):t.jsx("div",{className:"text-2xl",children:e.icon}),t.jsx("div",{className:"text-xl",style:{display:"none"},children:"๐"})]}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800 flex items-center",children:[e.name,!e.isSolana&&KI(e.type)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),e.isSolana&&(null==(r=e.wallet)?void 0:r.adapter)&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full",children:"DETECTED"}),e.isSolana&&(null==(n=d.connectedWallet)?void 0:n.id)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"}),!e.isSolana&&(null==s?void 0:s.walletType)===e.type&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full",children:"CONNECTED"})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.isSolana&&(null==(i=d.connectedWallet)?void 0:i.id)===e.type?`Connected โข ${null==(o=d.publicKey)?void 0:o.slice(0,6)}...${null==(c=d.publicKey)?void 0:c.slice(-4)}`:(null==s?void 0:s.walletType)===e.type?`Connected โข ${null==(l=s.account)?void 0:l.slice(0,6)}...${null==(u=s.account)?void 0:u.slice(-4)}`:e.description})]}),a&&p===e.type&&t.jsx("div",{className:"animate-spin rounded-full h-5 w-5 border-b-2 border-[#7042D2]"})]})},getOptionKey:e=>e.type,getOptionValue:e=>e.type,getSearchableText:e=>`${e.name} ${e.description}`,disabled:a})]}):t.jsx("div",{className:"text-center p-4",children:t.jsx("p",{className:"text-gray-500",children:"Please select a network first"})})},tE=(()=>{if("undefined"!=typeof process&&process.env)return!1;if("undefined"!=typeof window){const e=window.location.hostname;return"localhost"===e||"127.0.0.1"===e||e.includes("192.168.")}return!1})()||(()=>{if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search);return"true"===e.get("debug")||"true"===e.get("debugMode")}return!1})(),rE=({paymentData:e,selectedToken:n,selectedNetwork:i,config:o,onPaymentStarted:s=()=>{},onError:a=()=>{}})=>{var c,l;const[u,h]=r.useState(null),[d,p]=r.useState(!1),[f,m]=r.useState([]),[g,y]=r.useState(!1),[v,b]=r.useState(0);r.useEffect(()=>{var t,r,o;(null==e?void 0:e.id)&&(null==n?void 0:n.contractAddress)&&(null==i?void 0:i.chainId)&&((null==(t=null==e?void 0:e.contractCall)?void 0:t.contractAddress)||(null==e?void 0:e.contractAddress))?w("success","โ
Payment data complete",{paymentId:e.id,tokenContract:n.contractAddress,chainId:i.chainId,paymentContract:(null==(o=null==e?void 0:e.contractCall)?void 0:o.contractAddress)||(null==e?void 0:e.contractAddress)}):(w("debug","โณ Waiting for complete payment data",{hasPaymentId:!!(null==e?void 0:e.id),hasTokenContract:!!(null==n?void 0:n.contractAddress),hasChainId:!!(null==i?void 0:i.chainId),hasPaymentContract:!(!(null==(r=null==e?void 0:e.contractCall)?void 0:r.contractAddress)&&!(null==e?void 0:e.contractAddress)),checkCount:v}),b(e=>e+1))},[e,n,i,v]);const w=(e,t,r=null)=>{const n=(new Date).toLocaleTimeString(),i={id:Date.now()+Math.random(),type:e,message:t,data:r,timestamp:n};tE&&(m(e=>[...e,i].slice(-20)),e.toUpperCase())},x=[{id:"metamask",name:"MetaMask",icon:"๐ฆ",description:"Connect with MetaMask mobile"},{id:"trust",name:"Trust Wallet",icon:"๐ก๏ธ",description:"Connect with Trust Wallet"},{id:"coinbase",name:"Coinbase Wallet",icon:"๐",description:"Connect with Coinbase Wallet"}];if(!e)return t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"โ ๏ธ Payment Required"}),t.jsx("div",{className:"text-sm text-amber-700",children:"Please create a payment before selecting a wallet"})]})});const k=(null==e?void 0:e.id)&&(null==n?void 0:n.contractAddress)&&(null==i?void 0:i.chainId)&&((null==(c=null==e?void 0:e.contractCall)?void 0:c.contractAddress)||(null==e?void 0:e.contractAddress));return t.jsx("div",{className:"space-y-4",children:k?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:"Bricolage Grotesque, sans-serif"},children:"Select Mobile Wallet"}),t.jsx(DI,{options:x,value:u||"",onChange:async t=>{const r=x.find(e=>e.id===t);if(r){h(t),p(!0);try{if(w("info",`๐ Mobile wallet selected: ${r.name}`),!e)throw new Error("Payment data not available. Please create payment first.");w("debug","๐ Payment Data Check",{hasPaymentData:!!e,hasSelectedToken:!!n,hasSelectedNetwork:!!i,hasConfig:!!o,paymentId:(null==e?void 0:e.id)||(null==e?void 0:e.splitterPaymentId),tokenAddress:null==n?void 0:n.contractAddress,networkChainId:null==i?void 0:i.chainId,amount:(null==e?void 0:e.totalAmount)||(null==e?void 0:e.amount)||(null==o?void 0:o.amount)});const a=YI(e,0,i,0,t);if(!a)throw new Error("Failed to generate payment URL");w("success","๐ฑ Generated payment URL",{url:a,length:a.length});const c=JI(t,a);if(!c)throw new Error(`Failed to generate ${r.name} deep link`);w("success",`๐ Deep link generated for ${r.name}`,{deepLink:c}),s({walletType:t,walletName:r.name,paymentUrl:a,deepLink:c}),setTimeout(()=>{w("info",`๐ฑ Opening ${r.name}...`),window.location.href=c},500)}catch(vu){w("error","โ Mobile wallet connection failed",{error:vu.message,walletId:t,hasPaymentData:!!e,hasSelectedToken:!!n,hasSelectedNetwork:!!i}),a(vu.message),p(!1),h(null)}}},placeholder:"Choose your wallet...",renderOption:e=>t.jsxs("div",{className:"flex items-center space-x-3",children:[t.jsx("div",{className:"w-8 h-8 flex items-center justify-center",children:t.jsx("div",{className:"text-2xl",children:e.icon})}),t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name,u===e.id&&d&&t.jsx("span",{className:"ml-2 px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full animate-pulse",children:"Opening..."})]}),t.jsx("div",{className:"text-sm text-gray-500",children:e.description})]})]}),getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.description}`,disabled:d}),t.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"Select a wallet to open it with your payment details"})]}),d&&u&&t.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg animate-pulse",children:t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-blue-600 border-t-transparent"}),t.jsxs("div",{className:"text-sm text-blue-700",children:["Opening ",null==(l=x.find(e=>e.id===u))?void 0:l.name,"..."]})]})}),t.jsxs("div",{className:"p-3 bg-gray-50 rounded-lg",children:[t.jsxs("div",{className:"flex justify-between items-center text-sm",children:[t.jsx("span",{className:"text-gray-600",children:"Amount:"}),t.jsxs("span",{className:"font-semibold text-gray-800",children:[e.totalAmount," ",(null==n?void 0:n.symbol)||"USDC"]})]}),t.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[t.jsx("span",{className:"text-gray-600",children:"Network:"}),t.jsx("span",{className:"text-gray-800",children:(null==i?void 0:i.name)||"Ethereum"})]})]}),t.jsx("div",{className:"p-3 bg-purple-50 border border-purple-200 rounded-lg",children:t.jsxs("div",{className:"text-xs text-purple-700",children:[t.jsx("div",{className:"font-medium mb-1",children:"๐ฑ Mobile Payment"}),t.jsx("div",{children:"Your selected wallet app will open with payment details pre-filled"})]})}),tE&&t.jsxs("div",{className:"mt-4",children:[t.jsxs("button",{onClick:()=>y(!g),className:"w-full text-xs py-2 px-3 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors",children:[g?"๐ฝ Hide Debug Info":"๐ง Show Debug Info"," (",f.length," logs)"]}),g&&t.jsxs("div",{className:"mt-2 p-3 bg-gray-900 text-green-400 rounded-lg text-xs font-mono max-h-80 overflow-y-auto",children:[t.jsx("div",{className:"text-white mb-2 font-bold",children:"๐ฑ Mobile Debug Panel"}),0===f.length?t.jsx("div",{className:"text-gray-400",children:"No debug logs yet. Try selecting a wallet..."}):f.map(e=>t.jsxs("div",{className:"mb-3 pb-2 border-b border-gray-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("span",{className:"px-2 py-1 rounded text-xs font-bold "+("error"===e.type?"bg-red-600 text-white":"success"===e.type?"bg-green-600 text-white":"debug"===e.type?"bg-blue-600 text-white":"bg-gray-600 text-white"),children:e.type.toUpperCase()}),t.jsx("span",{className:"text-gray-400",children:e.timestamp})]}),t.jsx("div",{className:"text-yellow-300 mb-1",children:e.message}),e.data&&t.jsx("div",{className:"text-gray-300 text-xs",children:t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer text-blue-300 hover:text-blue-200",children:"๐ Data"}),t.jsx("pre",{className:"mt-1 p-2 bg-gray-800 rounded overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(e.data,null,2)})]})})]},e.id)),t.jsx("button",{onClick:()=>m([]),className:"mt-2 px-3 py-1 bg-red-600 text-white rounded text-xs hover:bg-red-700",children:"Clear Logs"})]})]})]}):t.jsx("div",{className:"p-4 bg-amber-50 rounded-lg border border-amber-200",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-amber-800 font-medium mb-2",children:"โณ Preparing Payment..."}),t.jsx("div",{className:"text-sm text-amber-700",children:"Payment is being prepared. Please wait a moment..."}),t.jsx("div",{className:"mt-3",children:t.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-amber-600 border-t-transparent mx-auto"})})]})})})},nE=({error:e,onRetry:r,onDismiss:n,context:i="payment",className:o=""})=>{if(!e)return null;const s=tv(e),a=(e=>{switch(e){case"user_rejected":return"info";case"insufficient_funds":case"wrong_network":case"wallet_disconnected":case"payment_pending":return"warning";case"network_error":case"gas_error":case"rate_limited":return"error";default:return"critical"}})(s.type),c=(e=>{switch(e){case"user_rejected":default:return"Try Again";case"insufficient_funds":return"Add Funds & Retry";case"wrong_network":return"Switch Network & Retry";case"wallet_disconnected":return"Reconnect Wallet";case"payment_pending":return"Check Again";case"network_error":case"rate_limited":return"Retry";case"popup_blocked":return"Allow Popups & Retry";case"mobile_wallet_error":return"Open Wallet App"}})(s.type),l={info:{container:"bg-blue-50 border-blue-200",title:"text-blue-800",message:"text-blue-700",icon:"โน๏ธ",button:"bg-blue-600 hover:bg-blue-700"},warning:{container:"bg-amber-50 border-amber-200",title:"text-amber-800",message:"text-amber-700",icon:"โ ๏ธ",button:"bg-amber-600 hover:bg-amber-700"},error:{container:"bg-red-50 border-red-200",title:"text-red-800",message:"text-red-700",icon:"โ",button:"bg-red-600 hover:bg-red-700"},critical:{container:"bg-red-50 border-red-300",title:"text-red-900",message:"text-red-800",icon:"๐จ",button:"bg-red-700 hover:bg-red-800"}},u=l[a]||l.error;return t.jsxs("div",{className:`p-4 border rounded-lg ${u.container} ${o}`,children:[t.jsxs("div",{className:"flex items-start space-x-3",children:[t.jsx("div",{className:"flex-shrink-0 text-xl",children:u.icon}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:`font-semibold ${u.title} mb-1`,children:s.title}),t.jsx("div",{className:`text-sm ${u.message} mb-2`,children:s.message}),s.suggestion&&t.jsxs("div",{className:`text-xs ${u.message} opacity-90`,children:["๐ก ",s.suggestion]})]}),n&&t.jsx("button",{onClick:n,className:"flex-shrink-0 text-gray-400 hover:text-gray-600 transition-colors","aria-label":"Dismiss error",children:t.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 20 20",children:t.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})})]}),r&&t.jsxs("div",{className:"mt-3 flex justify-end space-x-2",children:[n&&"info"===a&&t.jsx("button",{onClick:n,className:"px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 transition-colors",children:"Cancel"}),t.jsx("button",{onClick:r,className:`px-4 py-2 text-sm font-medium text-white rounded-md transition-colors ${u.button}`,children:c})]}),!1]})},iE="method",oE="confirm",sE="processing",aE="success",cE="wallet",lE="qr",uE="Bricolage Grotesque, sans-serif",hE=new i.QueryClient,dE=({publicKey:e,apiKey:i,apiSecret:s,apiUrl:a,config:c,onSuccess:l,onError:u,onClose:h,isOpen:d,theme:p="light"})=>{const f=((e,t,n)=>{const[i,o]=r.useState("method"),[s,a]=r.useState([]),[c,l]=r.useState([]),[u,h]=r.useState(null),[d,p]=r.useState(null),[f,m]=r.useState(null),[g,y]=r.useState(null),[v,b]=r.useState(!1),[w,x]=r.useState(""),[k,_]=r.useState(!1),[S,C]=r.useState("Processing transaction..."),[I,E]=r.useState("wallet"),[A,M]=r.useState(null),N=r.useRef(new ff(e,t,n));return{currentStep:i,networks:s,tokens:c,selectedNetwork:u,selectedToken:d,paymentMethod:f,paymentData:g,loading:v,error:w,processing:k,processingMessage:S,paymentType:I,actualTransactionHash:A,setCurrentStep:o,setSelectedNetwork:h,setSelectedToken:p,setPaymentMethod:m,setError:x,setProcessing:_,setProcessingMessage:C,setPaymentType:E,setActualTransactionHash:M,loadData:async()=>{var e,t;try{b(!0),x("");const[r,n]=await Promise.all([N.current.getNetworks(),N.current.getTokens()]),i=(null==(e=r.networks)?void 0:e.reduce((e,t)=>{if("tron"===t.shortName||"algorand"===t.shortName)return e;const r="solana"===t.shortName||"solana"===t.chainType;if(!(r||t.chainId&&null!==t.chainId))return e;const n=r?`solana-${t.shortName}`:`${t.chainId}-${t.shortName}`;return e.some(e=>("solana"===e.shortName||"solana"===e.chainType?`solana-${e.shortName}`:`${e.chainId}-${e.shortName}`)===n)||e.push(t),e},[]))||[],o=(null==(t=n.stablecoins)?void 0:t.reduce((e,t)=>{var r,n,i;if(!["USDC","USDT","SOL"].includes(t.symbol))return e;if("tron"===(null==(r=t.Network)?void 0:r.shortName)||"algorand"===(null==(n=t.Network)?void 0:n.shortName))return e;const o=`${t.symbol}-${(null==(i=t.Network)?void 0:i.shortName)||t.networkId}`;return e.some(e=>{var t;return`${e.symbol}-${(null==(t=e.Network)?void 0:t.shortName)||e.networkId}`===o})||e.push(t),e},[]))||[];a(i),l(o)}catch(EE){x("Failed to load payment options. Using fallback data.")}finally{b(!1)}},createPayment:async e=>{var t;try{b(!0),x("");const r={amount:e.amount,currency:d.symbol,network:u.shortName,customerEmail:e.customerEmail,callbackUrl:e.callbackUrl,metadata:{...e.metadata,merchantWalletAddresses:e.merchantWalletAddresses,paymentMethod:f,selectedNetwork:u.shortName,selectedToken:d.symbol,wagmiEnabled:!0}},n=await N.current.createPayment(r);y(n.payment),lf.trackPaymentCreated(null==(t=n.payment)?void 0:t.id,e.amount,u.shortName,d.symbol),o("confirm")}catch(EE){x(EE.message),lf.trackError("payment_creation_failed",EE.message,{amount:e.amount,network:null==u?void 0:u.shortName,token:null==d?void 0:d.symbol})}finally{b(!1)}},failPayment:async(e="Payment cancelled by user")=>{if(null==g?void 0:g.id)try{await N.current.failPayment(g.id,e)}catch(t){}},resetState:()=>{o("method"),h(null),p(null),m(null),y(null),x(""),_(!1),M(null),E("wallet")},resetTransactionState:()=>{x(""),_(!1),M(null),o("confirm")},api:N.current}})(a,e||i,e?null:s),m=(()=>{const[e,t]=r.useState(null),[i,s]=r.useState(null),[a,c]=r.useState(""),{connect:l,connectors:u}=n.useConnect(),{isConnected:h,address:d,chain:p}=n.useAccount(),{switchChain:f}=n.useSwitchChain();return r.useEffect(()=>{s(h&&d?{account:d,chainId:null==p?void 0:p.id,walletType:e}:null)},[h,d,p,e]),{selectedWalletType:e,connectedWallet:i,connectionError:a,isConnected:h,address:d,chain:p,connectors:u,handleWalletSelection:e=>{t(e),c("")},connectWallet:async(e,t=null)=>{var r,n,i;if(!e)return c("Please select a wallet first"),!1;try{if(c(""),await l({connector:e}),t){const a=Nf(t.shortName),l=(null==(r=e.name)?void 0:r.toLowerCase())||"",u=l.includes("zerion")||l.includes("trust")||l.includes("rabby")?5e3:500;await new Promise(e=>setTimeout(e,u));const h=o.getAccount(pf).chainId;if(a&&h!==a)try{await f({chainId:a}),await new Promise(e=>setTimeout(e,1e3))}catch(s){return 4001===s.code||(null==(n=s.message)?void 0:n.includes("User rejected"))?c("Network switch was cancelled by user"):(null==(i=s.message)?void 0:i.includes("Unrecognized chain ID"))?c(`${t.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${t.name}. Please switch manually in your wallet.`),!1}}return!0}catch(EE){return 4001===EE.code||EE.message.includes("User rejected")||EE.message.includes("rejected")?c("User cancelled the connection request"):c(`Failed to connect to ${e.name}. Please try again.`),!1}},disconnectWallet:()=>{s(null),t(null),c("")},switchChain:f,ensureCorrectNetwork:async e=>{var t,r;if(!e)return!0;try{const i=Nf(e.shortName),s=o.getAccount(pf).chainId;if(i&&s!==i)try{return await f({chainId:i}),await new Promise(e=>setTimeout(e,1e3)),!0}catch(n){return 4001===n.code||(null==(t=n.message)?void 0:t.includes("User rejected"))?c("Network switch was cancelled. Please switch to the correct network in your wallet."):(null==(r=n.message)?void 0:r.includes("Unrecognized chain ID"))?c(`${e.name} network is not added to your wallet. Please add it manually.`):c(`Failed to switch to ${e.name}. Please switch manually in your wallet.`),!1}return!0}catch(U){return c("Failed to verify network. Please check your wallet connection."),!1}},clearError:()=>{c("")},setSelectedWalletType:t,connect:l}})(),g=(()=>{const[e,t]=r.useState(null),[n,i]=r.useState(null),[o,s]=r.useState(!1),[a,c]=r.useState(null),[l,u]=r.useState([]);r.useEffect(()=>{var e,t,r,n,i;const o=[];"undefined"!=typeof window&&(null==(e=window.solana)?void 0:e.isPhantom)&&o.push({...xf.PHANTOM,adapter:window.solana}),"undefined"!=typeof window&&(null==(t=window.solflare)?void 0:t.isSolflare)&&o.push({...xf.SOLFLARE,adapter:window.solflare}),"undefined"!=typeof window&&(null==(r=window.backpack)?void 0:r.isBackpack)&&o.push({...xf.BACKPACK,adapter:window.backpack}),"undefined"!=typeof window&&(null==(n=window.trustwallet)?void 0:n.solana)&&o.push({...xf.TRUST_WALLET,adapter:window.trustwallet.solana}),"undefined"!=typeof window&&(null==(i=window.magicEden)?void 0:i.solana)&&o.push({...xf.MAGIC_EDEN,adapter:window.magicEden.solana}),u(o)},[]);const h=r.useCallback(()=>{t(null),i(null)},[]),d=r.useCallback(e=>{if(e){const r=e.toString();i(r),t(e=>e?{...e,publicKey:r}:null)}else h()},[h]),p=r.useCallback(async e=>{s(!0),c(null);try{const r=l.find(t=>t.id===e);if(!r)throw new Error(`Wallet ${e} not found. Please install it first.`);const n=r.adapter,o=await n.connect(),s=(null==o?void 0:o.publicKey)||n.publicKey;if(!s)throw new Error("Failed to get wallet public key");const a=s.toString();return t({id:e,name:r.name,adapter:n,publicKey:a}),i(a),n.on&&(n.on("disconnect",h),n.on("accountChanged",d)),s.toString()}catch(EE){console.error("โ Error connecting to Solana wallet:",EE);let t=EE.message||"Failed to connect wallet";throw(4001===EE.code||t.includes("User rejected"))&&(t="Connection request was rejected"),c(t),new Error(t)}finally{s(!1)}},[l,h,d]),f=r.useCallback(async()=>{if(null==e?void 0:e.adapter)try{e.adapter.removeListener&&(e.adapter.removeListener("disconnect",h),e.adapter.removeListener("accountChanged",d)),await e.adapter.disconnect()}catch(EE){console.error("Error disconnecting wallet:",EE)}t(null),i(null)},[e,h,d]),m=r.useCallback(e=>l.some(t=>t.id===e),[l]),g=r.useCallback(e=>{const t=Object.values(xf).find(t=>t.id===e);if(!t)return null;const r=/Android|iPhone|iPad|iPod/i.test(navigator.userAgent),n=/iPhone|iPad|iPod/i.test(navigator.userAgent),i=/Android/i.test(navigator.userAgent);if(r){if(n&&t.installUrl.ios)return t.installUrl.ios;if(i&&t.installUrl.android)return t.installUrl.android}return t.installUrl.chrome||t.downloadUrl},[]),y=r.useCallback(async(e,t=1e9)=>{if(!n)throw new Error("Wallet not connected");try{const{PublicKey:r}=await Promise.resolve().then(()=>lI),i=new r(n),o=await e.requestAirdrop(i,t);return await e.confirmTransaction(o),o}catch(EE){throw console.error("โ Airdrop failed:",EE),EE}},[n]);return{connectedWallet:e,publicKey:n,address:n,isConnecting:o,error:a,availableWallets:l,connectWallet:p,disconnectWallet:f,isWalletInstalled:m,getInstallUrl:g,requestAirdrop:y,isConnected:!!e&&!!n}})(),y=r.useMemo(()=>f.selectedNetwork?Pf(f.selectedNetwork.type||f.selectedNetwork.shortName||f.selectedNetwork.id):If,[f.selectedNetwork])===Ef,v=r.useMemo(()=>!(!y||!f.selectedNetwork)&&(e=>{if(!e)return!1;const t=!0===e.isTestnet||"true"===e.isTestnet,r=(e.name||"").toLowerCase().includes("devnet"),n=(e.shortName||"").toLowerCase().includes("devnet"),i=(e.type||"").toLowerCase().includes("devnet"),o="103"===e.chainId||103===e.chainId,s=(e.id||"").toLowerCase().includes("devnet");return t||r||n||i||o||s})(f.selectedNetwork),[y,f.selectedNetwork]),b=r.useMemo(()=>{if(!y||!f.selectedNetwork)return[];return kf(v?"solana-devnet":"solana-mainnet")},[y,f.selectedNetwork,v]),w=((e,t)=>{const[n,i]=r.useState(!1),[o,s]=r.useState(null),[a,c]=r.useState(null),l=r.useRef(0),u=r.useCallback(()=>{const t=Array.isArray(e)?e:[e];if(!t||0===t.length||!t[0])return null;const r=t[l.current%t.length];return new oI(r,"confirmed")},[e]);return r.useCallback(()=>{const t=Array.isArray(e)?e:[e];l.current=(l.current+1)%t.length},[e]),{isProcessing:n,txSignature:o,error:a,sendSOL:r.useCallback(async(e,r)=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const n=u();if(!n)throw new Error("Solana RPC connection not available. Please select a Solana network.");const o=t.adapter,a=Math.floor(r*cI),c=new __(t.publicKey),l=new __(e),h=(new $_).add(nS.transfer({fromPubkey:c,toPubkey:l,lamports:a})),{blockhash:d,lastValidBlockHeight:p}=await n.getLatestBlockhash();h.recentBlockhash=d,h.feePayer=c;const f=await o.signTransaction(h),m=await n.sendRawTransaction(f.serialize()),g=await n.confirmTransaction({signature:m,blockhash:d,lastValidBlockHeight:p});if(g.value.err)throw new Error("Transaction failed: "+JSON.stringify(g.value.err));return s(m),i(!1),{signature:m,success:!0}}catch(EE){throw console.error("โ SOL transaction failed:",EE),c(EE.message||"Transaction failed"),i(!1),EE}},[t,u]),sendSPLToken:r.useCallback(async(e,r,n,o)=>{if(!(null==t?void 0:t.adapter)||!t.publicKey)throw new Error("Wallet not connected");i(!0),c(null),s(null);try{const a=u();if(!a)throw new Error("Solana RPC connection not available. Please select a Solana network.");const c=t.adapter,l=Math.floor(n*Math.pow(10,o)),h=new __(t.publicKey),d=new __(r),p=new __(e),f=await CI(p,h,!1,uI,hI),m=await CI(p,d,!1,uI,hI),g=(new $_).add(NI(f,m,h,l,[],uI)),{blockhash:y,lastValidBlockHeight:v}=await a.getLatestBlockhash();g.recentBlockhash=y,g.feePayer=h;const b=await c.signTransaction(g),w=await a.sendRawTransaction(b.serialize()),x=await a.confirmTransaction({signature:w,blockhash:y,lastValidBlockHeight:v});if(x.value.err)throw new Error("Transaction failed: "+JSON.stringify(x.value.err));return s(w),i(!1),{signature:w,success:!0}}catch(EE){console.error("โ SPL Token transaction failed:",EE);let t=EE.message||"Transaction failed";throw t.includes("Account not found")?t="Recipient token account not found. They need to have received this token before.":t.includes("insufficient")?t="Insufficient balance":t.includes("User rejected")&&(t="Transaction was rejected"),c(t),i(!1),new Error(t)}},[t,u]),getSOLBalance:r.useCallback(async e=>{try{const r=u();if(!r)return console.warn("โ ๏ธ Cannot fetch SOL balance: RPC connection not available"),0;const n=new __(e||t.publicKey);return await r.getBalance(n)/cI}catch(EE){return console.error("Error getting SOL balance:",EE),0}},[t,u]),getSPLTokenBalance:r.useCallback(async(e,r)=>{try{const n=u();if(!n)return console.warn("โ ๏ธ Cannot fetch SPL token balance: RPC connection not available"),0;const i=new __(r||t.publicKey),o=new __(e),s=await CI(o,i,!1,uI,hI),a=await n.getTokenAccountBalance(s);return parseFloat(a.value.uiAmount||0)}catch(EE){return console.error("Error getting SPL token balance:",EE),0}},[t,u]),estimateFee:r.useCallback(async()=>{try{const e=u();return e?(await e.getRecentBlockhash(),5e-6):5e-6}catch(EE){return console.error("Error estimating fee:",EE),5e-6}},[u]),connection:u()}})(b,g.connectedWallet),x=jI(b,g.connectedWallet,v),[k,_]=r.useState("metamask"),[S,C]=r.useState(!1),[I,E]=r.useState(()=>!("undefined"==typeof window||!window.sessionStorage)&&"true"===sessionStorage.getItem("coinley_mobile_payment_started")),[A,M]=r.useState(!1);r.useEffect(()=>{C(HI())},[]);const{currentStep:N,networks:P,tokens:B,selectedNetwork:T,selectedToken:O,paymentData:R,loading:L,error:U,paymentType:j,loadData:D,createPayment:F,failPayment:z,resetState:q,setSelectedNetwork:W,setSelectedToken:$,setPaymentType:G,setCurrentStep:V,setError:H}=f,{connectedWallet:K,address:Z,connectWallet:Y,handleWalletSelection:J}=m,X=ov(R,O,T,Z,f.api,m),{executePaymentTransaction:Q,processFinalPayment:ee,transactionStep:te,transactionError:re,currentTransactionHash:ne}=X;r.useEffect(()=>{N===aE&&"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.removeItem("coinley_mobile_payment_started")},[N]),r.useEffect(()=>{if(d){D(),q(),lf.trackModalOpened(null==c?void 0:c.merchantName,null==c?void 0:c.amount);const e=window.scrollY;document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%",document.body.style.overflow="hidden"}else{const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}return()=>{if(d){const e=document.body.style.top;document.body.style.position="",document.body.style.top="",document.body.style.width="",document.body.style.overflow="",window.scrollTo(0,-1*parseInt(e||"0"))}}},[d]),r.useEffect(()=>{if("processing"===te||"approve"===te||"splitPayment"===te){const e=setTimeout(()=>{H("Transaction timed out. Please try again."),V(oE),X.resetTransaction()},12e4);return()=>clearTimeout(e)}},[te]);const ie=async()=>{lf.trackModalClosed("user_cancelled"),await z(),h()};return d?t.jsxs("div",{className:"fixed inset-0 z-50",children:[t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:ie,"aria-hidden":"true"}),t.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",style:{zIndex:51},children:t.jsxs("div",{className:"relative pt-4 w-full max-w-md max-h-[90vh] mx-auto shadow-xl bg-gray-100 rounded-3xl flex flex-col overflow-hidden",style:{zIndex:52},children:[t.jsxs("div",{className:"flex-shrink-0 bg-white flex justify-between items-center mb-3 mr-3 ml-3 py-3 px-2 rounded-full",children:[t.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[t.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center",children:t.jsx("img",{src:uf,alt:"Coinley"})}),t.jsx("span",{className:"text-base font-semibold text-gray-800",style:{fontFamily:uE},children:"Payment Details"})]}),N!==aE&&N!==sE&&t.jsx("button",{onClick:ie,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c&&N!==aE&&t.jsx("div",{className:"flex-shrink-0 mb-3 px-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"text-xs text-gray-600",children:"Total Amount"}),t.jsxs("div",{className:"text-3xl font-bold text-[#7042D2] mt-1 leading-tight tracking-tight",style:{fontFamily:uE},children:["$",(oe=c.amount,parseFloat(oe).toFixed(2))]}),t.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"No additional fees"}),t.jsx("div",{className:"text-xs text-gray-600 mt-2",children:"Payment to:"}),t.jsxs("div",{className:"text-sm font-semibold mt-0.5 flex gap-1.5 items-center justify-center",style:{fontFamily:uE},children:[t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),c.merchantName||"Merchant"]})]})}),t.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain",children:[t.jsx(FI,{currentStep:N,targetStep:iE,children:t.jsxs("div",{className:"pb-4 pt-3 px-5 bg-white rounded-t-2xl",children:[t.jsx("h3",{className:"font-semibold text-center mb-3 text-sm",style:{fontFamily:uE},children:"Choose Payment Method"}),t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:uE},children:"Select Network"}),t.jsx(DI,{options:P,value:(null==T?void 0:T.id)||"",onChange:e=>{const t=P.find(t=>t.id===e);W(t),$(null),lf.trackNetworkSelected(null==t?void 0:t.name,null==c?void 0:c.merchantName)},placeholder:"Choose your network...",renderOption:e=>{var r,n;const i="object"==typeof(o=e)&&(null==o?void 0:o.logo)?o.logo:"object"==typeof o&&(null==o?void 0:o.shortName)?WI[o.shortName.toLowerCase()]:"string"==typeof o?WI[o.toLowerCase()]:null;var o;return t.jsxs("div",{className:"flex items-center space-x-3",children:[i?t.jsx("img",{src:i,alt:e.name,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:i?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(r=e.shortName)?void 0:r.slice(0,2).toUpperCase()})}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-gray-800",children:e.name}),t.jsx("div",{className:"text-sm text-gray-500",children:null==(n=e.shortName)?void 0:n.toUpperCase()})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.shortName}`,disabled:L})]}),T&&t.jsxs("div",{className:"space-y-3 mb-4",children:[t.jsx("label",{className:"block text-sm font-medium text-gray-700",style:{fontFamily:uE},children:"Select Token"}),t.jsx(DI,{options:B.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==T?void 0:T.shortName)||e.networkId===(null==T?void 0:T.id)}),value:(null==O?void 0:O.id)||"",onChange:e=>{const t=B.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==T?void 0:T.shortName)||e.networkId===(null==T?void 0:T.id)}).find(t=>t.id===e);$(t),lf.trackTokenSelected(null==t?void 0:t.symbol,null==T?void 0:T.name,null==c?void 0:c.merchantName)},placeholder:"Choose your token...",renderOption:e=>{var r,n;const i=GI(e.symbol);return t.jsxs("div",{className:"flex items-center space-x-3",children:[i?t.jsx("img",{src:i,alt:e.symbol,className:"w-8 h-8 rounded-full",onError:e=>{e.target.style.display="none",e.target.nextSibling.style.display="flex"}}):null,t.jsx("div",{className:"w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center",style:{display:i?"none":"flex"},children:t.jsx("span",{className:"text-xs font-bold text-gray-600",children:null==(r=e.symbol)?void 0:r.slice(0,2)})}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-gray-800",children:[e.name," (",e.symbol,")"]}),t.jsxs("div",{className:"text-sm text-gray-500",children:[(null==(n=e.Network)?void 0:n.name)||"Unknown Network",e.isStablecoin&&t.jsx("span",{className:"ml-2 text-green-600",children:"โข Stablecoin"})]})]})]})},getOptionKey:e=>e.id,getOptionValue:e=>e.id,getSearchableText:e=>`${e.name} ${e.symbol}`,disabled:L})]}),T&&O&&t.jsx("button",{onClick:()=>F(c),disabled:L,className:"w-full bg-[#7042D2] text-white py-4 px-4 rounded-xl hover:bg-[#5b34b1] disabled:opacity-50 font-semibold transition-all duration-200 shadow-lg hover:shadow-xl",style:{fontFamily:uE},children:L?"Creating Payment...":"Continue"})]})}),t.jsx(FI,{currentStep:N,targetStep:oE,children:T&&O&&R&&t.jsxs("div",{className:"pb-4 pt-4 px-4 bg-white rounded-t-2xl",children:[!S&&t.jsx("div",{className:"mb-4",children:t.jsxs("div",{className:"flex border-b border-gray-200",children:[t.jsx("button",{onClick:()=>G(cE),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(j===cE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:uE},children:"Connect Wallet"}),t.jsx("button",{onClick:()=>G(lE),className:"py-3 px-6 text-sm font-semibold transition-all duration-200 "+(j===lE?"border-b-2 border-[#7042D2] text-[#7042D2]":"text-gray-500 hover:text-gray-700"),style:{fontFamily:uE},children:"QR Code"})]})}),S?t.jsx(rE,{paymentData:R,selectedToken:O,selectedNetwork:T,config:c,onPaymentStarted:e=>{E(!0),"undefined"!=typeof window&&window.sessionStorage&&sessionStorage.setItem("coinley_mobile_payment_started","true"),e.walletName},onError:e=>{H(e)}}):j===cE?t.jsx(eE,{selectedNetwork:T,onWalletSelect:J,onConnect:async e=>{await Y(e,T)},connectedWallet:y?g.connectedWallet:K,loading:L,solanaWallet:g,onSolanaConnect:async({walletType:e,publicKey:t,wallet:r})=>{}}):null,j===lE&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mb-2",children:[t.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1.5 text-center",style:{fontFamily:uE},children:"Optimize QR for:"}),t.jsx("div",{className:"flex gap-1.5 justify-center flex-wrap",children:[{id:"metamask",name:"MetaMask",icon:"๐ฆ"},{id:"trust",name:"Trust",icon:"๐ก๏ธ"},{id:"coinbase",name:"Coinbase",icon:"๐"}].map(e=>t.jsxs("button",{onClick:()=>_(e.id),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 "+(k===e.id?"bg-[#7042D2] text-white shadow-md":"bg-gray-100 text-gray-700 hover:bg-gray-200"),style:{fontFamily:uE},children:[t.jsx("span",{className:"text-sm",children:e.icon}),t.jsx("span",{children:e.name})]},e.id))})]}),t.jsx(QI,{amount:(null==R?void 0:R.totalAmount)||(null==R?void 0:R.amount)||(null==c?void 0:c.amount),currency:null==O?void 0:O.symbol,network:null==T?void 0:T.shortName,theme:p,paymentData:R,config:c,selectedToken:O,selectedNetwork:T,preferredWallet:k,compact:!0})]}),(U||re)&&t.jsx("div",{className:"mt-4",children:t.jsx(nE,{error:re||U,onRetry:()=>{H(""),X.resetTransaction(),"error"===te&&K&&Q()},onDismiss:()=>{H(""),X.resetTransaction()},context:"payment"})}),t.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:()=>V(iE),className:"w-full py-2.5 px-3 bg-gray-200 hover:bg-gray-300 text-[#7042D2] font-semibold rounded-xl transition-all duration-200 text-sm",style:{fontFamily:uE},children:"Back"}),t.jsx("button",{type:"button",onClick:async()=>{var e,t,r,n,i,o,s,a,c,u,h,d,p,m,b,k;if(S&&I){if(!(null==R?void 0:R.id))return void H("Payment ID not found. Please refresh and try again.");try{M(!0),V(sE),H("");const s=await f.api.checkPaymentStatus(R.id);if("completed"===(null==(e=s.payment)?void 0:e.status))V(aE),l&&l({paymentId:R.id,transactionHash:s.payment.transactionHash,senderAddress:s.payment.senderWalletAddress||s.payment.fromAddress||Z||(null==g?void 0:g.publicKey),network:null==T?void 0:T.shortName,currency:null==O?void 0:O.symbol,paymentDetails:s.payment});else if("pending"===(null==(t=s.payment)?void 0:t.status)){const e=await f.api.verifyQRPayment(R.id);if(e.success&&e.verified)V(aE),l&&l({paymentId:R.id,transactionHash:null==(r=e.onChainData)?void 0:r.transactionHash,senderAddress:(null==(n=e.onChainData)?void 0:n.from)||(null==(i=e.payment)?void 0:i.senderWalletAddress)||Z||(null==g?void 0:g.publicKey),network:null==T?void 0:T.shortName,currency:null==O?void 0:O.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";H(`${t}. Please complete the payment in your wallet and try again.`),V(oE)}}else"failed"===(null==(o=s.payment)?void 0:o.status)?(H("Payment failed. Please try creating a new payment."),V(oE)):(H("Payment not found. Please verify the payment ID and try again."),V(oE))}catch(_){H(`Verification failed: ${_.message}. Please ensure payment was completed and try again.`),V(oE)}finally{M(!1)}}else if(j!==lE){if(y&&g.isConnected||K&&Z)try{let e;if(V(sE),H(""),y){const t=(null==R?void 0:R.recipientWallet)||(null==R?void 0:R.merchantWallet)||(null==R?void 0:R.merchantWalletAddress);if(!t)throw new Error("Merchant wallet address not found");if("SOL"===O.symbol||O.isNative){e=(await w.sendSOL(t,parseFloat(R.totalAmount||R.amount))).signature}else{const r=parseFloat(R.totalAmount||R.amount),n=O.decimals||6,i=null==(p=O.symbol)?void 0:p.toUpperCase(),o=(v?wf:bf)[i];let s=O.address||O.contractAddress;(null==o?void 0:o.address)&&(s=o.address);if(R.coinleyWallet&&R.merchantPercentage&&R.coinleyPercentage){const i=Math.floor(r*Math.pow(10,n));(r*R.merchantPercentage/1e4).toFixed(6),(r*R.coinleyPercentage/1e4).toFixed(6);e=(await x.splitPayment({paymentId:R.id,tokenMintAddress:s,amount:i,merchantWallet:t,coinleyWallet:R.coinleyWallet,merchantPercentage:R.merchantPercentage,coinleyPercentage:R.coinleyPercentage})).signature}else{e=(await w.sendSPLToken(s,t,r,n)).signature}}await f.api.processPayment(R.id,e,T.shortName,g.publicKey)}else e=await Q();e&&(H(""),X.setTransactionError(""),V(aE),l&&l({paymentId:R.id,transactionHash:e,senderAddress:y?null==g?void 0:g.publicKey:Z,network:null==T?void 0:T.shortName,currency:null==O?void 0:O.symbol,paymentDetails:R}))}catch(_){V(oE),(null==(m=_.message)?void 0:m.includes("User rejected"))||(null==(b=_.message)?void 0:b.includes("User denied"))||4001===_.code||"ACTION_REJECTED"===_.code?H("Transaction was cancelled by user. Please try again."):H(_.message||"Transaction failed. Please try again."),y?null==(k=w.resetTransaction)||k.call(w):X.resetTransaction()}}else{if(!(null==R?void 0:R.id))return void H("Payment ID not found. Please refresh and try again.");try{V(sE),H("");const e=await f.api.checkPaymentStatus(R.id);if("completed"===(null==(s=e.payment)?void 0:s.status))V(aE),l&&l({paymentId:R.id,transactionHash:e.payment.transactionHash,senderAddress:e.payment.senderWalletAddress||e.payment.fromAddress||Z||(null==g?void 0:g.publicKey),network:null==T?void 0:T.shortName,currency:null==O?void 0:O.symbol,paymentDetails:e.payment});else if("pending"===(null==(a=e.payment)?void 0:a.status)){const e=await f.api.verifyQRPayment(R.id);if(e.success&&e.verified)V(aE),l&&l({paymentId:R.id,transactionHash:null==(c=e.onChainData)?void 0:c.transactionHash,senderAddress:(null==(u=e.onChainData)?void 0:u.from)||(null==(h=e.payment)?void 0:h.senderWalletAddress)||Z||(null==g?void 0:g.publicKey),network:null==T?void 0:T.shortName,currency:null==O?void 0:O.symbol,paymentDetails:e.payment});else{const t=e.message||"Payment not yet confirmed on blockchain";H(`${t}. Please complete the payment and try again.`),V(oE)}}else"failed"===(null==(d=e.payment)?void 0:d.status)?(H("Payment failed. Please try creating a new payment."),V(oE)):(H("Payment not found. Please verify the payment ID and try again."),V(oE))}catch(_){H(`Verification failed: ${_.message}. Please ensure payment was completed and try again.`),V(oE)}}},className:"bg-green-600 text-white w-full py-2.5 px-3 font-semibold rounded-xl hover:bg-green-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 text-sm",disabled:(()=>{const e=j===cE&&!S&&!y&&!K,t=j===cE&&!S&&y&&!g.isConnected,r=S&&!I,n="processing"===te,i=w.isProcessing,o=x.isProcessing;return e||t||r||n||i||o||A})(),style:{fontFamily:uE},children:A?"Verifying...":"processing"===te||w.isProcessing||x.isProcessing?"Processing...":S&&I?"I Have Paid":S?"Select Wallet":j===lE?"I Have Paid":"Pay Now"})]})]})}),t.jsx(FI,{currentStep:N,targetStep:sE,children:t.jsx(zI,{status:"processing",message:y?x.isProcessing?"Processing payment split...":w.isProcessing?"Confirming Solana transaction...":"Processing your Solana payment...":"approve"===te?"Approving token spending...":"splitPayment"===te?"Processing payment split...":ne?"Confirming transaction on blockchain...":"Processing your payment...",theme:p,transactionHash:y?w.txSignature:ne,selectedNetwork:T})}),t.jsx(FI,{currentStep:N,targetStep:aE,children:t.jsx(zI,{status:"success",message:"Payment completed successfully!",theme:p,payment:R,transactionHash:y?w.txSignature||(null==R?void 0:R.transactionHash):ne||(null==R?void 0:R.transactionHash),selectedPaymentMethod:O,selectedNetwork:T,merchantName:(null==c?void 0:c.merchantName)||"Merchant",onClose:h})}),(U||re)&&t.jsxs("div",{className:"p-4 bg-red-50 border border-red-200 rounded-lg mx-6 mb-4",children:[t.jsx("p",{className:"text-red-800 text-sm",children:U||re}),t.jsx("button",{onClick:()=>{H(""),X.setTransactionError("")},className:"mt-2 text-red-600 hover:text-red-800 text-xs underline",children:"Dismiss"})]})]}),N!==aE&&t.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",style:{fontFamily:uE},children:[t.jsxs("p",{children:["Powered by ",t.jsx("span",{className:"text-[#7042D2] font-semibold",children:"Coinley"})," - Multi-Wallet Support"]}),t.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})]}):null;var oe},pE=e=>t.jsx(n.WagmiProvider,{config:pf,children:t.jsx(i.QueryClientProvider,{client:hE,children:t.jsx(dE,{...e})})}),fE=r.createContext(null),mE=r.forwardRef(({customerEmail:e="",merchantName:t="",onSuccess:n,onError:i,onClose:o,theme:s="light",autoOpen:a=!1,testMode:c=!1,debug:l=!1,merchantWalletAddresses:u={}},h)=>{const d=r.useContext(fE);if(!d)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:p,closePayment:f}=d,m=t=>{try{if(!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const r={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...u,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};p(r,{onSuccess:n,onError:i,onClose:o})}catch(vu){i&&i(vu)}},g=()=>{f()};return r.useImperativeHandle(h,()=>({open:m,close:g})),null});mE.displayName="CoinleyCheckout";const gE={ethereum:Hy,bsc:Uy,polygon:Yy,arbitrum:Ty,optimism:Zy,avalanche:Oy},yE=[{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],type:"function"}];const vE=new class{constructor(){this.clients=new Map}getClient(e){if(!this.clients.has(e)){const t=gE[e];if(!t)throw new Error(`Unsupported network: ${e}`);const r=c.createPublicClient({chain:t,transport:c.http()});this.clients.set(e,r)}return this.clients.get(e)}async checkNativeBalance(e,t){try{const r=this.getClient(t),n=await r.getBalance({address:e}),i=c.formatUnits(n,18);return{balance:parseFloat(i),balanceWei:n.toString(),symbol:this.getNativeTokenSymbol(t),decimals:18}}catch(vu){throw new Error(`Failed to check native balance: ${vu.message}`)}}async checkTokenBalance(e,t,r){try{const n=this.getClient(r),i=c.getContract({address:t,abi:yE,client:n}),[o,s,a]=await Promise.all([i.read.balanceOf([e]),i.read.decimals().catch(()=>18),i.read.symbol().catch(()=>"TOKEN")]);return{balance:parseFloat(c.formatUnits(o,s)),balanceWei:o.toString(),symbol:a,decimals:s,tokenAddress:t}}catch(vu){throw new Error(`Failed to check token balance: ${vu.message}`)}}async validateBalance(e,t,r,n,i=!0){try{let o,s=null;o=t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,n):await this.checkNativeBalance(e,n),t.contractAddress&&i&&(s=await this.checkNativeBalance(e,n));const a=o.balance>=r,c=a?0:r-o.balance;let l=0,u=!0,h=0;if(i)if(l=this.estimateGasFee(n,!!t.contractAddress),t.contractAddress)u=s.balance>=l,h=u?0:l-s.balance;else{const e=r+l;u=o.balance>=e,h=u?0:e-o.balance}const d={isValid:a&&u,tokenBalance:o,nativeBalance:s,requiredAmount:r,estimatedGasFee:l,hasEnoughTokens:a,hasEnoughForGas:u,tokenShortfall:c,gasShortfall:h,errors:[]};if(a||d.errors.push(`Insufficient ${t.symbol} balance. Need ${r} ${t.symbol}, have ${o.balance.toFixed(6)} ${t.symbol}`),!u){const e=(null==s?void 0:s.symbol)||this.getNativeTokenSymbol(n);t.contractAddress?d.errors.push(`Insufficient ${e} for gas fees. Need ~${l.toFixed(6)} ${e}, have ${s.balance.toFixed(6)} ${e}`):d.errors.push(`Insufficient ${e} for payment + gas. Need ${(r+l).toFixed(6)} ${e} total, have ${o.balance.toFixed(6)} ${e}`)}return d}catch(vu){return{isValid:!1,errors:[`Failed to check balance: ${vu.message}`],tokenBalance:null,nativeBalance:null}}}estimateGasFee(e,t=!1){return{ethereum:t?.001:5e-4,bsc:t?5e-4:3e-4,polygon:t?.01:.005,arbitrum:t?3e-4:2e-4,optimism:t?3e-4:2e-4,avalanche:t?.001:5e-4}[e]||.001}getNativeTokenSymbol(e){return{ethereum:"ETH",bsc:"BNB",polygon:"MATIC",arbitrum:"ETH",optimism:"ETH",avalanche:"AVAX"}[e]||"ETH"}async getBalance(e,t,r){return t.contractAddress?await this.checkTokenBalance(e,t.contractAddress,r):await this.checkNativeBalance(e,r)}formatBalance(e,t,r=6){return null==e?"Unknown":0===e?`0 ${t}`:e<.001?`${e.toFixed(8)} ${t}`:e<1?`${e.toFixed(6)} ${t}`:`${e.toFixed(4)} ${t}`}async checkMultipleBalances(e,t,r){try{const n=t.map(t=>this.getBalance(e,t,r).catch(e=>({error:e.message,symbol:t.symbol,balance:0})));return await Promise.all(n)}catch(vu){throw vu}}};class bE{constructor(e,t,r){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=r}async request(e,t={}){const r=`${this.baseURL}${e}`,n={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},i=await fetch(r,{...t,headers:n});if(!i.ok){const e=await i.json().catch(()=>({}));throw new Error(e.error||`HTTP ${i.status}`)}return i.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(vu){return{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"},{id:"137",name:"Polygon",shortName:"polygon",chainId:"0x89",type:"polygon"},{id:"42161",name:"Arbitrum",shortName:"arbitrum",chainId:"0xa4b1",type:"arbitrum"},{id:"10",name:"Optimism",shortName:"optimism",chainId:"0xa",type:"optimism"},{id:"43114",name:"Avalanche",shortName:"avalanche",chainId:"0xa86a",type:"avalanche"},{id:"42220",name:"Celo",shortName:"celo",chainId:"0xa4ec",type:"celo"},{id:"8453",name:"Base",shortName:"base",chainId:"0x2105",type:"base"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(vu){return{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"2",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E641a3FA62e50A9da1CE0647a2bFBC5A",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}},{id:"3",name:"Binance USD",symbol:"BUSD",contractAddress:"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"4",name:"USD Coin",symbol:"USDC",contractAddress:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",decimals:18,networkId:"56",Network:{shortName:"bsc",name:"BSC"}},{id:"5",name:"USD Coin",symbol:"USDC",contractAddress:"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"6",name:"Tether USD",symbol:"USDT",contractAddress:"0xc2132D05D31c914a87C6611C10748AEb04B58e8F",decimals:6,networkId:"137",Network:{shortName:"polygon",name:"Polygon"}},{id:"7",name:"Tether USD",symbol:"USDT",contractAddress:"0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"8",name:"USD Coin",symbol:"USDC",contractAddress:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,networkId:"42161",Network:{shortName:"arbitrum",name:"Arbitrum"}},{id:"9",name:"Tether USD",symbol:"USDT",contractAddress:"0x94b008aA00579c1307B0EF2c499aD98a8ce58e58",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"10",name:"USD Coin",symbol:"USDC",contractAddress:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",decimals:6,networkId:"10",Network:{shortName:"optimism",name:"Optimism"}},{id:"11",name:"Tether USD",symbol:"USDT",contractAddress:"0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"12",name:"USD Coin",symbol:"USDC",contractAddress:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",decimals:6,networkId:"43114",Network:{shortName:"avalanche",name:"Avalanche"}},{id:"13",name:"Tether USD",symbol:"USDT",contractAddress:"0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"14",name:"USD Coin",symbol:"USDC",contractAddress:"0xcebA9300f2b948710d2653dD7B07f33A8B32118C",decimals:6,networkId:"42220",Network:{shortName:"celo",name:"Celo"}},{id:"15",name:"Tether USD",symbol:"USDT",contractAddress:"0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}},{id:"16",name:"USD Coin",symbol:"USDC",contractAddress:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,networkId:"8453",Network:{shortName:"base",name:"Base"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async updatePaymentStatus(e,t,r=null){return await this.request(`/api/payments/${e}/status`,{method:"PUT",body:JSON.stringify({status:t,transactionHash:r})})}}class wE{constructor(e={}){if(!e.publicKey&&!e.apiKey)throw new Error("CoinleyVanilla: publicKey or apiKey is required");if(!e.publicKey&&!e.apiSecret)throw new Error("CoinleyVanilla: apiSecret is required when using apiKey");if(!e.apiUrl)throw new Error("CoinleyVanilla: apiUrl is required");this.config={publicKey:e.publicKey||null,apiKey:e.apiKey||null,apiSecret:e.apiSecret||null,apiUrl:e.apiUrl.replace(/\/$/,""),theme:e.theme||"light",debug:e.debug||!1,...e},this.isOpen=!1,this.root=null,this.container=null,this.callbacks={},this.currentPayment=null,this.config.debug}open(e,t={}){if(!this.isOpen)try{this._validatePaymentConfig(e),this.callbacks=t,this.currentPayment=e,this._createContainer(),this.root=d.createRoot(this.container),this.isOpen=!0,this.root.render(r.createElement(pE,{publicKey:this.config.publicKey,apiKey:this.config.apiKey,apiSecret:this.config.apiSecret,apiUrl:this.config.apiUrl,isOpen:!0,theme:this.config.theme,config:{amount:e.amount,customerEmail:e.customerEmail,merchantName:e.merchantName||"Merchant",callbackUrl:e.callbackUrl||this._getDefaultCallbackUrl(),merchantWalletAddresses:e.merchantWalletAddresses||{},preferredNetwork:e.preferredNetwork,preferredCurrency:e.preferredCurrency,metadata:{...e.metadata,source:"vanilla-sdk",sdkVersion:"2.0.0",timestamp:(new Date).toISOString()}},onSuccess:this._handleSuccess.bind(this),onError:this._handleError.bind(this),onClose:this._handleClose.bind(this)})),this.config.debug}catch(vu){t.onError&&t.onError(vu.message||"Failed to open payment modal")}}close(){this.isOpen&&(this._cleanup(),this.config.debug)}isPaymentOpen(){return this.isOpen}updateConfig(e){this.config={...this.config,...e},this.config.debug}getConfig(){return{...this.config}}getCurrentPayment(){return this.currentPayment?{...this.currentPayment}:null}_validatePaymentConfig(e){if(!e)throw new Error("Payment configuration is required");if(!e.amount||"number"!=typeof e.amount||e.amount<=0)throw new Error("Valid amount (number > 0) is required");if(!e.customerEmail||"string"!=typeof e.customerEmail)throw new Error("Customer email is required");if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e.customerEmail))throw new Error("Invalid email format");if(e.merchantWalletAddresses){if("object"!=typeof e.merchantWalletAddresses)throw new Error("merchantWalletAddresses must be an object");Object.keys(e.merchantWalletAddresses).length}}_createContainer(){this.container||(this.container=document.createElement("div"),this.container.id="coinley-payment-container",this.container.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 999999;\n ",document.body.appendChild(this.container))}_getDefaultCallbackUrl(){return"undefined"!=typeof window?`${window.location.origin}/api/webhooks/coinley`:""}_handleSuccess(e,t,r){this.config.debug,this.callbacks.onSuccess&&this.callbacks.onSuccess(e,t,r)}_handleError(e){this.config.debug,this.callbacks.onError&&this.callbacks.onError(e)}_handleClose(){this._cleanup(),this.callbacks.onClose&&this.callbacks.onClose()}_cleanup(){if(this.isOpen=!1,this.root){try{this.root.unmount()}catch(vu){}this.root=null}this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null),this.currentPayment=null}}function xE(){document.querySelectorAll('script[src*="coinley-vanilla"]').forEach(e=>{const t=e.getAttribute("data-public-key"),r=e.getAttribute("data-api-key"),n=e.getAttribute("data-api-secret"),i=e.getAttribute("data-api-url"),o=e.getAttribute("data-theme")||"light",s=e.hasAttribute("data-debug");if((t||r&&n)&&i)try{window.coinley=new wE({publicKey:t,apiKey:r,apiSecret:n,apiUrl:i,theme:o,debug:s})}catch(vu){}})}"undefined"!=typeof window&&(window.CoinleyVanilla=wE,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",xE):xE());class kE{constructor(e="https://paymentscreen.vercel.app/"){this.basePaymentUrl=e.endsWith("/")?e:e+"/"}generatePaymentURL(e){const{merchant:t,amount:r,productAmount:n,platformFee:i,networkFee:o,token:s="USDC",network:a="Ethereum Mainnet",merchantAddress:c}=e;if(!t)throw new Error("Merchant name is required");if(!r)throw new Error("Amount is required");if(!c)throw new Error("Merchant address (smart contract) is required");const l=n||.95*r,u=i||.03*r,h=o||.02*r,d=new URLSearchParams({merchant:t,amount:r.toString(),productAmount:l.toString(),platformFee:u.toString(),networkFee:h.toString(),token:s,network:a,merchantAddress:c});return this.basePaymentUrl+"?"+d.toString()}async generateQRCode(e,t={}){const{width:r=300,margin:n=2,colorDark:i="#7c3aed",colorLight:o="#ffffff"}=t;try{const t=this.generatePaymentURL(e);return{qrCodeDataURL:await u.toDataURL(t,{width:r,margin:n,color:{dark:i,light:o}}),paymentURL:t,paymentData:{...e,qrCodeUrl:t}}}catch(vu){throw new Error(`Failed to generate QR code: ${vu.message}`)}}async generateQRCodeToCanvas(e,t,r={}){const{width:n=300,margin:i=2,colorDark:o="#7c3aed",colorLight:s="#ffffff"}=r;try{const r=this.generatePaymentURL(e);return await u.toCanvas(t,r,{width:n,margin:i,color:{dark:o,light:s}}),r}catch(vu){throw new Error(`Failed to generate QR code to canvas: ${vu.message}`)}}validatePaymentData(e){const t=[],r=[];e.merchant||t.push("Merchant name is required"),(!e.amount||e.amount<=0)&&t.push("Valid amount is required"),e.merchantAddress||t.push("Merchant address (smart contract) is required"),e.merchantAddress&&!/^0x[a-fA-F0-9]{40}$/.test(e.merchantAddress)&&t.push("Invalid Ethereum address format for merchantAddress"),e.amount>1e4&&r.push("Large payment amount detected");return(e.platformFee||0)+(e.networkFee||0)>.1*e.amount&&r.push("High fees detected (>10% of total amount)"),{isValid:0===t.length,errors:t,warnings:r}}async createPaymentQR(e){const{merchantName:t,amount:r,productAmount:n,platformFee:i,networkFee:o,token:s,network:a,merchantWalletAddresses:c,selectedNetwork:l="ethereum",...u}=e,h={merchant:t||"Coinley Merchant",amount:r,productAmount:n,platformFee:i,networkFee:o,token:s||"USDC",network:a||"Ethereum Mainnet",merchantAddress:(null==c?void 0:c[l])||(null==c?void 0:c.ethereum)||(null==c?void 0:c.splitPaymentContract),...u},d=this.validatePaymentData(h);if(!d.isValid)throw new Error(`Payment validation failed: ${d.errors.join(", ")}`);return{...await this.generateQRCode(h),validation:d,instructions:{userAction:"Scan this QR code with your mobile wallet to pay",expectedFlow:"QR Scan โ Payment Screen โ Wallet Connect โ Split Payment โ Confirmation",supportedWallets:["MetaMask","Trust Wallet","Coinbase Wallet","WalletConnect compatible wallets"]}}}}const _E=new kE,SE={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,r=4)=>e?e.length<=t+r?e:`${e.slice(0,t)}...${e.slice(-r)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class CE extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const IE={react:"\nimport { CoinleyProvider, CoinleyCheckout } from 'coinley-test';\n\n// New recommended way - using publicKey only\n<CoinleyProvider\n publicKey=\"pk_your-public-key\"\n apiUrl=\"https://api.coinley.io\"\n>\n <CoinleyCheckout\n ref={checkoutRef}\n onSuccess={({ paymentId, transactionHash, senderAddress, network, currency, paymentDetails }) => {\n console.log('Payment successful!');\n console.log('Payment ID:', paymentId);\n console.log('Transaction Hash:', transactionHash);\n console.log('Sender Address:', senderAddress); // Wallet address that made the payment\n console.log('Network:', network); // e.g., 'ethereum', 'bsc', 'polygon'\n console.log('Currency:', currency); // e.g., 'USDT', 'USDC'\n console.log('Full Details:', paymentDetails);\n }}\n onError={(error) => console.error('Error:', error)}\n onClose={() => console.log('Closed')}\n />\n</CoinleyProvider>\n\n// Legacy way (still supported) - using apiKey + apiSecret\n<CoinleyProvider\n apiKey=\"your-api-key\"\n apiSecret=\"your-api-secret\"\n apiUrl=\"https://api.coinley.io\"\n>\n ...\n</CoinleyProvider>\n ",vanilla:'\n\x3c!-- Include via CDN --\x3e\n<script src="https://unpkg.com/coinley-test@latest/vanilla"><\/script>\n<link rel="stylesheet" href="https://unpkg.com/coinley-test@latest/vanilla/style.css">\n\n<script>\n// New recommended way - using publicKey only\nconst coinley = new CoinleyVanilla({\n publicKey: "pk_your-public-key",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Legacy way (still supported)\nconst coinleyLegacy = new CoinleyVanilla({\n apiKey: "your-api-key",\n apiSecret: "your-api-secret",\n apiUrl: "https://api.coinley.io",\n theme: "light"\n});\n\n// Use in checkout\ncoinley.open({\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n}, {\n onSuccess: ({ paymentId, transactionHash, senderAddress, network, currency, paymentDetails }) => {\n console.log(\'Payment successful!\');\n console.log(\'Sender Address:\', senderAddress); // Wallet that made the payment\n console.log(\'Network:\', network); // e.g., \'ethereum\', \'bsc\'\n console.log(\'Currency:\', currency); // e.g., \'USDT\', \'USDC\'\n },\n onError: (error) => console.error(\'Error:\', error),\n onClose: () => console.log(\'Closed\')\n});\n<\/script>\n '};e.CoinleyCheckout=mE,e.CoinleyError=CE,e.CoinleyProvider=({publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,theme:s="light",debug:a=!1,children:c})=>{const[l,u]=r.useState(!1),[h,d]=r.useState(null),[p,f]=r.useState({}),[m,g]=r.useState(""),y=()=>{u(!1),d(null),p.onClose&&p.onClose()},v={openPayment:(e,t)=>{d(e),t&&f(t),u(!0)},closePayment:y};return t.jsxs(fE.Provider,{value:v,children:[c,l&&h&&t.jsx(pE,{publicKey:e,apiKey:n,apiSecret:i,apiUrl:o,isOpen:l,config:h,theme:s,debug:a,merchantName:m,onSuccess:p.onSuccess,onError:p.onError,onClose:y})]})},e.CoinleyVanilla=wE,e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=pE,e.PaymentAPI=class{constructor(e,t,r=null){t&&t.startsWith("pk_")?(this.publicKey=t,this.apiKey=null,this.apiSecret=null):(this.publicKey=null,this.apiKey=t,this.apiSecret=r),this.api=h.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{if(this.publicKey)e.headers["x-public-key"]=this.publicKey;else{e.headers["x-api-key"]=this.apiKey,e.headers["x-api-secret"]=this.apiSecret;const t=this.generateMerchantToken();t&&(e.headers.Authorization=`Bearer ${t}`)}return e},e=>Promise.reject(e)),this.api.interceptors.response.use(e=>e,e=>{var t,r,n;if(401===(null==(t=e.response)?void 0:t.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(r=e.response)?void 0:r.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(n=e.response)?void 0:n.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(vu){return null}}async request(e,t={}){var r,n;try{return(await this.api({url:e,method:t.method||"GET",data:t.data||t.body?JSON.parse(t.body||"{}"):void 0,...t})).data}catch(vu){if(null==(n=null==(r=vu.response)?void 0:r.data)?void 0:n.error)throw new Error(vu.response.data.error);throw new Error(vu.message||"Request failed")}}async createPayment(e){var t,r;try{return(await this.api.post("/api/payments/create",e)).data}catch(vu){if(null==(r=null==(t=vu.response)?void 0:t.data)?void 0:r.error)throw new Error(vu.response.data.error);throw new Error(vu.message||"Failed to create payment")}}async getPayment(e){var t,r;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(vu){if(null==(r=null==(t=vu.response)?void 0:t.data)?void 0:r.error)throw new Error(vu.response.data.error);throw new Error(vu.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(vu){return{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:1,type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:56,type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:137,type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(vu){return{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,r;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(vu){if(null==(r=null==(t=vu.response)?void 0:t.data)?void 0:r.error)throw new Error(vu.response.data.error);throw new Error(vu.message||"Failed to verify payment")}}async processPayment(e,t,r,n){var i;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:r,senderAddress:n})).data}catch(vu){if(null==(i=vu.response)?void 0:i.data){const t=vu.response.data,r=t.error||t.message||"Payment processing failed",n=new Error(r);throw n.isAlreadyCompleted=t.isAlreadyCompleted||!1,n.verificationAttempts=t.verificationAttempts||0,n.statusCode=vu.response.status,n.originalData=t,n}throw new Error(vu.message||"Failed to process PaymentSplitter transaction")}}async getContractInfo(e){var t,r;try{return(await this.api.get(`/api/payments/contract/${e}`)).data.contractInfo}catch(vu){if(null==(r=null==(t=vu.response)?void 0:t.data)?void 0:r.error)throw new Error(vu.response.data.error);throw new Error(vu.message||"Failed to get contract information")}}async getPaymentSplitterStatus(e){var t,r;try{return(await this.api.get(`/api/payments/splitter-status/${e}`)).data.paymentSplitterStatus}catch(vu){if(null==(r=null==(t=vu.response)?void 0:t.data)?void 0:r.error)throw new Error(vu.response.data.error);throw new Error(vu.message||"Failed to get PaymentSplitter status")}}async checkPaymentSplitterHealth(){try{return(await this.api.get("/api/payments/health")).data.paymentSplitterHealth}catch(vu){return{error:vu.message}}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(vu){return!1}}},e.PaymentQRGenerator=kE,e.QRCodePayment=({apiKey:e,apiSecret:n,apiUrl:i,config:o,onSuccess:s,onError:a,onClose:c,isOpen:l,theme:h="light",mode:d="splitpayment",splitPaymentUrl:p="https://paymentscreen.vercel.app/"})=>{var f;const[m,g]=r.useState("network"),[y,v]=r.useState([]),[b,w]=r.useState([]),[x,k]=r.useState(null),[_,S]=r.useState(null),[C,I]=r.useState(null),[E,A]=r.useState(!1),[M,N]=r.useState(""),[P,B]=r.useState(""),[T,O]=r.useState(""),[R,L]=r.useState(""),[U,j]=r.useState(!1),[D,F]=r.useState(""),[z,q]=r.useState(!1),[W,$]=r.useState(null),G=r.useRef(new bE(i,e,n)),V=r.useRef(null);r.useEffect(()=>(l&&(K(),H()),()=>{V.current&&clearInterval(V.current)}),[l]);const H=()=>{g("network"),k(null),S(null),I(null),N(""),B(""),O(""),L(""),j(!1),F(""),q(!1),$(null),V.current&&clearInterval(V.current)},K=async()=>{try{A(!0),N("");const[e,t]=await Promise.all([G.current.getNetworks(),G.current.getTokens()]);v(e.networks||[]),w(t.stablecoins||[])}catch(EE){N("Failed to load payment options.")}finally{A(!1)}},Z=async e=>{if(!_||!x||!C)return!1;try{const t=await vE.validateBalance(e,_,C.totalAmount,x.shortName,!0);return $(t),!!t.isValid||(N(`Insufficient balance: ${t.errors.join(", ")}`),!1)}catch(t){return N(`Failed to check balance: ${t.message}`),!1}};if(!l)return null;const Y="dark"===h;return t.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:t.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(Y?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[t.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(Y?"border-gray-700":"border-gray-200"),children:[t.jsxs("div",{className:"text-center flex-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:"splitpayment"===d?"Split Payment QR":"QR Code Payment"}),o.amount&&t.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",o.amount.toFixed(2)]}),t.jsx("p",{className:"text-xs text-blue-600",children:"splitpayment"===d?"๐ฑ Scan to redirect to payment screen":"๐ฑ Scan with mobile wallet"})]}),t.jsx("button",{onClick:c,className:"ml-4 text-gray-500 hover:text-gray-700 "+(Y?"hover:text-gray-300":""),children:"โ"})]}),t.jsxs("div",{className:"p-4 min-h-[400px]",children:[M&&t.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[M,t.jsx("button",{onClick:()=>N(""),className:"ml-2 text-red-500 hover:text-red-700",children:"โ"})]}),"network"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsx("h3",{className:"font-medium text-center",children:"Select Network"}),t.jsx("div",{className:"space-y-2",children:y.map(e=>{var r;const n=null==(r=o.merchantWalletAddresses)?void 0:r[e.shortName];return t.jsxs("button",{onClick:()=>{k(e),g("token")},disabled:!n,className:"w-full p-3 border rounded-lg text-left transition-colors "+(n?"hover:border-purple-500 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"):"opacity-50 cursor-not-allowed "+(Y?"border-gray-700":"border-gray-100")),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsxs("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:[e.shortName.toUpperCase(),!n&&" (No merchant address configured)"]})]},e.id)})})]}),"token"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("button",{onClick:()=>g("network"),className:""+(Y?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"โ"}),t.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==x?void 0:x.name]})]}),t.jsx("div",{className:"space-y-2",children:b.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==x?void 0:x.shortName)}).map(e=>t.jsxs("button",{onClick:()=>{S(e),(async e=>{var t,r;try{A(!0),N("");const n={amount:o.amount,currency:e.symbol,network:x.shortName,customerEmail:o.customerEmail,callbackUrl:o.callbackUrl,metadata:{...o.metadata,merchantWalletAddresses:o.merchantWalletAddresses,paymentMethod:"split_payment_qr",selectedNetwork:x.shortName,selectedToken:e.symbol}},i=await G.current.createPayment(n);I(i.payment);const s=(null==(t=o.merchantWalletAddresses)?void 0:t.splitPaymentContract)||(null==(r=o.merchantWalletAddresses)?void 0:r[x.shortName]);if(!s)throw new Error("Split payment contract address not found in config");const a=new URLSearchParams({merchant:o.merchantName||"Coinley Merchant",amount:i.payment.totalAmount.toString(),productAmount:(.95*i.payment.totalAmount).toFixed(2),platformFee:(.03*i.payment.totalAmount).toFixed(2),networkFee:(.02*i.payment.totalAmount).toFixed(2),token:e.symbol,network:x.name,merchantAddress:s,paymentId:i.payment.id}),c=p+"?"+a.toString();B(c);const l=await u.toDataURL(c,{width:256,margin:2,color:{dark:"#7c3aed",light:"#ffffff"}});O(l),g("scan")}catch(n){N(n.message||"Failed to generate split payment QR code")}finally{A(!1)}})(e)},disabled:E,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors disabled:opacity-50 "+(Y?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[t.jsx("div",{className:"font-medium",children:e.name}),t.jsx("div",{className:"text-sm "+(Y?"text-gray-400":"text-gray-500"),children:e.symbol})]},e.id))})]}),"scan"===m&&t.jsx("div",{className:"space-y-4",children:t.jsxs("div",{className:"text-center",children:[t.jsx("h3",{className:"font-medium mb-4",children:"splitpayment"===d?"Scan QR Code to Open Payment Screen":"Scan QR Code with Mobile Wallet"}),T?t.jsxs("div",{className:"flex flex-col items-center space-y-4",children:[t.jsx("div",{className:"p-4 rounded-lg "+(Y?"bg-gray-800":"bg-gray-50"),children:t.jsx("img",{src:T,alt:"Payment QR Code",className:"mx-auto",style:{width:"200px",height:"200px"}})}),t.jsxs("div",{className:"text-sm space-y-1 "+(Y?"text-gray-300":"text-gray-600"),children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Amount:"}),t.jsxs("span",{className:"font-medium",children:[null==C?void 0:C.totalAmount," ",null==_?void 0:_.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Network:"}),t.jsx("span",{className:"font-medium",children:null==x?void 0:x.name})]}),"splitpayment"===d&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Merchant:"}),t.jsx("span",{className:"font-medium",children:o.merchantName||"Coinley Merchant"})]})]}),t.jsx("div",{className:"p-3 rounded-lg text-xs "+(Y?"bg-blue-900 text-blue-200":"bg-blue-50 text-blue-600"),children:"splitpayment"===d?t.jsxs(t.Fragment,{children:["๐ฑ Scan this QR code with your mobile wallet to open the payment screen.",t.jsx("br",{}),"The payment screen will auto-connect your wallet and execute the split payment."]}):"๐ฑ Open your mobile wallet and scan this QR code to connect and pay"}),"splitpayment"===d?t.jsx("button",{onClick:()=>window.open(P,"_blank"),className:"w-full bg-purple-600 text-white py-2 px-4 rounded hover:bg-purple-700 text-sm",children:"๐ Test Payment Screen (Opens in new tab)"}):t.jsx("button",{onClick:async()=>{try{A(!0),N("");const e="0x742d35Cc6634C0532925a3b8D9a5C7C47C77E4";F(e),j(!0),await Z(e),g("confirm")}catch(e){N("Failed to simulate wallet connection")}finally{A(!1)}},disabled:E,className:"w-full bg-gray-600 text-white py-2 px-4 rounded hover:bg-gray-700 disabled:opacity-50 text-sm",children:E?"Connecting...":"๐งช Simulate Wallet Scan (Test)"})]}):t.jsxs("div",{className:"flex items-center justify-center py-8",children:[t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"}),t.jsx("span",{className:"ml-2",children:"Generating QR Code..."})]})]})}),"confirm"===m&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"text-center",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4",children:t.jsx("span",{className:"text-2xl",children:"๐ฑ"})}),t.jsx("h3",{className:"font-medium",children:"Mobile Wallet Connected"}),t.jsx("p",{className:"text-sm mt-2 "+(Y?"text-gray-300":"text-gray-600"),children:"Ready to complete payment"})]}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[t.jsx("p",{className:"text-green-600 text-sm font-medium",children:"โ
Wallet Connected"}),t.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==D?void 0:D.slice(0,6),"...",null==D?void 0:D.slice(-4)]})]}),W&&t.jsx("div",{className:"p-3 rounded-lg border "+(W.isValid?"bg-green-50 border-green-200":"bg-red-50 border-red-200"),children:t.jsxs("div",{className:"space-y-2 text-sm",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Required:"}),t.jsxs("span",{className:"font-medium",children:[null==C?void 0:C.totalAmount," ",null==_?void 0:_.symbol]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Your Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughTokens?"text-green-600":"text-red-600"),children:vE.formatBalance(null==(f=W.tokenBalance)?void 0:f.balance,null==_?void 0:_.symbol)})]}),W.nativeBalance&&t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{children:"Gas Balance:"}),t.jsx("span",{className:"font-medium "+(W.hasEnoughForGas?"text-green-600":"text-red-600"),children:vE.formatBalance(W.nativeBalance.balance,W.nativeBalance.symbol)})]})]})}),t.jsx("button",{onClick:async()=>{try{q(!0),N("");const e=`0x${Math.random().toString(16).substring(2,66)}`;await new Promise(e=>setTimeout(e,3e3)),g("success"),null==s||s(C.id,e,{network:x.name,token:_.symbol,amount:C.totalAmount,method:"qr_code",walletAddress:D})}catch(e){N("Transaction confirmation failed")}finally{q(!1)}},disabled:z||!(null==W?void 0:W.isValid),className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium",children:z?"Processing Payment...":(null==W?void 0:W.isValid)?`Confirm Payment of ${null==C?void 0:C.totalAmount} ${null==_?void 0:_.symbol}`:"Insufficient Balance"})]})]}),"success"===m&&t.jsxs("div",{className:"text-center space-y-4",children:[t.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:t.jsx("span",{className:"text-2xl",children:"โ
"})}),t.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),t.jsx("p",{className:"text-sm "+(Y?"text-gray-300":"text-gray-600"),children:"Transaction completed via QR code scan"}),t.jsx("button",{onClick:c,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 font-medium",children:"Close"})]}),E&&"scan"!==m&&"confirm"!==m&&t.jsx("div",{className:"flex items-center justify-center py-8",children:t.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:n})=>{const[i,o]=r.useState(e);return r.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",i)},[i]),t.jsx("div",{className:`coinley-theme-${i}`,children:n})},e.USAGE_EXAMPLES=IE,e.VERSION="0.0.27",e.generatePaymentQR=(e,t)=>_E.generateQRCode(e,t),e.generatePaymentURL=e=>_E.generatePaymentURL(e),e.paymentQR=_E,e.sdkAnalytics=lf,e.useCoinley=()=>{const e=r.useContext(fE);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=SE,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|
|
3
133
|
//# sourceMappingURL=index.umd.js.map
|