PageSourceSearch

https://cdn.swapkit.dev/widget/latest/wallet-keystore-vco0hSG3.js

js swapkit.dev collected 2026-09-25 20:01:46 UTC 457,116 bytes, 10,578 lines download raw bytes

1import { p as process$1, B as Buffer } from './polyfill-buffer-BWpSmsqZ.js';
2import { c as cryptoBrowserifyExports } from './shared-crypto-CivzVn4_.js';
3
4function commonjsRequire(path) {
5	throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
6}
7
8var l$3;((o)=>{o.Adi="ADI";o.Aleo="ALEO";o.Aptos="APT";o.Arbitrum="ARB";o.Arc="ARC";o.Aurora="AURORA";o.Avalanche="AVAX";o.Base="BASE";o.Berachain="BERA";o.BinanceSmartChain="BSC";o.Bitcoin="BTC";o.BitcoinCash="BCH";o.Botanix="BOTANIX";o.Cardano="ADA";o.Chainflip="FLIP";o.Core="CORE";o.Corn="CORN";o.Cosmos="GAIA";o.Cronos="CRO";o.Dash="DASH";o.Dogecoin="DOGE";o.Ethereum="ETH";o.Gnosis="GNO";o.Harbor="HARBOR";o.Hyperevm="HYPEREVM";o.Hype="HYPE";o.Kujira="KUJI";o.Litecoin="LTC";o.Linea="LINEA";o.Maya="MAYA";o.MegaETH="MEGAETH";o.Monad="MONAD";o.Near="NEAR";o.Noble="NOBLE";o.Optimism="OP";o.Plasma="XPL";o.Polkadot="DOT";o.Polygon="POL";o.Radix="XRD";o.Ripple="XRP";o.Robinhood="HOOD";o.Solana="SOL";o.Sonic="SONIC";o.Spark="SPARK";o.Stellar="XLM";o.Starknet="STRK";o.Sui="SUI";o.THORChain="THOR";o.Ton="TON";o.Tron="TRON";o.Unichain="UNI";o.XLayer="XLAYER";o.Zcash="ZEC";})(l$3||={});var T$2;((C)=>{C.Harbor="MAYA_HARBOR";C.THORChain="THOR_STAGENET";C.Maya="MAYA_STAGENET";})(T$2||={});var m$2;((n)=>{n.Adi="36900";n.Aleo="aleo";n.Aptos="aptos";n.Arbitrum="42161";n.Arc="5042";n.Aurora="1313161554";n.Avalanche="43114";n.Base="8453";n.Berachain="80094";n.BinanceSmartChain="56";n.Bitcoin="bitcoin";n.BitcoinCash="bitcoincash";n.Botanix="3637";n.Cardano="cardano";n.Chainflip="chainflip";n.Core="1116";n.Corn="21000000";n.Cosmos="cosmoshub-4";n.Cronos="25";n.Dash="dash";n.Dogecoin="dogecoin";n.Ethereum="1";n.Gnosis="100";n.Harbor="harbor-1";n.HarborStagenet="harbor-stagenet-1";n.Hyperevm="999";n.Hype="hype";n.Kujira="kaiyo-1";
8n.Litecoin="litecoin";n.Linea="59144";n.Maya="mayachain-mainnet-v1";n.MayaStagenet="mayachain-stagenet-v1";n.MegaETH="4326";n.Monad="143";n.Near="near";n.Noble="noble-1";n.Optimism="10";n.Plasma="9745";n.Polkadot="polkadot";n.Polygon="137";n.Radix="radix-mainnet";n.Ripple="ripple";n.Robinhood="4663";n.Solana="solana";n.Sonic="146";n.Spark="spark";n.Stellar="stellar";n.Starknet="0x534e5f4d41494e";n.Sui="sui";n.THORChain="thorchain-1";n.THORChainStagenet="thorchain-stagenet-v2";n.Ton="ton";n.Tron="728126428";n.Unichain="130";n.XLayer="196";n.Zcash="zcash";})(m$2||={});function e$1(a){return a}var h$2="cosmos",f$1=e$1({baseDecimal:6,blockTime:2,chain:"GAIA",chainId:"cosmoshub-4",coinType:118,explorerUrl:"https://www.mintscan.io/cosmos",name:"Cosmos",nativeCurrency:"ATOM",networkDerivationPath:[44,118,0,0,0],rpcUrls:["https://cosmos-rpc.publicnode.com:443","https://cosmos-rpc.publicnode.com"],type:h$2}),u$1=e$1({baseDecimal:8,blockTime:6,chain:"THOR",chainId:"thorchain-1",coinType:931,explorerUrl:"https://runescan.io",name:"THORChain",nativeCurrency:"RUNE",networkDerivationPath:[44,931,0,0,0],nodeUrl:"https://gateway.liquify.com/chain/thorchain_api",rpcUrls:["https://gateway.liquify.com/chain/thorchain_rpc"],type:h$2}),d$1=e$1({baseDecimal:8,blockTime:6,chain:"THOR_STAGENET",chainId:"thorchain-stagenet-v2",coinType:931,explorerUrl:"https://runescan.io",name:"THORChain",nativeCurrency:"RUNE",networkDerivationPath:[44,931,0,0,0],nodeUrl:"https://stagenet-thornode.thorchain.network",rpcUrls:["https://stagenet-rpc.thorchain.network","https://stagenet-thornode.thorchain.network"],type:h$2}),k$3=e$1({baseDecimal:8,blockTime:6,chain:"MAYA",chainId:"mayachain-mainnet-v1",coinType:931,explorerUrl:"https://www.mayascan.org",name:"Maya",nativeCurrency:"CACAO",networkDerivationPath:[44,931,0,0,0],nodeUrl:"https://mayanode.mayachain.info",rpcUrls:["https://tendermint.mayachain.info","https://maya-tendermint.publicnode.com","https://mayanode.mayachain.info"],type:h$2}),v$1=e$1({baseDecimal:8,blockTime:6,chain:"HARBOR",chainId:"harbor-1",coinType:931,explorerUrl:"",name:"Harbor",nativeCurrency:"HRB",networkDerivationPath:[44,931,0,0,0],rpcUrls:["https://xnode.harbor-dev.xyz/xnode"],type:h$2}),A$1=e$1({baseDecimal:8,blockTime:6,chain:"MAYA_HARBOR",chainId:"harbor-stagenet-1",coinType:931,explorerUrl:"",name:"Harbor",nativeCurrency:"HRB",networkDerivationPath:[44,931,0,0,0],rpcUrls:["https://xnode.harbor-dev.xyz/xnode"],type:h$2}),y$1=e$1({baseDecimal:8,blockTime:6,chain:"MAYA_STAGENET",chainId:"mayachain-stagenet-v1",coinType:931,explorerUrl:"https://www.mayascan.org",name:"Maya",nativeCurrency:"CACAO",networkDerivationPath:[44,931,0,0,0],nodeUrl:"https://stagenet.mayanode.mayachain.info",rpcUrls:["https://stagenet.mayanode.mayachain.info"],type:h$2}),H$1=e$1({baseDecimal:6,blockTime:2.2,chain:"KUJI",chainId:"kaiyo-1",coinType:118,explorerUrl:"https://finder.kujira.network/kaiyo-1",name:"Kujira",nativeCurrency:"KUJI",networkDerivationPath:[44,118,0,0,0],rpcUrls:["https://kujira-rpc.ibs.team","https://kujira-rpc.polkachu.com","https://rpc-kujira.synergynodes.com/"],type:h$2}),D$1=e$1({baseDecimal:6,blockTime:1.3,chain:"NOBLE",chainId:"noble-1",coinType:118,explorerUrl:"https://www.mintscan.io/noble",name:"Noble",nativeCurrency:"USDC",networkDerivationPath:[44,118,0,0,0],rpcUrls:["https://noble-rpc.polkachu.com","https://rpc.noble.xyz","https://rpc.cosmos.directory/noble"],type:h$2}),R$2=[f$1,u$1,k$3,H$1,D$1,v$1],_e$1=["GAIA","KUJI","MAYA","NOBLE","THOR","HARBOR"],je=[d$1,y$1,A$1],Ve$1=["MAYA_STAGENET","THOR_STAGENET","MAYA_HARBOR"],qe$1={[f$1.chain]:"cosmos",[u$1.chain]:"thor",[d$1.chain]:"sthor",[k$3.chain]:"maya",[y$1.chain]:"smaya",[H$1.chain]:"kujira",[D$1.chain]:"noble",[v$1.chain]:"harbor",[A$1.chain]:"sharbor"},Ze$1=[u$1.chain,k$3.chain];var r$1="evm",t$1=18,i$1=60,c$3=[44,60,0,0,0],L$5=e$1({baseDecimal:t$1,blockTime:12.5,chain:"ETH",chainId:"1",chainIdHex:"0x1",coinType:i$1,explorerUrl:"https://etherscan.io",name:"Ethereum",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://ethereum-rpc.publicnode.com","https://eth.llamarpc.com","https://cloudflare-eth.com"],type:r$1}),N$2=e$1({baseDecimal:t$1,blockTime:1,chain:"BSC",chainId:"56",chainIdHex:"0x38",coinType:i$1,explorerUrl:"https://bscscan.com",name:"BinanceSmartChain",nativeCurrency:"BNB",networkDerivationPath:c$3,rpcUrls:["https://bsc-dataseed.binance.org","https://bsc-rpc.gateway.pokt.network","https://bsc-dataseed2.binance.org"],type:r$1}),X$2=e$1({baseDecimal:t$1,blockTime:2,chain:"AVAX",chainId:"43114",chainIdHex:"0xa86a",coinType:i$1,explorerUrl:"https://snowtrace.io",name:"Avalanche",nativeCurrency:"AVAX",networkDerivationPath:c$3,rpcUrls:["https://api.avax.network/ext/bc/C/rpc","https://avalanche-c-chain-rpc.publicnode.com"],type:r$1}),K$2=e$1({baseDecimal:t$1,blockTime:2.1,chain:"POL",chainId:"137",chainIdHex:"0x89",coinType:i$1,explorerUrl:"https://polygonscan.com",name:"Polygon",nativeCurrency:"POL",networkDerivationPath:c$3,rpcUrls:["https://polygon-rpc.com","https://polygon.llamarpc.com","https://polygon-bor-rpc.publicnode.com"],type:r$1}),G$2=e$1({baseDecimal:t$1,blockTime:1,chain:"ADI",chainId:"36900",chainIdHex:"0x9024",coinType:i$1,explorerUrl:"https://explorer.adifoundation.ai",name:"ADI Chain",nativeCurrency:"ADI",networkDerivationPath:c$3,rpcUrls:["https://rpc.adifoundation.ai"],type:r$1}),Y$2=e$1({baseDecimal:t$1,blockTime:0.3,chain:"ARB",chainId:"42161",chainIdHex:"0xa4b1",coinType:i$1,explorerUrl:"https://arbiscan.io",name:"Arbitrum",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://arb1.arbitrum.
8io/rpc","https://arb-mainnet.g.alchemy.com/v2/demo","https://arbitrum.blockpi.network/v1/rpc/public"],type:r$1}),z$4=e$1({baseDecimal:t$1,blockTime:0.5,chain:"ARC",chainId:"5042",chainIdHex:"0x13b2",coinType:i$1,explorerUrl:"https://www.arcexplorer.org",name:"Arc",nativeCurrency:"USDC",networkDerivationPath:c$3,rpcUrls:["https://cold-cosmopolitan-snow.arc-mainnet.quiknode.pro/567f314ad8375450f38ede489b380fada4b1d6d0"],type:r$1}),_$1=e$1({baseDecimal:t$1,blockTime:2,chain:"OP",chainId:"10",chainIdHex:"0xa",coinType:i$1,explorerUrl:"https://optimistic.etherscan.io",name:"Optimism",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://mainnet.optimism.io","https://optimism.llamarpc.com","https://1rpc.io/op"],type:r$1}),j$3=e$1({baseDecimal:t$1,blockTime:2,chain:"BASE",chainId:"8453",chainIdHex:"0x2105",coinType:i$1,explorerUrl:"https://basescan.org",name:"Base",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://base-rpc.publicnode.com","https://base.blockpi.network/v1/rpc/public","https://1rpc.io/base"],type:r$1}),V$1=e$1({baseDecimal:t$1,blockTime:5.2,chain:"GNO",chainId:"100",chainIdHex:"0x64",coinType:i$1,explorerUrl:"https://gnosisscan.io",name:"Gnosis",nativeCurrency:"xDAI",networkDerivationPath:c$3,rpcUrls:["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org","https://rpc.ankr.com/gnosis"],type:r$1}),q$1=e$1({baseDecimal:t$1,blockTime:1,chain:"AURORA",chainId:"1313161554",chainIdHex:"0x4e454152",coinType:i$1,explorerUrl:"https://explorer.mainnet.aurora.dev",name:"Aurora",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://aurora-rpc.publicnode.com","https://1rpc.io/aurora","https://mainnet.aurora.dev"],type:r$1}),Z$2=e$1({baseDecimal:t$1,blockTime:2,chain:"BERA",chainId:"80094",chainIdHex:"0x138de",coinType:i$1,explorerUrl:"https://berascan.com",name:"Berachain",nativeCurrency:"BERA",networkDerivationPath:c$3,rpcUrls:["https://berachain-rpc.publicnode.com","https://rpc.berachain.com","https://berachain.drpc.org"],type:r$1}),F$2=e$1({baseDecimal:t$1,blockTime:1,chain:"HYPEREVM",chainId:"999",chainIdHex:"0x3e7",coinType:i$1,explorerUrl:"https://app.hyperliquid.xyz/explorer",name:"HyperEVM",nativeCurrency:"HYPE",networkDerivationPath:c$3,rpcUrls:["https://rpc.hyperliquid.xyz/evm","https://rpc.hypurrscan.io"],type:r$1}),J$2=e$1({baseDecimal:t$1,blockTime:2,chain:"UNI",chainId:"130",chainIdHex:"0x82",coinType:i$1,explorerUrl:"https://unichain.blockscout.com",name:"Unichain",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://unichain-rpc.publicnode.com","https://unichain.drpc.org"],type:r$1}),Q$2=e$1({baseDecimal:t$1,blockTime:2,chain:"CORN",chainId:"21000000",chainIdHex:"0x1406f40",coinType:i$1,explorerUrl:"https://cornscan.io",name:"Corn",nativeCurrency:"BTCN",networkDerivationPath:c$3,rpcUrls:["https://mainnet.corn-rpc.com","https://rpc.ankr.com/corn_maizenet"],type:r$1}),W$3=e$1({baseDecimal:t$1,blockTime:2,chain:"CORE",chainId:"1116",chainIdHex:"0x45c",coinType:i$1,explorerUrl:"https://corescan.io",name:"Core",nativeCurrency:"CORE",networkDerivationPath:c$3,rpcUrls:["https://rpc.coredao.org","https://1rpc.io/core"],type:r$1}),ee$1=e$1({baseDecimal:t$1,blockTime:2,chain:"BOTANIX",chainId:"3637",chainIdHex:"0xe35",coinType:i$1,explorerUrl:"https://botanixscan.io",name:"Botanix",nativeCurrency:"BTC",networkDerivationPath:c$3,rpcUrls:["https://rpc.botanixlabs.com"],type:r$1}),ne$1=e$1({baseDecimal:t$1,blockTime:2,chain:"CRO",chainId:"25",chainIdHex:"0x19",coinType:i$1,explorerUrl:"https://croscan.io",name:"Cronos",nativeCurrency:"CRO",networkDerivationPath:c$3,rpcUrls:["https://rpc.vvs.finance"],type:r$1}),oe$1=e$1({baseDecimal:t$1,blockTime:2,chain:"XLAYER",chainId:"196",chainIdHex:"0xc4",coinType:i$1,explorerUrl:"https://www.oklink.com/x-layer",name:"X Layer",nativeCurrency:"OKB",networkDerivationPath:c$3,rpcUrls:["https://xlayerrpc.okx.com"],type:r$1}),ae$2=e$1({baseDecimal:t$1,blockTime:2,chain:"SONIC",chainId:"146",chainIdHex:"0x92",coinType:i$1,explorerUrl:"https://sonicscan.io",name:"Sonic",nativeCurrency:"S",networkDerivationPath:c$3,rpcUrls:["https://rpc.soniclabs.com","https://sonic.drpc.org"],type:r$1}),re$1=e$1({baseDecimal:t$1,blockTime:0.4,chain:"MONAD",chainId:"143",chainIdHex:"0x8f",coinType:i$1,explorerUrl:"https://monvision.io",name:"Monad",nativeCurrency:"MON",networkDerivationPath:c$3,rpcUrls:["https://rpc.monad.xyz/","https://rpc3.monad.xyz/","https://rpc-mainnet.monadinfra.com/"],type:r$1}),te$1=e$1({baseDecimal:t$1,blockTime:0.01,chain:"MEGAETH",chainId:"4326",chainIdHex:"0x10e6",coinType:i$1,explorerUrl:"",name:"MegaETH",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:[],type:r$1}),ie$2=e$1({baseDecimal:t$1,blockTime:2,chain:"LINEA",chainId:"59144",chainIdHex:"0xe708",coinType:i$1,explorerUrl:"https://lineascan.build",name:"Linea",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://linea-rpc.publicnode.com","https://linea.drpc.org","https://1rpc.io/linea"],type:r$1}),ce$1=e$1({baseDecimal:t$1,blockTime:0.25,chain:"HOOD",chainId:"4663",chainIdHex:"0x1237",coinType:i$1,explorerUrl:"https://robinhoodchain.blockscout.com",name:"Robinhood Chain",nativeCurrency:"ETH",networkDerivationPath:c$3,rpcUrls:["https://rpc.mainnet.chain.robinhood.com"],type:r$1}),se$1=e$1({baseDecimal:t$1,blockTime:1,chain:"XPL",chainId:"9745",chainIdHex:"0x2611",coinType:i$1,explorerUrl:"https://plasmascan.to",name:"Plasma",nativeCurrency:"XPL",networkDerivationPath:c$3,rpcUrls:["https://rpc.plasma.to","https://plasma.drpc.org"],type:r$1}),O$1=[G$2,Y$2,z$4,q$1,X$2,j$3,Z$2,ee$1,N$2,W$3,Q$2,ne$1,L$5,V$1,ce$1,F$2,ie$2,te$1,re$1,_$1,se$1,K$2,ae$2,J$2,oe$1],We=["ADI","ARB","ARC","AURORA","AVAX","BASE","BERA","BSC","BOTANIX","CORE","CORN","CRO","ETH","GNO","HYPEREVM","LINEA","MEGAETH","MONAD","OP","XPL","POL","HOOD","SONIC","UNI","XLAYER"];var p$1="others",pe=e$1({baseDecimal:6,blockTime:5,chain:"ALEO",chainId:"aleo",coinType:683,explorerUrl:"https://aleoscan.io",name:"Aleo",nativeCurrency:"ALEO",networkDerivationPath:[44,683,0,0],rpcUrls:["https://api.explorer.provable.com/v1"],type:p$1}),he=e$1({baseDecimal:8,blockTime:1,chain:"APT",chainId:"aptos",coinType:637,explorerUrl:"https://explorer.aptoslabs.com",name:"Aptos",nativeCurrency:"APT",networkDerivationPath:[44,637,0,0,0],rpcUrls:["https://api.mainnet.aptoslabs.com/v1"],type:p$1}),le=e$1({baseDecimal:8,blockTime:1,chain:"HYPE",chainId:"hype",coinType:60,explorerUrl:"https://app.hyperliquid.xyz/explorer",name:"Hyperliquid",nativeCurrency:"HYPE",networkDerivationPath:[44,60,0,0,0],rpcUrls:["https://api.hyperliquid.xyz"],type:p$1}),me$1=e$1({baseDecimal:24,blockTime:1,chain:"NEAR",chainId:"near",coinType:397,explorerUrl:"https://nearblocks.io",name:"Near",nativeCurrency:"NEAR",networkDerivationPath:[44,397,0,0,0],rpcUrls:["https://rpc.mainnet.near.org","https://free.rpc.fastnear.com","https://1rpc.io/near","https://near.lava.build","https://near-mainnet.infura.io/v3/3cbfcafa5e1e48b7bb0ea41f2fbc4abf"],type:p$1}),be=e$1({baseDecimal:18,blockTime:5,chain:"XRD",chainId:"radix-mainnet",coinType:1022,explorerUrl:"https://dashboard.radixdlt.com",name:"Radix",nativeCurrency:"XRD",networkDerivationPath:[0,0,0,0,0],rpcUrls:["https://radix-mainnet.rpc.grove.city/v1/326002fc/core","https://mainnet.radixdlt.com","https://radix-mainnet.rpc.grove.city/v1"],type:p$1}),Ce$1=e$1({baseDecimal:6,blockTime:5,chain:"XRP",chainId:"ripple",coinType:144,explorerUrl:"https://livenet.xrpl.org/",name:"Ripple",nativeCurrency:"XRP",networkDerivationPath:[44,144,0,0,0],rpcUrls:["wss://xrpl.ws/","wss://s1.ripple.com/","wss://s2.ripple.com/"],type:p$1}),xe$2=e$1({baseDecimal:9,blockTime:0.4,chain:"SOL",chainId:"solana",coinType:501,explorerUrl:"https://solscan.io",name:"Solana",nativeCurrency:"SOL",networkDerivationPath:[44,501,0,0,0],rpcUrls:["https://solana-rpc.publicnode.com","https://solana.drpc.org","https://api.mainnet-beta.solana.com"],type:p$1}),de$1=e$1({baseDecimal:8,blockTime:1,chain:"SPARK",chainId:"spark",coinType:0,explorerUrl:"https://sparkscan.io",name:"Spark",nativeCurrency:"BTC",networkDerivationPath:[8797555,1,0,0,0],rpcUrls:[],type:p$1}),ye$2=e$1({baseDecimal:9,blockTime:5,chain:"TON",chainId:"ton",coinType:607,explorerUrl:"https://tonscan.org",name:"Ton",nativeCurrency:"GRAM",networkDerivationPath:[44,607,0,0,0],rpcUrls:[],type:p$1}),Te$1=e$1({baseDecimal:6,blockTime:3,chain:"TRON",chainId:"728126428",chainIdHex:"0x2b6653dc",coinType:195,explorerUrl:"https://tronscan.org",name:"Tron",nativeCurrency:"TRX",networkDerivationPath:[44,195,0,0,0],rpcUrls:["https://tron-rpc.publicnode.com","https://api.tronstack.io","https://api.tron.network"],type:p$1}),ue=e$1({baseDecimal:7,blockTime:5,chain:"XLM",chainId:"stellar",coinType:148,explorerUrl:"https://stellar.expert",name:"Stellar",nativeCurrency:"XLM",networkDerivationPath:[44,148,0,0,0],rpcUrls:["https://horizon.stellar.org","https://horizon.stellar.lobstr.co"],type:p$1}),ke$2=e$1({baseDecimal:9,blockTime:5,chain:"SUI",chainId:"sui",coinType:784,explorerUrl:"https://suiscan.xyz",name:"Sui",nativeCurrency:"SUI",networkDerivationPath:[44,784,0,0,0],rpcUrls:["https://fullnode.mainnet.sui.io:443"],type:p$1}),ge$2=e$1({baseDecimal:6,blockTime:600,chain:"ADA",chainId:"cardano",coinType:1815,explorerUrl:"https://cexplorer.io",name:"Cardano",nativeCurrency:"ADA",networkDerivationPath:[1852,1815,0,0,0],rpcUrls:["https://api.koios.rest/api/v1","https://cardano-mainnet.blockfrost.io/api/v0"],type:p$1}),Ue$2=e$1({baseDecimal:18,blockTime:6,chain:"STRK",chainId:"0x534e5f4d41494e",coinType:9004,explorerUrl:"https://starkscan.co",name:"Starknet",nativeCurrency:"STRK",networkDerivationPath:[44,9004,0,0,0],rpcUrls:["https://starknet-rpc.publicnode.com","https://starknet.drpc.org","https://rpc.starknet.lava.build"],type:p$1}),g$2=[he,me$1,be,Ce$1,xe$2,de$1,ue,ye$2,Te$1,ke$2,ge$2,Ue$2,le,pe],on=g$2.map((a)=>a.chain);var S$3="substrate",fe$1=e$1({baseDecimal:10,blockTime:6,chain:"DOT",chainId:"polkadot",coinType:354,explorerUrl:"https://polkadot.subscan.io",name:"Polkadot",nativeCurrency:"DOT",networkDerivationPath:[0,0,0,0,0],rpcUrls:["wss://rpc.polkadot.io","wss://polkadot-rpc.dwellir.com","wss://polkadot.api.onfinality.io/public-ws"],type:S$3}),ve$1=e$1({baseDecimal:18,blockTime:5,chain:"FLIP",chainId:"chainflip",coinType:2
8112,explorerUrl:"https://explorer.polkascan.io/polkadot",name:"Chainflip",nativeCurrency:"FLIP",networkDerivationPath:[0,0,0,0,0],rpcUrls:["wss://mainnet-archive.chainflip.io","wss://archive-1.mainnet.chainflip.io","wss://archive-2.mainnet.chainflip.io"],type:S$3}),P$3=[fe$1,ve$1],cn$1=["DOT","FLIP"];var b$3="utxo",Ae$2=e$1({baseDecimal:8,blockTime:600,chain:"BTC",chainId:"bitcoin",coinType:0,explorerUrl:"https://blockchair.com/bitcoin",name:"Bitcoin",nativeCurrency:"BTC",networkDerivationPath:[84,0,0,0,0],rpcUrls:["https://bitcoin-rpc.publicnode.com","https://bitcoin.publicnode.com"],type:b$3}),He$2=e$1({baseDecimal:8,blockTime:600,chain:"BCH",chainId:"bitcoincash",coinType:145,explorerUrl:"https://www.blockchair.com/bitcoin-cash",name:"BitcoinCash",nativeCurrency:"BCH",networkDerivationPath:[44,145,0,0,0],rpcUrls:["https://bch-dataseed.binance.org","https://bch.getblock.io/mainnet"],type:b$3}),De$1=e$1({baseDecimal:8,blockTime:150,chain:"LTC",chainId:"litecoin",coinType:2,explorerUrl:"https://blockchair.com/litecoin",name:"Litecoin",nativeCurrency:"LTC",networkDerivationPath:[84,2,0,0,0],rpcUrls:["https://ltc.getblock.io/mainnet","https://litecoin.publicnode.com"],type:b$3}),Re$1=e$1({baseDecimal:8,blockTime:60,chain:"DOGE",chainId:"dogecoin",coinType:3,explorerUrl:"https://blockchair.com/dogecoin",name:"Dogecoin",nativeCurrency:"DOGE",networkDerivationPath:[44,3,0,0,0],rpcUrls:["https://doge.getblock.io/mainnet","https://dogecoin.publicnode.com"],type:b$3}),Oe$2=e$1({baseDecimal:8,blockTime:150,chain:"DASH",chainId:"dash",coinType:5,explorerUrl:"https://blockchair.com/dash",name:"Dash",nativeCurrency:"DASH",networkDerivationPath:[44,5,0,0,0],rpcUrls:["https://dash-rpc.publicnode.com","https://dash.getblock.io/mainnet"],type:b$3}),Se$2=e$1({baseDecimal:8,blockTime:75,chain:"ZEC",chainId:"zcash",coinType:133,explorerUrl:"https://blockchair.com/zcash",name:"Zcash",nativeCurrency:"ZEC",networkDerivationPath:[44,133,0,0,0],rpcUrls:[],type:b$3}),I$2=[Ae$2,He$2,De$1,Re$1,Oe$2,Se$2],ln$1=["BTC","BCH","DASH","DOGE","LTC","ZEC"];var U$1=[...I$2,...O$1,...R$2,...P$3,...g$2].sort((a,s)=>a.chain.localeCompare(s.chain)),Pe$2=Object.values(l$3),un$1=["THOR_STAGENET","MAYA_STAGENET"],Ie$2=U$1.reduce((a,s)=>(a[s.chain]=s,a[s.chainId]=s,a),{});function w$2(a){return Ie$2[a]||{}}var {chainIdToChain:we$2,chainToBaseDecimal:Ee,chainToBlockTime:Be$1,explorerUrls:Me$2,rpcUrls:Le$2}=Pe$2.reduce((a,s)=>{let{chainId:x,baseDecimal:C,blockTime:E,explorerUrl:B,rpcUrls:M}=w$2(s);return a.chainIdToChain[x]=s,a.chainToBaseDecimal[s]=C,a.chainToBlockTime[s]=E,a.explorerUrls[s]=B,a.rpcUrls[s]=M[0]||"",a},{chainIdToChain:{},chainToBaseDecimal:{},chainToBlockTime:{},explorerUrls:{},rpcUrls:{MAYA_STAGENET:y$1.rpcUrls[0],THOR_STAGENET:d$1.rpcUrls[0]}}),kn$1={THOR:"https://gateway.liquify.com/chain/thorchain_api",MAYA:"https://mayanode.mayachain.info",THOR_STAGENET:"https://stagenet-thornode.thorchain.network",MAYA_STAGENET:"https://stagenet.mayanode.mayachain.info"},gn$1=Le$2,Un$1=Me$2,fn=Object.fromEntries(U$1.flatMap(({chain:a,chainId:s})=>[[a,s]])),vn$1=we$2,An$1=Ee,Hn$1=Be$1;function Dn(a){return w$2(a).coinType}var Ne$2={60:"ETH",118:"GAIA",931:"THOR"},Xe$1=U$1.reduce((a,s)=>{let x=s.chain;if(!(s.coinType in a)||Ne$2[s.coinType]===x)a[s.coinType]=x;return a},{});function Rn$1(a){return Xe$1[a]}
9
10const t=Symbol.for("@ts-pattern/matcher"),e=Symbol.for("@ts-pattern/isVariadic"),n="@ts-pattern/anonymous-select-key",r=t=>Boolean(t&&"object"==typeof t),i=e=>e&&!!e[t],o=(n,s,c)=>{if(i(n)){const e=n[t](),{matched:r,selections:i}=e.match(s);
10return r&&i&&Object.keys(i).forEach(t=>c(t,i[t])),r}if(r(n)){if(!r(s))return  false;if(Array.isArray(n)){if(!Array.isArray(s))return  false;let t=[],r=[],u=[];for(const o of n.keys()){const s=n[o];i(s)&&s[e]?u.push(s):u.length?r.push(s):t.push(s);}if(u.length){if(u.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(s.length<t.length+r.length)return  false;const e=s.slice(0,t.length),n=0===r.length?[]:s.slice(-r.length),i=s.slice(t.length,0===r.length?Infinity:-r.length);return t.every((t,n)=>o(t,e[n],c))&&r.every((t,e)=>o(t,n[e],c))&&(0===u.length||o(u[0],i,c))}return n.length===s.length&&n.every((t,e)=>o(t,s[e],c))}return Reflect.ownKeys(n).every(e=>{const r=n[e];return (e in s||i(u=r)&&"optional"===u[t]().matcherType)&&o(r,s[e],c);var u;})}return Object.is(s,n)},s$1=e=>{var n,o,u;return r(e)?i(e)?null!=(n=null==(o=(u=e[t]()).getSelectionKeys)?void 0:o.call(u))?n:[]:Array.isArray(e)?c$2(e,s$1):c$2(Object.values(e),s$1):[]},c$2=(t,e)=>t.reduce((t,n)=>t.concat(e(n)),[]);function u(...t){if(1===t.length){const[e]=t;return t=>o(e,t,()=>{})}if(2===t.length){const[e,n]=t;return o(e,n,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${t.length}.`)}function a(t){return Object.assign(t,{optional:()=>h$1(t),and:e=>d(t,e),or:e=>y(t,e),select:e=>void 0===e?v(t):v(e,t)})}function l$2(t){return Object.assign((t=>Object.assign(t,{[Symbol.iterator](){let n=0;const r=[{value:Object.assign(t,{[e]:true}),done:false},{done:true,value:void 0}];return {next:()=>{var t;return null!=(t=r[n++])?t:r.at(-1)}}}}))(t),{optional:()=>l$2(h$1(t)),select:e=>l$2(void 0===e?v(t):v(e,t))})}function h$1(e){return a({[t]:()=>({match:t=>{let n={};const r=(t,e)=>{n[t]=e;};return void 0===t?(s$1(e).forEach(t=>r(t,void 0)),{matched:true,selections:n}):{matched:o(e,t,r),selections:n}},getSelectionKeys:()=>s$1(e),matcherType:"optional"})})}const f=(t,e)=>{for(const n of t)if(!e(n))return  false;return  true},g$1=(t,e)=>{for(const[n,r]of t.entries())if(!e(r,n))return  false;return  true},m$1=(t,e)=>{const n=Reflect.ownKeys(t);for(const r of n)if(!e(r,t[r]))return  false;return  true};function d(...e){return a({[t]:()=>({match:t=>{let n={};const r=(t,e)=>{n[t]=e;};return {matched:e.every(e=>o(e,t,r)),selections:n}},getSelectionKeys:()=>c$2(e,s$1),matcherType:"and"})})}function y(...e){return a({[t]:()=>({match:t=>{let n={};const r=(t,e)=>{n[t]=e;};return c$2(e,s$1).forEach(t=>r(t,void 0)),{matched:e.some(e=>o(e,t,r)),selections:n}},getSelectionKeys:()=>c$2(e,s$1),matcherType:"or"})})}function p(e){return {[t]:()=>({match:t=>({matched:Boolean(e(t))})})}}function v(...e){const r="string"==typeof e[0]?e[0]:void 0,i=2===e.length?e[1]:"string"==typeof e[0]?void 0:e[0];return a({[t]:()=>({match:t=>{let e={[null!=r?r:n]:t};return {matched:void 0===i||o(i,t,(t,n)=>{e[t]=n;}),selections:e}},getSelectionKeys:()=>[null!=r?r:n].concat(void 0===i?[]:s$1(i))})})}function b$2(t){return  true}function w$1(t){return "number"==typeof t}function S$2(t){return "string"==typeof t}function j$2(t){return "bigint"==typeof t}const K$1=a(p(b$2)),O=a(p(b$2)),E$1=K$1,x=t=>Object.assign(a(t),{startsWith:e=>{return x(d(t,(n=e,p(t=>S$2(t)&&t.startsWith(n)))));var n;},endsWith:e=>{return x(d(t,(n=e,p(t=>S$2(t)&&t.endsWith(n)))));var n;},minLength:e=>x(d(t,(t=>p(e=>S$2(e)&&e.length>=t))(e))),length:e=>x(d(t,(t=>p(e=>S$2(e)&&e.length===t))(e))),maxLength:e=>x(d(t,(t=>p(e=>S$2(e)&&e.length<=t))(e))),includes:e=>{return x(d(t,(n=e,p(t=>S$2(t)&&t.includes(n)))));var n;},regex:e=>{return x(d(t,(n=e,p(t=>S$2(t)&&Boolean(t.match(n))))));var n;}}),A=x(p(S$2)),N$1=t=>Object.assign(a(t),{between:(e,n)=>N$1(d(t,((t,e)=>p(n=>w$1(n)&&t<=n&&e>=n))(e,n))),lt:e=>N$1(d(t,(t=>p(e=>w$1(e)&&e<t))(e))),gt:e=>N$1(d(t,(t=>p(e=>w$1(e)&&e>t))(e))),lte:e=>N$1(d(t,(t=>p(e=>w$1(e)&&e<=t))(e))),gte:e=>N$1(d(t,(t=>p(e=>w$1(e)&&e>=t))(e))),int:()=>N$1(d(t,p(t=>w$1(t)&&Number.isInteger(t)))),finite:()=>N$1(d(t,p(t=>w$1(t)&&Number.isFinite(t)))),positive:()=>N$1(d(t,p(t=>w$1(t)&&t>0))),negative:()=>N$1(d(t,p(t=>w$1(t)&&t<0)))}),P$2=N$1(p(w$1)),k$2=t=>Object.assign(a(t),{between:(e,n)=>k$2(d(t,((t,e)=>p(n=>j$2(n)&&t<=n&&e>=n))(e,n))),lt:e=>k$2(d(t,(t=>p(e=>j$2(e)&&e<t))(e))),gt:e=>k$2(d(t,(t=>p(e=>j$2(e)&&e>t))(e))),lte:e=>k$2(d(t,(t=>p(e=>j$2(e)&&e<=t))(e))),gte:e=>k$2(d(t,(t=>p(e=>j$2(e)&&e>=t))(e))),positive:()=>k$2(d(t,p(t=>j$2(t)&&t>0))),negative:()=>k$2(d(t,p(t=>j$2(t)&&t<0)))}),T$1=k$2(p(j$2)),B$3=a(p(function(t){return "boolean"==typeof t})),_=a(p(function(t){return "symbol"==typeof t})),W$2=a(p(function(t){return null==t}
10)),$=a(p(function(t){return null!=t}));var z$3={__proto__:null,matcher:t,optional:h$1,array:function(...e){return l$2({[t]:()=>({match:t=>{if(!Array.isArray(t))return {matched:false};if(0===e.length)return {matched:true};const n=e[0];let r={};if(0===t.length)return s$1(n).forEach(t=>{r[t]=[];}),{matched:true,selections:r};const i=(t,e)=>{r[t]=(r[t]||[]).concat([e]);};return {matched:t.every(t=>o(n,t,i)),selections:r}},getSelectionKeys:()=>0===e.length?[]:s$1(e[0])})})},set:function(...e){return a({[t]:()=>({match:t=>{if(!(t instanceof Set))return {matched:false};let n={};if(0===t.size)return {matched:true,selections:n};if(0===e.length)return {matched:true};const r=(t,e)=>{n[t]=(n[t]||[]).concat([e]);},i=e[0];return {matched:f(t,t=>o(i,t,r)),selections:n}},getSelectionKeys:()=>0===e.length?[]:s$1(e[0])})})},map:function(...e){return a({[t]:()=>({match:t=>{if(!(t instanceof Map))return {matched:false};let n={};if(0===t.size)return {matched:true,selections:n};const r=(t,e)=>{n[t]=(n[t]||[]).concat([e]);};if(0===e.length)return {matched:true};var i;if(1===e.length)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null==(i=e[0])?void 0:i.toString()}`);const[s,c]=e;return {matched:g$1(t,(t,e)=>{const n=o(s,e,r),i=o(c,t,r);return n&&i}),selections:n}},getSelectionKeys:()=>0===e.length?[]:[...s$1(e[0]),...s$1(e[1])]})})},record:function(...e){return a({[t]:()=>({match:t=>{if(null===t||"object"!=typeof t||Array.isArray(t))return {matched:false};var n;if(0===e.length)throw new Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${null==(n=e[0])?void 0:n.toString()}`);let r={};const i=(t,e)=>{r[t]=(r[t]||[]).concat([e]);},[s,c]=1===e.length?[A,e[0]]:e;return {matched:m$1(t,(t,e)=>{const n="string"!=typeof t||Number.isNaN(Number(t))?null:Number(t),r=null!==n&&o(s,n,i),u=o(s,t,i),a=o(c,e,i);return (u||r)&&a}),selections:r}},getSelectionKeys:()=>0===e.length?[]:[...s$1(e[0]),...s$1(e[1])]})})},intersection:d,union:y,not:function(e){return a({[t]:()=>({match:t=>({matched:!o(e,t,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:p,select:v,any:K$1,unknown:O,_:E$1,string:A,number:P$2,bigint:T$1,boolean:B$3,symbol:_,nullish:W$2,nonNullable:$,instanceOf:function(t){return a(p(function(t){return e=>e instanceof t}(t)))},shape:function(t){return a(p(u(t)))}};let I$1 = class I extends Error{constructor(t){let e;try{e=JSON.stringify(t);}catch(n){e=t;}super(`Pattern matching error: no pattern matches value ${e}`),this.input=void 0,this.input=t;}};const L$4={matched:false,value:void 0};function M$1(t){return new R$1(t,L$4)}let R$1 = class R{constructor(t,e){this.input=void 0,this.state=void 0,this.input=t,this.state=e;}with(...t){if(this.state.matched)return this;const e=t[t.length-1],r=[t[0]];let i;3===t.length&&"function"==typeof t[1]?i=t[1]:t.length>2&&r.push(...t.slice(1,t.length-1));let s=false,c={};const u=(t,e)=>{s=true,c[t]=e;},a=!r.some(t=>o(t,this.input,u))||i&&!Boolean(i(this.input))?L$4:{matched:true,value:e(s?n in c?c[n]:c:this.input,this.input)};return new R(this.input,a)}when(t,e){if(this.state.matched)return this;const n=Boolean(t(this.input));return new R(this.input,n?{matched:true,value:e(this.input,this.input)}:L$4)}otherwise(t){return this.state.matched?this.state.value:t(this.input)}exhaustive(t=F$1){return this.state.matched?this.state.value:t(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}};function F$1(t){throw new I$1(t)}
11
12const index$4 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
13	__proto__: null,
14	NonExhaustiveError: I$1,
15	P: z$3,
16	Pattern: z$3,
17	isMatching: u,
18	match: M$1
19}, Symbol.toStringTag, { value: 'Module' }));
20
21const createStoreImpl = (createState) => {
22  let state;
23  const listeners = /* @__PURE__ */ new Set();
24  const setState = (partial, replace) => {
25    const nextState = typeof partial === "function" ? partial(state) : partial;
26    if (!Object.is(nextState, state)) {
27      const previousState = state;
28      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
29      listeners.forEach((listener) => listener(state, previousState));
30    }
31  };
32  const getState = () => state;
33  const getInitialState = () => initialState;
34  const subscribe = (listener) => {
35    listeners.add(listener);
36    return () => listeners.delete(listener);
37  };
38  const api = { setState, getState, getInitialState, subscribe };
39  const initialState = state = createState(setState, getState, api);
40  return api;
41};
42const createStore = ((createState) => createState ? createStoreImpl(createState) : createStoreImpl);
43
44const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
45const _32n = /* @__PURE__ */ BigInt(32);
46// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
47// }` to match little-endian word order rather than the property names.
48function fromBig(n, le = false) {
49    if (le)
50        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
51    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
52}
53// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
54// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
55function split(lst, le = false) {
56    const len = lst.length;
57    let Ah = new Uint32Array(len);
58    let Al = new Uint32Array(len);
59    for (let i = 0; i < len; i++) {
60        const { h, l } = fromBig(lst[i], le);
61        [Ah[i], Al[i]] = [h, l];
62    }
63    return [Ah, Al];
64}
65// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.
66const shrSH = (h, _l, s) => h >>> s;
67// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.
68const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
69// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
70const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
71// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
72const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
73// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
74const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
75// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
76const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
77// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.
78const rotr32H = (_h, l) => l;
79// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.
80const rotr32L = (h, _l) => h;
81// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
82const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
83// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
84const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
85// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
86const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
87// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
88const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
89// Add two split 64-bit words and return the split `{ h, l }` sum.
90// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out
91// of the low sum and instead use division.
92function add(Ah, Al, Bh, Bl) {
93    const l = (Al >>> 0) + (Bl >>> 0);
94    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
95}
96// Addition with more than 2 elements
97// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.
98const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
99// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.
100const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
101// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.
102const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
103// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.
104const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
105// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.
106const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
107// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.
108const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
109
110/**
111 * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
112 * @param a - value to test
113 * @returns `true` when the value is a Uint8Array-compatible view.
114 * @example
115 * Check whether a value is a Uint8Array-compatible view.
116 * ```ts
117 * isBytes(new Uint8Array([1, 2, 3]));
118 * ```
119 */
120function isBytes$1(a) {
121    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
122    // The fallback still requires a real ArrayBuffer view, so plain
123    // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
124    // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
125    return (a instanceof Uint8Array ||
126        (ArrayBuffer.isView(a) &&
127            a.constructor.name === 'Uint8Array' &&
128            'BYTES_PER_ELEMENT' in a &&
129            a.BYTES_PER_ELEMENT === 1));
130}
131/**
132 * Asserts something is a non-negative integer.
133 * @param n - number to validate
134 * @param title - label included in thrown errors
135 * @throws On wrong argument types. {@link TypeError}
136 * @throws On wrong argument ranges or values. {@link RangeError}
137 * @example
138 * Validate a non-negative integer option.
139 * ```ts
140 * anumber(32, 'length');
141 * ```
142 */
143function anumber$1(n, title = '') {
144    if (typeof n !== 'number') {
145        const prefix = title && `"${title}" `;
146        throw new TypeError(`${prefix}
146expected number, got ${typeof n}`);
147    }
148    if (!Number.isSafeInteger(n) || n < 0) {
149        const prefix = title && `"${title}" `;
150        throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
151    }
152}
153/**
154 * Asserts something is Uint8Array.
155 * @param value - value to validate
156 * @param length - optional exact length constraint
157 * @param title - label included in thrown errors
158 * @returns The validated byte array.
159 * @throws On wrong argument types. {@link TypeError}
160 * @throws On wrong argument ranges or values. {@link RangeError}
161 * @example
162 * Validate that a value is a byte array.
163 * ```ts
164 * abytes(new Uint8Array([1, 2, 3]));
165 * ```
166 */
167function abytes$1(value, length, title = '') {
168    const bytes = isBytes$1(value);
169    const len = value?.length;
170    const needsLen = length !== undefined;
171    if (!bytes || (needsLen && len !== length)) {
172        const prefix = title && `"${title}" `;
173        const ofLen = needsLen ? ` of length ${length}` : '';
174        const got = bytes ? `length=${len}` : `type=${typeof value}`;
175        const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
176        if (!bytes)
177            throw new TypeError(message);
178        throw new RangeError(message);
179    }
180    return value;
181}
182/**
183 * Asserts something is a wrapped hash constructor.
184 * @param h - hash constructor to validate
185 * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
186 * @throws On invalid hash metadata ranges or values. {@link RangeError}
187 * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
188 * @example
189 * Validate a callable hash wrapper.
190 * ```ts
191 * import { ahash } from '@noble/hashes/utils.js';
192 * import { sha256 } from '@noble/hashes/sha2.js';
193 * ahash(sha256);
194 * ```
195 */
196function ahash(h) {
197    if (typeof h !== 'function' || typeof h.create !== 'function')
198        throw new TypeError('Hash must wrapped by utils.createHasher');
199    anumber$1(h.outputLen);
200    anumber$1(h.blockLen);
201    // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
202    // validation and can produce empty outputs instead of failing fast.
203    if (h.outputLen < 1)
204        throw new Error('"outputLen" must be >= 1');
205    if (h.blockLen < 1)
206        throw new Error('"blockLen" must be >= 1');
207}
208/**
209 * Asserts a hash instance has not been destroyed or finished.
210 * @param instance - hash instance to validate
211 * @param checkFinished - whether to reject finalized instances
212 * @throws If the hash instance has already been destroyed or finalized. {@link Error}
213 * @example
214 * Validate that a hash instance is still usable.
215 * ```ts
216 * import { aexists } from '@noble/hashes/utils.js';
217 * import { sha256 } from '@noble/hashes/sha2.js';
218 * const hash = sha256.create();
219 * aexists(hash);
220 * ```
221 */
222function aexists(instance, checkFinished = true) {
223    if (instance.destroyed)
224        throw new Error('Hash instance has been destroyed');
225    if (checkFinished && instance.finished)
226        throw new Error('Hash#digest() has already been called');
227}
228/**
229 * Asserts output is a sufficiently-sized byte array.
230 * @param out - destination buffer
231 * @param instance - hash instance providing output length
232 * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
233 * @throws On wrong argument types. {@link TypeError}
234 * @throws On wrong argument ranges or values. {@link RangeError}
235 * @example
236 * Validate a caller-provided digest buffer.
237 * ```ts
238 * import { aoutput } from '@noble/hashes/utils.js';
239 * import { sha256 } from '@noble/hashes/sha2.js';
240 * const hash = sha256.create();
241 * aoutput(new Uint8Array(hash.outputLen), hash);
242 * ```
243 */
244function aoutput(out, instance) {
245    abytes$1(out, undefined, 'digestInto() output');
246    const min = instance.outputLen;
247    if (out.length < min) {
248        throw new RangeError('"digestInto() output" expected to be of length >=' + min);
249    }
250}
251/**
252 * Casts a typed array view to Uint8Array.
253 * @param arr - source typed array
254 * @returns Uint8Array view over the same buffer.
255 * @example
256 * Reinterpret a typed array as bytes.
257 * ```ts
258 * u8(new Uint32Array([1, 2]));
259 * ```
260 */
261function u8(arr) {
262    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
263}
264/**
265 * Casts a typed array view to Uint32Array.
266 * `arr.byteOffset` must already be 4-byte aligned or the platform
267 * Uint32Array constructor will throw.
268 * @param arr - source typed array
269 * @returns Uint32Array view over the same buffer.
270 * @example
271 * Reinterpret a byte array as 32-bit words.
272 * ```ts
273 * u32(new Uint8Array(8));
274 * ```
275 */
276function u32(arr) {
277    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
278}
279/**
280 * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
281 * @param arrays - arrays to overwrite with zeros
282 * @example
283 * Zeroize sensitive buffers in place.
284 * ```ts
285 * clean(new Uint8Array([1, 2, 3]));
286 * ```
287 */
288function clean(...arrays) {
289    for (let i = 0; i < arrays.length; i++) {
290        arrays[i].fill(0);
291    }
292}
293/**
294 * Creates a DataView for byte-level manipulation.
295 * @param arr - source typed array
296 * @returns DataView over the same buffer region.
297 * @example
298 * Create a DataView over an existing buffer.
299 * ```ts
300 * createView(new Uint8Array(4));
301 * ```
302 */
303function createView(arr) {
304    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
305}
306/**
307 * Rotate-right operation for uint32 values.
308 * @param word - source word
309 * @param shift - shift amount in bits
310 * @returns Rotated word.
311 * @example
312 * Rotate a 32-bit word to the right.
313 * ```ts
314 * rotr(0x12345678, 8);
315 * ```
316 */
317function rotr(word, shift) {
318    return (word << (32 - shift)) | (word >>> shift);
319}
320/**
321 * Rotate-left operation for uint32 values.
322 * @param word - source word
323 * @param shift - shift amount in bits
324 * @returns Rotated word.
325 * @example
326 * Rotate a 32-bit word to the left.
327 * ```ts
328 * rotl(0x12345678, 8);
329 * ```
330 */
331function rotl(word, shift) {
332    return (word << shift) | ((word >>> (32 - shift)) >>> 0);
333}
334/** Whether the current platform is little-endian. */
335const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
336/**
337 * Byte-swap operation for uint32 values.
338 * @param word - source word
339 * @returns Word with reversed byte order.
340 * @example
341 * Reverse the byte order of a 32-bit word.
342 * ```ts
343 * byteSwap(0x11223344);
344 * ```
345 */
346function byteSwap(word) {
347    return (((word << 24) & 0xff000000) |
348        ((word << 8) & 0xff0000) |
349        ((word >>> 8) & 0xff00) |
350        ((word >>> 24) & 0xff));
351}
352/**
353 * Conditionally byte-swaps one 32-bit word on big-endian platforms.
354 * @param n - source word
355 * @returns Original or byte-swapped word depending on platform endianness.
356 * @example
357 * Normalize a 32-bit word for host endianness.
358 * ```ts
359 * swap8IfBE(0x11223344);
360 * ```
361 */
362const swap8IfBE = isLE
363    ? (n) => n
364    : (n) => byteSwap(n) >>> 0;
365/**
366 * Byte-swaps every word of a Uint32Array in place.
367 * @param arr - array to mutate
368 * @returns The same array after mutation; callers pass live state arrays here.
369 * @example
370 * Reverse the byte order of every word in place.
371 * ```ts
372 * byteSwap32(new Uint32Array([0x11223344]));
373 * ```
374 */
375function byteSwap32(arr) {
376    for (let i = 0; i < arr.length; i++) {
377        arr[i] = byteSwap(arr[i]);
378    }
379    return arr;
380}
381/**
382 * Conditionally byte-swaps a Uint32Array on big-endian platforms.
383 * @param u - array to normalize for host endianness
384 * @returns Original or byte-swapped array depending on platform endianness.
385 *   On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
386 * @example
387 * Normalize a word array for host endianness.
388 * ```ts
389 * swap32IfBE(new Uint32Array([0x11223344]));
390 * ```
391 */
392const swap32IfBE = isLE
393    ? (u) => u
394    : byteSwap32;
395// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
396const hasHexBuiltin$1 = /* @__PURE__ */ (() => 
397// @ts-ignore
398typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
399// Array where index 0xf0 (240) is mapped to string 'f0'
400const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
401/**
402 * Convert byte array to hex string.
403 * Uses the built-in function when available and assumes it matches the tested
404 * fallback semantics.
405 * @param bytes - bytes to encode
406 * @returns Lowercase hexadecimal string.
407 * @throws On wrong argument types. {@link TypeError}
408 * @example
409 * Convert bytes to lowercase hexadecimal.
410 * ```ts
411 * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
412 * ```
413 */
414function bytesToHex(bytes) {
415    abytes$1(bytes);
416    // @ts-ignore
417    if (hasHexBuiltin$1)
418        return bytes.toHex();
419    // pre-caching improves the speed 6x
420    let hex = '';
421    for (let i = 0; i < bytes.length; i++) {
422        hex += hexes[bytes[i]];
423    }
424    return hex;
425}
426// We use optimized technique to convert hex string to byte array
427const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
428function asciiToBase16(ch) {
429    if (ch >= asciis._0 && ch <= asciis._9)
430        return ch - asciis._0; // '2' => 50-48
431    if (ch >= asciis.A && ch <= asciis.F)
432        return ch - (asciis.A - 10); // 'B' => 66-(65-10)
433    if (ch >= asciis.a && ch <= asciis.f)
434        return ch - (asciis.a - 10); // 'b' => 98-(97-10)
435    return;
436}
437/**
438 * Convert hex string to byte array. Uses built-in function, when available.
439 * @param hex - hexadecimal string to decode
440 * @returns Decoded bytes.
441 * @throws On wrong argument types. {@link TypeError}
442 * @throws On wrong argument ranges or values. {@link RangeError}
443 * @example
444 * Decode lowercase hexadecimal into bytes.
445 * ```ts
446 * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
447 * ```
448 */
449function hexToBytes(hex) {
450    if (typeof hex !== 'string')
451        throw new TypeError('hex string expected, got ' + typeof hex);
452    if (hasHexBuiltin$1) {
453        try {
454            return Uint8Array.fromHex(hex);
455        }
456        catch (error) {
457            if (error instanceof SyntaxError)
458                throw new RangeError(error.message);
459            throw error;
460        }
461    }
462    const hl = hex.length;
463    const al = hl / 2;
464    if (hl % 2)
465        throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
466    const array = new Uint8Array(al);
467    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
468        const n1 = asciiToBase16(hex.charCodeAt(hi));
469        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
470        if (n1 === undefined || n2 === undefined) {
471            const char = hex[hi] + hex[hi + 1];
472            throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
473        }
474        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
475    }
476    return array;
477}
478/**
479 * There is no setImmediate in browser and setTimeout is slow.
480 * This yields to the Promise/microtask scheduler queue, not to timers or the
481 * full macrotask event loop.
482 * @example
483 * Yield to the next scheduler tick.
484 * ```ts
485 * await nextTick();
486 * ```
487 */
488const nextTick = async () => { };
489/**
490 * Returns control to the Promise/microtask scheduler every `tick`
491 * milliseconds to avoid blocking long loops.
492 * @param iters - number of loop iterations to run
493 * @param tick - maximum time slice in milliseconds
494 * @param cb - callback executed on each iteration
495 * @example
496 * Run a loop that periodically yields back to the event loop.
497 * ```ts
498 * await asyncLoop(2, 0, () => {});
499 * ```
500 */
501async function asyncLoop(iters, tick, cb) {
502    let ts = Date.now();
503    for (let i = 0; i < iters; i++) {
504        cb(i);
505        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
506        const diff = Date.now() - ts;
507        if (diff >= 0 && diff < tick)
508            continue;
509        await nextTick();
510        ts += diff;
511    }
512}
513/**
514 * Converts string to bytes using UTF8 encoding.
515 * Built-in doesn't validate input to be string: we do the check.
516 * Non-ASCII details are delegated to the platform `TextEncoder`.
517 * @param str - string to encode
518 * @returns UTF-8 encoded bytes.
519 * @throws On wrong argument types. {@link TypeError}
520 * @example
521 * Encode a string as UTF-8 bytes.
522 * ```ts
523 * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
524 * ```
525 */
526function utf8ToBytes(str) {
527    if (typeof str !== 'string')
528        throw new TypeError('string expected');
529    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
530}
531/**
532 * Helper for KDFs: consumes Uint8Array or string.
533 * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.
534 * @param data - user-provided KDF input
535 * @param errorTitle - label included in thrown errors
536 * @returns Byte representation of the input.
537 * @throws On wrong argument types. {@link TypeError}
538 * @example
539 * Normalize KDF input to bytes.
540 * ```ts
541 * kdfInputToBytes('password');
542 * ```
543 */
544function kdfInputToBytes(data, errorTitle = '') {
545    if (typeof data === 'string')
546        return utf8ToBytes(data);
547    return abytes$1(data, undefined, errorTitle);
548}
549/**
550 * Copies several Uint8Arrays into one.
551 * @param arrays - arrays to concatenate
552 * @returns Concatenated byte array.
553 * @throws On wrong argument types. {@link TypeError}
554 * @example
555 * Concatenate multiple byte arrays.
556 * ```ts
557 * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
558 * ```
559 */
560function concatBytes(...arrays) {
561    let sum = 0;
562    for (let i = 0; i < arrays.length; i++) {
563        const a = arrays[i];
564        abytes$1(a);
565        sum += a.length;
566    }
567    const res = new Uint8Array(sum);
568    for (let i = 0, pad = 0; i < arrays.length; i++) {
569        const a = arrays[i];
570        res.set(a, pad);
571        pad += a.length;
572    }
573    return res;
574}
575/**
576 * Merges default options and passed options.
577 * @param defaults - base option object
578 * @param opts - user overrides
579 * @returns Merged option object. The merge mutates `defaults` in place.
580 * @throws On wrong argument types. {@link TypeError}
581 * @example
582 * Merge user overrides onto default options.
583 * ```ts
584 * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
585 * ```
586 */
587function checkOpts(defaults, opts) {
588    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
589        throw new TypeError('options must be object or undefined');
590    const merged = Object.assign(defaults, opts);
591    return merged;
592}
593/**
594 * Creates a callable hash function from a stateful class constructor.
595 * @param hashCons - hash constructor or factory
596 * @param info - optional metadata such as DER OID
597 * @returns Frozen callable hash wrapper with `.create()`.
598 *   Wrapper construction eagerly calls `hashCons(undefined)` once to read
599 *   `outputLen` / `blockLen`, so constructor side effects happen at module
600 *   init time.
601 * @example
602 * Wrap a stateful hash constructor into a callable helper.
603 * ```ts
604 * import { createHasher } from '@noble/hashes/utils.js';
605 * import { sha256 } from '@noble/hashes/sha2.js';
606 * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
607 * wrapped(new Uint8Array([1]));
608 * ```
609 */
610function createHasher(hashCons, info = {}) {
611    const hashC = (msg, opts) => hashCons(opts)
612        .update(msg)
613        .digest();
614    const tmp = hashCons(undefined);
615    hashC.outputLen = tmp.outputLen;
616    hashC.blockLen = tmp.blockLen;
617    hashC.canXOF = tmp.canXOF;
618    hashC.create = (opts) => hashCons(opts);
619    Object.assign(hashC, info);
620    return Object.freeze(hashC);
621}
622/**
623 * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
624 * @param bytesLength - number of random bytes to generate
625 * @returns Random bytes.
626 * The platform `getRandomValues()` implementation still defines any
627 * single-call length cap, and this helper rejects oversize requests
628 * with a stable library `RangeError` instead of host-specific errors.
629 * @throws On wrong argument types. {@link TypeError}
630 * @throws On wrong argument ranges or values. {@link RangeError}
631 * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
632 * @example
633 * Generate a fresh random key or nonce.
634 * ```ts
635 * const key = randomBytes(16);
636 * ```
637 */
638function randomBytes(bytesLength = 32) {
639    // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
640    anumber$1(bytesLength, 'bytesLength');
641    const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
642    if (typeof cr?.getRandomValues !== 'function')
643        throw new Error('crypto.getRandomValues must be defined');
644    // Web Cryptography API Level 2 §10.1.1:
645    // if `byteLength > 65536`, throw `QuotaExceededError`.
646    // Keep the guard explicit so callers can see the quota in code
647    // instead of discovering it by reading the spec or host errors.
648    // This wrapper surfaces the same quota as a stable library RangeError.
649    if (bytesLength > 65536)
650        throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
651    return cr.getRandomValues(new Uint8Array(bytesLength));
652}
653/**
654 * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
655 * @param suffix - final OID byte for the selected hash.
656 *   The helper accepts any byte even though only the documented NIST hash
657 *   suffixes are meaningful downstream.
658 * @returns Object containing the DER-encoded OID.
659 * @example
660 * Build OID metadata for a NIST hash.
661 * ```ts
662 * oidNist(0x01);
663 * ```
664 */
665const oidNist = (suffix) => ({
666    // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
667    // Larger suffix values would need base-128 OID encoding and a different length byte.
668    oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
669});
670
671/**
672 * SHA3 (keccak) hash function, based on a new "Sponge function" design.
673 * Different from older hashes, the internal state is bigger than output size.
674 *
675 * Check out
676 * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},
677 * {@link https://keccak.team/keccak.html | Website}, and
678 * {@link https://crypto.stackexchange.com/q/15727 | the differences between
679 * SHA-3 and Keccak}.
680 *
681 * Check out `sha3-addons` module for cSHAKE, k12, and others.
682 * @module
683 */
684// No __PURE__ annotations in sha3 header:
685// EVERYTHING is in fact used on every export.
686// Various per round constants calculations
687const _0n = BigInt(0);
688const _1n = BigInt(1);
689const _2n = BigInt(2);
690const _7n = BigInt(7);
691const _256n = BigInt(256);
692// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors
693// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.
694const _0x71n = BigInt(0x71);
695const SHA3_PI = [];
696const SHA3_ROTL = [];
697const _SHA3_IOTA = []; // no pure annotation: var is always used
698for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
699    // Pi
700    [x, y] = [y, (2 * x + 3 * y) % 5];
701    SHA3_PI.push(2 * (5 * y + x));
702    // Rotational
703    SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
704    // Iota
vendor: 4,151 bytes, lines 705-814
705    let t = _0n;
706    for (let j = 0; j < 7; j++) {
707        R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
708        if (R & _2n)
709            t ^= _1n << ((_1n << BigInt(j)) - _1n);
710    }
711    _SHA3_IOTA.push(t);
712}
713const IOTAS = split(_SHA3_IOTA, true);
714// `split(..., true)` keeps the local little-endian lane-word layout used by
715// `state32`, so these `H` / `L` tables follow the file's first-word /
716// second-word lane slots rather than `_u64.ts`'s usual high/low naming.
717const SHA3_IOTA_H = IOTAS[0];
718const SHA3_IOTA_L = IOTAS[1];
719// Left rotation (without 0, 32, 64)
720const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
721const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
722/**
723 * `keccakf1600` internal permutation, additionally allows adjusting the round count.
724 * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
725 *   in this file's local little-endian lane-word order
726 * @param rounds - number of rounds to execute
727 * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
728 * @example
729 * Permute a Keccak state with the default 24 rounds.
730 * ```ts
731 * keccakP(new Uint32Array(50));
732 * ```
733 */
734function keccakP(s, rounds = 24) {
735    anumber$1(rounds, 'rounds');
736    // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.
737    if (rounds < 1 || rounds > 24)
738        throw new Error('"rounds" expected integer 1..24');
739    const B = new Uint32Array(5 * 2);
740    // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
741    for (let round = 24 - rounds; round < 24; round++) {
742        // Theta θ
743        for (let x = 0; x < 10; x++)
744            B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
745        for (let x = 0; x < 10; x += 2) {
746            const idx1 = (x + 8) % 10;
747            const idx0 = (x + 2) % 10;
748            const B0 = B[idx0];
749            const B1 = B[idx0 + 1];
750            const Th = rotlH(B0, B1, 1) ^ B[idx1];
751            const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
752            for (let y = 0; y < 50; y += 10) {
753                s[x + y] ^= Th;
754                s[x + y + 1] ^= Tl;
755            }
756        }
757        // Rho (ρ) and Pi (π)
758        let curH = s[2];
759        let curL = s[3];
760        for (let t = 0; t < 24; t++) {
761            const shift = SHA3_ROTL[t];
762            const Th = rotlH(curH, curL, shift);
763            const Tl = rotlL(curH, curL, shift);
764            const PI = SHA3_PI[t];
765            curH = s[PI];
766            curL = s[PI + 1];
767            s[PI] = Th;
768            s[PI + 1] = Tl;
769        }
770        // Chi (χ)
771        // Same as:
772        // for (let x = 0; x < 10; x++) B[x] = s[y + x];
773        // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
774        for (let y = 0; y < 50; y += 10) {
775            const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
776            s[y] ^= ~s[y + 2] & s[y + 4];
777            s[y + 1] ^= ~s[y + 3] & s[y + 5];
778            s[y + 2] ^= ~s[y + 4] & s[y + 6];
779            s[y + 3] ^= ~s[y + 5] & s[y + 7];
780            s[y + 4] ^= ~s[y + 6] & s[y + 8];
781            s[y + 5] ^= ~s[y + 7] & s[y + 9];
782            s[y + 6] ^= ~s[y + 8] & b0;
783            s[y + 7] ^= ~s[y + 9] & b1;
784            s[y + 8] ^= ~b0 & b2;
785            s[y + 9] ^= ~b1 & b3;
786        }
787        // Iota (ι)
788        s[0] ^= SHA3_IOTA_H[round];
789        s[1] ^= SHA3_IOTA_L[round];
790    }
791    clean(B);
792}
793/**
794 * Keccak sponge function.
795 * @param blockLen - absorb/squeeze rate in bytes
796 * @param suffix - domain separation suffix byte
797 * @param outputLen - default digest length in bytes. This base sponge only
798 *   requires a non-negative integer; wrappers that need positive output
799 *   lengths must enforce that themselves.
800 * @param enableXOF - whether XOF output is allowed
801 * @param rounds - number of Keccak-f rounds
802 * @example
803 * Build a sponge state, absorb bytes, then finalize a digest.
804 * ```ts
805 * const hash = new Keccak(136, 0x06, 32);
806 * hash.update(new Uint8Array([1, 2, 3]));
807 * hash.digest();
808 * ```
809 */
810class Keccak {
811    state;
812    pos = 0;
813    posOut = 0;
814    finished = false;
815    state32;
816    destroyed = false;
817    blockLen;
818    suffix;
819    outputLen;
820    canXOF;
821    enableXOF = false;
822    rounds;
823    // NOTE: we accept arguments in bytes instead of bits here.
824    constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
825        this.blockLen = blockLen;
826        this.suffix = suffix;
827        this.outputLen = outputLen;
828        this.enableXOF = enableXOF;
829        this.canXOF = enableXOF;
830        this.rounds = rounds;
831        // Can be passed from user as dkLen
832        anumber$1(outputLen, 'outputLen');
833        // 1600 = 5x5 matrix of 64bit.  1600 bits === 200 bytes
834        // 0 < blockLen < 200
835        if (!(0 < blockLen && blockLen < 200))
836            throw new Error('only keccak-f1600 function is supported');
837        this.state = new Uint8Array(200);
838        this.state32 = u32(this.state);
839    }
840    clone() {
841        return this._cloneInto();
842    }
843    keccak() {
844        swap32IfBE(this.state32);
845        keccakP(this.state32, this.rounds);
846        swap32IfBE(this.state32);
847        this.posOut = 0;
848        this.pos = 0;
849    }
850    update(data) {
851        aexists(this);
852        abytes$1(data);
853        const { blockLen, state } = this;
854        const len = data.length;
855        for (let pos = 0; pos < len;) {
856            const take = Math.min(blockLen - this.pos, len - pos);
857            for (let i = 0; i < take; i++)
858                state[this.pos++] ^= data[pos++];
859            if (this.pos === blockLen)
860                this.keccak();
861        }
862        return this;
863    }
864    finish() {
865        if (this.finished)
866            return;
867        this.finished = true;
868        const { state, suffix, pos, blockLen } = this;
869        // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.
870        // These byte values already include the first padding bit, while the
871        // final `0x80` below supplies the closing `1` bit in the last rate byte.
872        state[pos] ^= suffix;
873        // If that combined suffix lands in the last rate byte and already sets
874        // bit 7, absorb it first so the final pad10*1 bit can be xored into a
875        // fresh block.
876        if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
877            this.keccak();
878        state[blockLen - 1] ^= 0x80;
879        this.keccak();
880    }
881    writeInto(out) {
882        aexists(this, false);
883        abytes$1(out);
884        this.finish();
885        const bufferOut = this.state;
886        const { blockLen } = this;
887        for (let pos = 0, len = out.length; pos < len;) {
888            if (this.posOut >= blockLen)
889                this.keccak();
890            const take = Math.min(blockLen - this.posOut, len - pos);
891            out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
892            this.posOut += take;
893            pos += take;
894        }
895        return out;
896    }
897    xofInto(out) {
898        // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base
899        // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/
900        // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.
901        if (!this.enableXOF)
902            throw new Error('XOF is not possible for this instance');
903        return this.writeInto(out);
904    }
905    xof(bytes) {
906        anumber$1(bytes);
907        return this.xofInto(new Uint8Array(bytes));
908    }
909    digestInto(out) {
910        aoutput(out, this);
911        if (this.finished)
912            throw new Error('digest() was already called');
913        // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.
914        this.writeInto(out.subarray(0, this.outputLen));
915        this.destroy();
916    }
917    digest() {
918        const out = new Uint8Array(this.outputLen);
919        this.digestInto(out);
920        return out;
921    }
922    destroy() {
923        this.destroyed = true;
924        clean(this.state);
925    }
926    _cloneInto(to) {
927        const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
928        to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
929        // Reused destinations can come from a different rate/capacity variant, so clone must rewrite
930        // the sponge geometry as well as the state words.
931        to.blockLen = blockLen;
932        to.state32.set(this.state32);
933        to.pos = this.pos;
934        to.posOut = this.posOut;
935        to.finished = this.finished;
936        to.rounds = rounds;
937        // Suffix can change in cSHAKE
938        to.suffix = suffix;
939        to.outputLen = outputLen;
940        to.enableXOF = enableXOF;
941        // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone
942        // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.
943        to.canXOF = this.canXOF;
944        to.destroyed = this.destroyed;
945        return to;
946    }
947}
948const genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
949/**
950 * Keccak-256 hash function. Different from SHA3-256.
951 * @param msg - message bytes to hash
952 * @returns Digest bytes.
953 * @example
954 * Hash a message with Keccak-256.
955 * ```ts
956 * keccak_256(new Uint8Array([97, 98, 99]));
957 * ```
958 */
959const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);
960
961var _a$1;
962function $constructor(name, initializer, params) {
963    function init(inst, def) {
964        if (!inst._zod) {
965            Object.defineProperty(inst, "_zod", {
966                value: {
967                    def,
968                    constr: _,
969                    traits: new Set(),
970                },
971                enumerable: false,
972            });
973        }
974        if (inst._zod.traits.has(name)) {
975            return;
976        }
977        inst._zod.traits.add(name);
978        initializer(inst, def);
979        // support prototype modifications
980        const proto = _.prototype;
981        const keys = Object.keys(proto);
982        for (let i = 0; i < keys.length; i++) {
983            const k = keys[i];
984            if (!(k in inst)) {
985                inst[k] = proto[k].bind(inst);
986            }
987        }
988    }
989    // doesn't work if Parent has a constructor with arguments
990    const Parent = params?.Parent ?? Object;
991    class Definition extends Parent {
992    }
993    Object.defineProperty(Definition, "name", { value: name });
994    function _(def) {
995        var _a;
996        const inst = params?.Parent ? new Definition() : this;
997        init(inst, def);
998        (_a = inst._zod).deferred ?? (_a.deferred = []);
999        for (const fn of inst._zod.deferred) {
1000            fn();
1001        }
1002        return inst;
1003    }
1004    Object.defineProperty(_, "init", { value: init });
1005    Object.defineProperty(_, Symbol.hasInstance, {
1006        value: (inst) => {
1007            if (params?.Parent && inst instanceof params.Parent)
1008                return true;
1009            return inst?._zod?.traits?.has(name);
1010        },
1011    });
1012    Object.defineProperty(_, "name", { value: name });
1013    return _;
1014}
1015class $ZodAsyncError extends Error {
1016    constructor() {
1017        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
1018    }
1019}
1020class $ZodEncodeError extends Error {
1021    constructor(name) {
1022        super(`Encountered unidirectional transform during encode: ${name}`);
1023        this.name = "ZodEncodeError";
1024    }
1025}
1026(_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {});
1027const globalConfig = globalThis.__zod_globalConfig;
1028function config(newConfig) {
1029    return globalConfig;
1030}
1031
1032function getEnumValues(entries) {
1033    const numericValues = Object.values(entries).filter((v) => typeof v === "number");
1034    const values = Object.entries(entries)
1035        .filter(([k, _]) => numericValues.indexOf(+k) === -1)
1036        .map(([_, v]) => v);
1037    return values;
1038}
1039function jsonStringifyReplacer(_, value) {
1040    if (typeof value === "bigint")
1041        return value.toString();
1042    return value;
1043}
1044function cached(getter) {
1045    return {
1046        get value() {
1047            {
1048                const value = getter();
1049                Object.defineProperty(this, "value", { value });
1050                return value;
1051            }
1052        },
1053    };
1054}
1055function nullish(input) {
1056    return input === null || input === undefined;
1057}
1058function cleanRegex(source) {
1059    const start = source.startsWith("^") ? 1 : 0;
1060    const end = source.endsWith("$") ? source.length - 1 : source.length;
1061    return source.slice(start, end);
1062}
1063function floatSafeRemainder(val, step) {
1064    const ratio = val / step;
1065    const roundedRatio = Math.round(ratio);
1066    // Use a relative epsilon scaled to the magnitude of the result
1067    const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
1068    if (Math.abs(ratio - roundedRatio) < tolerance)
1069        return 0;
1070    return ratio - roundedRatio;
1071}
1072const EVALUATING = /* @__PURE__*/ Symbol("evaluating");
1073function defineLazy(object, key, getter) {
1074    let value = undefined;
1075    Object.defineProperty(object, key, {
1076        get() {
1077            if (value === EVALUATING) {
1078                // Circular reference detected, return undefined to break the cycle
1079                return undefined;
1080            }
1081            if (value === undefined) {
1082                value = EVALUATING;
1083                value = getter();
1084            }
1085            return value;
1086        },
1087        set(v) {
1088            Object.defineProperty(object, key, {
1089                value: v,
1090                // configurable: true,
1091            });
1092            // object[key] = v;
1093        },
1094        configurable: true,
1095    });
1096}
1097function assignProp(target, prop, value) {
1098    Object.defineProperty(target, prop, {
1099        value,
1100        writable: true,
1101        enumerable: true,
1102        configurable: true,
1103    });
1104}
1105function mergeDefs(...defs) {
1106    const mergedDescriptors = {};
1107    for (const def of defs) {
1108        const descriptors = Object.getOwnPropertyDescriptors(def);
1109        Object.assign(mergedDescriptors, descriptors);
1110    }
1111    return Object.defineProperties({}, mergedDescriptors);
1112}
1113function esc(str) {
1114    return JSON.stringify(str);
1115}
vendor: 10,035 bytes, lines 1116-1409
1116function slugify(input) {
1117    return input
1118        .toLowerCase()
1119        .trim()
1120        .replace(/[^\w\s-]/g, "")
1121        .replace(/[\s_-]+/g, "-")
1122        .replace(/^-+|-+$/g, "");
1123}
1124const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
1125function isObject(data) {
1126    return typeof data === "object" && data !== null && !Array.isArray(data);
1127}
1128const allowsEval = /* @__PURE__*/ cached(() => {
1129    // Skip the probe under `jitless`: strict CSPs report the caught `new Function`
1130    // as a `securitypolicyviolation` even though the throw is swallowed.
1131    if (globalConfig.jitless) {
1132        return false;
1133    }
1134    // @ts-ignore
1135    if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
1136        return false;
1137    }
1138    try {
1139        const F = Function;
1140        new F("");
1141        return true;
1142    }
1143    catch (_) {
1144        return false;
1145    }
1146});
1147function isPlainObject(o) {
1148    if (isObject(o) === false)
1149        return false;
1150    // modified constructor
1151    const ctor = o.constructor;
1152    if (ctor === undefined)
1153        return true;
1154    if (typeof ctor !== "function")
1155        return true;
1156    // modified prototype
1157    const prot = ctor.prototype;
1158    if (isObject(prot) === false)
1159        return false;
1160    // ctor doesn't have static `isPrototypeOf`
1161    if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
1162        return false;
1163    }
1164    return true;
1165}
1166function shallowClone(o) {
1167    if (isPlainObject(o))
1168        return { ...o };
1169    if (Array.isArray(o))
1170        return [...o];
1171    if (o instanceof Map)
1172        return new Map(o);
1173    if (o instanceof Set)
1174        return new Set(o);
1175    return o;
1176}
1177const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]);
1178function escapeRegex(str) {
1179    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1180}
1181// zod-specific utils
1182function clone(inst, def, params) {
1183    const cl = new inst._zod.constr(def ?? inst._zod.def);
1184    if (!def || params?.parent)
1185        cl._zod.parent = inst;
1186    return cl;
1187}
1188function normalizeParams(_params) {
1189    const params = _params;
1190    if (!params)
1191        return {};
1192    if (typeof params === "string")
1193        return { error: () => params };
1194    if (params?.message !== undefined) {
1195        if (params?.error !== undefined)
1196            throw new Error("Cannot specify both `message` and `error` params");
1197        params.error = params.message;
1198    }
1199    delete params.message;
1200    if (typeof params.error === "string")
1201        return { ...params, error: () => params.error };
1202    return params;
1203}
1204function optionalKeys(shape) {
1205    return Object.keys(shape).filter((k) => {
1206        return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
1207    });
1208}
1209const NUMBER_FORMAT_RANGES = {
1210    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
1211    int32: [-2147483648, 2147483647],
1212    uint32: [0, 4294967295],
1213    float32: [-34028234663852886e22, 3.4028234663852886e38],
1214    float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
1215};
1216function pick(schema, mask) {
1217    const currDef = schema._zod.def;
1218    const checks = currDef.checks;
1219    const hasChecks = checks && checks.length > 0;
1220    if (hasChecks) {
1221        throw new Error(".pick() cannot be used on object schemas containing refinements");
1222    }
1223    const def = mergeDefs(schema._zod.def, {
1224        get shape() {
1225            const newShape = {};
1226            for (const key in mask) {
1227                if (!(key in currDef.shape)) {
1228                    throw new Error(`Unrecognized key: "${key}"`);
1229                }
1230                if (!mask[key])
1231                    continue;
1232                newShape[key] = currDef.shape[key];
1233            }
1234            assignProp(this, "shape", newShape); // self-caching
1235            return newShape;
1236        },
1237        checks: [],
1238    });
1239    return clone(schema, def);
1240}
1241function omit(schema, mask) {
1242    const currDef = schema._zod.def;
1243    const checks = currDef.checks;
1244    const hasChecks = checks && checks.length > 0;
1245    if (hasChecks) {
1246        throw new Error(".omit() cannot be used on object schemas containing refinements");
1247    }
1248    const def = mergeDefs(schema._zod.def, {
1249        get shape() {
1250            const newShape = { ...schema._zod.def.shape };
1251            for (const key in mask) {
1252                if (!(key in currDef.shape)) {
1253                    throw new Error(`Unrecognized key: "${key}"`);
1254                }
1255                if (!mask[key])
1256                    continue;
1257                delete newShape[key];
1258            }
1259            assignProp(this, "shape", newShape); // self-caching
1260            return newShape;
1261        },
1262        checks: [],
1263    });
1264    return clone(schema, def);
1265}
1266function extend(schema, shape) {
1267    if (!isPlainObject(shape)) {
1268        throw new Error("Invalid input to extend: expected a plain object");
1269    }
1270    const checks = schema._zod.def.checks;
1271    const hasChecks = checks && checks.length > 0;
1272    if (hasChecks) {
1273        // Only throw if new shape overlaps with existing shape
1274        // Use getOwnPropertyDescriptor to check key existence without accessing values
1275        const existingShape = schema._zod.def.shape;
1276        for (const key in shape) {
1277            if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
1278                throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
1279            }
1280        }
1281    }
1282    const def = mergeDefs(schema._zod.def, {
1283        get shape() {
1284            const _shape = { ...schema._zod.def.shape, ...shape };
1285            assignProp(this, "shape", _shape); // self-caching
1286            return _shape;
1287        },
1288    });
1289    return clone(schema, def);
1290}
1291function safeExtend(schema, shape) {
1292    if (!isPlainObject(shape)) {
1293        throw new Error("Invalid input to safeExtend: expected a plain object");
1294    }
1295    const def = mergeDefs(schema._zod.def, {
1296        get shape() {
1297            const _shape = { ...schema._zod.def.shape, ...shape };
1298            assignProp(this, "shape", _shape); // self-caching
1299            return _shape;
1300        },
1301    });
1302    return clone(schema, def);
1303}
1304function merge(a, b) {
1305    if (a._zod.def.checks?.length) {
1306        throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
1307    }
1308    const def = mergeDefs(a._zod.def, {
1309        get shape() {
1310            const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
1311            assignProp(this, "shape", _shape); // self-caching
1312            return _shape;
1313        },
1314        get catchall() {
1315            return b._zod.def.catchall;
1316        },
1317        checks: b._zod.def.checks ?? [],
1318    });
1319    return clone(a, def);
1320}
1321function partial(Class, schema, mask) {
1322    const currDef = schema._zod.def;
1323    const checks = currDef.checks;
1324    const hasChecks = checks && checks.length > 0;
1325    if (hasChecks) {
1326        throw new Error(".partial() cannot be used on object schemas containing refinements");
1327    }
1328    const def = mergeDefs(schema._zod.def, {
1329        get shape() {
1330            const oldShape = schema._zod.def.shape;
1331            const shape = { ...oldShape };
1332            if (mask) {
1333                for (const key in mask) {
1334                    if (!(key in oldShape)) {
1335                        throw new Error(`Unrecognized key: "${key}"`);
1336                    }
1337                    if (!mask[key])
1338                        continue;
1339                    // if (oldShape[key]!._zod.optin === "optional") continue;
1340                    shape[key] = Class
1341                        ? new Class({
1342                            type: "optional",
1343                            innerType: oldShape[key],
1344                        })
1345                        : oldShape[key];
1346                }
1347            }
1348            else {
1349                for (const key in oldShape) {
1350                    // if (oldShape[key]!._zod.optin === "optional") continue;
1351                    shape[key] = Class
1352                        ? new Class({
1353                            type: "optional",
1354                            innerType: oldShape[key],
1355                        })
1356                        : oldShape[key];
1357                }
1358            }
1359            assignProp(this, "shape", shape); // self-caching
1360            return shape;
1361        },
1362        checks: [],
1363    });
1364    return clone(schema, def);
1365}
1366function required(Class, schema, mask) {
1367    const def = mergeDefs(schema._zod.def, {
1368        get shape() {
1369            const oldShape = schema._zod.def.shape;
1370            const shape = { ...oldShape };
1371            if (mask) {
1372                for (const key in mask) {
1373                    if (!(key in shape)) {
1374                        throw new Error(`Unrecognized key: "${key}"`);
1375                    }
1376                    if (!mask[key])
1377                        continue;
1378                    // overwrite with non-optional
1379                    shape[key] = new Class({
1380                        type: "nonoptional",
1381                        innerType: oldShape[key],
1382                    });
1383                }
1384            }
1385            else {
1386                for (const key in oldShape) {
1387                    // overwrite with non-optional
1388                    shape[key] = new Class({
1389                        type: "nonoptional",
1390                        innerType: oldShape[key],
1391                    });
1392                }
1393            }
1394            assignProp(this, "shape", shape); // self-caching
1395            return shape;
1396        },
1397    });
1398    return clone(schema, def);
1399}
1400// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
1401function aborted(x, startIndex = 0) {
1402    if (x.aborted === true)
1403        return true;
1404    for (let i = startIndex; i < x.issues.length; i++) {
1405        if (x.issues[i]?.continue !== true) {
1406            return true;
1407        }
1408    }
1409    return false;
1410}
1411// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).
1412// Used to respect `abort: true` in .refine() even for checks that have a `when` function.
1413function explicitlyAborted(x, startIndex = 0) {
1414    if (x.aborted === true)
1415        return true;
1416    for (let i = startIndex; i < x.issues.length; i++) {
1417        if (x.issues[i]?.continue === false) {
1418            return true;
1419        }
1420    }
1421    return false;
1422}
1423function prefixIssues(path, issues) {
1424    return issues.map((iss) => {
1425        var _a;
1426        (_a = iss).path ?? (_a.path = []);
1427        iss.path.unshift(path);
1428        return iss;
1429    });
1430}
1431function unwrapMessage(message) {
1432    return typeof message === "string" ? message : message?.message;
1433}
1434function finalizeIssue(iss, ctx, config) {
1435    const message = iss.message
1436        ? iss.message
1437        : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
1438            unwrapMessage(ctx?.error?.(iss)) ??
1439            unwrapMessage(config.customError?.(iss)) ??
1440            unwrapMessage(config.localeError?.(iss)) ??
1441            "Invalid input");
1442    const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
1443    rest.path ?? (rest.path = []);
1444    rest.message = message;
1445    if (ctx?.reportInput) {
1446        rest.input = _input;
1447    }
1448    return rest;
1449}
1450function getLengthableOrigin(input) {
1451    if (Array.isArray(input))
1452        return "array";
1453    if (typeof input === "string")
1454        return "string";
1455    return "unknown";
1456}
1457function issue(...args) {
1458    const [iss, input, inst] = args;
1459    if (typeof iss === "string") {
1460        return {
1461            message: iss,
1462            code: "custom",
1463            input,
1464            inst,
1465        };
1466    }
1467    return { ...iss };
1468}
1469
1470const initializer$1 = (inst, def) => {
1471    inst.name = "$ZodError";
1472    Object.defineProperty(inst, "_zod", {
1473        value: inst._zod,
1474        enumerable: false,
1475    });
1476    Object.defineProperty(inst, "issues", {
1477        value: def,
1478        enumerable: false,
1479    });
1480    inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
1481    Object.defineProperty(inst, "toString", {
1482        value: () => inst.message,
1483        enumerable: false,
1484    });
1485};
1486const $ZodError = $constructor("$ZodError", initializer$1);
1487const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
1488function flattenError(error, mapper = (issue) => issue.message) {
1489    const fieldErrors = {};
1490    const formErrors = [];
1491    for (const sub of error.issues) {
1492        if (sub.path.length > 0) {
1493            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
1494            fieldErrors[sub.path[0]].push(mapper(sub));
1495        }
1496        else {
1497            formErrors.push(mapper(sub));
1498        }
1499    }
1500    return { formErrors, fieldErrors };
1501}
1502function formatError(error, mapper = (issue) => issue.message) {
1503    const fieldErrors = { _errors: [] };
1504    const processError = (error, path = []) => {
1505        for (const issue of error.issues) {
1506            if (issue.code === "invalid_union" && issue.errors.length) {
1507                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
1508            }
1509            else if (issue.code === "invalid_key") {
1510                processError({ issues: issue.issues }, [...path, ...issue.path]);
1511            }
1512            else if (issue.code === "invalid_element") {
1513                processError({ issues: issue.issues }, [...path, ...issue.path]);
1514            }
1515            else {
1516                const fullpath = [...path, ...issue.path];
1517                if (fullpath.length === 0) {
1518                    fieldErrors._errors.push(mapper(issue));
1519                }
1520                else {
1521                    let curr = fieldErrors;
1522                    let i = 0;
1523                    while (i < fullpath.length) {
1524                        const el = fullpath[i];
1525                        const terminal = i === fullpath.length - 1;
1526                        if (!terminal) {
1527                            curr[el] = curr[el] || { _errors: [] };
1528                        }
1529                        else {
1530                            curr[el] = curr[el] || { _errors: [] };
1531                            curr[el]._errors.push(mapper(issue));
1532                        }
1533                        curr = curr[el];
1534                        i++;
1535                    }
1536                }
1537            }
1538        }
1539    };
1540    processError(error);
1541    return fieldErrors;
1542}
1543
1544const _parse = (_Err) => (schema, value, _ctx, _params) => {
1545    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
1546    const result = schema._zod.run({ value, issues: [] }, ctx);
1547    if (result instanceof Promise) {
1548        throw new $ZodAsyncError();
1549    }
1550    if (result.issues.length) {
1551        const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1552        captureStackTrace(e, _params?.callee);
1553        throw e;
1554    }
1555    return result.value;
1556};
1557const parse$1 = /* @__PURE__*/ _parse($ZodRealError);
1558const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
1559    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
1560    let result = schema._zod.run({ value, issues: [] }, ctx);
1561    if (result instanceof Promise)
1562        result = await result;
1563    if (result.issues.length) {
1564        const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1565        captureStackTrace(e, params?.callee);
1566        throw e;
1567    }
1568    return result.value;
1569};
1570const parseAsync$1 = /* @__PURE__*/ _parseAsync($ZodRealError);
1571const _safeParse = (_Err) => (schema, value, _ctx) => {
1572    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
1573    const result = schema._zod.run({ value, issues: [] }, ctx);
1574    if (result instanceof Promise) {
1575        throw new $ZodAsyncError();
1576    }
1577    return result.issues.length
1578        ? {
1579            success: false,
1580            error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
1581        }
1582        : { success: true, data: result.value };
1583};
1584const safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError);
1585const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
1586    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
1587    let result = schema._zod.run({ value, issues: [] }, ctx);
1588    if (result instanceof Promise)
1589        result = await result;
1590    return result.issues.length
1591        ? {
1592            success: false,
1593            error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
1594        }
1595        : { success: true, data: result.value };
1596};
1597const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
1598const _encode = (_Err) => (schema, value, _ctx) => {
1599    const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1600    return _parse(_Err)(schema, value, ctx);
1601};
1602const _decode = (_Err) => (schema, value, _ctx) => {
1603    return _parse(_Err)(schema, value, _ctx);
1604};
1605const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
1606    const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1607    return _parseAsync(_Err)(schema, value, ctx);
1608};
1609const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
1610    return _parseAsync(_Err)(schema, value, _ctx);
1611};
1612const _safeEncode = (_Err) => (schema, value, _ctx) => {
1613    const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1614    return _safeParse(_Err)(schema, value, ctx);
1615};
1616const _safeDecode = (_Err) => (schema, value, _ctx) => {
1617    return _safeParse(_Err)(schema, value, _ctx);
1618};
1619const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
1620    const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
1621    return _safeParseAsync(_Err)(schema, value, ctx);
1622};
1623const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
1624    return _safeParseAsync(_Err)(schema, value, _ctx);
1625};
1626
1627/**
1628 * @deprecated CUID v1 is deprecated by its authors due to information leakage
1629 * (timestamps embedded in the id). Use {@link cuid2} instead.
1630 * See https://github.com/paralleldrive/cuid.
1631 */
1632const cuid = /^[cC][0-9a-z]{6,}$/;
1633const cuid2 = /^[0-9a-z]+$/;
1634const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
1635const xid = /^[0-9a-vA-V]{20}$/;
1636const ksuid = /^[A-Za-z0-9]{27}$/;
1637const nanoid = /^[a-zA-Z0-9_-]{21}$/;
1638/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
1639const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
1640/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
1641const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
1642/** Returns a regex for validating an RFC 9562/4122 UUID.
1643 *
1644 * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
1645const uuid = (version) => {
1646    if (!version)
1647        return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
1648    return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
1649};
1650/** Practical email validation */
1651const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
1652// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
1653const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1654function emoji() {
1655    return new RegExp(_emoji$1, "u");
1656}
1657const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1658const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
1659const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
1660const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
1661// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
1662const base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4}
1662)*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
1663const base64url$1 = /^[A-Za-z0-9_-]*$/;
1664const httpProtocol = /^https?$/;
1665// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
1666// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15
1667const e164 = /^\+[1-9]\d{6,14}$/;
1668// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1669const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
1670const date$2 = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
1671function timeSource(args) {
1672    const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
1673    const regex = typeof args.precision === "number"
1674        ? args.precision === -1
1675            ? `${hhmm}`
1676            : args.precision === 0
1677                ? `${hhmm}:[0-5]\\d`
1678                : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
1679        : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
1680    return regex;
1681}
1682function time$1(args) {
1683    return new RegExp(`^${timeSource(args)}$`);
1684}
1685// Adapted from https://stackoverflow.com/a/3143231
1686function datetime$1(args) {
1687    const time = timeSource({ precision: args.precision });
1688    const opts = ["Z"];
1689    if (args.local)
1690        opts.push("");
1691    // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
1692    if (args.offset)
1693        opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1694    const timeRegex = `${time}(?:${opts.join("|")})`;
1695    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1696}
1697const string$1 = (params) => {
1698    const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
1699    return new RegExp(`^${regex}$`);
1700};
1701const integer = /^-?\d+$/;
1702const number$2 = /^-?\d+(?:\.\d+)?$/;
1703const boolean$1 = /^(?:true|false)
vendor: 15,483 bytes, lines 1703-2159
1703$/i;
1704// regex for string with no uppercase letters
1705const lowercase = /^[^A-Z]*$/;
1706// regex for string with no lowercase letters
1707const uppercase = /^[^a-z]*$/;
1708
1709// import { $ZodType } from "./schemas.js";
1710const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
1711    var _a;
1712    inst._zod ?? (inst._zod = {});
1713    inst._zod.def = def;
1714    (_a = inst._zod).onattach ?? (_a.onattach = []);
1715});
1716const numericOriginMap = {
1717    number: "number",
1718    bigint: "bigint",
1719    object: "date",
1720};
1721const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => {
1722    $ZodCheck.init(inst, def);
1723    const origin = numericOriginMap[typeof def.value];
1724    inst._zod.onattach.push((inst) => {
1725        const bag = inst._zod.bag;
1726        const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
1727        if (def.value < curr) {
1728            if (def.inclusive)
1729                bag.maximum = def.value;
1730            else
1731                bag.exclusiveMaximum = def.value;
1732        }
1733    });
1734    inst._zod.check = (payload) => {
1735        if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
1736            return;
1737        }
1738        payload.issues.push({
1739            origin,
1740            code: "too_big",
1741            maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
1742            input: payload.value,
1743            inclusive: def.inclusive,
1744            inst,
1745            continue: !def.abort,
1746        });
1747    };
1748});
1749const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => {
1750    $ZodCheck.init(inst, def);
1751    const origin = numericOriginMap[typeof def.value];
1752    inst._zod.onattach.push((inst) => {
1753        const bag = inst._zod.bag;
1754        const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
1755        if (def.value > curr) {
1756            if (def.inclusive)
1757                bag.minimum = def.value;
1758            else
1759                bag.exclusiveMinimum = def.value;
1760        }
1761    });
1762    inst._zod.check = (payload) => {
1763        if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
1764            return;
1765        }
1766        payload.issues.push({
1767            origin,
1768            code: "too_small",
1769            minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
1770            input: payload.value,
1771            inclusive: def.inclusive,
1772            inst,
1773            continue: !def.abort,
1774        });
1775    };
1776});
1777const $ZodCheckMultipleOf = 
1778/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => {
1779    $ZodCheck.init(inst, def);
1780    inst._zod.onattach.push((inst) => {
1781        var _a;
1782        (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
1783    });
1784    inst._zod.check = (payload) => {
1785        if (typeof payload.value !== typeof def.value)
1786            throw new Error("Cannot mix number and bigint in multiple_of check.");
1787        const isMultiple = typeof payload.value === "bigint"
1788            ? payload.value % def.value === BigInt(0)
1789            : floatSafeRemainder(payload.value, def.value) === 0;
1790        if (isMultiple)
1791            return;
1792        payload.issues.push({
1793            origin: typeof payload.value,
1794            code: "not_multiple_of",
1795            divisor: def.value,
1796            input: payload.value,
1797            inst,
1798            continue: !def.abort,
1799        });
1800    };
1801});
1802const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
1803    $ZodCheck.init(inst, def); // no format checks
1804    def.format = def.format || "float64";
1805    const isInt = def.format?.includes("int");
1806    const origin = isInt ? "int" : "number";
1807    const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
1808    inst._zod.onattach.push((inst) => {
1809        const bag = inst._zod.bag;
1810        bag.format = def.format;
1811        bag.minimum = minimum;
1812        bag.maximum = maximum;
1813        if (isInt)
1814            bag.pattern = integer;
1815    });
1816    inst._zod.check = (payload) => {
1817        const input = payload.value;
1818        if (isInt) {
1819            if (!Number.isInteger(input)) {
1820                // invalid_format issue
1821                // payload.issues.push({
1822                //   expected: def.format,
1823                //   format: def.format,
1824                //   code: "invalid_format",
1825                //   input,
1826                //   inst,
1827                // });
1828                // invalid_type issue
1829                payload.issues.push({
1830                    expected: origin,
1831                    format: def.format,
1832                    code: "invalid_type",
1833                    continue: false,
1834                    input,
1835                    inst,
1836                });
1837                return;
1838                // not_multiple_of issue
1839                // payload.issues.push({
1840                //   code: "not_multiple_of",
1841                //   origin: "number",
1842                //   input,
1843                //   inst,
1844                //   divisor: 1,
1845                // });
1846            }
1847            if (!Number.isSafeInteger(input)) {
1848                if (input > 0) {
1849                    // too_big
1850                    payload.issues.push({
1851                        input,
1852                        code: "too_big",
1853                        maximum: Number.MAX_SAFE_INTEGER,
1854                        note: "Integers must be within the safe integer range.",
1855                        inst,
1856                        origin,
1857                        inclusive: true,
1858                        continue: !def.abort,
1859                    });
1860                }
1861                else {
1862                    // too_small
1863                    payload.issues.push({
1864                        input,
1865                        code: "too_small",
1866                        minimum: Number.MIN_SAFE_INTEGER,
1867                        note: "Integers must be within the safe integer range.",
1868                        inst,
1869                        origin,
1870                        inclusive: true,
1871                        continue: !def.abort,
1872                    });
1873                }
1874                return;
1875            }
1876        }
1877        if (input < minimum) {
1878            payload.issues.push({
1879                origin: "number",
1880                input,
1881                code: "too_small",
1882                minimum,
1883                inclusive: true,
1884                inst,
1885                continue: !def.abort,
1886            });
1887        }
1888        if (input > maximum) {
1889            payload.issues.push({
1890                origin: "number",
1891                input,
1892                code: "too_big",
1893                maximum,
1894                inclusive: true,
1895                inst,
1896                continue: !def.abort,
1897            });
1898        }
1899    };
1900});
1901const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
1902    var _a;
1903    $ZodCheck.init(inst, def);
1904    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1905        const val = payload.value;
1906        return !nullish(val) && val.length !== undefined;
1907    });
1908    inst._zod.onattach.push((inst) => {
1909        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
1910        if (def.maximum < curr)
1911            inst._zod.bag.maximum = def.maximum;
1912    });
1913    inst._zod.check = (payload) => {
1914        const input = payload.value;
1915        const length = input.length;
1916        if (length <= def.maximum)
1917            return;
1918        const origin = getLengthableOrigin(input);
1919        payload.issues.push({
1920            origin,
1921            code: "too_big",
1922            maximum: def.maximum,
1923            inclusive: true,
1924            input,
1925            inst,
1926            continue: !def.abort,
1927        });
1928    };
1929});
1930const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
1931    var _a;
1932    $ZodCheck.init(inst, def);
1933    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1934        const val = payload.value;
1935        return !nullish(val) && val.length !== undefined;
1936    });
1937    inst._zod.onattach.push((inst) => {
1938        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
1939        if (def.minimum > curr)
1940            inst._zod.bag.minimum = def.minimum;
1941    });
1942    inst._zod.check = (payload) => {
1943        const input = payload.value;
1944        const length = input.length;
1945        if (length >= def.minimum)
1946            return;
1947        const origin = getLengthableOrigin(input);
1948        payload.issues.push({
1949            origin,
1950            code: "too_small",
1951            minimum: def.minimum,
1952            inclusive: true,
1953            input,
1954            inst,
1955            continue: !def.abort,
1956        });
1957    };
1958});
1959const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1960    var _a;
1961    $ZodCheck.init(inst, def);
1962    (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1963        const val = payload.value;
1964        return !nullish(val) && val.length !== undefined;
1965    });
1966    inst._zod.onattach.push((inst) => {
1967        const bag = inst._zod.bag;
1968        bag.minimum = def.length;
1969        bag.maximum = def.length;
1970        bag.length = def.length;
1971    });
1972    inst._zod.check = (payload) => {
1973        const input = payload.value;
1974        const length = input.length;
1975        if (length === def.length)
1976            return;
1977        const origin = getLengthableOrigin(input);
1978        const tooBig = length > def.length;
1979        payload.issues.push({
1980            origin,
1981            ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
1982            inclusive: true,
1983            exact: true,
1984            input: payload.value,
1985            inst,
1986            continue: !def.abort,
1987        });
1988    };
1989});
1990const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
1991    var _a, _b;
1992    $ZodCheck.init(inst, def);
1993    inst._zod.onattach.push((inst) => {
1994        const bag = inst._zod.bag;
1995        bag.format = def.format;
1996        if (def.pattern) {
1997            bag.patterns ?? (bag.patterns = new Set());
1998            bag.patterns.add(def.pattern);
1999        }
2000    });
2001    if (def.pattern)
2002        (_a = inst._zod).check ?? (_a.check = (payload) => {
2003            def.pattern.lastIndex = 0;
2004            if (def.pattern.test(payload.value))
2005                return;
2006            payload.issues.push({
2007                origin: "string",
2008                code: "invalid_format",
2009                format: def.format,
2010                input: payload.value,
2011                ...(def.pattern ? { pattern: def.pattern.toString() } : {}),
2012                inst,
2013                continue: !def.abort,
2014            });
2015        });
2016    else
2017        (_b = inst._zod).check ?? (_b.check = () => { });
2018});
2019const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
2020    $ZodCheckStringFormat.init(inst, def);
2021    inst._zod.check = (payload) => {
2022        def.pattern.lastIndex = 0;
2023        if (def.pattern.test(payload.value))
2024            return;
2025        payload.issues.push({
2026            origin: "string",
2027            code: "invalid_format",
2028            format: "regex",
2029            input: payload.value,
2030            pattern: def.pattern.toString(),
2031            inst,
2032            continue: !def.abort,
2033        });
2034    };
2035});
2036const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
2037    def.pattern ?? (def.pattern = lowercase);
2038    $ZodCheckStringFormat.init(inst, def);
2039});
2040const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
2041    def.pattern ?? (def.pattern = uppercase);
2042    $ZodCheckStringFormat.init(inst, def);
2043});
2044const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
2045    $ZodCheck.init(inst, def);
2046    const escapedRegex = escapeRegex(def.includes);
2047    const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
2048    def.pattern = pattern;
2049    inst._zod.onattach.push((inst) => {
2050        const bag = inst._zod.bag;
2051        bag.patterns ?? (bag.patterns = new Set());
2052        bag.patterns.add(pattern);
2053    });
2054    inst._zod.check = (payload) => {
2055        if (payload.value.includes(def.includes, def.position))
2056            return;
2057        payload.issues.push({
2058            origin: "string",
2059            code: "invalid_format",
2060            format: "includes",
2061            includes: def.includes,
2062            input: payload.value,
2063            inst,
2064            continue: !def.abort,
2065        });
2066    };
2067});
2068const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
2069    $ZodCheck.init(inst, def);
2070    const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
2071    def.pattern ?? (def.pattern = pattern);
2072    inst._zod.onattach.push((inst) => {
2073        const bag = inst._zod.bag;
2074        bag.patterns ?? (bag.patterns = new Set());
2075        bag.patterns.add(pattern);
2076    });
2077    inst._zod.check = (payload) => {
2078        if (payload.value.startsWith(def.prefix))
2079            return;
2080        payload.issues.push({
2081            origin: "string",
2082            code: "invalid_format",
2083            format: "starts_with",
2084            prefix: def.prefix,
2085            input: payload.value,
2086            inst,
2087            continue: !def.abort,
2088        });
2089    };
2090});
2091const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
2092    $ZodCheck.init(inst, def);
2093    const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
2094    def.pattern ?? (def.pattern = pattern);
2095    inst._zod.onattach.push((inst) => {
2096        const bag = inst._zod.bag;
2097        bag.patterns ?? (bag.patterns = new Set());
2098        bag.patterns.add(pattern);
2099    });
2100    inst._zod.check = (payload) => {
2101        if (payload.value.endsWith(def.suffix))
2102            return;
2103        payload.issues.push({
2104            origin: "string",
2105            code: "invalid_format",
2106            format: "ends_with",
2107            suffix: def.suffix,
2108            input: payload.value,
2109            inst,
2110            continue: !def.abort,
2111        });
2112    };
2113});
2114const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
2115    $ZodCheck.init(inst, def);
2116    inst._zod.check = (payload) => {
2117        payload.value = def.tx(payload.value);
2118    };
2119});
2120
2121class Doc {
2122    constructor(args = []) {
2123        this.content = [];
2124        this.indent = 0;
2125        if (this)
2126            this.args = args;
2127    }
2128    indented(fn) {
2129        this.indent += 1;
2130        fn(this);
2131        this.indent -= 1;
2132    }
2133    write(arg) {
2134        if (typeof arg === "function") {
2135            arg(this, { execution: "sync" });
2136            arg(this, { execution: "async" });
2137            return;
2138        }
2139        const content = arg;
2140        const lines = content.split("\n").filter((x) => x);
2141        const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
2142        const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
2143        for (const line of dedented) {
2144            this.content.push(line);
2145        }
2146    }
2147    compile() {
2148        const F = Function;
2149        const args = this?.args;
2150        const content = this?.content ?? [``];
2151        const lines = [...content.map((x) => `  ${x}`)];
2152        // console.log(lines.join("\n"));
2153        return new F(...args, lines.join("\n"));
2154    }
2155}
2156
2157const version = {
2158    major: 4,
2159    minor: 
vendor: 4,230 bytes, lines 2159-2268
21594,
2160    patch: 3,
2161};
2162
2163const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
2164    var _a;
2165    inst ?? (inst = {});
2166    inst._zod.def = def; // set _def property
2167    inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
2168    inst._zod.version = version;
2169    const checks = [...(inst._zod.def.checks ?? [])];
2170    // if inst is itself a checks.$ZodCheck, run it as a check
2171    if (inst._zod.traits.has("$ZodCheck")) {
2172        checks.unshift(inst);
2173    }
2174    for (const ch of checks) {
2175        for (const fn of ch._zod.onattach) {
2176            fn(inst);
2177        }
2178    }
2179    if (checks.length === 0) {
2180        // deferred initializer
2181        // inst._zod.parse is not yet defined
2182        (_a = inst._zod).deferred ?? (_a.deferred = []);
2183        inst._zod.deferred?.push(() => {
2184            inst._zod.run = inst._zod.parse;
2185        });
2186    }
2187    else {
2188        const runChecks = (payload, checks, ctx) => {
2189            let isAborted = aborted(payload);
2190            let asyncResult;
2191            for (const ch of checks) {
2192                if (ch._zod.def.when) {
2193                    if (explicitlyAborted(payload))
2194                        continue;
2195                    const shouldRun = ch._zod.def.when(payload);
2196                    if (!shouldRun)
2197                        continue;
2198                }
2199                else if (isAborted) {
2200                    continue;
2201                }
2202                const currLen = payload.issues.length;
2203                const _ = ch._zod.check(payload);
2204                if (_ instanceof Promise && ctx?.async === false) {
2205                    throw new $ZodAsyncError();
2206                }
2207                if (asyncResult || _ instanceof Promise) {
2208                    asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
2209                        await _;
2210                        const nextLen = payload.issues.length;
2211                        if (nextLen === currLen)
2212                            return;
2213                        if (!isAborted)
2214                            isAborted = aborted(payload, currLen);
2215                    });
2216                }
2217                else {
2218                    const nextLen = payload.issues.length;
2219                    if (nextLen === currLen)
2220                        continue;
2221                    if (!isAborted)
2222                        isAborted = aborted(payload, currLen);
2223                }
2224            }
2225            if (asyncResult) {
2226                return asyncResult.then(() => {
2227                    return payload;
2228                });
2229            }
2230            return payload;
2231        };
2232        const handleCanaryResult = (canary, payload, ctx) => {
2233            // abort if the canary is aborted
2234            if (aborted(canary)) {
2235                canary.aborted = true;
2236                return canary;
2237            }
2238            // run checks first, then
2239            const checkResult = runChecks(payload, checks, ctx);
2240            if (checkResult instanceof Promise) {
2241                if (ctx.async === false)
2242                    throw new $ZodAsyncError();
2243                return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
2244            }
2245            return inst._zod.parse(checkResult, ctx);
2246        };
2247        inst._zod.run = (payload, ctx) => {
2248            if (ctx.skipChecks) {
2249                return inst._zod.parse(payload, ctx);
2250            }
2251            if (ctx.direction === "backward") {
2252                // run canary
2253                // initial pass (no checks)
2254                const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
2255                if (canary instanceof Promise) {
2256                    return canary.then((canary) => {
2257                        return handleCanaryResult(canary, payload, ctx);
2258                    });
2259                }
2260                return handleCanaryResult(canary, payload, ctx);
2261            }
2262            // forward
2263            const result = inst._zod.parse(payload, ctx);
2264            if (result instanceof Promise) {
2265                if (ctx.async === false)
2266                    throw new $ZodAsyncError();
2267                return result.then((result) => runChecks(result, checks, ctx));
2268            }
2269            return runChecks(result, checks, ctx);
2270        };
2271    }
2272    // Lazy initialize ~standard to avoid creating objects for every schema
2273    defineLazy(inst, "~standard", () => ({
2274        validate: (value) => {
2275            try {
2276                const r = safeParse$1(inst, value);
2277                return r.success ? { value: r.data } : { issues: r.error?.issues };
2278            }
2279            catch (_) {
2280                return safeParseAsync$1(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
2281            }
2282        },
2283        vendor: "zod",
2284        version: 1,
2285    }));
2286});
2287const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
2288    $ZodType.init(inst, def);
2289    inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
2290    inst._zod.parse = (payload, _) => {
2291        if (def.coerce)
2292            try {
2293                payload.value = String(payload.value);
2294            }
2295            catch (_) { }
2296        if (typeof payload.value === "string")
2297            return payload;
2298        payload.issues.push({
2299            expected: "string",
2300            code: "invalid_type",
2301            input: payload.value,
2302            inst,
2303        });
2304        return payload;
2305    };
2306});
2307const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
2308    // check initialization must come first
2309    $ZodCheckStringFormat.init(inst, def);
2310    $ZodString.init(inst, def);
2311});
2312const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
2313    def.pattern ?? (def.pattern = guid);
2314    $ZodStringFormat.init(inst, def);
2315});
2316const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
2317    if (def.version) {
2318        const versionMap = {
2319            v1: 1,
2320            v2: 2,
2321            v3: 3,
2322            v4: 4,
2323            v5: 5,
2324            v6: 6,
2325            v7: 7,
2326            v8: 8,
2327        };
2328        const v = versionMap[def.version];
2329        if (v === undefined)
2330            throw new Error(`Invalid UUID version: "${def.version}"`);
2331        def.pattern ?? (def.pattern = uuid(v));
2332    }
2333    else
2334        def.pattern ?? (def.pattern = uuid());
2335    $ZodStringFormat.init(inst, def);
2336});
2337const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
2338    def.pattern ?? (def.pattern = email);
2339    $ZodStringFormat.init(inst, def);
2340});
2341const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
2342    $ZodStringFormat.init(inst, def);
2343    inst._zod.check = (payload) => {
2344        try {
2345            // Trim whitespace from input
2346            const trimmed = payload.value.trim();
2347            // When normalize is off, require :// for http/https URLs
2348            // This prevents strings like "http:example.com" or "https:/path" from being silently accepted
2349            if (!def.normalize && def.protocol?.source === httpProtocol.source) {
2350                if (!/^https?:\/\//i.test(trimmed)) {
2351                    payload.issues.push({
2352                        code: "invalid_format",
2353                        format: "url",
2354                        note: "Invalid URL format",
2355                        input: payload.value,
2356                        inst,
2357                        continue: !def.abort,
2358                    });
2359                    return;
2360                }
2361            }
2362            // @ts-ignore
2363            const url = new URL(trimmed);
2364            if (def.hostname) {
2365                def.hostname.lastIndex = 0;
2366                if (!def.hostname.test(url.hostname)) {
2367                    payload.issues.push({
2368                        code: "invalid_format",
2369                        format: "url",
2370                        note: "Invalid hostname",
2371                        pattern: def.hostname.source,
2372                        input: payload.value,
2373                        inst,
2374                        continue: !def.abort,
2375                    });
2376                }
2377            }
2378            if (def.protocol) {
2379                def.protocol.lastIndex = 0;
2380                if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
2381                    payload.issues.push({
vendor: 8,869 bytes, lines 2382-2643
2382                        code: "invalid_format",
2383                        format: "url",
2384                        note: "Invalid protocol",
2385                        pattern: def.protocol.source,
2386                        input: payload.value,
2387                        inst,
2388                        continue: !def.abort,
2389                    });
2390                }
2391            }
2392            // Set the output value based on normalize flag
2393            if (def.normalize) {
2394                // Use normalized URL
2395                payload.value = url.href;
2396            }
2397            else {
2398                // Preserve the original input (trimmed)
2399                payload.value = trimmed;
2400            }
2401            return;
2402        }
2403        catch (_) {
2404            payload.issues.push({
2405                code: "invalid_format",
2406                format: "url",
2407                input: payload.value,
2408                inst,
2409                continue: !def.abort,
2410            });
2411        }
2412    };
2413});
2414const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
2415    def.pattern ?? (def.pattern = emoji());
2416    $ZodStringFormat.init(inst, def);
2417});
2418const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
2419    def.pattern ?? (def.pattern = nanoid);
2420    $ZodStringFormat.init(inst, def);
2421});
2422/**
2423 * @deprecated CUID v1 is deprecated by its authors due to information leakage
2424 * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
2425 * See https://github.com/paralleldrive/cuid.
2426 */
2427const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
2428    def.pattern ?? (def.pattern = cuid);
2429    $ZodStringFormat.init(inst, def);
2430});
2431const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
2432    def.pattern ?? (def.pattern = cuid2);
2433    $ZodStringFormat.init(inst, def);
2434});
2435const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
2436    def.pattern ?? (def.pattern = ulid);
2437    $ZodStringFormat.init(inst, def);
2438});
2439const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
2440    def.pattern ?? (def.pattern = xid);
2441    $ZodStringFormat.init(inst, def);
2442});
2443const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
2444    def.pattern ?? (def.pattern = ksuid);
2445    $ZodStringFormat.init(inst, def);
2446});
2447const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
2448    def.pattern ?? (def.pattern = datetime$1(def));
2449    $ZodStringFormat.init(inst, def);
2450});
2451const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
2452    def.pattern ?? (def.pattern = date$2);
2453    $ZodStringFormat.init(inst, def);
2454});
2455const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
2456    def.pattern ?? (def.pattern = time$1(def));
2457    $ZodStringFormat.init(inst, def);
2458});
2459const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
2460    def.pattern ?? (def.pattern = duration$1);
2461    $ZodStringFormat.init(inst, def);
2462});
2463const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
2464    def.pattern ?? (def.pattern = ipv4);
2465    $ZodStringFormat.init(inst, def);
2466    inst._zod.bag.format = `ipv4`;
2467});
2468const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
2469    def.pattern ?? (def.pattern = ipv6);
2470    $ZodStringFormat.init(inst, def);
2471    inst._zod.bag.format = `ipv6`;
2472    inst._zod.check = (payload) => {
2473        try {
2474            // @ts-ignore
2475            new URL(`http://[${payload.value}]`);
2476            // return;
2477        }
2478        catch {
2479            payload.issues.push({
2480                code: "invalid_format",
2481                format: "ipv6",
2482                input: payload.value,
2483                inst,
2484                continue: !def.abort,
2485            });
2486        }
2487    };
2488});
2489const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
2490    def.pattern ?? (def.pattern = cidrv4);
2491    $ZodStringFormat.init(inst, def);
2492});
2493const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
2494    def.pattern ?? (def.pattern = cidrv6); // not used for validation
2495    $ZodStringFormat.init(inst, def);
2496    inst._zod.check = (payload) => {
2497        const parts = payload.value.split("/");
2498        try {
2499            if (parts.length !== 2)
2500                throw new Error();
2501            const [address, prefix] = parts;
2502            if (!prefix)
2503                throw new Error();
2504            const prefixNum = Number(prefix);
2505            if (`${prefixNum}` !== prefix)
2506                throw new Error();
2507            if (prefixNum < 0 || prefixNum > 128)
2508                throw new Error();
2509            // @ts-ignore
2510            new URL(`http://[${address}]`);
2511        }
2512        catch {
2513            payload.issues.push({
2514                code: "invalid_format",
2515                format: "cidrv6",
2516                input: payload.value,
2517                inst,
2518                continue: !def.abort,
2519            });
2520        }
2521    };
2522});
2523//////////////////////////////   ZodBase64   //////////////////////////////
2524function isValidBase64(data) {
2525    if (data === "")
2526        return true;
2527    // atob ignores whitespace, so reject it up front.
2528    if (/\s/.test(data))
2529        return false;
2530    if (data.length % 4 !== 0)
2531        return false;
2532    try {
2533        // @ts-ignore
2534        atob(data);
2535        return true;
2536    }
2537    catch {
2538        return false;
2539    }
2540}
2541const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
2542    def.pattern ?? (def.pattern = base64$1);
2543    $ZodStringFormat.init(inst, def);
2544    inst._zod.bag.contentEncoding = "base64";
2545    inst._zod.check = (payload) => {
2546        if (isValidBase64(payload.value))
2547            return;
2548        payload.issues.push({
2549            code: "invalid_format",
2550            format: "base64",
2551            input: payload.value,
2552            inst,
2553            continue: !def.abort,
2554        });
2555    };
2556});
2557//////////////////////////////   ZodBase64   //////////////////////////////
2558function isValidBase64URL(data) {
2559    if (!base64url$1.test(data))
2560        return false;
2561    const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
2562    const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
2563    return isValidBase64(padded);
2564}
2565const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
2566    def.pattern ?? (def.pattern = base64url$1);
2567    $ZodStringFormat.init(inst, def);
2568    inst._zod.bag.contentEncoding = "base64url";
2569    inst._zod.check = (payload) => {
2570        if (isValidBase64URL(payload.value))
2571            return;
2572        payload.issues.push({
2573            code: "invalid_format",
2574            format: "base64url",
2575            input: payload.value,
2576            inst,
2577            continue: !def.abort,
2578        });
2579    };
2580});
2581const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
2582    def.pattern ?? (def.pattern = e164);
2583    $ZodStringFormat.init(inst, def);
2584});
2585//////////////////////////////   ZodJWT   //////////////////////////////
2586function isValidJWT(token, algorithm = null) {
2587    try {
2588        const tokensParts = token.split(".");
2589        if (tokensParts.length !== 3)
2590            return false;
2591        const [header] = tokensParts;
2592        if (!header)
2593            return false;
2594        // @ts-ignore
2595        const parsedHeader = JSON.parse(atob(header));
2596        if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
2597            return false;
2598        if (!parsedHeader.alg)
2599            return false;
2600        if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
2601            return false;
2602        return true;
2603    }
2604    catch {
2605        return false;
2606    }
2607}
2608const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
2609    $ZodStringFormat.init(inst, def);
2610    inst._zod.check = (payload) => {
2611        if (isValidJWT(payload.value, def.alg))
2612            return;
2613        payload.issues.push({
2614            code: "invalid_format",
2615            format: "jwt",
2616            input: payload.value,
2617            inst,
2618            continue: !def.abort,
2619        });
2620    };
2621});
2622const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
2623    $ZodType.init(inst, def);
2624    inst._zod.pattern = inst._zod.bag.pattern ?? number$2;
2625    inst._zod.parse = (payload, _ctx) => {
2626        if (def.coerce)
2627            try {
2628                payload.value = Number(payload.value);
2629            }
2630            catch (_) { }
2631        const input = payload.value;
2632        if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
2633            return payload;
2634        }
2635        const received = typeof input === "number"
2636            ? Number.isNaN(input)
2637                ? "NaN"
2638                : !Number.isFinite(input)
2639                    ? "Infinity"
2640                    : undefined
2641            : undefined;
2642        payload.issues.push({
2643            expected: "number",
vendor: 13,619 bytes, lines 2644-3058
2644            code: "invalid_type",
2645            input,
2646            inst,
2647            ...(received ? { received } : {}),
2648        });
2649        return payload;
2650    };
2651});
2652const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => {
2653    $ZodCheckNumberFormat.init(inst, def);
2654    $ZodNumber.init(inst, def); // no format checks
2655});
2656const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
2657    $ZodType.init(inst, def);
2658    inst._zod.pattern = boolean$1;
2659    inst._zod.parse = (payload, _ctx) => {
2660        if (def.coerce)
2661            try {
2662                payload.value = Boolean(payload.value);
2663            }
2664            catch (_) { }
2665        const input = payload.value;
2666        if (typeof input === "boolean")
2667            return payload;
2668        payload.issues.push({
2669            expected: "boolean",
2670            code: "invalid_type",
2671            input,
2672            inst,
2673        });
2674        return payload;
2675    };
2676});
2677const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => {
2678    $ZodType.init(inst, def);
2679    inst._zod.parse = (payload) => payload;
2680});
2681const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
2682    $ZodType.init(inst, def);
2683    inst._zod.parse = (payload) => payload;
2684});
2685const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
2686    $ZodType.init(inst, def);
2687    inst._zod.parse = (payload, _ctx) => {
2688        payload.issues.push({
2689            expected: "never",
2690            code: "invalid_type",
2691            input: payload.value,
2692            inst,
2693        });
2694        return payload;
2695    };
2696});
2697const $ZodDate = /*@__PURE__*/ $constructor("$ZodDate", (inst, def) => {
2698    $ZodType.init(inst, def);
2699    inst._zod.parse = (payload, _ctx) => {
2700        if (def.coerce) {
2701            try {
2702                payload.value = new Date(payload.value);
2703            }
2704            catch (_err) { }
2705        }
2706        const input = payload.value;
2707        const isDate = input instanceof Date;
2708        const isValidDate = isDate && !Number.isNaN(input.getTime());
2709        if (isValidDate)
2710            return payload;
2711        payload.issues.push({
2712            expected: "date",
2713            code: "invalid_type",
2714            input,
2715            ...(isDate ? { received: "Invalid Date" } : {}),
2716            inst,
2717        });
2718        return payload;
2719    };
2720});
2721function handleArrayResult(result, final, index) {
2722    if (result.issues.length) {
2723        final.issues.push(...prefixIssues(index, result.issues));
2724    }
2725    final.value[index] = result.value;
2726}
2727const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
2728    $ZodType.init(inst, def);
2729    inst._zod.parse = (payload, ctx) => {
2730        const input = payload.value;
2731        if (!Array.isArray(input)) {
2732            payload.issues.push({
2733                expected: "array",
2734                code: "invalid_type",
2735                input,
2736                inst,
2737            });
2738            return payload;
2739        }
2740        payload.value = Array(input.length);
2741        const proms = [];
2742        for (let i = 0; i < input.length; i++) {
2743            const item = input[i];
2744            const result = def.element._zod.run({
2745                value: item,
2746                issues: [],
2747            }, ctx);
2748            if (result instanceof Promise) {
2749                proms.push(result.then((result) => handleArrayResult(result, payload, i)));
2750            }
2751            else {
2752                handleArrayResult(result, payload, i);
2753            }
2754        }
2755        if (proms.length) {
2756            return Promise.all(proms).then(() => payload);
2757        }
2758        return payload; //handleArrayResultsAsync(parseResults, final);
2759    };
2760});
2761function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
2762    const isPresent = key in input;
2763    if (result.issues.length) {
2764        // For optional-in/out schemas, ignore errors on absent keys.
2765        if (isOptionalIn && isOptionalOut && !isPresent) {
2766            return;
2767        }
2768        final.issues.push(...prefixIssues(key, result.issues));
2769    }
2770    if (!isPresent && !isOptionalIn) {
2771        if (!result.issues.length) {
2772            final.issues.push({
2773                code: "invalid_type",
2774                expected: "nonoptional",
2775                input: undefined,
2776                path: [key],
2777            });
2778        }
2779        return;
2780    }
2781    if (result.value === undefined) {
2782        if (isPresent) {
2783            final.value[key] = undefined;
2784        }
2785    }
2786    else {
2787        final.value[key] = result.value;
2788    }
2789}
2790function normalizeDef(def) {
2791    const keys = Object.keys(def.shape);
2792    for (const k of keys) {
2793        if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
2794            throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
2795        }
2796    }
2797    const okeys = optionalKeys(def.shape);
2798    return {
2799        ...def,
2800        keys,
2801        keySet: new Set(keys),
2802        numKeys: keys.length,
2803        optionalKeys: new Set(okeys),
2804    };
2805}
2806function handleCatchall(proms, input, payload, ctx, def, inst) {
2807    const unrecognized = [];
2808    const keySet = def.keySet;
2809    const _catchall = def.catchall._zod;
2810    const t = _catchall.def.type;
2811    const isOptionalIn = _catchall.optin === "optional";
2812    const isOptionalOut = _catchall.optout === "optional";
2813    for (const key in input) {
2814        // skip __proto__ so it can't replace the result prototype via the
2815        // assignment setter on the plain {} we build into
2816        if (key === "__proto__")
2817            continue;
2818        if (keySet.has(key))
2819            continue;
2820        if (t === "never") {
2821            unrecognized.push(key);
2822            continue;
2823        }
2824        const r = _catchall.run({ value: input[key], issues: [] }, ctx);
2825        if (r instanceof Promise) {
2826            proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
2827        }
2828        else {
2829            handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
2830        }
2831    }
2832    if (unrecognized.length) {
2833        payload.issues.push({
2834            code: "unrecognized_keys",
2835            keys: unrecognized,
2836            input,
2837            inst,
2838        });
2839    }
2840    if (!proms.length)
2841        return payload;
2842    return Promise.all(proms).then(() => {
2843        return payload;
2844    });
2845}
2846const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
2847    // requires cast because technically $ZodObject doesn't extend
2848    $ZodType.init(inst, def);
2849    // const sh = def.shape;
2850    const desc = Object.getOwnPropertyDescriptor(def, "shape");
2851    if (!desc?.get) {
2852        const sh = def.shape;
2853        Object.defineProperty(def, "shape", {
2854            get: () => {
2855                const newSh = { ...sh };
2856                Object.defineProperty(def, "shape", {
2857                    value: newSh,
2858                });
2859                return newSh;
2860            },
2861        });
2862    }
2863    const _normalized = cached(() => normalizeDef(def));
2864    defineLazy(inst._zod, "propValues", () => {
2865        const shape = def.shape;
2866        const propValues = {};
2867        for (const key in shape) {
2868            const field = shape[key]._zod;
2869            if (field.values) {
2870                propValues[key] ?? (propValues[key] = new Set());
2871                for (const v of field.values)
2872                    propValues[key].add(v);
2873            }
2874        }
2875        return propValues;
2876    });
2877    const isObject$1 = isObject;
2878    const catchall = def.catchall;
2879    let value;
2880    inst._zod.parse = (payload, ctx) => {
2881        value ?? (value = _normalized.value);
2882        const input = payload.value;
2883        if (!isObject$1(input)) {
2884            payload.issues.push({
2885                expected: "object",
2886                code: "invalid_type",
2887                input,
2888                inst,
2889            });
2890            return payload;
2891        }
2892        payload.value = {};
2893        const proms = [];
2894        const shape = value.shape;
2895        for (const key of value.keys) {
2896            const el = shape[key];
2897            const isOptionalIn = el._zod.optin === "optional";
2898            const isOptionalOut = el._zod.optout === "optional";
2899            const r = el._zod.run({ value: input[key], issues: [] }, ctx);
2900            if (r instanceof Promise) {
2901                proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
2902            }
2903            else {
2904                handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
2905            }
2906        }
2907        if (!catchall) {
2908            return proms.length ? Promise.all(proms).then(() => payload) : payload;
2909        }
2910        return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
2911    };
2912});
2913const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => {
2914    // requires cast because technically $ZodObject doesn't extend
2915    $ZodObject.init(inst, def);
2916    const superParse = inst._zod.parse;
2917    const _normalized = cached(() => normalizeDef(def));
2918    const generateFastpass = (shape) => {
2919        const doc = new Doc(["shape", "payload", "ctx"]);
2920        const normalized = _normalized.value;
2921        const parseStr = (key) => {
2922            const k = esc(key);
2923            return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
2924        };
2925        doc.write(`const input = payload.value;`);
2926        const ids = Object.create(null);
2927        let counter = 0;
2928        for (const key of normalized.keys) {
2929            ids[key] = `key_${counter++}`;
2930        }
2931        // A: preserve key order {
2932        doc.write(`const newResult = {};`);
2933        for (const key of normalized.keys) {
2934            const id = ids[key];
2935            const k = esc(key);
2936            const schema = shape[key];
2937            const isOptionalIn = schema?._zod?.optin === "optional";
2938            const isOptionalOut = schema?._zod?.optout === "optional";
2939            doc.write(`const ${id} = ${parseStr(key)};`);
2940            if (isOptionalIn && isOptionalOut) {
2941                // For optional-in/out schemas, ignore errors on absent keys
2942                doc.write(`
2943        if (${id}.issues.length) {
2944          if (${k} in input) {
2945            payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2946              ...iss,
2947              path: iss.path ? [${k}, ...iss.path] : [${k}]
2948            })));
2949          }
2950        }
2951        
2952        if (${id}.value === undefined) {
2953          if (${k} in input) {
2954            newResult[${k}] = undefined;
2955          }
2956        } else {
2957          newResult[${k}] = ${id}.value;
2958        }
2959        
2960      `);
2961            }
2962            else if (!isOptionalIn) {
2963                doc.write(`
2964        const ${id}_present = ${k} in input;
2965        if (${id}.issues.length) {
2966          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2967            ...iss,
2968            path: iss.path ? [${k}, ...iss.path] : [${k}]
2969          })));
2970        }
2971        if (!${id}_present && !${id}.issues.length) {
2972          payload.issues.push({
2973            code: "invalid_type",
2974            expected: "nonoptional",
2975            input: undefined,
2976            path: [${k}]
2977          });
2978        }
2979
2980        if (${id}_present) {
2981          if (${id}.value === undefined) {
2982            newResult[${k}] = undefined;
2983          } else {
2984            newResult[${k}] = ${id}.value;
2985          }
2986        }
2987
2988      `);
2989            }
2990            else {
2991                doc.write(`
2992        if (${id}.issues.length) {
2993          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
2994            ...iss,
2995            path: iss.path ? [${k}, ...iss.path] : [${k}]
2996          })));
2997        }
2998        
2999        if (${id}.value === undefined) {
3000          if (${k} in input) {
3001            newResult[${k}] = undefined;
3002          }
3003        } else {
3004          newResult[${k}] = ${id}.value;
3005        }
3006        
3007      `);
3008            }
3009        }
3010        doc.write(`payload.value = newResult;`);
3011        doc.write(`return payload;`);
3012        const fn = doc.compile();
3013        return (payload, ctx) => fn(shape, payload, ctx);
3014    };
3015    let fastpass;
3016    const isObject$1 = isObject;
3017    const jit = !globalConfig.jitless;
3018    const allowsEval$1 = allowsEval;
3019    const fastEnabled = jit && allowsEval$1.value; // && !def.catchall;
3020    const catchall = def.catchall;
3021    let value;
3022    inst._zod.parse = (payload, ctx) => {
3023        value ?? (value = _normalized.value);
3024        const input = payload.value;
3025        if (!isObject$1(input)) {
3026            payload.issues.push({
3027                expected: "object",
3028                code: "invalid_type",
3029                input,
3030                inst,
3031            });
3032            return payload;
3033        }
3034        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
3035            // always synchronous
3036            if (!fastpass)
3037                fastpass = generateFastpass(def.shape);
3038            payload = fastpass(payload, ctx);
3039            if (!catchall)
3040                return payload;
3041            return handleCatchall([], input, payload, ctx, value, inst);
3042        }
3043        return superParse(payload, ctx);
3044    };
3045});
3046function handleUnionResults(results, final, inst, ctx) {
3047    for (const result of results) {
3048        if (result.issues.length === 0) {
3049            final.value = result.value;
3050            return final;
3051        }
3052    }
3053    const nonaborted = results.filter((r) => !aborted(r));
3054    if (nonaborted.length === 1) {
3055        final.value = nonaborted[0].value;
3056        return nonaborted[0];
3057    }
3058    final.issues.push({
vendor: 13,212 bytes, lines 3059-3390
3059        code: "invalid_union",
3060        input: final.value,
3061        inst,
3062        errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
3063    });
3064    return final;
3065}
3066const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
3067    $ZodType.init(inst, def);
3068    defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
3069    defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
3070    defineLazy(inst._zod, "values", () => {
3071        if (def.options.every((o) => o._zod.values)) {
3072            return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
3073        }
3074        return undefined;
3075    });
3076    defineLazy(inst._zod, "pattern", () => {
3077        if (def.options.every((o) => o._zod.pattern)) {
3078            const patterns = def.options.map((o) => o._zod.pattern);
3079            return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
3080        }
3081        return undefined;
3082    });
3083    const first = def.options.length === 1 ? def.options[0]._zod.run : null;
3084    inst._zod.parse = (payload, ctx) => {
3085        if (first) {
3086            return first(payload, ctx);
3087        }
3088        let async = false;
3089        const results = [];
3090        for (const option of def.options) {
3091            const result = option._zod.run({
3092                value: payload.value,
3093                issues: [],
3094            }, ctx);
3095            if (result instanceof Promise) {
3096                results.push(result);
3097                async = true;
3098            }
3099            else {
3100                if (result.issues.length === 0)
3101                    return result;
3102                results.push(result);
3103            }
3104        }
3105        if (!async)
3106            return handleUnionResults(results, payload, inst, ctx);
3107        return Promise.all(results).then((results) => {
3108            return handleUnionResults(results, payload, inst, ctx);
3109        });
3110    };
3111});
3112const $ZodDiscriminatedUnion = 
3113/*@__PURE__*/
3114$constructor("$ZodDiscriminatedUnion", (inst, def) => {
3115    def.inclusive = false;
3116    $ZodUnion.init(inst, def);
3117    const _super = inst._zod.parse;
3118    defineLazy(inst._zod, "propValues", () => {
3119        const propValues = {};
3120        for (const option of def.options) {
3121            const pv = option._zod.propValues;
3122            if (!pv || Object.keys(pv).length === 0)
3123                throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
3124            for (const [k, v] of Object.entries(pv)) {
3125                if (!propValues[k])
3126                    propValues[k] = new Set();
3127                for (const val of v) {
3128                    propValues[k].add(val);
3129                }
3130            }
3131        }
3132        return propValues;
3133    });
3134    const disc = cached(() => {
3135        const opts = def.options;
3136        const map = new Map();
3137        for (const o of opts) {
3138            const values = o._zod.propValues?.[def.discriminator];
3139            if (!values || values.size === 0)
3140                throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
3141            for (const v of values) {
3142                if (map.has(v)) {
3143                    throw new Error(`Duplicate discriminator value "${String(v)}"`);
3144                }
3145                map.set(v, o);
3146            }
3147        }
3148        return map;
3149    });
3150    inst._zod.parse = (payload, ctx) => {
3151        const input = payload.value;
3152        if (!isObject(input)) {
3153            payload.issues.push({
3154                code: "invalid_type",
3155                expected: "object",
3156                input,
3157                inst,
3158            });
3159            return payload;
3160        }
3161        const opt = disc.value.get(input?.[def.discriminator]);
3162        if (opt) {
3163            return opt._zod.run(payload, ctx);
3164        }
3165        // Fall back to union matching when the fast discriminator path fails:
3166        // - explicitly enabled via unionFallback, or
3167        // - during backward direction (encode), since codec-based discriminators
3168        //   have different values in forward vs backward directions
3169        if (def.unionFallback || ctx.direction === "backward") {
3170            return _super(payload, ctx);
3171        }
3172        // no matching discriminator
3173        payload.issues.push({
3174            code: "invalid_union",
3175            errors: [],
3176            note: "No matching discriminator",
3177            discriminator: def.discriminator,
3178            options: Array.from(disc.value.keys()),
3179            input,
3180            path: [def.discriminator],
3181            inst,
3182        });
3183        return payload;
3184    };
3185});
3186const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
3187    $ZodType.init(inst, def);
3188    inst._zod.parse = (payload, ctx) => {
3189        const input = payload.value;
3190        const left = def.left._zod.run({ value: input, issues: [] }, ctx);
3191        const right = def.right._zod.run({ value: input, issues: [] }, ctx);
3192        const async = left instanceof Promise || right instanceof Promise;
3193        if (async) {
3194            return Promise.all([left, right]).then(([left, right]) => {
3195                return handleIntersectionResults(payload, left, right);
3196            });
3197        }
3198        return handleIntersectionResults(payload, left, right);
3199    };
3200});
3201function mergeValues(a, b) {
3202    // const aType = parse.t(a);
3203    // const bType = parse.t(b);
3204    if (a === b) {
3205        return { valid: true, data: a };
3206    }
3207    if (a instanceof Date && b instanceof Date && +a === +b) {
3208        return { valid: true, data: a };
3209    }
3210    if (isPlainObject(a) && isPlainObject(b)) {
3211        const bKeys = Object.keys(b);
3212        const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
3213        const newObj = { ...a, ...b };
3214        for (const key of sharedKeys) {
3215            const sharedValue = mergeValues(a[key], b[key]);
3216            if (!sharedValue.valid) {
3217                return {
3218                    valid: false,
3219                    mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
3220                };
3221            }
3222            newObj[key] = sharedValue.data;
3223        }
3224        return { valid: true, data: newObj };
3225    }
3226    if (Array.isArray(a) && Array.isArray(b)) {
3227        if (a.length !== b.length) {
3228            return { valid: false, mergeErrorPath: [] };
3229        }
3230        const newArray = [];
3231        for (let index = 0; index < a.length; index++) {
3232            const itemA = a[index];
3233            const itemB = b[index];
3234            const sharedValue = mergeValues(itemA, itemB);
3235            if (!sharedValue.valid) {
3236                return {
3237                    valid: false,
3238                    mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
3239                };
3240            }
3241            newArray.push(sharedValue.data);
3242        }
3243        return { valid: true, data: newArray };
3244    }
3245    return { valid: false, mergeErrorPath: [] };
3246}
3247function handleIntersectionResults(result, left, right) {
3248    // Track which side(s) report each key as unrecognized
3249    const unrecKeys = new Map();
3250    let unrecIssue;
3251    for (const iss of left.issues) {
3252        if (iss.code === "unrecognized_keys") {
3253            unrecIssue ?? (unrecIssue = iss);
3254            for (const k of iss.keys) {
3255                if (!unrecKeys.has(k))
3256                    unrecKeys.set(k, {});
3257                unrecKeys.get(k).l = true;
3258            }
3259        }
3260        else {
3261            result.issues.push(iss);
3262        }
3263    }
3264    for (const iss of right.issues) {
3265        if (iss.code === "unrecognized_keys") {
3266            for (const k of iss.keys) {
3267                if (!unrecKeys.has(k))
3268                    unrecKeys.set(k, {});
3269                unrecKeys.get(k).r = true;
3270            }
3271        }
3272        else {
3273            result.issues.push(iss);
3274        }
3275    }
3276    // Report only keys unrecognized by BOTH sides
3277    const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
3278    if (bothKeys.length && unrecIssue) {
3279        result.issues.push({ ...unrecIssue, keys: bothKeys });
3280    }
3281    if (aborted(result))
3282        return result;
3283    const merged = mergeValues(left.value, right.value);
3284    if (!merged.valid) {
3285        throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
3286    }
3287    result.value = merged.data;
3288    return result;
3289}
3290const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
3291    $ZodType.init(inst, def);
3292    inst._zod.parse = (payload, ctx) => {
3293        const input = payload.value;
3294        if (!isPlainObject(input)) {
3295            payload.issues.push({
3296                expected: "record",
3297                code: "invalid_type",
3298                input,
3299                inst,
3300            });
3301            return payload;
3302        }
3303        const proms = [];
3304        const values = def.keyType._zod.values;
3305        if (values) {
3306            payload.value = {};
3307            const recordKeys = new Set();
3308            for (const key of values) {
3309                if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
3310                    recordKeys.add(typeof key === "number" ? key.toString() : key);
3311                    const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
3312                    if (keyResult instanceof Promise) {
3313                        throw new Error("Async schemas not supported in object keys currently");
3314                    }
3315                    if (keyResult.issues.length) {
3316                        payload.issues.push({
3317                            code: "invalid_key",
3318                            origin: "record",
3319                            issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
3320                            input: key,
3321                            path: [key],
3322                            inst,
3323                        });
3324                        continue;
3325                    }
3326                    const outKey = keyResult.value;
3327                    const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
3328                    if (result instanceof Promise) {
3329                        proms.push(result.then((result) => {
3330                            if (result.issues.length) {
3331                                payload.issues.push(...prefixIssues(key, result.issues));
3332                            }
3333                            payload.value[outKey] = result.value;
3334                        }));
3335                    }
3336                    else {
3337                        if (result.issues.length) {
3338                            payload.issues.push(...prefixIssues(key, result.issues));
3339                        }
3340                        payload.value[outKey] = result.value;
3341                    }
3342                }
3343            }
3344            let unrecognized;
3345            for (const key in input) {
3346                if (!recordKeys.has(key)) {
3347                    unrecognized = unrecognized ?? [];
3348                    unrecognized.push(key);
3349                }
3350            }
3351            if (unrecognized && unrecognized.length > 0) {
3352                payload.issues.push({
3353                    code: "unrecognized_keys",
3354                    input,
3355                    inst,
3356                    keys: unrecognized,
3357                });
3358            }
3359        }
3360        else {
3361            payload.value = {};
3362            // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()
3363            for (const key of Reflect.ownKeys(input)) {
3364                if (key === "__proto__")
3365                    continue;
3366                if (!Object.prototype.propertyIsEnumerable.call(input, key))
3367                    continue;
3368                let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
3369                if (keyResult instanceof Promise) {
3370                    throw new Error("Async schemas not supported in object keys currently");
3371                }
3372                // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)
3373                // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals
3374                const checkNumericKey = typeof key === "string" && number$2.test(key) && keyResult.issues.length;
3375                if (checkNumericKey) {
3376                    const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
3377                    if (retryResult instanceof Promise) {
3378                        throw new Error("Async schemas not supported in object keys currently");
3379                    }
3380                    if (retryResult.issues.length === 0) {
3381                        keyResult = retryResult;
3382                    }
3383                }
3384                if (keyResult.issues.length) {
3385                    if (def.mode === "loose") {
3386                        // Pass through unchanged
3387                        payload.value[key] = input[key];
3388                    }
3389                    else {
3390                        // Default "strict" behavior: error on invali
vendor: 13,968 bytes, lines 3390-3740
3390d key
3391                        payload.issues.push({
3392                            code: "invalid_key",
3393                            origin: "record",
3394                            issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
3395                            input: key,
3396                            path: [key],
3397                            inst,
3398                        });
3399                    }
3400                    continue;
3401                }
3402                const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
3403                if (result instanceof Promise) {
3404                    proms.push(result.then((result) => {
3405                        if (result.issues.length) {
3406                            payload.issues.push(...prefixIssues(key, result.issues));
3407                        }
3408                        payload.value[keyResult.value] = result.value;
3409                    }));
3410                }
3411                else {
3412                    if (result.issues.length) {
3413                        payload.issues.push(...prefixIssues(key, result.issues));
3414                    }
3415                    payload.value[keyResult.value] = result.value;
3416                }
3417            }
3418        }
3419        if (proms.length) {
3420            return Promise.all(proms).then(() => payload);
3421        }
3422        return payload;
3423    };
3424});
3425const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
3426    $ZodType.init(inst, def);
3427    const values = getEnumValues(def.entries);
3428    const valuesSet = new Set(values);
3429    inst._zod.values = valuesSet;
3430    inst._zod.pattern = new RegExp(`^(${values
3431        .filter((k) => propertyKeyTypes.has(typeof k))
3432        .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString()))
3433        .join("|")})$`);
3434    inst._zod.parse = (payload, _ctx) => {
3435        const input = payload.value;
3436        if (valuesSet.has(input)) {
3437            return payload;
3438        }
3439        payload.issues.push({
3440            code: "invalid_value",
3441            values,
3442            input,
3443            inst,
3444        });
3445        return payload;
3446    };
3447});
3448const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => {
3449    $ZodType.init(inst, def);
3450    if (def.values.length === 0) {
3451        throw new Error("Cannot create literal schema with no valid values");
3452    }
3453    const values = new Set(def.values);
3454    inst._zod.values = values;
3455    inst._zod.pattern = new RegExp(`^(${def.values
3456        .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)))
3457        .join("|")})$`);
3458    inst._zod.parse = (payload, _ctx) => {
3459        const input = payload.value;
3460        if (values.has(input)) {
3461            return payload;
3462        }
3463        payload.issues.push({
3464            code: "invalid_value",
3465            values: def.values,
3466            input,
3467            inst,
3468        });
3469        return payload;
3470    };
3471});
3472const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
3473    $ZodType.init(inst, def);
3474    inst._zod.optin = "optional";
3475    inst._zod.parse = (payload, ctx) => {
3476        if (ctx.direction === "backward") {
3477            throw new $ZodEncodeError(inst.constructor.name);
3478        }
3479        const _out = def.transform(payload.value, payload);
3480        if (ctx.async) {
3481            const output = _out instanceof Promise ? _out : Promise.resolve(_out);
3482            return output.then((output) => {
3483                payload.value = output;
3484                payload.fallback = true;
3485                return payload;
3486            });
3487        }
3488        if (_out instanceof Promise) {
3489            throw new $ZodAsyncError();
3490        }
3491        payload.value = _out;
3492        payload.fallback = true;
3493        return payload;
3494    };
3495});
3496function handleOptionalResult(result, input) {
3497    if (input === undefined && (result.issues.length || result.fallback)) {
3498        return { issues: [], value: undefined };
3499    }
3500    return result;
3501}
3502const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
3503    $ZodType.init(inst, def);
3504    inst._zod.optin = "optional";
3505    inst._zod.optout = "optional";
3506    defineLazy(inst._zod, "values", () => {
3507        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
3508    });
3509    defineLazy(inst._zod, "pattern", () => {
3510        const pattern = def.innerType._zod.pattern;
3511        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
3512    });
3513    inst._zod.parse = (payload, ctx) => {
3514        if (def.innerType._zod.optin === "optional") {
3515            const input = payload.value;
3516            const result = def.innerType._zod.run(payload, ctx);
3517            if (result instanceof Promise)
3518                return result.then((r) => handleOptionalResult(r, input));
3519            return handleOptionalResult(result, input);
3520        }
3521        if (payload.value === undefined) {
3522            return payload;
3523        }
3524        return def.innerType._zod.run(payload, ctx);
3525    };
3526});
3527const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => {
3528    // Call parent init - inherits optin/optout = "optional"
3529    $ZodOptional.init(inst, def);
3530    // Override values/pattern to NOT add undefined
3531    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
3532    defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
3533    // Override parse to just delegate (no undefined handling)
3534    inst._zod.parse = (payload, ctx) => {
3535        return def.innerType._zod.run(payload, ctx);
3536    };
3537});
3538const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
3539    $ZodType.init(inst, def);
3540    defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
3541    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
3542    defineLazy(inst._zod, "pattern", () => {
3543        const pattern = def.innerType._zod.pattern;
3544        return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
3545    });
3546    defineLazy(inst._zod, "values", () => {
3547        return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
3548    });
3549    inst._zod.parse = (payload, ctx) => {
3550        // Forward direction (decode): allow null to pass through
3551        if (payload.value === null)
3552            return payload;
3553        return def.innerType._zod.run(payload, ctx);
3554    };
3555});
3556const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
3557    $ZodType.init(inst, def);
3558    // inst._zod.qin = "true";
3559    inst._zod.optin = "optional";
3560    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
3561    inst._zod.parse = (payload, ctx) => {
3562        if (ctx.direction === "backward") {
3563            return def.innerType._zod.run(payload, ctx);
3564        }
3565        // Forward direction (decode): apply defaults for undefined input
3566        if (payload.value === undefined) {
3567            payload.value = def.defaultValue;
3568            /**
3569             * $ZodDefault returns the default value immediately in forward direction.
3570             * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe.   */
3571            return payload;
3572        }
3573        // Forward direction: continue with default handling
3574        const result = def.innerType._zod.run(payload, ctx);
3575        if (result instanceof Promise) {
3576            return result.then((result) => handleDefaultResult(result, def));
3577        }
3578        return handleDefaultResult(result, def);
3579    };
3580});
3581function handleDefaultResult(payload, def) {
3582    if (payload.value === undefined) {
3583        payload.value = def.defaultValue;
3584    }
3585    return payload;
3586}
3587const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
3588    $ZodType.init(inst, def);
3589    inst._zod.optin = "optional";
3590    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
3591    inst._zod.parse = (payload, ctx) => {
3592        if (ctx.direction === "backward") {
3593            return def.innerType._zod.run(payload, ctx);
3594        }
3595        // Forward direction (decode): apply prefault for undefined input
3596        if (payload.value === undefined) {
3597            payload.value = def.defaultValue;
3598        }
3599        return def.innerType._zod.run(payload, ctx);
3600    };
3601});
3602const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
3603    $ZodType.init(inst, def);
3604    defineLazy(inst._zod, "values", () => {
3605        const v = def.innerType._zod.values;
3606        return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
3607    });
3608    inst._zod.parse = (payload, ctx) => {
3609        const result = def.innerType._zod.run(payload, ctx);
3610        if (result instanceof Promise) {
3611            return result.then((result) => handleNonOptionalResult(result, inst));
3612        }
3613        return handleNonOptionalResult(result, inst);
3614    };
3615});
3616function handleNonOptionalResult(payload, inst) {
3617    if (!payload.issues.length && payload.value === undefined) {
3618        payload.issues.push({
3619            code: "invalid_type",
3620            expected: "nonoptional",
3621            input: payload.value,
3622            inst,
3623        });
3624    }
3625    return payload;
3626}
3627const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
3628    $ZodType.init(inst, def);
3629    inst._zod.optin = "optional";
3630    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
3631    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
3632    inst._zod.parse = (payload, ctx) => {
3633        if (ctx.direction === "backward") {
3634            return def.innerType._zod.run(payload, ctx);
3635        }
3636        // Forward direction (decode): apply catch logic
3637        const result = def.innerType._zod.run(payload, ctx);
3638        if (result instanceof Promise) {
3639            return result.then((result) => {
3640                payload.value = result.value;
3641                if (result.issues.length) {
3642                    payload.value = def.catchValue({
3643                        ...payload,
3644                        error: {
3645                            issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
3646                        },
3647                        input: payload.value,
3648                    });
3649                    payload.issues = [];
3650                    payload.fallback = true;
3651                }
3652                return payload;
3653            });
3654        }
3655        payload.value = result.value;
3656        if (result.issues.length) {
3657            payload.value = def.catchValue({
3658                ...payload,
3659                error: {
3660                    issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
3661                },
3662                input: payload.value,
3663            });
3664            payload.issues = [];
3665            payload.fallback = true;
3666        }
3667        return payload;
3668    };
3669});
3670const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
3671    $ZodType.init(inst, def);
3672    defineLazy(inst._zod, "values", () => def.in._zod.values);
3673    defineLazy(inst._zod, "optin", () => def.in._zod.optin);
3674    defineLazy(inst._zod, "optout", () => def.out._zod.optout);
3675    defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
3676    inst._zod.parse = (payload, ctx) => {
3677        if (ctx.direction === "backward") {
3678            const right = def.out._zod.run(payload, ctx);
3679            if (right instanceof Promise) {
3680                return right.then((right) => handlePipeResult(right, def.in, ctx));
3681            }
3682            return handlePipeResult(right, def.in, ctx);
3683        }
3684        const left = def.in._zod.run(payload, ctx);
3685        if (left instanceof Promise) {
3686            return left.then((left) => handlePipeResult(left, def.out, ctx));
3687        }
3688        return handlePipeResult(left, def.out, ctx);
3689    };
3690});
3691function handlePipeResult(left, next, ctx) {
3692    if (left.issues.length) {
3693        // prevent further checks
3694        left.aborted = true;
3695        return left;
3696    }
3697    return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
3698}
3699const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
3700    $ZodType.init(inst, def);
3701    defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
3702    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
3703    defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
3704    defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
3705    inst._zod.parse = (payload, ctx) => {
3706        if (ctx.direction === "backward") {
3707            return def.innerType._zod.run(payload, ctx);
3708        }
3709        const result = def.innerType._zod.run(payload, ctx);
3710        if (result instanceof Promise) {
3711            return result.then(handleReadonlyResult);
3712        }
3713        return handleReadonlyResult(result);
3714    };
3715});
3716function handleReadonlyResult(payload) {
3717    payload.value = Object.freeze(payload.value);
3718    return payload;
3719}
3720const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
3721    $ZodCheck.init(inst, def);
3722    $ZodType.init(inst, def);
3723    inst._zod.parse = (payload, _) => {
3724        return payload;
3725    };
3726    inst._zod.check = (payload) => {
3727        const input = payload.value;
3728        const r = def.fn(input);
3729        if (r instanceof Promise) {
3730            return r.then((r) => handleRefineResult(r, payload, input, inst));
3731        }
3732        handleRefineResult(r, payload, input, inst);
3733        return;
3734    };
3735});
3736function handleRefineResult(result, payload, input, inst) {
3737    if (!result) {
3738        const _iss = {
3739            code: "custom",
3740            input,
vendor: 13,031 bytes, lines 3741-4288
3741            inst, // incorporates params.error into issue reporting
3742            path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting
3743            continue: !inst._zod.def.abort,
3744            // params: inst._zod.def.params,
3745        };
3746        if (inst._zod.def.params)
3747            _iss.params = inst._zod.def.params;
3748        payload.issues.push(issue(_iss));
3749    }
3750}
3751
3752var _a;
3753class $ZodRegistry {
3754    constructor() {
3755        this._map = new WeakMap();
3756        this._idmap = new Map();
3757    }
3758    add(schema, ..._meta) {
3759        const meta = _meta[0];
3760        this._map.set(schema, meta);
3761        if (meta && typeof meta === "object" && "id" in meta) {
3762            this._idmap.set(meta.id, schema);
3763        }
3764        return this;
3765    }
3766    clear() {
3767        this._map = new WeakMap();
3768        this._idmap = new Map();
3769        return this;
3770    }
3771    remove(schema) {
3772        const meta = this._map.get(schema);
3773        if (meta && typeof meta === "object" && "id" in meta) {
3774            this._idmap.delete(meta.id);
3775        }
3776        this._map.delete(schema);
3777        return this;
3778    }
3779    get(schema) {
3780        // return this._map.get(schema) as any;
3781        // inherit metadata
3782        const p = schema._zod.parent;
3783        if (p) {
3784            const pm = { ...(this.get(p) ?? {}) };
3785            delete pm.id; // do not inherit id
3786            const f = { ...pm, ...this._map.get(schema) };
3787            return Object.keys(f).length ? f : undefined;
3788        }
3789        return this._map.get(schema);
3790    }
3791    has(schema) {
3792        return this._map.has(schema);
3793    }
3794}
3795// registries
3796function registry() {
3797    return new $ZodRegistry();
3798}
3799(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
3800const globalRegistry = globalThis.__zod_globalRegistry;
3801
3802// @__NO_SIDE_EFFECTS__
3803function _string(Class, params) {
3804    return new Class({
3805        type: "string",
3806        ...normalizeParams(params),
3807    });
3808}
3809// @__NO_SIDE_EFFECTS__
3810function _email(Class, params) {
3811    return new Class({
3812        type: "string",
3813        format: "email",
3814        check: "string_format",
3815        abort: false,
3816        ...normalizeParams(params),
3817    });
3818}
3819// @__NO_SIDE_EFFECTS__
3820function _guid(Class, params) {
3821    return new Class({
3822        type: "string",
3823        format: "guid",
3824        check: "string_format",
3825        abort: false,
3826        ...normalizeParams(params),
3827    });
3828}
3829// @__NO_SIDE_EFFECTS__
3830function _uuid(Class, params) {
3831    return new Class({
3832        type: "string",
3833        format: "uuid",
3834        check: "string_format",
3835        abort: false,
3836        ...normalizeParams(params),
3837    });
3838}
3839// @__NO_SIDE_EFFECTS__
3840function _uuidv4(Class, params) {
3841    return new Class({
3842        type: "string",
3843        format: "uuid",
3844        check: "string_format",
3845        abort: false,
3846        version: "v4",
3847        ...normalizeParams(params),
3848    });
3849}
3850// @__NO_SIDE_EFFECTS__
3851function _uuidv6(Class, params) {
3852    return new Class({
3853        type: "string",
3854        format: "uuid",
3855        check: "string_format",
3856        abort: false,
3857        version: "v6",
3858        ...normalizeParams(params),
3859    });
3860}
3861// @__NO_SIDE_EFFECTS__
3862function _uuidv7(Class, params) {
3863    return new Class({
3864        type: "string",
3865        format: "uuid",
3866        check: "string_format",
3867        abort: false,
3868        version: "v7",
3869        ...normalizeParams(params),
3870    });
3871}
3872// @__NO_SIDE_EFFECTS__
3873function _url(Class, params) {
3874    return new Class({
3875        type: "string",
3876        format: "url",
3877        check: "string_format",
3878        abort: false,
3879        ...normalizeParams(params),
3880    });
3881}
3882// @__NO_SIDE_EFFECTS__
3883function _emoji(Class, params) {
3884    return new Class({
3885        type: "string",
3886        format: "emoji",
3887        check: "string_format",
3888        abort: false,
3889        ...normalizeParams(params),
3890    });
3891}
3892// @__NO_SIDE_EFFECTS__
3893function _nanoid(Class, params) {
3894    return new Class({
3895        type: "string",
3896        format: "nanoid",
3897        check: "string_format",
3898        abort: false,
3899        ...normalizeParams(params),
3900    });
3901}
3902/**
3903 * @deprecated CUID v1 is deprecated by its authors due to information leakage
3904 * (timestamps embedded in the id). Use {@link _cuid2} instead.
3905 * See https://github.com/paralleldrive/cuid.
3906 */
3907// @__NO_SIDE_EFFECTS__
3908function _cuid(Class, params) {
3909    return new Class({
3910        type: "string",
3911        format: "cuid",
3912        check: "string_format",
3913        abort: false,
3914        ...normalizeParams(params),
3915    });
3916}
3917// @__NO_SIDE_EFFECTS__
3918function _cuid2(Class, params) {
3919    return new Class({
3920        type: "string",
3921        format: "cuid2",
3922        check: "string_format",
3923        abort: false,
3924        ...normalizeParams(params),
3925    });
3926}
3927// @__NO_SIDE_EFFECTS__
3928function _ulid(Class, params) {
3929    return new Class({
3930        type: "string",
3931        format: "ulid",
3932        check: "string_format",
3933        abort: false,
3934        ...normalizeParams(params),
3935    });
3936}
3937// @__NO_SIDE_EFFECTS__
3938function _xid(Class, params) {
3939    return new Class({
3940        type: "string",
3941        format: "xid",
3942        check: "string_format",
3943        abort: false,
3944        ...normalizeParams(params),
3945    });
3946}
3947// @__NO_SIDE_EFFECTS__
3948function _ksuid(Class, params) {
3949    return new Class({
3950        type: "string",
3951        format: "ksuid",
3952        check: "string_format",
3953        abort: false,
3954        ...normalizeParams(params),
3955    });
3956}
3957// @__NO_SIDE_EFFECTS__
3958function _ipv4(Class, params) {
3959    return new Class({
3960        type: "string",
3961        format: "ipv4",
3962        check: "string_format",
3963        abort: false,
3964        ...normalizeParams(params),
3965    });
3966}
3967// @__NO_SIDE_EFFECTS__
3968function _ipv6(Class, params) {
3969    return new Class({
3970        type: "string",
3971        format: "ipv6",
3972        check: "string_format",
3973        abort: false,
3974        ...normalizeParams(params),
3975    });
3976}
3977// @__NO_SIDE_EFFECTS__
3978function _cidrv4(Class, params) {
3979    return new Class({
3980        type: "string",
3981        format: "cidrv4",
3982        check: "string_format",
3983        abort: false,
3984        ...normalizeParams(params),
3985    });
3986}
3987// @__NO_SIDE_EFFECTS__
3988function _cidrv6(Class, params) {
3989    return new Class({
3990        type: "string",
3991        format: "cidrv6",
3992        check: "string_format",
3993        abort: false,
3994        ...normalizeParams(params),
3995    });
3996}
3997// @__NO_SIDE_EFFECTS__
3998function _base64(Class, params) {
3999    return new Class({
4000        type: "string",
4001        format: "base64",
4002        check: "string_format",
4003        abort: false,
4004        ...normalizeParams(params),
4005    });
4006}
4007// @__NO_SIDE_EFFECTS__
4008function _base64url(Class, params) {
4009    return new Class({
4010        type: "string",
4011        format: "base64url",
4012        check: "string_format",
4013        abort: false,
4014        ...normalizeParams(params),
4015    });
4016}
4017// @__NO_SIDE_EFFECTS__
4018function _e164(Class, params) {
4019    return new Class({
4020        type: "string",
4021        format: "e164",
4022        check: "string_format",
4023        abort: false,
4024        ...normalizeParams(params),
4025    });
4026}
4027// @__NO_SIDE_EFFECTS__
4028function _jwt(Class, params) {
4029    return new Class({
4030        type: "string",
4031        format: "jwt",
4032        check: "string_format",
4033        abort: false,
4034        ...normalizeParams(params),
4035    });
4036}
4037// @__NO_SIDE_EFFECTS__
4038function _isoDateTime(Class, params) {
4039    return new Class({
4040        type: "string",
4041        format: "datetime",
4042        check: "string_format",
4043        offset: false,
4044        local: false,
4045        precision: null,
4046        ...normalizeParams(params),
4047    });
4048}
4049// @__NO_SIDE_EFFECTS__
4050function _isoDate(Class, params) {
4051    return new Class({
4052        type: "string",
4053        format: "date",
4054        check: "string_format",
4055        ...normalizeParams(params),
4056    });
4057}
4058// @__NO_SIDE_EFFECTS__
4059function _isoTime(Class, params) {
4060    return new Class({
4061        type: "string",
4062        format: "time",
4063        check: "string_format",
4064        precision: null,
4065        ...normalizeParams(params),
4066    });
4067}
4068// @__NO_SIDE_EFFECTS__
4069function _isoDuration(Class, params) {
4070    return new Class({
4071        type: "string",
4072        format: "duration",
4073        check: "string_format",
4074        ...normalizeParams(params),
4075    });
4076}
4077// @__NO_SIDE_EFFECTS__
4078function _number(Class, params) {
4079    return new Class({
4080        type: "number",
4081        checks: [],
4082        ...normalizeParams(params),
4083    });
4084}
4085// @__NO_SIDE_EFFECTS__
4086function _coercedNumber(Class, params) {
4087    return new Class({
4088        type: "number",
4089        coerce: true,
4090        checks: [],
4091        ...normalizeParams(params),
4092    });
4093}
4094// @__NO_SIDE_EFFECTS__
4095function _int(Class, params) {
4096    return new Class({
4097        type: "number",
4098        check: "number_format",
4099        abort: false,
4100        format: "safeint",
4101        ...normalizeParams(params),
4102    });
4103}
4104// @__NO_SIDE_EFFECTS__
4105function _boolean(Class, params) {
4106    return new Class({
4107        type: "boolean",
4108        ...normalizeParams(params),
4109    });
4110}
4111// @__NO_SIDE_EFFECTS__
4112function _any(Class) {
4113    return new Class({
4114        type: "any",
4115    });
4116}
4117// @__NO_SIDE_EFFECTS__
4118function _unknown(Class) {
4119    return new Class({
4120        type: "unknown",
4121    });
4122}
4123// @__NO_SIDE_EFFECTS__
4124function _never(Class, params) {
4125    return new Class({
4126        type: "never",
4127        ...normalizeParams(params),
4128    });
4129}
4130// @__NO_SIDE_EFFECTS__
4131function _date(Class, params) {
4132    return new Class({
4133        type: "date",
4134        ...normalizeParams(params),
4135    });
4136}
4137// @__NO_SIDE_EFFECTS__
4138function _lt(value, params) {
4139    return new $ZodCheckLessThan({
4140        check: "less_than",
4141        ...normalizeParams(params),
4142        value,
4143        inclusive: false,
4144    });
4145}
4146// @__NO_SIDE_EFFECTS__
4147function _lte(value, params) {
4148    return new $ZodCheckLessThan({
4149        check: "less_than",
4150        ...normalizeParams(params),
4151        value,
4152        inclusive: true,
4153    });
4154}
4155// @__NO_SIDE_EFFECTS__
4156function _gt(value, params) {
4157    return new $ZodCheckGreaterThan({
4158        check: "greater_than",
4159        ...normalizeParams(params),
4160        value,
4161        inclusive: false,
4162    });
4163}
4164// @__NO_SIDE_EFFECTS__
4165function _gte(value, params) {
4166    return new $ZodCheckGreaterThan({
4167        check: "greater_than",
4168        ...normalizeParams(params),
4169        value,
4170        inclusive: true,
4171    });
4172}
4173// @__NO_SIDE_EFFECTS__
4174function _multipleOf(value, params) {
4175    return new $ZodCheckMultipleOf({
4176        check: "multiple_of",
4177        ...normalizeParams(params),
4178        value,
4179    });
4180}
4181// @__NO_SIDE_EFFECTS__
4182function _maxLength(maximum, params) {
4183    const ch = new $ZodCheckMaxLength({
4184        check: "max_length",
4185        ...normalizeParams(params),
4186        maximum,
4187    });
4188    return ch;
4189}
4190// @__NO_SIDE_EFFECTS__
4191function _minLength(minimum, params) {
4192    return new $ZodCheckMinLength({
4193        check: "min_length",
4194        ...normalizeParams(params),
4195        minimum,
4196    });
4197}
4198// @__NO_SIDE_EFFECTS__
4199function _length(length, params) {
4200    return new $ZodCheckLengthEquals({
4201        check: "length_equals",
4202        ...normalizeParams(params),
4203        length,
4204    });
4205}
4206// @__NO_SIDE_EFFECTS__
4207function _regex(pattern, params) {
4208    return new $ZodCheckRegex({
4209        check: "string_format",
4210        format: "regex",
4211        ...normalizeParams(params),
4212        pattern,
4213    });
4214}
4215// @__NO_SIDE_EFFECTS__
4216function _lowercase(params) {
4217    return new $ZodCheckLowerCase({
4218        check: "string_format",
4219        format: "lowercase",
4220        ...normalizeParams(params),
4221    });
4222}
4223// @__NO_SIDE_EFFECTS__
4224function _uppercase(params) {
4225    return new $ZodCheckUpperCase({
4226        check: "string_format",
4227        format: "uppercase",
4228        ...normalizeParams(params),
4229    });
4230}
4231// @__NO_SIDE_EFFECTS__
4232function _includes(includes, params) {
4233    return new $ZodCheckIncludes({
4234        check: "string_format",
4235        format: "includes",
4236        ...normalizeParams(params),
4237        includes,
4238    });
4239}
4240// @__NO_SIDE_EFFECTS__
4241function _startsWith(prefix, params) {
4242    return new $ZodCheckStartsWith({
4243        check: "string_format",
4244        format: "starts_with",
4245        ...normalizeParams(params),
4246        prefix,
4247    });
4248}
4249// @__NO_SIDE_EFFECTS__
4250function _endsWith(suffix, params) {
4251    return new $ZodCheckEndsWith({
4252        check: "string_format",
4253        format: "ends_with",
4254        ...normalizeParams(params),
4255        suffix,
4256    });
4257}
4258// @__NO_SIDE_EFFECTS__
4259function _overwrite(tx) {
4260    return new $ZodCheckOverwrite({
4261        check: "overwrite",
4262        tx,
4263    });
4264}
4265// normalize
4266// @__NO_SIDE_EFFECTS__
4267function _normalize(form) {
4268    return _overwrite((input) => input.normalize(form));
4269}
4270// trim
4271// @__NO_SIDE_EFFECTS__
4272function _trim() {
4273    return _overwrite((input) => input.trim());
4274}
4275// toLowerCase
4276// @__NO_SIDE_EFFECTS__
4277function _toLowerCase() {
4278    return _overwrite((input) => input.toLowerCase());
4279}
4280// toUpperCase
4281// @__NO_SIDE_EFFECTS__
4282function _toUpperCase() {
4283    return _overwrite((input) => input.toUpperCase());
4284}
4285// slugify
4286// @__NO_SIDE_EFFECTS__
4287function _slugify() {
4288    return _overwrite((input) =>
vendor: 4,833 bytes, lines 4288-4432
4288 slugify(input));
4289}
4290// @__NO_SIDE_EFFECTS__
4291function _array(Class, element, params) {
4292    return new Class({
4293        type: "array",
4294        element,
4295        // get element() {
4296        //   return element;
4297        // },
4298        ...normalizeParams(params),
4299    });
4300}
4301// same as _custom but defaults to abort:false
4302// @__NO_SIDE_EFFECTS__
4303function _refine(Class, fn, _params) {
4304    const schema = new Class({
4305        type: "custom",
4306        check: "custom",
4307        fn: fn,
4308        ...normalizeParams(_params),
4309    });
4310    return schema;
4311}
4312// @__NO_SIDE_EFFECTS__
4313function _superRefine(fn, params) {
4314    const ch = _check((payload) => {
4315        payload.addIssue = (issue$1) => {
4316            if (typeof issue$1 === "string") {
4317                payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
4318            }
4319            else {
4320                // for Zod 3 backwards compatibility
4321                const _issue = issue$1;
4322                if (_issue.fatal)
4323                    _issue.continue = false;
4324                _issue.code ?? (_issue.code = "custom");
4325                _issue.input ?? (_issue.input = payload.value);
4326                _issue.inst ?? (_issue.inst = ch);
4327                _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...
4328                payload.issues.push(issue(_issue));
4329            }
4330        };
4331        return fn(payload.value, payload);
4332    }, params);
4333    return ch;
4334}
4335// @__NO_SIDE_EFFECTS__
4336function _check(fn, params) {
4337    const ch = new $ZodCheck({
4338        check: "custom",
4339        ...normalizeParams(params),
4340    });
4341    ch._zod.check = fn;
4342    return ch;
4343}
4344
4345// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {
4346//   return {
4347//     processor: inputs.processor,
4348//     metadataRegistry: inputs.metadata ?? globalRegistry,
4349//     target: inputs.target ?? "draft-2020-12",
4350//     unrepresentable: inputs.unrepresentable ?? "throw",
4351//   };
4352// }
4353function initializeContext(params) {
4354    // Normalize target: convert old non-hyphenated versions to hyphenated versions
4355    let target = params?.target ?? "draft-2020-12";
4356    if (target === "draft-4")
4357        target = "draft-04";
4358    if (target === "draft-7")
4359        target = "draft-07";
4360    return {
4361        processors: params.processors ?? {},
4362        metadataRegistry: params?.metadata ?? globalRegistry,
4363        target,
4364        unrepresentable: params?.unrepresentable ?? "throw",
4365        override: params?.override ?? (() => { }),
4366        io: params?.io ?? "output",
4367        counter: 0,
4368        seen: new Map(),
4369        cycles: params?.cycles ?? "ref",
4370        reused: params?.reused ?? "inline",
4371        external: params?.external ?? undefined,
4372    };
4373}
4374function process(schema, ctx, _params = { path: [], schemaPath: [] }) {
4375    var _a;
4376    const def = schema._zod.def;
4377    // check for schema in seens
4378    const seen = ctx.seen.get(schema);
4379    if (seen) {
4380        seen.count++;
4381        // check if cycle
4382        const isCycle = _params.schemaPath.includes(schema);
4383        if (isCycle) {
4384            seen.cycle = _params.path;
4385        }
4386        return seen.schema;
4387    }
4388    // initialize
4389    const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
4390    ctx.seen.set(schema, result);
4391    // custom method overrides default behavior
4392    const overrideSchema = schema._zod.toJSONSchema?.();
4393    if (overrideSchema) {
4394        result.schema = overrideSchema;
4395    }
4396    else {
4397        const params = {
4398            ..._params,
4399            schemaPath: [..._params.schemaPath, schema],
4400            path: _params.path,
4401        };
4402        if (schema._zod.processJSONSchema) {
4403            schema._zod.processJSONSchema(ctx, result.schema, params);
4404        }
4405        else {
4406            const _json = result.schema;
4407            const processor = ctx.processors[def.type];
4408            if (!processor) {
4409                throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
4410            }
4411            processor(schema, ctx, _json, params);
4412        }
4413        const parent = schema._zod.parent;
4414        if (parent) {
4415            // Also set ref if processor didn't (for inheritance)
4416            if (!result.ref)
4417                result.ref = parent;
4418            process(parent, ctx, params);
4419            ctx.seen.get(parent).isParent = true;
4420        }
4421    }
4422    // metadata
4423    const meta = ctx.metadataRegistry.get(schema);
4424    if (meta)
4425        Object.assign(result.schema, meta);
4426    if (ctx.io === "input" && isTransforming(schema)) {
4427        // examples/defaults only apply to output type of pipe
4428        delete result.schema.examples;
4429        delete result.schema.default;
4430    }
4431    // set prefault as default
4432    if (ctx.io === "input" && "_prefault" in result.schema
vendor: 8,724 bytes, lines 4432-4651
4432)
4433        (_a = result.schema).default ?? (_a.default = result.schema._prefault);
4434    delete result.schema._prefault;
4435    // pulling fresh from ctx.seen in case it was overwritten
4436    const _result = ctx.seen.get(schema);
4437    return _result.schema;
4438}
4439function extractDefs(ctx, schema
4440// params: EmitParams
4441) {
4442    // iterate over seen map;
4443    const root = ctx.seen.get(schema);
4444    if (!root)
4445        throw new Error("Unprocessed schema. This is a bug in Zod.");
4446    // Track ids to detect duplicates across different schemas
4447    const idToSchema = new Map();
4448    for (const entry of ctx.seen.entries()) {
4449        const id = ctx.metadataRegistry.get(entry[0])?.id;
4450        if (id) {
4451            const existing = idToSchema.get(id);
4452            if (existing && existing !== entry[0]) {
4453                throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
4454            }
4455            idToSchema.set(id, entry[0]);
4456        }
4457    }
4458    // returns a ref to the schema
4459    // defId will be empty if the ref points to an external schema (or #)
4460    const makeURI = (entry) => {
4461        // comparing the seen objects because sometimes
4462        // multiple schemas map to the same seen object.
4463        // e.g. lazy
4464        // external is configured
4465        const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
4466        if (ctx.external) {
4467            const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`;
4468            // check if schema is in the external registry
4469            const uriGenerator = ctx.external.uri ?? ((id) => id);
4470            if (externalId) {
4471                return { ref: uriGenerator(externalId) };
4472            }
4473            // otherwise, add to __shared
4474            const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
4475            entry[1].defId = id; // set defId so it will be reused if needed
4476            return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
4477        }
4478        if (entry[1] === root) {
4479            return { ref: "#" };
4480        }
4481        // self-contained schema
4482        const uriPrefix = `#`;
4483        const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
4484        const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
4485        return { defId, ref: defUriPrefix + defId };
4486    };
4487    // stored cached version in `def` property
4488    // remove all properties, set $ref
4489    const extractToDef = (entry) => {
4490        // if the schema is already a reference, do not extract it
4491        if (entry[1].schema.$ref) {
4492            return;
4493        }
4494        const seen = entry[1];
4495        const { ref, defId } = makeURI(entry);
4496        seen.def = { ...seen.schema };
4497        // defId won't be set if the schema is a reference to an external schema
4498        // or if the schema is the root schema
4499        if (defId)
4500            seen.defId = defId;
4501        // wipe away all properties except $ref
4502        const schema = seen.schema;
4503        for (const key in schema) {
4504            delete schema[key];
4505        }
4506        schema.$ref = ref;
4507    };
4508    // throw on cycles
4509    // break cycles
4510    if (ctx.cycles === "throw") {
4511        for (const entry of ctx.seen.entries()) {
4512            const seen = entry[1];
4513            if (seen.cycle) {
4514                throw new Error("Cycle detected: " +
4515                    `#/${seen.cycle?.join("/")}/<root>` +
4516                    '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
4517            }
4518        }
4519    }
4520    // extract schemas into $defs
4521    for (const entry of ctx.seen.entries()) {
4522        const seen = entry[1];
4523        // convert root schema to # $ref
4524        if (schema === entry[0]) {
4525            extractToDef(entry); // this has special handling for the root schema
4526            continue;
4527        }
4528        // extract schemas that are in the external registry
4529        if (ctx.external) {
4530            const ext = ctx.external.registry.get(entry[0])?.id;
4531            if (schema !== entry[0] && ext) {
4532                extractToDef(entry);
4533                continue;
4534            }
4535        }
4536        // extract schemas with `id` meta
4537        const id = ctx.metadataRegistry.get(entry[0])?.id;
4538        if (id) {
4539            extractToDef(entry);
4540            continue;
4541        }
4542        // break cycles
4543        if (seen.cycle) {
4544            // any
4545            extractToDef(entry);
4546            continue;
4547        }
4548        // extract reused schemas
4549        if (seen.count > 1) {
4550            if (ctx.reused === "ref") {
4551                extractToDef(entry);
4552                // biome-ignore lint:
4553                continue;
4554            }
4555        }
4556    }
4557}
4558function finalize(ctx, schema) {
4559    const root = ctx.seen.get(schema);
4560    if (!root)
4561        throw new Error("Unprocessed schema. This is a bug in Zod.");
4562    // flatten refs - inherit properties from parent schemas
4563    const flattenRef = (zodSchema) => {
4564        const seen = ctx.seen.get(zodSchema);
4565        // already processed
4566        if (seen.ref === null)
4567            return;
4568        const schema = seen.def ?? seen.schema;
4569        const _cached = { ...schema };
4570        const ref = seen.ref;
4571        seen.ref = null; // prevent infinite recursion
4572        if (ref) {
4573            flattenRef(ref);
4574            const refSeen = ctx.seen.get(ref);
4575            const refSchema = refSeen.schema;
4576            // merge referenced schema into current
4577            if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
4578                // older drafts can't combine $ref with other properties
4579                schema.allOf = schema.allOf ?? [];
4580                schema.allOf.push(refSchema);
4581            }
4582            else {
4583                Object.assign(schema, refSchema);
4584            }
4585            // restore child's own properties (child wins)
4586            Object.assign(schema, _cached);
4587            const isParentRef = zodSchema._zod.parent === ref;
4588            // For parent chain, child is a refinement - remove parent-only properties
4589            if (isParentRef) {
4590                for (const key in schema) {
4591                    if (key === "$ref" || key === "allOf")
4592                        continue;
4593                    if (!(key in _cached)) {
4594                        delete schema[key];
4595                    }
4596                }
4597            }
4598            // When ref was extracted to $defs, remove properties that match the definition
4599            if (refSchema.$ref && refSeen.def) {
4600                for (const key in schema) {
4601                    if (key === "$ref" || key === "allOf")
4602                        continue;
4603                    if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {
4604                        delete schema[key];
4605                    }
4606                }
4607            }
4608        }
4609        // If parent was extracted (has $ref), propagate $ref to this schema
4610        // This handles cases like: readonly().meta({id}).describe()
4611        // where processor sets ref to innerType but parent should be referenced
4612        const parent = zodSchema._zod.parent;
4613        if (parent && parent !== ref) {
4614            // Ensure parent is processed first so its def has inherited properties
4615            flattenRef(parent);
4616            const parentSeen = ctx.seen.get(parent);
4617            if (parentSeen?.schema.$ref) {
4618                schema.$ref = parentSeen.schema.$ref;
4619                // De-duplicate with parent's definition
4620                if (parentSeen.def) {
4621                    for (const key in schema) {
4622                        if (key === "$ref" || key === "allOf")
4623                            continue;
4624                        if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {
4625                            delete schema[key];
4626                        }
4627                    }
4628                }
4629            }
4630        }
4631        // execute overrides
4632        ctx.override({
4633            zodSchema: zodSchema,
4634            jsonSchema: schema,
4635            path: seen.path ?? [],
4636        });
4637    };
4638    for (const entry of [...ctx.seen.entries()].reverse()) {
4639        flattenRef(entry[0]);
4640    }
4641    const result = {};
4642    if (ctx.target === "draft-2020-12") {
4643        result.$schema = "https://json-schema.org/draft/2020-12/schema";
4644    }
4645    else if (ctx.target === "draft-07") {
4646        result.$schema = "http://json-schema.org/draft-07/schema#";
4647    }
4648    else if (ctx.target === "draft-04") {
4649        result.$schema = "http://json-schema.org/draft-04/schema#";
4650    }
4651    else 
4651if (ctx.target === "openapi-3.0") ;
4652    else ;
4653    if (ctx.external?.uri) {
4654        const id = ctx.external.registry.get(schema)?.id;
4655        if (!id)
4656            throw new Error("Schema is missing an `id` property");
4657        result.$id = ctx.external.uri(id);
4658    }
4659    Object.assign(result, root.def ?? root.schema);
4660    // The `id` in `.meta()` is a Zod-specific registration tag used to extract
4661    // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it
4662    // from the output body where it would otherwise leak. The id is preserved
4663    // implicitly via the $defs key (and via $ref paths).
4664    const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
4665    if (rootMetaId !== undefined && result.id === rootMetaId)
4666        delete result.id;
4667    // build defs object
4668    const defs = ctx.external?.defs ?? {};
4669    for (const entry of ctx.seen.entries()) {
4670        const seen = entry[1];
4671        if (seen.def && seen.defId) {
4672            if (seen.def.id === seen.defId)
4673                delete seen.def.id;
4674            defs[seen.defId] = seen.def;
4675        }
4676    }
4677    // set definitions in result
4678    if (ctx.external) ;
4679    else {
4680        if (Object.keys(defs).length > 0) {
vendor: 4,369 bytes, lines 4681-4809
4681            if (ctx.target === "draft-2020-12") {
4682                result.$defs = defs;
4683            }
4684            else {
4685                result.definitions = defs;
4686            }
4687        }
4688    }
4689    try {
4690        // this "finalizes" this schema and ensures all cycles are removed
4691        // each call to finalize() is functionally independent
4692        // though the seen map is shared
4693        const finalized = JSON.parse(JSON.stringify(result));
4694        Object.defineProperty(finalized, "~standard", {
4695            value: {
4696                ...schema["~standard"],
4697                jsonSchema: {
4698                    input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
4699                    output: createStandardJSONSchemaMethod(schema, "output", ctx.processors),
4700                },
4701            },
4702            enumerable: false,
4703            writable: false,
4704        });
4705        return finalized;
4706    }
4707    catch (_err) {
4708        throw new Error("Error converting schema to JSON.");
4709    }
4710}
4711function isTransforming(_schema, _ctx) {
4712    const ctx = _ctx ?? { seen: new Set() };
4713    if (ctx.seen.has(_schema))
4714        return false;
4715    ctx.seen.add(_schema);
4716    const def = _schema._zod.def;
4717    if (def.type === "transform")
4718        return true;
4719    if (def.type === "array")
4720        return isTransforming(def.element, ctx);
4721    if (def.type === "set")
4722        return isTransforming(def.valueType, ctx);
4723    if (def.type === "lazy")
4724        return isTransforming(def.getter(), ctx);
4725    if (def.type === "promise" ||
4726        def.type === "optional" ||
4727        def.type === "nonoptional" ||
4728        def.type === "nullable" ||
4729        def.type === "readonly" ||
4730        def.type === "default" ||
4731        def.type === "prefault") {
4732        return isTransforming(def.innerType, ctx);
4733    }
4734    if (def.type === "intersection") {
4735        return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
4736    }
4737    if (def.type === "record" || def.type === "map") {
4738        return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
4739    }
4740    if (def.type === "pipe") {
4741        if (_schema._zod.traits.has("$ZodCodec"))
4742            return true;
4743        return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
4744    }
4745    if (def.type === "object") {
4746        for (const key in def.shape) {
4747            if (isTransforming(def.shape[key], ctx))
4748                return true;
4749        }
4750        return false;
4751    }
4752    if (def.type === "union") {
4753        for (const option of def.options) {
4754            if (isTransforming(option, ctx))
4755                return true;
4756        }
4757        return false;
4758    }
4759    if (def.type === "tuple") {
4760        for (const item of def.items) {
4761            if (isTransforming(item, ctx))
4762                return true;
4763        }
4764        if (def.rest && isTransforming(def.rest, ctx))
4765            return true;
4766        return false;
4767    }
4768    return false;
4769}
4770/**
4771 * Creates a toJSONSchema method for a schema instance.
4772 * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.
4773 */
4774const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
4775    const ctx = initializeContext({ ...params, processors });
4776    process(schema, ctx);
4777    extractDefs(ctx, schema);
4778    return finalize(ctx, schema);
4779};
4780const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
4781    const { libraryOptions, target } = params ?? {};
4782    const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });
4783    process(schema, ctx);
4784    extractDefs(ctx, schema);
4785    return finalize(ctx, schema);
4786};
4787
4788const formatMap = {
4789    guid: "uuid",
4790    url: "uri",
4791    datetime: "date-time",
4792    json_string: "json-string",
4793    regex: "", // do not set
4794};
4795// ==================== SIMPLE TYPE PROCESSORS ====================
4796const stringProcessor = (schema, ctx, _json, _params) => {
4797    const json = _json;
4798    json.type = "string";
4799    const { minimum, maximum, format, patterns, contentEncoding } = schema._zod
4800        .bag;
4801    if (typeof minimum === "number")
4802        json.minLength = minimum;
4803    if (typeof maximum === "number")
4804        json.maxLength = maximum;
4805    // custom pattern overrides format
4806    if (format) {
4807        json.format = formatMap[format] ?? format;
4808        if (json.format === "")
4809            delete json.format;
4809 // empty format is not valid
4810        // JSON Schema format: "time" requires a full time with offset or Z
4811        // z.iso.time() does not include timezone information, so format: "time" should never be used
4812        if (format === "time") {
4813            delete json.format;
4814        }
4815    }
4816    if (contentEncoding)
4817        json.contentEncoding = contentEncoding;
4818    if (patterns && patterns.size > 0) {
4819        const regexes = [...patterns];
4820        if (regexes.length === 1)
4821            json.pattern = regexes[0].source;
4822        else if (regexes.length > 1) {
4823            json.allOf = [
4824                ...regexes.map((regex) => ({
4825                    ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0"
4826                        ? { type: "string" }
4827                        : {}),
4828                    pattern: regex.source,
4829                })),
4830            ];
4831        }
4832    }
4833};
4834const numberProcessor = (schema, ctx, _json, _params) => {
4835    const json = _json;
4836    const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
4837    if (typeof format === "string" && format.includes("int"))
4838        json.type = "integer";
4839    else
4840        json.type = "number";
4841    // when both minimum and exclusiveMinimum exist, pick the more restrictive one
4842    const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
4843    const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
4844    const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
4845    if (exMin) {
4846        if (legacy) {
4847            json.minimum = exclusiveMinimum;
4848            json.exclusiveMinimum = true;
4849        }
4850        else {
4851            json.exclusiveMinimum = exclusiveMinimum;
4852        }
4853    }
4854    else if (typeof minimum === "number") {
4855        json.minimum = minimum;
4856    }
4857    if (exMax) {
4858        if (legacy) {
4859            json.maximum = exclusiveMaximum;
4860            json.exclusiveMaximum = true;
4861        }
4862        else {
4863            json.exclusiveMaximum = exclusiveMaximum;
4864        }
4865    }
4866    else if (typeof maximum === "number") {
4867        json.maximum = maximum;
4868    }
4869    if (typeof multipleOf === "number")
4870        json.multipleOf = multipleOf;
4871};
4872const booleanProcessor = (_schema, _ctx, json, _params) => {
4873    json.type = "boolean";
4874};
4875const neverProcessor = (_schema, _ctx, json, _params) => {
4876    json.not = {};
4877};
4878const anyProcessor = (_schema, _ctx, _json, _params) => {
4879    // empty schema accepts anything
4880};
4881const unknownProcessor = (_schema, _ctx, _json, _params) => {
4882    // empty schema accepts anything
4883};
4884const dateProcessor = (_schema, ctx, _json, _params) => {
4885    if (ctx.unrepresentable === "throw") {
4886        throw new Error("Date cannot be represented in JSON Schema");
4887    }
4888};
4889const enumProcessor = (schema, _ctx, json, _params) => {
4890    const def = schema._zod.def;
4891    const values = getEnumValues(def.entries);
4892    // Number enums can have both string and number values
4893    if (values.every((v) => typeof v === "number"))
4894        json.type = "number";
4895    if (values.every((v) => typeof v === "string"))
4896        json.type = "string";
4897    json.enum = values;
4898};
4899const literalProcessor = (schema, ctx, json, _params) => {
4900    const def = schema._zod.def;
4901    const vals = [];
4902    for (const val of def.values) {
4903        if (val === undefined) {
4904            if (ctx.unrepresentable === "throw") {
4905                throw new Error("Literal `undefined` cannot be represented in JSON Schema");
4906            }
4907        }
4908        else if (typeof val === "bigint") {
4909            if (ctx.unrepresentable === "throw") {
4910                throw new Error("BigInt literals cannot be represented in JSON Schema");
4911            }
4912            else {
4913                vals.push(Number(val));
4914            }
4915        }
4916        else {
4917            vals.push(val);
4918        }
4919    }
4920    if (vals.length === 0) ;
4921    else if (vals.length === 1) {
4922        const val = vals[0];
4923        json.type = val === null ? "null" : typeof val;
vendor: 6,974 bytes, lines 4924-5124
4924        if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
4925            json.enum = [val];
4926        }
4927        else {
4928            json.const = val;
4929        }
4930    }
4931    else {
4932        if (vals.every((v) => typeof v === "number"))
4933            json.type = "number";
4934        if (vals.every((v) => typeof v === "string"))
4935            json.type = "string";
4936        if (vals.every((v) => typeof v === "boolean"))
4937            json.type = "boolean";
4938        if (vals.every((v) => v === null))
4939            json.type = "null";
4940        json.enum = vals;
4941    }
4942};
4943const customProcessor = (_schema, ctx, _json, _params) => {
4944    if (ctx.unrepresentable === "throw") {
4945        throw new Error("Custom types cannot be represented in JSON Schema");
4946    }
4947};
4948const transformProcessor = (_schema, ctx, _json, _params) => {
4949    if (ctx.unrepresentable === "throw") {
4950        throw new Error("Transforms cannot be represented in JSON Schema");
4951    }
4952};
4953// ==================== COMPOSITE TYPE PROCESSORS ====================
4954const arrayProcessor = (schema, ctx, _json, params) => {
4955    const json = _json;
4956    const def = schema._zod.def;
4957    const { minimum, maximum } = schema._zod.bag;
4958    if (typeof minimum === "number")
4959        json.minItems = minimum;
4960    if (typeof maximum === "number")
4961        json.maxItems = maximum;
4962    json.type = "array";
4963    json.items = process(def.element, ctx, {
4964        ...params,
4965        path: [...params.path, "items"],
4966    });
4967};
4968const objectProcessor = (schema, ctx, _json, params) => {
4969    const json = _json;
4970    const def = schema._zod.def;
4971    json.type = "object";
4972    json.properties = {};
4973    const shape = def.shape;
4974    for (const key in shape) {
4975        json.properties[key] = process(shape[key], ctx, {
4976            ...params,
4977            path: [...params.path, "properties", key],
4978        });
4979    }
4980    // required keys
4981    const allKeys = new Set(Object.keys(shape));
4982    const requiredKeys = new Set([...allKeys].filter((key) => {
4983        const v = def.shape[key]._zod;
4984        if (ctx.io === "input") {
4985            return v.optin === undefined;
4986        }
4987        else {
4988            return v.optout === undefined;
4989        }
4990    }));
4991    if (requiredKeys.size > 0) {
4992        json.required = Array.from(requiredKeys);
4993    }
4994    // catchall
4995    if (def.catchall?._zod.def.type === "never") {
4996        // strict
4997        json.additionalProperties = false;
4998    }
4999    else if (!def.catchall) {
5000        // regular
5001        if (ctx.io === "output")
5002            json.additionalProperties = false;
5003    }
5004    else if (def.catchall) {
5005        json.additionalProperties = process(def.catchall, ctx, {
5006            ...params,
5007            path: [...params.path, "additionalProperties"],
5008        });
5009    }
5010};
5011const unionProcessor = (schema, ctx, json, params) => {
5012    const def = schema._zod.def;
5013    // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)
5014    // This includes both z.xor() and discriminated unions
5015    const isExclusive = def.inclusive === false;
5016    const options = def.options.map((x, i) => process(x, ctx, {
5017        ...params,
5018        path: [...params.path, isExclusive ? "oneOf" : "anyOf", i],
5019    }));
5020    if (isExclusive) {
5021        json.oneOf = options;
5022    }
5023    else {
5024        json.anyOf = options;
5025    }
5026};
5027const intersectionProcessor = (schema, ctx, json, params) => {
5028    const def = schema._zod.def;
5029    const a = process(def.left, ctx, {
5030        ...params,
5031        path: [...params.path, "allOf", 0],
5032    });
5033    const b = process(def.right, ctx, {
5034        ...params,
5035        path: [...params.path, "allOf", 1],
5036    });
5037    const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
5038    const allOf = [
5039        ...(isSimpleIntersection(a) ? a.allOf : [a]),
5040        ...(isSimpleIntersection(b) ? b.allOf : [b]),
5041    ];
5042    json.allOf = allOf;
5043};
5044const recordProcessor = (schema, ctx, _json, params) => {
5045    const json = _json;
5046    const def = schema._zod.def;
5047    json.type = "object";
5048    // For looseRecord with regex patterns, use patternProperties
5049    // This correctly represents "only validate keys matching the pattern" semantics
5050    // and composes well with allOf (intersections)
5051    const keyType = def.keyType;
5052    const keyBag = keyType._zod.bag;
5053    const patterns = keyBag?.patterns;
5054    if (def.mode === "loose" && patterns && patterns.size > 0) {
5055        // Use patternProperties for looseRecord with regex patterns
5056        const valueSchema = process(def.valueType, ctx, {
5057            ...params,
5058            path: [...params.path, "patternProperties", "*"],
5059        });
5060        json.patternProperties = {};
5061        for (const pattern of patterns) {
5062            json.patternProperties[pattern.source] = valueSchema;
5063        }
5064    }
5065    else {
5066        // Default behavior: use propertyNames + additionalProperties
5067        if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
5068            json.propertyNames = process(def.keyType, ctx, {
5069                ...params,
5070                path: [...params.path, "propertyNames"],
5071            });
5072        }
5073        json.additionalProperties = process(def.valueType, ctx, {
5074            ...params,
5075            path: [...params.path, "additionalProperties"],
5076        });
5077    }
5078    // Add required for keys with discrete values (enum, literal, etc.)
5079    const keyValues = keyType._zod.values;
5080    if (keyValues) {
5081        const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
5082        if (validKeyValues.length > 0) {
5083            json.required = validKeyValues;
5084        }
5085    }
5086};
5087const nullableProcessor = (schema, ctx, json, params) => {
5088    const def = schema._zod.def;
5089    const inner = process(def.innerType, ctx, params);
5090    const seen = ctx.seen.get(schema);
5091    if (ctx.target === "openapi-3.0") {
5092        seen.ref = def.innerType;
5093        json.nullable = true;
5094    }
5095    else {
5096        json.anyOf = [inner, { type: "null" }];
5097    }
5098};
5099const nonoptionalProcessor = (schema, ctx, _json, params) => {
5100    const def = schema._zod.def;
5101    process(def.innerType, ctx, params);
5102    const seen = ctx.seen.get(schema);
5103    seen.ref = def.innerType;
5104};
5105const defaultProcessor = (schema, ctx, json, params) => {
5106    const def = schema._zod.def;
5107    process(def.innerType, ctx, params);
5108    const seen = ctx.seen.get(schema);
5109    seen.ref = def.innerType;
5110    json.default = JSON.parse(JSON.stringify(def.defaultValue));
5111};
5112const prefaultProcessor = (schema, ctx, json, params) => {
5113    const def = schema._zod.def;
5114    process(def.innerType, ctx, params);
5115    const seen = ctx.seen.get(schema);
5116    seen.ref = def.innerType;
5117    if (ctx.io === "input")
5118        json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
5119};
5120const catchProcessor = (schema, ctx, json, params) => {
5121    const def = schema._zod.def;
5122    process(def.innerType, ctx, params);
5123    const seen = ctx.seen.get(schema);
5124    seen.ref = def.innerType;
5125    let catchValue;
5126    try {
5127        catchValue = def.catchValue(undefined);
5128    }
5129    catch {
5130        throw new Error("Dynamic catch values are not supported in JSON Schema");
5131    }
5132    json.default = catchValue;
5133};
5134const pipeProcessor = (schema, ctx, _json, params) => {
5135    const def = schema._zod.def;
5136    const inIsTransform = def.in._zod.traits.has("$ZodTransform");
5137    const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out;
5138    process(innerType, ctx, params);
5139    const seen = ctx.seen.get(schema);
5140    seen.ref = innerType;
5141};
5142const readonlyProcessor = (schema, ctx, json, params) => {
5143    const def = schema._zod.def;
5144    process(def.innerType, ctx, params);
5145    const seen = ctx.seen.get(schema);
5146    seen.ref = def.innerType;
5147    json.readOnly = true;
5148};
5149const optionalProcessor = (schema, ctx, _json, params) => {
5150    const def = schema._zod.def;
5151    process(def.innerType, ctx, params);
5152    const seen = ctx.seen.get(schema);
5153    seen.ref = def.innerType;
5154};
5155
5156const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
5157    $ZodISODateTime.init(inst, def);
5158    ZodStringFormat.init(inst, def);
5159});
5160function datetime(params) {
5161    return _isoDateTime(ZodISODateTime, params);
5162}
5163const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
5164    $ZodISODate.init(inst, def);
5165    ZodStringFormat.init(inst, def);
5166});
5167function date$1(params) {
5168    return _isoDate(ZodISODate, params);
5169}
5170const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
5171    $ZodISOTime.init(inst, def);
5172    ZodStringFormat.init(inst, def);
5173});
5174function time(params) {
5175    return _isoTime(ZodISOTime, params);
5176}
5177const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
5178    $ZodISODuration.init(inst, def);
5179    ZodStringFormat.init(inst, def);
5180});
5181function duration(params) {
5182    return _isoDuration(ZodISODuration, params);
5183}
5184
5185const initializer = (inst, issues) => {
5186    $ZodError.init(inst, issues);
5187    inst.name = "ZodError";
5188    Object.defineProperties(inst, {
5189        format: {
5190            value: (mapper) => formatError(inst, mapper),
5191            // enumerable: false,
5192        },
5193        flatten: {
5194            value: (mapper) => flattenError(inst, mapper),
5195            // enumerable: false,
5196        },
5197        addIssue: {
5198            value: (issue) => {
5199                inst.issues.push(issue);
5200                inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
5201            },
5202            // enumerable: false,
5203        },
5204        addIssues: {
5205            value: (issues) => {
5206                inst.issues.push(...issues);
5207                inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
5208            },
5209            // enumerable: false,
5210        },
5211        isEmpty: {
5212            get() {
5213                return inst.issues.length === 0;
5214            },
5215            // enumerable: false,
5216        },
5217    });
5218    // Object.defineProperty(inst, "isEmpty", {
5219    //   get() {
5220    //     return inst.issues.length === 0;
5221    //   },
5222    // });
5223};
5224const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, {
5225    Parent: Error,
5226});
5227// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
5228// export type ErrorMapCtx = core.$ZodErrorMapCtx;
5229
5230const parse = /* @__PURE__ */ _parse(ZodRealError);
5231const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
5232const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
5233const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
5234// Codec functions
5235const encode = /* @__PURE__ */ _encode(ZodRealError);
5236const decode = /* @__PURE__ */ _decode(ZodRealError);
5237const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
5238const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
5239const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
5240const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
5241const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
5242const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
5243
5244// Lazy-bind builder methods.
5245//
5246// Builder methods (`.optional`, `.array`, `.refine`, ...) live as
5247// non-enumerable getters on each concrete schema constructor's
5248// prototype. On first access from an instance the getter allocates
5249// `fn.bind(this)` and caches it as an own property on that instance,
5250// so detached usage (`const m = schema.optional; m()`) still works
5251// and the per-instance allocation only happens for methods actually
5252// touched.
5253//
5254// One install per (prototype, group), memoized by `_installedGroups`.
5255const _installedGroups = /* @__PURE__ */ new WeakMap();
5256function _installLazyMethods(inst, group, methods) {
5257    const proto = Object.getPrototypeOf(inst);
5258    let installed = _installedGroups.get(proto);
5259    if (!installed) {
5260        installed = new Set();
5261        _installedGroups.set(proto, installed);
5262    }
5263    if (installed.has(group))
5264        return;
5265    installed.add(group);
5266    for (const key in methods) {
5267        const fn = methods[key];
5268        Object.defineProperty(proto, key, {
5269            configurable: true,
5270            enumerable: false,
5271            get() {
5272                const bound = fn.bind(this);
5273                Object.defineProperty(this, key, {
5274                    configurable: true,
5275                    writable: true,
5276                    enumerable: true,
5277                    value: bound,
5278                });
5279                return bound;
5280            },
5281            set(v) {
5282                Object.defineProperty(this, key, {
5283                    configurable: true,
5284                    writable: true,
5285                    enumerable: true,
5286                    value: v,
5287                });
5288            },
5289        });
5290    }
5291}
5292const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
5293    $ZodType.init(inst, def);
5294    Object.assign(inst["~standard"], {
5295        jsonSchema: {
5296            input: createStandardJSONSchemaMethod(inst, "input"),
5297            output: createStandardJSONSchemaMethod(inst, "output"),
5298        },
5299    });
5300    inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
5301    inst.def = def;
5302    inst.type = def.type;
5303    Object.defineProperty(inst, "_def", { value: def });
5304    // Parse-family is intentionally kept as per-instance closures: these are
5305    // the hot path AND the most-detached methods (`arr.map(schema.parse)`,
5306    // `const { parse } = schema`, etc.). Eager closures here mean callers pay
5307    // ~12 closure allocations per schema but get monomorphic call sites and
5308    // detached usage that "just works".
5309    inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
5310    inst.safeParse = (data, params) => safeParse(inst, data, params);
5311    inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
5312    inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
5313    inst.spa = inst.safeParseAsync;
5314    inst.encode = (data, params) => encode(inst, data, params);
5315    inst.decode = (data, params) => decode(inst, data, params);
5316    inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
5317    inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
5318    inst.safeEncode = (data, params) => safeEncode(inst, data, params);
5319    inst.safeDecode = (data, params) => safeDecode(inst, data, params);
5320    inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
5321    inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
5322    // All builder methods are placed on the internal prototype as lazy-bind
5323    // getters. On first access per-instance, a bound thunk is allocated and
5324    // cached as an own property; subsequent accesses skip the getter. This
5325    // means: no per-instance allocation for unused methods, full
5326    // detachability preserved (`const m = schema.optional; m()` works), and
5327    // shared underlying function references across all instances.
5328    _installLazyMethods(inst, "ZodType", {
5329        check(...chks) {
5330            const def = this.def;
5331            return this.clone(mergeDefs(def, {
5332                checks: [
5333                    ...(def.checks ?? []),
5334                    ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
5335                ],
5336            }), { parent: true });
5337        },
5338        with(...chks) {
5339            return this.check(...chks);
5340        },
5341        clone(def, params) {
5342            return clone(this, def, params);
5343        },
5344        brand() {
5345            return this;
5346        },
5347        register(reg, meta) {
5348            reg.add(this, meta);
5349            return this;
5350        },
5351        refine(check, params) {
5352            return this.check(refine(check, params));
5353        },
5354        superRefine(refinement, params) {
5355            return this.check(superRefine(refinement, params));
5356        },
5357        overwrite(fn) {
5358            return this.check(_overwrite(fn));
5359        },
5360        optional() {
5361            return optional(this);
5362        },
5363        exactOptional() {
5364            return exactOptional(this);
5365        },
5366        nullable() {
5367            return nullable(this);
5368        },
5369        nullish() {
5370            return optional(nullable(this));
5371        },
5372        nonoptional(params) {
5373            return nonoptional(this, params);
5374        },
5375        array() {
5376            return array(this);
5377        },
5378        or(arg) {
5379            return union([this, arg]);
5380        },
5381        and(arg) {
5382            return intersection(this, arg);
5383        },
5384        transform(tx) {
5385            return pipe(this, transform(tx));
5386        },
5387        default(d) {
5388            return _default(this, d);
5389        },
5390        prefault(d) {
5391            return prefault(this, d);
5392        },
5393        catch(params) {
5394            return _catch(this, params);
5395        },
5396        pipe(target) {
5397            return pipe(this, target);
5398        },
5399        readonly() {
5400            return readonly(this);
5401        },
5402        describe(description) {
5403            const cl = this.clone();
5404            globalRegistry.add(cl, { description });
5405            return cl;
5406        },
5407        meta(...args) {
5408            // overloaded: meta() returns the registered metadata, meta(data)
5409            // returns a clone with `data` registered. The mapped type picks
5410            // up the second overload, so we accept variadic any-args and
5411            // return `any` to satisfy both at runtime.
5412            if (args.length === 0)
5413                return globalRegistry.get(this);
5414            const cl = this.clone();
5415            globalRegistry.add(cl, args[0]);
5416            return cl;
5417        },
5418        isOptional() {
5419            return this.safeParse(undefined).success;
5420        },
5421        isNullable() {
5422            return this.safeParse(null).success;
5423        },
5424        apply(fn) {
5425            return fn(this);
5426        },
5427    });
5428    Object.defineProperty(inst, "description", {
5429        get() {
5430            return globalRegistry.get(inst)?.description;
5431        },
5432        configurable: true,
5433    });
5434    return inst;
5435});
5436/** @internal */
5437const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
5438    $ZodString.init(inst, def);
5439    ZodType.init(inst, def);
5440    inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json);
5441    const bag = inst._zod.bag;
5442    inst.format = bag.format ?? null;
5443    inst.minLength = bag.minimum ?? null;
5444    inst.maxLength = bag.maximum ?? null;
5445    _installLazyMethods(inst, "_ZodString", {
5446        regex(...args) {
5447            return this.check(_regex(...args));
5448        },
5449        includes(...args) {
5450            return this.check(_includes(...args));
5451        },
5452        startsWith(...args) {
5453            return this.check(_startsWith(...args));
5454        },
5455        endsWith(...args) {
5456            return this.check(_endsWith(...args));
5457        },
5458        min(...args) {
5459            return this.check(_minLength(...args));
5460        },
5461        max(...args) {
5462            return this.check(_maxLength(...args));
5463        },
5464        length(...args) {
5465            return this.check(_length(...args));
5466        },
5467        nonempty(...args) {
5468            return this.check(_minLength(1, ...args));
5469        },
5470        lowercase(params) {
5471            return this.check(_lowercase(params));
5472        },
5473        uppercase(params) {
5474            return this.check(_uppercase(params));
5475        },
5476        trim() {
5477            return this.check(_trim());
5478        },
5479        normalize(...args) {
5480            return this.check(_normalize(...args));
5481        },
5482        toLowerCase() {
5483            return this.check(_toLowerCase());
5484        },
5485        toUpperCase() {
5486            return this.check(_toUpperCase());
5487        },
5488        slugify() {
5489            return this.check(_slugify());
5490        },
5491    });
5492});
5493const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
5494    $ZodString.init(inst, def);
5495    _ZodString.init(inst, def);
5496    inst.email = (params) => inst.check(_email(ZodEmail, params));
5497    inst.url = (params) => inst.check(_url(ZodURL, params));
5498    inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
5499    inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
5500    inst.guid = (params) => inst.check(_guid(ZodGUID, params));
5501    inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
5502    inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
5503    inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
5504    inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
5505    inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
5506    inst.guid = (params) => inst.check(_guid(ZodGUID, params));
5507    inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
5508    inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
5509    inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
5510    inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
5511    inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
5512    inst.xid = (params) => inst.check(_xid(ZodXID, params));
5513    inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
5514    inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
5515    inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
5516    inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
5517    inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
5518    inst.e164 = (params) => inst.check(_e164(ZodE164, params));
5519    // iso
5520    inst.datetime = (params) => inst.check(datetime(params));
5521    inst.date = (params) => inst.check(date$1(params));
5522    inst.time = (params) => inst.check(time(params));
5523    inst.duration = (params) => inst.check(duration(params));
5524});
5525function string(params) {
5526    return _string(ZodString, params);
5527}
5528const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
5529    $ZodStringFormat.init(inst, def);
5530    _ZodString.init(inst, def);
5531});
5532const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
5533    // ZodStringFormat.init(inst, def);
5534    $ZodEmail.init(inst, def);
5535    ZodStringFormat.init(inst, def);
5536});
5537const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
5538    // ZodStringFormat.init(inst, def);
5539    $ZodGUID.init(inst, def);
5540    ZodStringFormat.init(inst, def);
5541});
5542const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
5543    // ZodStringFormat.init(inst, def);
5544    $ZodUUID.init(inst, def);
5545    ZodStringFormat.init(inst, def);
5546});
5547const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
5548    // ZodStringFormat.init(inst, def);
5549    $ZodURL.init(inst, def);
5550    ZodStringFormat.init(inst, def);
5551});
5552const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
5553    // ZodStringFormat.init(inst, def);
5554    $ZodEmoji.init(inst, def);
5555    ZodStringFormat.init(inst, def);
5556});
5557const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
5558    // ZodStringFormat.init(inst, def);
5559    $ZodNanoID.init(inst, def);
5560    ZodStringFormat.init(inst, def);
5561});
5562/**
5563 * @deprecated CUID v1 is deprecated by its authors due to information leakage
5564 * (timestamps embedded in the id). Use {@link ZodCUID2} instead.
5565 * See https://github.com/paralleldrive/cuid.
5566 */
5567const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
5568    // ZodStringFormat.init(inst, def);
5569    $ZodCUID.init(inst, def);
5570    ZodStringFormat.init(inst, def);
5571});
5572const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
5573    // ZodStringFormat.init(inst, def);
5574    $ZodCUID2.init(inst, def);
5575    ZodStringFormat.init(inst, def);
5576});
5577const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
5578    // ZodStringFormat.init(inst, def);
5579    $ZodULID.init(inst, def);
5580    ZodStringFormat.init(inst, def);
5581});
5582const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
5583    // ZodStringFormat.init(inst, def);
5584    $ZodXID.init(inst, def);
5585    ZodStringFormat.init(inst, def);
5586});
5587const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
5588    // ZodStringFormat.init(inst, def);
5589    $ZodKSUID.init(inst, def);
5590    ZodStringFormat.init(inst, def);
5591});
5592const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
5593    // ZodStringFormat.init(inst, def);
5594    $ZodIPv4.init(inst, def);
5595    ZodStringFormat.init(inst, def);
5596});
5597const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
5598    // ZodStringFormat.init(inst, def);
5599    $ZodIPv6.init(inst, def);
5600    ZodStringFormat.init(inst, def);
5601});
5602const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
5603    $ZodCIDRv4.init(inst, def);
5604    ZodStringFormat.init(inst, def);
5605});
5606const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
5607    $ZodCIDRv6.init(inst, def);
5608    ZodStringFormat.init(inst, def);
5609});
5610const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
5611    // ZodStringFormat.init(inst, def);
5612    $ZodBase64.init(inst, def);
5613    ZodStringFormat.init(inst, def);
5614});
5615const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
5616    // ZodStringFormat.init(inst, def);
5617    $ZodBase64URL.init(inst, def);
5618    ZodStringFormat.init(inst, def);
5619});
5620const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
5621    // ZodStringFormat.init(inst, def);
5622    $ZodE164.init(inst, def);
5623    ZodStringFormat.init(inst, def);
5624});
5625const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
5626    // ZodStringFormat.init(inst, def);
5627    $ZodJWT.init(inst, def);
5628    ZodStringFormat.init(inst, def);
5629});
5630const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
5631    $ZodNumber.init(inst, def);
5632    ZodType.init(inst, def);
5633    inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json);
5634    _installLazyMethods(inst, "ZodNumber", {
5635        gt(value, params) {
5636            return this.check(_gt(value, params));
5637        },
5638        gte(value, params) {
5639            return this.check(_gte(value, params));
5640        },
5641        min(value, params) {
5642            return this.check(_gte(value, params));
5643        },
5644        lt(value, params) {
5645            return this.check(_lt(value, params));
5646        },
5647        lte(value, params) {
5648            return this.check(_lte(value, params));
5649        },
5650        max(value, params) {
5651            return this.check(_lte(value, params));
5652        },
5653        int(params) {
5654            return this.check(int(params));
5655        },
5656        safe(params) {
5657            return this.check(int(params));
5658        },
5659        positive(params) {
5660            return this.check(_gt(0, params));
5661        },
5662        nonnegative(params) {
5663            return this.check(_gte(0, params));
5664        },
5665        negative(params) {
5666            return this.check(_lt(0, params));
5667        },
5668        nonpositive(params) {
5669            return this.check(_lte(0, params));
5670        },
5671        multipleOf(value, params) {
5672            return this.check(_multipleOf(value, params));
5673        },
5674        step(value, params) {
5675            return this.check(_multipleOf(value, params));
5676        },
5677        finite() {
5678            return this;
5679        },
5680    });
5681    const bag = inst._zod.bag;
5682    inst.minValue =
5683        Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
5684    inst.maxValue =
5685        Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
5686    inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
5687    inst.isFinite = true;
5688    inst.format = bag.format ?? null;
5689});
5690function number$1(params) {
5691    return _number(ZodNumber, params);
5692}
5693const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
5694    $ZodNumberFormat.init(inst, def);
5695    ZodNumber.init(inst, def);
5696});
5697function int(params) {
5698    return _int(ZodNumberFormat, params);
5699}
5700const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
5701    $ZodBoolean.init(inst, def);
5702    ZodType.init(inst, def);
5703    inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json);
5704});
5705function boolean(params) {
5706    return _boolean(ZodBoolean, params);
5707}
5708const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => {
5709    $ZodAny.init(inst, def);
5710    ZodType.init(inst, def);
5711    inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor();
5712});
5713function any() {
5714    return _any(ZodAny);
5715}
5716const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
5717    $ZodUnknown.init(inst, def);
5718    ZodType.init(inst, def);
5719    inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor();
5720});
5721function unknown() {
5722    return _unknown(ZodUnknown);
5723}
5724const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
5725    $ZodNever.init(inst, def);
5726    ZodType.init(inst, def);
5727    inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json);
5728});
5729function never(params) {
5730    return _never(ZodNever, params);
5731}
5732const ZodDate = /*@__PURE__*/ $constructor("ZodDate", (inst, def) => {
5733    $ZodDate.init(inst, def);
5734    ZodType.init(inst, def);
5735    inst._zod.processJSONSchema = (ctx, json, params) => dateProcessor(inst, ctx);
5736    inst.min = (value, params) => inst.check(_gte(value, params));
5737    inst.max = (value, params) => inst.check(_lte(value, params));
5738    const c = inst._zod.bag;
5739    inst.minDate = c.minimum ? new Date(c.minimum) : null;
5740    inst.maxDate = c.maximum ? new Date(c.maximum) : null;
5741});
5742function date(params) {
5743    return _date(ZodDate, params);
5744}
5745const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
5746    $ZodArray.init(inst, def);
5747    ZodType.init(inst, def);
5748    inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
5749    inst.element = def.element;
5750    _installLazyMethods(inst, "ZodArray", {
5751        min(n, params) {
5752            return this.check(_minLength(n, params));
5753        },
5754        nonempty(params) {
5755            return this.check(_minLength(1, params));
5756        },
5757        max(n, params) {
5758            return this.check(_maxLength(n, params));
5759        },
5760        length(n, params) {
5761            return this.check(_length(n, params));
5762        },
5763        unwrap() {
5764            return this.element;
5765        },
5766    });
5767});
5768function array(element, params) {
5769    return _array(ZodArray, element, params);
5770}
5771const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
5772    $ZodObjectJIT.init(inst, def);
5773    ZodType.init(inst, def);
5774    inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
5775    defineLazy(inst, "shape", () => {
5776        return def.shape;
5777    });
5778    _installLazyMethods(inst, "ZodObject", {
5779        keyof() {
5780            return _enum(Object.keys(this._zod.def.shape));
5781        },
5782        catchall(catchall) {
5783            return this.clone({ ...this._zod.def, catchall: catchall });
5784        },
5785        passthrough() {
5786            return this.clone({ ...this._zod.def, catchall: unknown() });
5787        },
5788        loose() {
5789            return this.clone({ ...this._zod.def, catchall: unknown() });
5790        },
5791        strict() {
5792            return this.clone({ ...this._zod.def, catchall: never() });
5793        },
5794        strip() {
5795            return this.clone({ ...this._zod.def, catchall: undefined });
5796        },
5797        extend(incoming) {
5798            return extend(this, incoming);
5799        },
5800        safeExtend(incoming) {
5801            return safeExtend(this, incoming);
5802        },
5803        merge(other) {
5804            return merge(this, other);
5805        },
5806        pick(mask) {
5807            return pick(this, mask);
5808        },
5809        omit(mask) {
5810            return omit(this, mask);
5811        },
5812        partial(...args) {
5813            return partial(ZodOptional, this, args[0]);
5814        },
5815        required(...args) {
5816            return required(ZodNonOptional, this, args[0]);
5817        },
5818    });
5819});
5820function object(shape, params) {
5821    const def = {
5822        type: "object",
5823        shape: shape ?? {},
5824        ...normalizeParams(params),
5825    };
5826    return new ZodObject(def);
5827}
5828// looseObject
5829function looseObject(shape, params) {
5830    return new ZodObject({
5831        type: "object",
5832        shape,
5833        catchall: unknown(),
5834        ...normalizeParams(params),
5835    });
5836}
5837const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
5838    $ZodUnion.init(inst, def);
5839    ZodType.init(inst, def);
5840    inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
5841    inst.options = def.options;
5842});
5843function union(options, params) {
5844    return new ZodUnion({
5845        type: "union",
5846        options: options,
5847        ...normalizeParams(params),
5848    });
5849}
5850const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => {
5851    ZodUnion.init(inst, def);
5852    $ZodDiscriminatedUnion.init(inst, def);
5853});
5854function discriminatedUnion(discriminator, options, params) {
5855    // const [options, params] = args;
5856    return new ZodDiscriminatedUnion({
5857        type: "union",
5858        options,
5859        discriminator,
5860        ...normalizeParams(params),
5861    });
5862}
5863const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
5864    $ZodIntersection.init(inst, def);
5865    ZodType.init(inst, def);
5866    inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
5867});
5868function intersection(left, right) {
5869    return new ZodIntersection({
5870        type: "intersection",
5871        left: left,
5872        right: right,
5873    });
5874}
5875const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => {
5876    $ZodRecord.init(inst, def);
5877    ZodType.init(inst, def);
5878    inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
5879    inst.keyType = def.keyType;
5880    inst.valueType = def.valueType;
5881});
5882function record(keyType, valueType, params) {
5883    // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()
5884    if (!valueType || !valueType._zod) {
5885        return new ZodRecord({
5886            type: "record",
5887            keyType: string(),
5888            valueType: keyType,
5889            ...normalizeParams(valueType),
5890        });
5891    }
5892    return new ZodRecord({
5893        type: "record",
5894        keyType,
5895        valueType: valueType,
5896        ...normalizeParams(params),
5897    });
5898}
5899const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
5900    $ZodEnum.init(inst, def);
5901    ZodType.init(inst, def);
5902    inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json);
5903    inst.enum = def.entries;
5904    inst.options = Object.values(def.entries);
5905    const keys = new Set(Object.keys(def.entries));
5906    inst.extract = (values, params) => {
5907        const newEntries = {};
5908        for (const value of values) {
5909            if (keys.has(value)) {
5910                newEntries[value] = def.entries[value];
5911            }
5912            else
5913                throw new Error(`Key ${value} not found in enum`);
5914        }
5915        return new ZodEnum({
5916            ...def,
5917            checks: [],
5918            ...normalizeParams(params),
vendor: 6,358 bytes, lines 5919-6097
5919            entries: newEntries,
5920        });
5921    };
5922    inst.exclude = (values, params) => {
5923        const newEntries = { ...def.entries };
5924        for (const value of values) {
5925            if (keys.has(value)) {
5926                delete newEntries[value];
5927            }
5928            else
5929                throw new Error(`Key ${value} not found in enum`);
5930        }
5931        return new ZodEnum({
5932            ...def,
5933            checks: [],
5934            ...normalizeParams(params),
5935            entries: newEntries,
5936        });
5937    };
5938});
5939function _enum(values, params) {
5940    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
5941    return new ZodEnum({
5942        type: "enum",
5943        entries,
5944        ...normalizeParams(params),
5945    });
5946}
5947const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => {
5948    $ZodLiteral.init(inst, def);
5949    ZodType.init(inst, def);
5950    inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json);
5951    inst.values = new Set(def.values);
5952    Object.defineProperty(inst, "value", {
5953        get() {
5954            if (def.values.length > 1) {
5955                throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
5956            }
5957            return def.values[0];
5958        },
5959    });
5960});
5961function literal(value, params) {
5962    return new ZodLiteral({
5963        type: "literal",
5964        values: Array.isArray(value) ? value : [value],
5965        ...normalizeParams(params),
5966    });
5967}
5968const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
5969    $ZodTransform.init(inst, def);
5970    ZodType.init(inst, def);
5971    inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx);
5972    inst._zod.parse = (payload, _ctx) => {
5973        if (_ctx.direction === "backward") {
5974            throw new $ZodEncodeError(inst.constructor.name);
5975        }
5976        payload.addIssue = (issue$1) => {
5977            if (typeof issue$1 === "string") {
5978                payload.issues.push(issue(issue$1, payload.value, def));
5979            }
5980            else {
5981                // for Zod 3 backwards compatibility
5982                const _issue = issue$1;
5983                if (_issue.fatal)
5984                    _issue.continue = false;
5985                _issue.code ?? (_issue.code = "custom");
5986                _issue.input ?? (_issue.input = payload.value);
5987                _issue.inst ?? (_issue.inst = inst);
5988                // _issue.continue ??= true;
5989                payload.issues.push(issue(_issue));
5990            }
5991        };
5992        const output = def.transform(payload.value, payload);
5993        if (output instanceof Promise) {
5994            return output.then((output) => {
5995                payload.value = output;
5996                payload.fallback = true;
5997                return payload;
5998            });
5999        }
6000        payload.value = output;
6001        payload.fallback = true;
6002        return payload;
6003    };
6004});
6005function transform(fn) {
6006    return new ZodTransform({
6007        type: "transform",
6008        transform: fn,
6009    });
6010}
6011const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
6012    $ZodOptional.init(inst, def);
6013    ZodType.init(inst, def);
6014    inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
6015    inst.unwrap = () => inst._zod.def.innerType;
6016});
6017function optional(innerType) {
6018    return new ZodOptional({
6019        type: "optional",
6020        innerType: innerType,
6021    });
6022}
6023const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => {
6024    $ZodExactOptional.init(inst, def);
6025    ZodType.init(inst, def);
6026    inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
6027    inst.unwrap = () => inst._zod.def.innerType;
6028});
6029function exactOptional(innerType) {
6030    return new ZodExactOptional({
6031        type: "optional",
6032        innerType: innerType,
6033    });
6034}
6035const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
6036    $ZodNullable.init(inst, def);
6037    ZodType.init(inst, def);
6038    inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
6039    inst.unwrap = () => inst._zod.def.innerType;
6040});
6041function nullable(innerType) {
6042    return new ZodNullable({
6043        type: "nullable",
6044        innerType: innerType,
6045    });
6046}
6047const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
6048    $ZodDefault.init(inst, def);
6049    ZodType.init(inst, def);
6050    inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
6051    inst.unwrap = () => inst._zod.def.innerType;
6052    inst.removeDefault = inst.unwrap;
6053});
6054function _default(innerType, defaultValue) {
6055    return new ZodDefault({
6056        type: "default",
6057        innerType: innerType,
6058        get defaultValue() {
6059            return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
6060        },
6061    });
6062}
6063const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
6064    $ZodPrefault.init(inst, def);
6065    ZodType.init(inst, def);
6066    inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
6067    inst.unwrap = () => inst._zod.def.innerType;
6068});
6069function prefault(innerType, defaultValue) {
6070    return new ZodPrefault({
6071        type: "prefault",
6072        innerType: innerType,
6073        get defaultValue() {
6074            return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
6075        },
6076    });
6077}
6078const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
6079    $ZodNonOptional.init(inst, def);
6080    ZodType.init(inst, def);
6081    inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
6082    inst.unwrap = () => inst._zod.def.innerType;
6083});
6084function nonoptional(innerType, params) {
6085    return new ZodNonOptional({
6086        type: "nonoptional",
6087        innerType: innerType,
6088        ...normalizeParams(params),
6089    });
6090}
6091const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
6092    $ZodCatch.init(inst, def);
6093    ZodType.init(inst, def);
6094    inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
6095    inst.unwrap = () => inst._zod.def.innerType;
6096    inst.removeCatch = inst.unwrap;
6097});
6098function _catch(innerType, catchValue) {
6099    return new ZodCatch({
6100        type: "catch",
6101        innerType: innerType,
6102        catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
6103    });
6104}
6105const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
6106    $ZodPipe.init(inst, def);
6107    ZodType.init(inst, def);
6108    inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
6109    inst.in = def.in;
6110    inst.out = def.out;
6111});
6112function pipe(in_, out) {
6113    return new ZodPipe({
6114        type: "pipe",
6115        in: in_,
6116        out: out,
6117        // ...util.normalizeParams(params),
6118    });
6119}
6120const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
6121    $ZodReadonly.init(inst, def);
6122    ZodType.init(inst, def);
6123    inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
6124    inst.unwrap = () => inst._zod.def.innerType;
6125});
6126function readonly(innerType) {
6127    return new ZodReadonly({
6128        type: "readonly",
6129        innerType: innerType,
6130    });
6131}
6132const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
6133    $ZodCustom.init(inst, def);
6134    ZodType.init(inst, def);
6135    inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx);
6136});
6137function refine(fn, _params = {}) {
6138    return _refine(ZodCustom, fn, _params);
6139}
6140// superRefine
6141function superRefine(fn, params) {
6142    return _superRefine(fn, params);
6143}
6144function _instanceof(cls, params = {}) {
6145    const inst = new ZodCustom({
6146        type: "custom",
6147        check: "custom",
6148        fn: (data) => data instanceof cls,
6149        abort: true,
6150        ...normalizeParams(params),
6151    });
6152    inst._zod.bag.Class = cls;
6153    // Override check to emit invalid_type instead of custom
6154    inst._zod.check = (payload) => {
6155        if (!(payload.value instanceof cls)) {
6156            payload.issues.push({
6157                code: "invalid_type",
6158                expected: cls.name,
6159                input: payload.value,
6160                inst,
6161                path: [...(inst._zod.def.path ?? [])],
6162            });
6163        }
6164    };
6165    return inst;
6166}
6167
6168function number(params) {
6169    return _coercedNumber(ZodNumber, params);
6170}
6171
6172var an=Object.defineProperty;var ln=(e)=>e;function cn(e,t){this[e]=ln.bind(null,t);}var ze$1=(e,t)=>{for(var n in t)an(e,n,{get:t[n],enumerable:true,configurable:true,set:cn.bind(t,n)});};((e)=>typeof commonjsRequire<"u"?commonjsRequire:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof commonjsRequire<"u"?commonjsRequire:t)[n]}):e)(function(e){if(typeof commonjsRequire<"u")return commonjsRequire.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Qs=Object.freeze(Object.fromEntries(Pe$2.map((e)=>[e,Object.freeze(w$2(e).networkDerivationPath)])));var ie$1;((l)=>{l.unknownError="unknownError";l.test_error="test_error";l.providerDetailsError="providerDetailsError";l.blockHeaderNotFound="blockHeaderNotFound";l.blockHashNotFoundAtHeight="blockHashNotFoundAtHeight";l.blockHashNotFoundAtHash="blockHashNotFoundAtHash";l.txHashMissing="txHashMissing";l.assetValueMissingInfo="assetValueMissingInfo";l.invalidAsset="invalidAsset";l.blockIsRequired="blockIsRequired";l.currentBlockHeaderNotFound="currentBlockHeaderNotFound";l.failedToRetrieveBalance="failedToRetrieveBalance";l.failedToRetrieveBlock="failedToRetrieveBlock";l.failedToRetrieveFees="failedToRetrieveFees";l.notImplementedBCH="notImplementedBCH";l.notImplementedDoge="notImplementedDoge";l.noPoolsFound="noPoolsFound";l.noVaultsFound="noVaultsFound";l.noTxFound="noTxFound";l.noInputCoinFound="noInputCoinFound";l.noBlockDataFound="noBlockDataFound";l.multipleCosmosMessages="multipleCosmosMessages";l.heightOrHashNotProvided="heightOrHashNotProvided";l.unknownDenom="unknownDenom";l.invalidBlockHeight="invalidBlockHeight";l.timestampExtrinsicNoArgumentsForBlock="timestampExtrinsicNoArgumentsForBlock";l.timestampExtrinsicNoTimestampForBlock="timestampExtrinsicNoTimestampForBlock";l.noTimestampExtrinsicForHash="noTimestampExtrinsicForHash";l.timestampExtrinsicNoArgumentsForHash="timestampExtrinsicNoArgumentsForHash";l.txMemoUndefined="txMemoUndefined";l.txMemoIncorrect="txMemoIncorrect";l.txTypeNotFound="txTypeNotFound";l.txNoMessage="txNoMessage";l.txNotFound="txNotFound";l.txReceiptNotFound="txReceiptNotFound";l.txParsingError="txParsingError";l.txLogsParsingError="txLogsParsingError";l.blockNotFound="blockNotFound";l.balanceNotFound="balanceNotFound";l.configError="configError";l.synthSwapDisallowed="synthSwapDisallowed";l.providerQuoteTimeout="providerQuoteTimeout";l.noQuoteResponse="noQuoteResponse";l.noPoolAssetsFound="noPoolAssetsFound";l.noThorchainPools="noThorchainPools";l.noMayachainPools="noMayachainPools";l.noThorchainNetworkInfo="noThorchainNetworkInfo";
6172l.invalidAffiliateFee="invalidAffiliateFee";l.invalidBuyAssetAddress="invalidBuyAssetAddress";l.invalidSellAssetAddress="invalidSellAssetAddress";l.invalidSourceAddress="invalidSourceAddress";l.invalidDestinationAddress="invalidDestinationAddress";l.sourceAddressIsSmartContract="sourceAddressIsSmartContract";l.destinationAddressIsSmartContract="destinationAddressIsSmartContract";l.invalidChainId="invalidChainId";l.unsupportedChainId="unsupportedChainId";l.unsupportedEVMChainId="unsupportedEVMChainId";l.unsupportedMethod="unsupportedMethod";l.unsupportedProvider="unsupportedProvider";l.invalidParamsForMethod="invalidParamsForMethod";l.unsupportedAdapter="unsupportedAdapter";l.noWhitelistTokens="noWhitelistTokens";l.failedFetchGasPrice="failedFetchGasPrice";l.failedToCreateDepositChannel="failedToCreateDepositChannel";l.noProviderDetailsFound="noProviderDetailsFound";l.noTokenListsFound="noTokenListsFound";l.tokenNotFound="tokenNotFound";l.tokenPriceNotFound="tokenPriceNotFound";l.tokenPriceFailedToUpdate="tokenPriceFailedToUpdate";l.swapAmountTooSmall="swapAmountTooSmall";l.legsArrayIsEmpty="legsArrayIsEmpty";l.failedToFetchQuoteForLeg="failedToFetchQuoteForLeg";l.noBlockHeaderFound="noBlockHeaderFound";l.failedToSimulateSwap="failedToSimulateSwap";l.addressScreeningFailed="addressScreeningFailed";l.noLiquidtyProvidersFound="noLiquidtyProvidersFound";l.insufficientLiquidity="insufficientLiquidity";l.noInboundDataFound="noInbounDataFound";l.noInboundAddressesFound="noInboundAddressesFound";l.noInboundAddressFoundForChain="noInboundAddressFoundForChain";l.noLastBlocksFound="noLastBlocksFound";l.noVersionFound="noVersionFound";l.noConstantsFound="noConstantsFound";l.noMimirsFound="noMimirsFound";l.noRoutesFound="noRoutesFound";l.quoteNotFound="quoteNotFound";l.ledgerSignFailed="ledgerSignFailed";l.ledgerWrongPayload="ledgerWrongPayload";l.ledgerFetchSwapFailed="ledgerFetchSwapFailed";l.failedToFetchTx="failedToFetchTx";l.failedBuildTransactionDetails="failedBuildTransactionDetails";l.noLegsForRoute="noLegsForRoute";l.noRouterAddressFound="noRouterAddressFound";l.noAggregatorAddressFound="noAggregatorAddressFound";l.noContractInstanceFound="noContractInstanceFound";l.noContractAddressFound="noContractAddressFound";l.invalidAffiliate="invalidAffiliate";l.thornameAffiliate="thornameAffiliate";l.providerNotfound="No provider found";l.noRecordFound="No Record found";l.slippageTooLow="Slippage too low";l.tradingHalted="tradingHalted";l.noWrappedGasAsset="noWrappedGasAsset";l.aggregatorAddressNotFound="aggregatorAddressNotFound";l.routerAddressNotFound="routerAddressNotFound";l.dummyAddressNotFound="dummyAddressNotFound";l.trackerError="trackerError";l.thorchainPoolUnavailable="thorchainPoolUnavailable";l.noOhlcvDataFound="noOhlcvDataFound";l.noTradingPairs="noTradingPairs";l.noLendingAvailability="noLendingAvailability";l.lendingRepayTooSmall="lendingRepayTooSmall";l.missingState="missingState";l.ledgerSwapNotFound="ledgerSwapNotFound";l.ledgerSwapNotReadyForTracking="ledgerSwapNotReadyForTracking";l.errorEstimatingGas="errorEstimatingGas";l.apiKeyInvalid="apiKeyInvalid";l.apiKeyFailedToUpdate="apiKeyFailedToUpdate";l.apiKeyExpired="apiKeyExpired";l.unauthorized="unauthorized";l.failedToCreateMemo="failedToCreateMemo";l.radixIncorrectInstructions="radixIncorrectInstructions";l.radixTxMissedParam="radixTxMissedParam";l.radixTxMissedAccount="radixTxMissedAccount";l.radixManifestParseError="radixManifestParseError";l.radixManifestBuildError="radixManifestBuildError";l.invalidAddressForChain="invalidAddressForChain";l.riskyAddress="riskyAddress";l.noRoutesToProcess="noRoutesToProcess";l.sellAssetAmountTooSmall="sellAssetAmountTooSmall";l.missingPrivateKey="missingPrivateKey";l.noMemoPriceProtection="noMemoPriceProtection";})(ie$1||={});var Pe$1;((r)=>{r.highSlippage="highSlippage";r.highPriceImpact="highPriceImpact";r.insufficientBalance="insufficientBalance";})(Pe$1||={});var E;((R)=>{R.CHAINFLIP="CHAINFLIP";R.CHAINFLIP_STREAMING="CHAINFLIP_STREAMING";R.JUPITER="JUPITER";R.MAYACHAIN="MAYACHAIN";R.MAYACHAIN_STREAMING="MAYACHAIN_STREAMING";R.ONEINCH="ONEINCH";R.PANCAKESWAP="PANCAKESWAP";R.SUSHISWAP_V2="SUSHISWAP_V2";R.THORCHAIN="THORCHAIN";R.THORCHAIN_STREAMING="THORCHAIN_STREAMING";R.TRADERJOE_V2="TRADERJOE_V2";R.UNISWAP_V2="UNISWAP_V2";R.UNISWAP_V3="UNISWAP_V3";R.NEAR="NEAR";R.GARDEN="GARDEN";R.OKX="OKX";R.HARBOR="HARBOR";R.FLASHNET="FLASHNET";R.MAYAN="MAYAN";})(E||={});var Ne$1;((_)=>{_.LIQUIDITY="liquidity";_.NETWORK="network";_.INBOUND="inbound";_.OUTBOUND="outbound";_.AFFILIATE="affiliate";_.TAX="tax";_.PRIORITY="priority";_.SERVICE="service";})(Ne$1||={});var un;((r)=>{r.Average="average";r.Fast="fast";r.Fastest="fastest";})(un||={});var gn;((n)=>{n.Approve="approve";n.CheckOnly="checkOnly";})(gn||={});var mn;((w)=>
6172{w.NAME_REGISTER="~";w.BOND="BOND";w.DEPOSIT="+";w.LEAVE="LEAVE";w.UNBOND="UNBOND";w.WITHDRAW="-";w.RUNEPOOL_DEPOSIT="POOL+";w.RUNEPOOL_WITHDRAW="POOL-";w.CLAIM_TCY="tcy";w.STAKE_TCY="tcy+";w.UNSTAKE_TCY="tcy-";})(mn||={});var Je$1={core_estimated_max_spendable_chain_not_supported:10001,core_extend_error:10002,core_inbound_data_not_found:10003,core_approve_asset_address_or_from_not_found:10004,core_plugin_not_found:10005,core_plugin_swap_not_found:10006,core_approve_asset_target_invalid:10007,core_explorer_unsupported_chain:10008,core_verify_message_not_supported:10009,core_chain_halted:10010,core_wallet_connection_not_found:10101,core_wallet_ctrl_not_installed:10102,core_wallet_evmwallet_not_installed:10103,core_wallet_walletconnect_not_installed:10104,core_wallet_keystore_not_installed:10105,core_wallet_ledger_not_installed:10106,core_wallet_trezor_not_installed:10107,core_wallet_keplr_not_installed:10108,core_wallet_okx_not_installed:10109,core_wallet_keepkey_not_installed:10110,core_wallet_talisman_not_installed:10111,core_wallet_not_keypair_wallet:10112,core_wallet_sign_message_not_supported:10113,core_wallet_connection_failed:10114,core_wallet_create_not_supported:10115,core_wallet_sign_typed_data_not_supported:10116,core_swap_invalid_params:10201,core_swap_route_not_complete:10202,core_swap_asset_not_recognized:10203,core_swap_contract_not_found:10204,core_swap_route_transaction_not_found:10205,core_swap_contract_not_supported:10206,core_swap_transaction_error:10207,core_swap_quote_mode_not_supported:10208,core_transaction_deposit_error:10301,core_transaction_create_liquidity_base_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_base_address:10306,core_transaction_add_liquidity_base_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,core_transaction_failed:10316,core_transaction_invalid_recipient_address:10317,wallet_connection_rejected_by_user:20001,wallet_missing_api_key:20002,wallet_chain_not_supported:20003,wallet_missing_params:20004,wallet_provider_not_found:20005,wallet_failed_to_add_or_switch_network:20006,wallet_ledger_connection_error:20101,wallet_ledger_connection_claimed:20102,wallet_ledger_get_address_error:20103,wallet_ledger_device_not_found:20104,wallet_ledger_device_locked:20105,wallet_ledger_transport_error:20106,wallet_ledger_public_key_error:20107,wallet_ledger_derivation_path_error:20108,wallet_ledger_signing_error:20109,wallet_ledger_app_not_open:20110,wallet_ledger_invalid_response:20111,wallet_ledger_method_not_supported:20112,wallet_ledger_invalid_params:20113,wallet_ledger_invalid_signature:20114,wallet_ledger_no_provider:20115,wallet_ledger_pubkey_not_found:20116,wallet_ledger_transport_not_defined:20117,wallet_ledger_webusb_not_supported:20118,wallet_ledger_chain_not_supported:20119,wallet_ledger_invalid_asset:20120,wallet_ledger_invalid_account:20121,wallet_ledger_address_not_found:20122,wallet_ledger_failed_to_get_address:20123,wallet_ledger_webhid_not_supported:20124,wallet_phantom_not_found:20201,wallet_ctrl_not_found:20301,wallet_ctrl_send_transaction_no_address:20302,wallet_ctrl_contract_address_not_provided:20303,wallet_ctrl_asset_not_defined:20304,wallet_walletconnect_project_id_not_specified:20401,wallet_walletconnect_connection_not_established:20402,wallet_walletconnect_namespace_not_supported:20403,wallet_walletconnect_chain_not_supported:20404,wallet_walletconnect_invalid_method:20405,wallet_walletconnect_method_not_supported:20406,wallet_trezor_failed_to_sign_transaction:20501,wallet_trezor_derivation_path_not_supported:20502,wallet_trezor_failed_to_get_address:20503,wallet_trezor_transport_error:20504,wallet_trezor_method_not_supported:20505,wallet_trezor_failed_to_get_public_key:20506,wallet_talisman_not_enabled:20601,wallet_talisman_not_found:20602,wallet_polkadot_not_found:20701,wallet_radix_not_found:20801,wallet_radix_transaction_failed:20802,wallet_radix_invalid_manifest:20803,wallet_radix_method_not_supported:20804,wallet_radix_no_account:20805,wallet_keepkey_not_found:20901,wallet_keepkey_asset_not_defined:20902,
6172wallet_keepkey_contract_address_not_provided:20903,wallet_keepkey_send_transaction_no_address:20904,wallet_keepkey_derivation_path_error:20905,wallet_keepkey_signing_error:20906,wallet_keepkey_transport_error:20907,wallet_keepkey_unsupported_chain:20908,wallet_keepkey_invalid_response:20909,wallet_keepkey_chain_not_supported:20910,wallet_keepkey_signer_not_found:20911,wallet_keepkey_no_accounts:20912,wallet_keepkey_method_not_supported:20913,wallet_keepkey_invalid_params:20914,wallet_keepkey_config_not_found:20915,wallet_keepkey_no_provider:20916,wallet_keepkey_account_not_found:20917,wallet_keepkey_failed_to_get_public_key:20918,wallet_bitkeep_not_found:21001,wallet_bitkeep_failed_to_switch_network:21002,wallet_bitkeep_no_accounts:21003,wallet_passkeys_sign_transaction_error:21101,wallet_passkeys_not_found:21102,wallet_passkeys_no_address:21103,wallet_passkeys_request_canceled:21104,wallet_passkeys_signature_canceled:21105,wallet_passkeys_failed_to_switch_network:21106,wallet_passkeys_chain_not_supported:21107,wallet_passkeys_instance_missing:21108,wallet_onekey_not_found:21201,wallet_onekey_sign_transaction_error:21202,wallet_okx_not_found:21301,wallet_okx_chain_not_supported:21302,wallet_okx_failed_to_switch_network:21303,wallet_okx_no_accounts:21304,wallet_keplr_not_found:21401,wallet_keplr_chain_not_supported:21402,wallet_keplr_signer_not_found:21403,wallet_keplr_no_accounts:21404,wallet_cosmostation_not_found:21501,wallet_cosmostation_chain_not_supported:21502,wallet_cosmostation_evm_provider_not_found:21503,wallet_cosmostation_keplr_provider_not_found:21504,wallet_cosmostation_no_accounts:21505,wallet_cosmostation_no_evm_accounts:21506,wallet_cosmostation_no_evm_address:21507,wallet_cosmostation_signer_not_found:21508,wallet_passkey_not_supported:21601,wallet_passkey_connection_failed:21602,wallet_coinbase_not_found:21701,wallet_coinbase_chain_not_supported:21702,wallet_coinbase_method_not_supported:21703,wallet_coinbase_no_accounts:21704,wallet_evm_extensions_failed_to_switch_network:21801,wallet_evm_extensions_no_provider:21802,wallet_evm_extensions_not_found:21803,wallet_keystore_invalid_password:21901,wallet_keystore_unsupported_version:21902,
6172wallet_keystore_invalid_word_count:21903,wallet_near_extensions_failed_to_switch_network:22001,wallet_near_extensions_no_provider:22002,wallet_near_extensions_not_found:22003,wallet_near_method_not_supported:22004,wallet_petra_not_found:22201,wallet_vultisig_not_found:22101,wallet_vultisig_contract_address_not_provided:22102,wallet_vultisig_asset_not_defined:22103,wallet_vultisig_send_transaction_no_address:22104,wallet_xaman_not_configured:23001,wallet_xaman_not_connected:23002,wallet_xaman_auth_failed:23003,wallet_xaman_connection_failed:23004,wallet_xaman_transaction_failed:23005,wallet_xaman_monitoring_failed:23006,wallet_tronlink_request_accounts_failed:24001,wallet_tronlink_locked:24002,chainflip_channel_error:30001,chainflip_unknown_asset:30002,chainflip_broker_invalid_params:30101,chainflip_broker_recipient_error:30102,chainflip_broker_register:30103,chainflip_broker_tx_error:30104,chainflip_broker_withdraw:30105,chainflip_broker_fund_only_flip_supported:30106,chainflip_broker_fund_invalid_address:30107,thorchain_chain_halted:40001,thorchain_trading_halted:40002,thorchain_asset_is_not_tcy:40003,thorchain_swapin_router_required:40101,thorchain_swapin_vault_required:40102,thorchain_swapin_memo_required:40103,thorchain_swapin_token_required:40104,thorchain_preferred_asset_payout_required:40105,toolbox_cosmos_account_not_found:50101,toolbox_cosmos_invalid_fee:50102,toolbox_cosmos_invalid_params:50103,toolbox_cosmos_no_signer:50104,toolbox_cosmos_not_supported:50105,toolbox_cosmos_signer_not_defined:50106,toolbox_cosmos_validate_address_prefix_not_found:50107,toolbox_cosmos_verify_signature_no_pubkey:50108,toolbox_evm_error_estimating_gas_limit:50201,toolbox_evm_error_sending_transaction:50202,toolbox_evm_gas_estimation_error:50203,toolbox_evm_invalid_gas_asset_address:50204,toolbox_evm_invalid_params:50205,toolbox_evm_invalid_transaction:50206,toolbox_evm_no_abi_fragment:50207,toolbox_evm_no_contract_address:50208,toolbox_evm_no_fee_data:50209,toolbox_evm_no_from_address:50210,toolbox_evm_no_gas_price:50211,toolbox_evm_no_signer_address:50212,toolbox_evm_no_signer:50213,toolbox_evm_no_to_address:50214,toolbox_evm_not_supported:50215,toolbox_evm_provider_not_eip1193_compatible:50216,toolbox_evm_invalid_eip7702_authorization:50217,toolbox_evm_nonce_conflict:50218,toolbox_evm_tx_already_known:50219,toolbox_utxo_api_error:50301,toolbox_utxo_broadcast_failed:50302,toolbox_utxo_insufficient_balance:50303,toolbox_utxo_invalid_address:50304,toolbox_utxo_invalid_params:50305,toolbox_utxo_invalid_transaction:50306,toolbox_utxo_no_signer:50307,toolbox_utxo_not_supported:50308,toolbox_utxo_tx_not_found:50309,toolbox_utxo_rbf_not_supported:50310,toolbox_utxo_tx_not_replaceable:50311,toolbox_utxo_tx_already_confirmed:50312,toolbox_utxo_rbf_fee_too_low:50313,toolbox_utxo_rbf_insufficient_change:50314,toolbox_utxo_unsupported_script_type:50315,toolbox_solana_no_signer:50401,toolbox_substrate_not_supported:50501,toolbox_substrate_transfer_error:50502,toolbox_radix_method_not_supported:50601,toolbox_ripple_get_balance_error:50701,toolbox_ripple_rpc_not_configured:50702,toolbox_ripple_signer_not_found:50703,toolbox_ripple_asset_not_supported:50704,toolbox_ripple_broadcast_error:50705,toolbox_ripple_get_trust_lines_error:50706,toolbox_ripple_invalid_trust_line_limit:50707,toolbox_tron_no_signer:50801,toolbox_tron_invalid_token_identifier:50802,toolbox_tron_token_transfer_failed:50803,toolbox_tron_transaction_creation_failed:50804,toolbox_tron_trongrid_api_error:50805,toolbox_tron_approve_failed:50806,toolbox_tron_invalid_token_contract:50807,toolbox_tron_allowance_check_failed:50808,toolbox_tron_invalid_transaction_integrity:50809,toolbox_tron_broadcast_failed:50810,toolbox_hypercore_no_signer:51001,toolbox_hypercore_payload_mismatch:51002,toolbox_hypercore_insufficient_balance:51003,toolbox_hypercore_destination_sanctioned:51004,toolbox_hypercore_transfer_hash_not_found:51005,toolbox_hypercore_pre_transfer_check_failed:51006,toolbox_cardano_sign_transaction_failed:50901,toolbox_near_no_signer:90601,toolbox_near_invalid_address:90602,toolbox_near_invalid_amount:90603,toolbox_near_transfer_failed:90604,toolbox_near_access_key_error:90605,toolbox_near_no_rpc_url:90606,toolbox_near_empty_batch:90607,toolbox_near_balance_failed:90608,toolbox_near_invalid_name:90609,toolbox_near_missing_contract_address:90610,toolbox_near_no_account:90611,toolbox_near_invalid_gas_params:90612,toolbox_near_no_public_key_found:90613,toolbox_near_sign_transaction_failed:90614,toolbox_sui_address_required:90701,toolbox_sui_keypair_required:90702,toolbox_sui_balance_error:90703,toolbox_sui_transaction_creation_error:90704,toolbox_sui_signing_error:90705,toolbox_sui_broadcast_error:90706,toolbox_sui_no_signer:90707,toolbox_sui_no_sender:90708,toolbox_sui_missing_coin_type:90709,toolbox_sui_no_coins_found:90710,toolbox_sui_insufficient_balance:90711,toolbox_starknet_no_signer:90801,toolbox_starknet_invalid_address:90802,toolbox_starknet_fee_estimation_failed:90803,toolbox_starknet_account_not_deployed:90804,toolbox_starknet_transaction_failed:90805,toolbox_ton_no_signer:90901,toolbox_ton_invali
6172d_address:90902,toolbox_ton_missing_jetton_address:90903,toolbox_ton_jetton_transfer_failed:90904,toolbox_ton_transaction_failed:90905,toolbox_aptos_address_required:91001,toolbox_aptos_keypair_required:91002,toolbox_aptos_balance_error:91003,toolbox_aptos_transaction_creation_error:91004,toolbox_aptos_signing_error:91005,toolbox_aptos_broadcast_error:91006,toolbox_aptos_no_signer:91007,toolbox_aptos_no_sender:91008,toolbox_aptos_missing_asset_type:91009,toolbox_aptos_insufficient_balance:91010,toolbox_stellar_no_signer:91101,toolbox_stellar_broadcast_error:91102,toolbox_stellar_invalid_address:91103,toolbox_stellar_account_not_found:91104,toolbox_stellar_transaction_failed:91105,toolbox_stellar_balance_error:91106,toolbox_stellar_trustline_asset_invalid:91112,toolbox_aleo_no_signer:91201,toolbox_aleo_invalid_address:91202,toolbox_aleo_balance_error:91203,toolbox_aleo_fee_estimation_failed:91204,toolbox_aleo_broadcast_error:91205,toolbox_aleo_transaction_failed:91206,toolbox_aleo_wasm_init_failed:91207,toolbox_aleo_unsupported_token:91208,toolbox_aleo_token_transfer_rejected:91209,toolbox_aleo_insufficient_fee_balance:91210,toolbox_aleo_no_unspent_records:91211,toolbox_aleo_conflicting_signers:91212,toolbox_aleo_no_rpc_urls:91213,toolbox_not_supported:59901,toolbox_fee_estimation_failed:59902,toolbox_sweep_amount_too_low:59903,toolbox_derivation_slot_unsupported:59904,plugin_near_invalid_name:41001,plugin_near_no_connection:41002,plugin_near_name_unavailable:41003,plugin_near_registration_failed:41004,plugin_near_transfer_failed:41005,plugin_garden_missing_data:42001,plugin_swapkit_swap_invalid_data:43001,plugin_swapkit_invalid_transaction:43002,plugin_swapkit_stellar_destination_wallet_not_found:43003,plugin_swapkit_unsupported_tx_type:43004,api_v2_invalid_response:60001,api_v2_server_error:60002,api_v2_invalid_method_key_hash:60003,helpers_invalid_number_different_decimals:70001,helpers_invalid_number_of_years:70002,helpers_invalid_identifier:70003,helpers_invalid_asset_url:70004,helpers_invalid_asset_identifier:70005,helpers_invalid_memo_type:70006,helpers_failed_to_switch_network:70007,helpers_not_found_provider:70008,helpers_chain_not_supported:70009,helpers_invalid_params:70010,helpers_invalid_response:70011,helpers_chain_no_public_or_set_rpc_url:70012,helpers_chain_rpc_connection_failed:70013,mcp_wallet_not_configured:90001,not_implemented:99999};function ke$1(e){return JSON.stringify(e,(t,n)=>typeof n==="bigint"?n.toString():n)}let b$1 = class b extends Error{static ErrorCode=Je$1;errorKey;info;constructor(e,t){let n=typeof e==="string",r=n?e:e.errorKey,s=n?void 0:e.info,a=`${r}${s?`: ${ke$1(s)}`:""}`;super(a);if(Object.setPrototypeOf(this,b.prototype),this.name="SwapKitError",this.errorKey=r,this.info=s,this.cause=t,t){let c=t instanceof Error?`${t.message}${t.cause?` (${t.cause})`:""}`:ke$1(t);console.error(`SwapKitError [${r}]: ${c}`);}else if(s)console.error(`SwapKitError [${r}]: ${ke$1(s)}`);}};function ti(e){let t=Je$1;for(let[n,r]of Object.entries(e)){if(Object.hasOwn(t,n)){if(t[n]===r)continue;throw new b$1({errorKey:"helpers_invalid_params",info:{code:r,existingCode:t[n],key:n}})}let s=Object.keys(t).find((a)=>t[a]===r);if(s)throw new b$1({errorKey:"helpers_invalid_params",info:{code:r,existingKey:s,key:n}});t[n]=r;}}var ge$1={BITGET:"BITGET",BRAVE:"BRAVE",COINBASE_MOBILE:"COINBASE_MOBILE",COINBASE_WEB:"COINBASE_WEB",COSMOSTATION:"COSMOSTATION",CTRL:"CTRL",EIP6963:"EIP6963",EXODUS:"EXODUS",KEEPKEY:"KEEPKEY",KEEPKEY_BEX:"KEEPKEY_BEX",KEPLR:"KEPLR",KEYSTORE:"KEYSTORE",LEAP:"LEAP",LEDGER:"LEDGER",METAMASK:"METAMASK",OKX:"OKX",OKX_MOBILE:"OKX_MOBILE",ONEKEY:"ONEKEY",PASSKEY_WALLET:"PASSKEY_WALLET",PASSKEYS:"PASSKEYS",PETRA:"PETRA",PHANTOM:"PHANTOM",POLKADOT_JS:"POLKADOT_JS",RADIX_WALLET:"RADIX_WALLET",TALISMAN:"TALISMAN",TREZOR:"TREZOR",TRONLINK:"TRONLINK",TRUSTWALLET_WEB:"TRUSTWALLET_WEB",VULTISIG:"VULTISIG",WALLET_SELECTOR:"WALLET_SELECTOR",WALLETCONNECT:"WALLETCONNECT",XAMAN:"XAMAN"},Oe$1=new Set;function Ze(e){return Oe$1.add(e),()=>Oe$1.delete(e)}function si(e,t){let n=ge$1;if(Object.hasOwn(n,e)){if(n[e]===t)return;throw new b$1({errorKey:"helpers_invalid_params",info:{existingV
6172alue:n[e],key:e,value:t}})}n[e]=t;for(let r of Oe$1)r(t);}var _n;((r)=>{r[r.NoError=36864]="NoError";r[r.LockedDevice=21781]="LockedDevice";r[r.TC_NotFound=65535]="TC_NotFound";})(_n||={});var An=Pe$2.reduce((e,t)=>{if(!e.THOR_STAGENET)e[T$2.Maya]=y$1.rpcUrls,e[T$2.THORChain]=d$1.rpcUrls;return e[t]=w$2(t).rpcUrls,e},{}),Sn={[l$3.THORChain]:u$1.nodeUrl,[l$3.Maya]:k$3.nodeUrl,[T$2.THORChain]:d$1.nodeUrl,[T$2.Maya]:y$1.nodeUrl},st={apiKeys:{blockchair:"",keepKey:"",passkeys:"",swapKit:"",walletConnectProjectId:"",xaman:""},chains:Pe$2,endpoints:{},envs:{apiUrl:"https://api.swapkit.dev",devApiUrl:"https://dev-api.swapkit.dev",isDev:false,isStagenet:false},feeMultipliers:void 0,integrations:{radix:{applicationName:"Swapkit Playground",applicationVersion:"0.0.1",dAppDefinitionAddress:"account_rdx128r289p58222hcvev7frs6kue76pl7pdcnw8725aw658v0zggkh9ws",network:{dashboardBase:"https://dashboard.radixdlt.com",networkId:1,networkName:"mainnet"}}},localMode:{enabled:false,quoteUrl:"http://localhost:3000",swapUrl:"http://localhost:3001"},requestOptions:{retry:{backoffMultiplier:2,baseDelay:300,maxDelay:5000,maxRetries:3},timeoutMs:30000},rpcUrls:An,thornodeUrls:Sn,v3SwapFlow:{enabled:typeof process$1<"u"&&process$1.env?.SWAPKIT_V3_SWAP_FLOW==="true"},wallets:Object.values(ge$1),widgetId:"",widgetKey:""},P$1=createStore((e)=>({...st,setApiKey:(t,n)=>e((r)=>({apiKeys:{...r.apiKeys,[t]:n}})),setConfig:(t)=>e((n)=>({apiKeys:{...n.apiKeys,...t?.apiKeys},chains:n.chains.concat(t?.chains||[]),endpoints:{...n.endpoints,...t?.endpoints},envs:{...n.envs,...t?.envs},feeMultipliers:t?.feeMultipliers||n.feeMultipliers,integrations:{...n.integrations,...t?.integrations},localMode:{...n.localMode,...t?.localMode},rpcUrls:{...n.rpcUrls,...t?.rpcUrls},thornodeUrls:{...n.thornodeUrls,...t?.thornodeUrls},v3SwapFlow:{...n.v3SwapFlow,...t?.v3SwapFlow},wallets:n.wallets.concat(t?.wallets||[]),widgetId:t?.widgetId||n.widgetId,widgetKey:t?.widgetKey||n.widgetKey})),setEndpoint:(t,n)=>e((r)=>({endpoints:{...r.endpoints,[t]:n}})),setEnv:(t,n)=>e((r)=>({envs:{...r.envs,[t]:n}})),setFeeMultipliers:(t)=>e(()=>({feeMultipliers:t})),setIntegrationConfig:(t,n)=>e((r)=>({integrations:{...r.integrations,[t]:n}})),setRequestOptions:(t)=>e((n)=>({requestOptions:{retry:{...n.requestOptions.retry,...t.retry},timeoutMs:t.timeoutMs||n.requestOptions.timeoutMs}})),setRpcUrl:(t,n)=>e((r)=>({rpcUrls:{...r.rpcUrls,[t]:n}})),setThornodeUrl:(t,n)=>e((r)=>({thornodeUrls:{...r.thornodeUrls,[t]:n}})),setWidgetId:(t)=>e({widgetId:t}),setWidgetKey:(t)=>e({widgetKey:t})}));Ze((e)=>{P$1.setState((t)=>t.wallets.includes(e)?t:{wallets:[...t.wallets,e]});});var T={get:(e)=>P$1.getState()[e],getState:P$1.getState,reinitialize:()=>P$1.setState({...st,wallets:Object.values(ge$1)}),set:(e)=>P$1.getState().setConfig(e),setApiKey:(e,t)=>P$1.getState().setApiKey(e,t),setEndpoint:(e,t)=>P$1.getState().setEndpoint(e,t),setEnv:(e,t)=>P$1.getState().setEnv(e,t),setFeeMultipliers:(e)=>P$1.getState().setFeeMultipliers(e),setIntegrationConfig:(e,t)=>P$1.getState().setIntegrationConfig(e,t),setRequestOptions:(e)=>P$1.getState().setRequestOptions(e),setRpcUrl:(e,t)=>P$1.getState().setRpcUrl(e,t),setThornodeUrl:(e,t)=>
6172P$1.getState().setThornodeUrl(e,t),setWidgetId:(e)=>P$1.getState().setWidgetId(e),setWidgetKey:(e)=>P$1.getState().setWidgetKey(e)};var Tn=(e)=>new Promise((t)=>setTimeout(t,e)),wn=(e,{baseDelay:t,backoffMultiplier:n,maxDelay:r})=>Math.min(t*n**e,r);function xn(e,t){if(e instanceof Error&&e.name==="AbortError")return  true;if(e instanceof TypeError)return  true;if(t===429)return  true;if(t&&t>=500&&t<600)return  true;return  false}var Rn=async(e,t)=>{let n=await fetch(e,t),r;try{r=await n.json();}catch{if(!n.ok)throw new b$1({errorKey:"helpers_invalid_response",info:{status:n.status,statusText:n.statusText}},{status:n.status,statusText:n.statusText});return {}}if(!n.ok){let a={data:r?.data,error:r?.error,message:r?.message,status:n.status};throw new b$1({errorKey:r?.error||"helpers_invalid_response",info:a},a)}let s=r?.routes?.length||r?.result||r?.data&&!r?.error;if(r?.error&&!s){let a={data:r.data,error:r.error,message:r.message,status:n.status};throw new b$1({errorKey:r.error,info:a},a)}if(r?.providerErrors?.length||r?.error&&s)console.warn("[SwapKit] Partial errors in response:",r.providerErrors||r.error);return r};function _e(e,t={}){return async function(r,s={}){let{searchParams:a,json:c,body:u,headers:_,dynamicHeader:A,retry:y,timeoutMs:w,abortController:O,onError:S,onSuccess:M,responseHandler:I,...C}={...t,...s},ne=T.get("requestOptions"),re={...ne.retry,...y},R=!!c||r.endsWith(".json"),Ye=Cn(r,a),se=A?await A():{},q=vn(R,{..._,...se}),sn=R?JSON.stringify(c):u,Ee;for(let ue=0;ue<=re.maxRetries;ue++){let je=O||new AbortController,Xe=setTimeout(()=>je.abort(),w||ne.timeoutMs);try{let V=await Rn(Ye,{...C,body:sn,headers:q,method:e,signal:je.signal});return clearTimeout(Xe),M?.(V)||I?.(V)||V}catch(V){clearTimeout(Xe),Ee=V;let on=V?.cause?.status;if(ue>=re.maxRetries||!xn(V,on))return S?S(V):Promise.reject(V);await Tn(wn(ue,re));}}return S?S(Ee):Promise.reject(Ee)}}function vn(e,t){return {...t,...e&&{"Content-Type":"application/json"}}}function Cn(e,t){let n=new URL(e);if(t)n.search=new URLSearchParams(t).toString();return n.toString()}var m={extend:(e)=>({extend:(t)=>m.extend({...e,...t}),get:_e("GET",e),post:_e("POST",e)}),get:_e("GET"),post:_e("POST")};async function it(e,t,n,r){let s=`${t}:${n}:${r}`,a=new TextEncoder,c=await crypto.subtle.importKey("raw",a.encode(e),{hash:"SHA-256",name:"HMAC"},false,["sign"]),u=await crypto.subtle.sign("HMAC",c,a.encode(s));return Array.from(new Uint8Array(u)).map((_)=>_.toString(16).padStart(2,"0")).join("")}function Ai(e,t){try{return e()}catch(n){if(t)throw new b$1(t,n);return}}var ot$1=new Set;function Y$1({condition:e,id:t,warning:n}){if(e){if(ot$1.has(t))return;console.warn(n),ot$1.add(t);}}function Pn(e){return M$1(e).with(...We,()=>({id:1,jsonrpc:"2.0",method:"eth_blockNumber",params:[]})).with(...ln$1,()=>({id:"test",jsonrpc:"1.0",method:"getblockchaininfo",params:[]})).with(..._e$1,...un$1,()=>({id:1,jsonrpc:"2.0",method:"status",params:{}})).with(l$3.Polkadot,l$3.Chainflip,()=>({id:1,jsonrpc:"2.0",method:"system_health",params:[]})).with(l$3.Solana,()=>({id:1,jsonrpc:"2.0",method:"getHealth"})).with(l$3.Sui,()=>({id:1,jsonrpc:"2.0",method:"sui_getSystemState",params:[]})).with(l$3.Ton,()=>({id:1,jsonrpc:"2.0",method:"getAddressInformation",params:{address:""}})).with(l$3.Aleo,l$3.Aptos,l$3.Tron,l$3.Radix,l$3.Stellar,()=>"").with(l$3.Hype,()=>({type:"meta"})).with(l$3.Near,()=>({id:"dontcare",jsonrpc:"2.0",method:"status",params:[]})).with(l$3.Ripple,()=>({id:1,jsonrpc:"2.0",method:"ping",params:[{}]})).with(l$3.Starknet,()=>({id:1,jsonrpc:"2.0",method:"starknet_chainId",params:[]})).otherwise(()=>{throw new b$1("helpers_chain_not_supported",{chain:e})})}function at(e){return M$1(e).with(l$3.Aptos,()=>"/-/healthy").with(l$3.Aleo,()=>"/mainnet/block/height/latest").with(l$3.Hype,()=>"/info").with(l$3.Radix,()=>"/status/network-configuration").with(l$3.Stellar,()=>"").with(l$3.Tron,()=>"/wallet/getnowblock").otherwise(()=>"")}async function lt(e,t){try{let n=t.startsWith("wss")?t.replace("wss","https"):t;if(e===l$3.Aleo||e===l$3.Stellar)return (await fetch(`${n}${at(e)}`,{cache:"no-store",method:"GET",signal:AbortSignal.timeout(3000)})).ok;return (await fetch(`${n}${at(e)}`,{body:JSON.stringify(Pn(e)),cache:"no-store",headers:{"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(3000)})).ok}catch{return  false}}var De=new Map,Nn=120000;function kn(e){let[t=""]=T.get("rpcUrls")[e];
6172if(!t)throw Y$1({condition:true,id:"helpers_chain_no_public_or_set_rpc_url",warning:`No public or set RPC URL found for chain. Please ensure you configured rpcUrls for ${e}.`}),new b$1("helpers_chain_no_public_or_set_rpc_url",{chain:e});let n=De.get(e);if(n&&Date.now()-n.timestamp<Nn)return n.url;return De.set(e,{timestamp:Date.now(),url:t}),t}async function j$1(e){let t=kn(e),[,...n]=T.get("rpcUrls")[e];if(await lt(e,t))return t;for(let s of n)if(await lt(e,s))return De.set(e,{timestamp:Date.now(),url:s}),s;throw new b$1("helpers_chain_rpc_connection_failed",{chain:e,fallbackUrls:n,primaryRpcUrl:t})}function Ci(e){Y$1({condition:true,id:"initializeRPCUrlsWithFallback",warning:"initializeRPCUrlsWithFallback is deprecated. Use static { rpcUrls, fallbackRpcUrls } SwapKit init config or dynamic SKConfig.setRpcUrl/setFallbackRpcUrl to configure RPC endpoints."});}function Ii({chain:e,txHash:t}){let{explorerUrl:n}=w$2(e);return M$1(e).with(..._e$1,l$3.Solana,()=>`${n}/tx/${t.startsWith("0x")?t.slice(2):t}`).with(...We,...cn$1,()=>`${n}/tx/${t.startsWith("0x")?t:`0x${t}`}`).with(...ln$1,l$3.Radix,l$3.Tron,()=>`${n}/transaction/${t.toLowerCase()}`).with(l$3.Near,()=>`${n}/txns/${t}`).with(l$3.Ripple,()=>`${n}/transactions/${t}`).with(l$3.Stellar,()=>`${n}/explorer/public/tx/${t}`).with(l$3.Sui,()=>`${n}/txblock/${t}`).with(l$3.Cardano,l$3.Hype,l$3.Spark,l$3.Ton,()=>`${n}/tx/${t}`).otherwise(()=>"")}function Ei({chain:e,address:t}){let{explorerUrl:n}=w$2(e);return M$1(e).with(l$3.Solana,l$3.Sui,l$3.Radix,()=>`${n}/account/${t}`).with(l$3.Stellar,()=>`${n}/explorer/public/account/${t}`).otherwise(()=>`${n}/address/${t}`)}function Pi(e){switch(e){case l$3.THORChain:return `${e}.RUNE`;case l$3.Cosmos:return `${e}.ATOM`;case l$3.BinanceSmartChain:return `${e}`;default:return `${e}.${e}`}}var gt=/^(0x)?[0-9a-fA-F]{40}$/;function fe(e){if(typeof e!=="string"||!gt.test(e))throw Error(`invalid address: ${e}`);let t=e.toLowerCase().replace(/^0x/,""),n=bytesToHex(keccak_256(new TextEncoder().encode(t))),r=[...t].map((a,c)=>Number.parseInt(n[c]??"0",16)>=8?a.toUpperCase():a).join(""),s=e.replace(/^0x/,"");if(/[A-F]/.test(s)&&/[a-f]/.test(s)&&s!==r)throw Error(`bad address checksum: ${e}`);return `0x${r}`}function mt(e){if(typeof e!=="string"||!gt.test(e))return  false;try{return fe(e),!0}catch{return  false}}var Bi=[`${l$3.Maya}.MAYA`,`${l$3.Maya}.CACAO`,`${l$3.Ethereum}.THOR`,`${l$3.Ethereum}.vTHOR`,`${l$3.Kujira}.USK`,`${l$3.Ethereum}.FLIP`,`${l$3.Radix}.XRD`],ft=[l$3.Arbitrum,l$3.Aurora,l$3.Base,l$3.Ethereum,l$3.Optimism,l$3.Robinhood];async function Hn(e){let{baseDecimal:t}=w$2(l$3.Radix);try{let n=await j$1(l$3.Radix),{manager:r}=await m.post(`${n}/state/resource`,{body:JSON.stringify({network:"mainnet",resource_address:e}),headers:{Accept:"*/*","Content-Type":"application/json"}});return r?.divisibility?.value?.divisibility}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn(`Failed to fetch Radix asset decimals for ${e}: ${r}`),t}}async function Vn(e){try{let t=await j$1(l$3.Radix);return (await m.post(`${t}/state/entity/details`,{body:JSON.stringify({addresses:[e],opt_ins:{explicit_metadata:["symbol"]}}),headers:{Accept:"*/*","Content-Type":"application/json"}})).items[0]?.explicit_metadata?.items.find((s)=>s.key==="symbol")?.value.typed.value||void 0}catch(t){let n=t instanceof Error?t.message:String(t);return console.warn(`Failed to fetch Radix asset symbol for ${e}: ${n}`),""}}async function yt({chain:e,address:t,methodHex:n,id:r}){let s=await j$1(e);return m.post(s,{body:JSON.stringify({id:r,jsonrpc:"2.0",method:"eth_call",params:[{data:n,to:t.toLowerCase()},"latest"]}),headers:{accept:"*/*","cache-control":"no-cache","content-type":"application/json"}})}function Un(e){if(!e||e==="0x")return "UNKNOWN";try{return bt(e.replace(/^0x/,""))?.trim()||"UNKNOWN"}catch(t){return console.warn(`Failed to decode ABI string from ${e}: ${t}`),"UNKNOWN"}}function $n(e,t){if(!e||e==="0x")return t;try{return Number(e)}catch(n){return console.warn(`Failed to decode ABI uint8 from ${e}: ${n}`),t}}async function Bn({chain:e,address:t}){let{baseDecimal:n}=w$2(e),r=t.toLowerCase();if(t===""||!r.startsWith("0x"))return n;let s=await yt({address:t,chain:e,id:2,methodHex:"0x313ce567"}).catch((c)=>(console.warn(`Could not fetch decimals for ${t} on ${e}: ${c.message}`),{result:""}));return $n(s.result,n)}async function Fn({chain:e,address:t}){let n=t.toLowerCase();if(n===""||!n.startsWith("0x"))return;let r=await yt({address:t,chain:e,id:1,methodHex:"0x95d89b41"}).catch((a)=>(console.warn(`Could not fetch symbol for ${t} on ${e}: ${a.message}`),{result:""}));return Un(r.result)}async function _t({rpcUrl:e,contractAddress:t,functionSelector:n}){return (await m.post(`${e}/wallet/triggerconstantcontract`,{body:JSON.stringify({contract_address:t,function_selector:n,owner_address:t,parameter:"",visible:true}),headers:{accept:"application/json","content-type":"application/json"}}).catch(()=>{return}))?.constant_result?.[0]}function ht(e){let t=e.match(/.{2}/g)?.map((n)=>Number.parseInt(n,16))??[];return new TextDecoder().decode(new Uint8Array(t))}function bt(e){return M$1(e).with(void 0,()=>{return}).when((t)=>t.length>=128,(t)=>{let n=Number.parseInt(t.slice(64,128),16),r=t.slice(128,128+n*2).replace(/(00)+$/,"");return r?ht(r):void 0}).when((t)=>t.length===64,(t)=>{let n=t.replace(/(00)+$/,"");if(n.length>0&&n.length%2===0)return ht(n);return}).otherwise(()=>{return})}function At({chain:e,address:t}){let{baseDecimal:n}=w$2(e),r={decimals:n,ticker:void 0};return M$1(e).with(...We,async()=>{try{if(!mt(t.replace(/^0X/,"0x")))return r;let[s,a]=await Promise.all([Fn({address:t,chain:e}),Bn({address:t,chain:e})]);return {decimals:a,ticker:s}}catch(s){return console.warn(`Failed to fetch token info for ${t} on ${e}: ${s?.code} ${s?.message}`),r}}).with(l$3.Solana,async()=>
6172{if(!t)return r;try{let s=await fetch(`https://lite-api.jup.ag/tokens/v2/search?query=${t}`);if(s.ok){let a=await s.json(),c=Array.isArray(a)?a[0]:a;if(c)return {decimals:c.decimals??n,ticker:c.symbol||void 0}}}catch(s){console.warn(`Failed to fetch Solana token info for ${t}: ${s?.code} ${s?.message}`);}return r}).with(l$3.Tron,async()=>{if(!t)return r;try{let s=await j$1(l$3.Tron),[a,c]=await Promise.all([_t({contractAddress:t,functionSelector:"symbol()",rpcUrl:s}),_t({contractAddress:t,functionSelector:"decimals()",rpcUrl:s})]),u=bt(a);return {decimals:a!==void 0&&c?Number(BigInt(`0x${c}`)):n,ticker:u}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Tron token info for ${t}: ${a}`),r}}).with(l$3.Near,async()=>{if(!t)return r;try{let s=await j$1(l$3.Near),a=await m.post(s,{body:JSON.stringify({id:"dontcare",jsonrpc:"2.0",method:"query",params:{account_id:t,args_base64:"e30=",finality:"final",method_name:"ft_metadata",request_type:"call_function"}}),headers:{accept:"application/json","content-type":"application/json"}});if(!a.result?.result)throw Error("NEAR ft_metadata returned no result");let c=JSON.parse(new TextDecoder().decode(new Uint8Array(a.result.result)));return {decimals:c?.decimals||n,ticker:c?.symbol}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Near token info for ${t}: ${a}`),r}}).with(l$3.Radix,async()=>{if(!t)return r;try{let[s,a]=await Promise.all([Vn(t),Hn(t)]);return {decimals:a,ticker:s}}catch(s){let a=s instanceof Error?s.message:String(s);return console.warn(`Failed to fetch Radix token info for ${t}: ${a}`),r}}).otherwise(async()=>r)}function St({chain:e,symbol:t}){return M$1(e).with(...ft,()=>t==="ETH").with(l$3.Arc,()=>t==="USDC").with(l$3.Avalanche,()=>t==="AVAX").with(l$3.Berachain,()=>t==="BERA").with(l$3.Hyperevm,()=>t==="HYPE").with(l$3.Hype,()=>t==="HYPE").with(l$3.Spark,()=>t==="BTC").with(l$3.BinanceSmartChain,()=>t==="BNB").with(l$3.Gnosis,()=>t==="xDAI"||t==="XDAI").with(l$3.Monad,()=>t==="MON").with(l$3.XLayer,()=>t==="OKB").with(l$3.Maya,()=>t==="CACAO").with(l$3.Cosmos,()=>t==="ATOM").with(l$3.THORChain,()=>t==="RUNE").with(l$3.Tron,()=>t==="TRX").with(l$3.Ripple,()=>t==="XRP").with(l$3.Ton,()=>t==="GRAM"||t==="TON").with(l$3.Radix,()=>`${e}.${t}`===ye$1(e).identifier).otherwise(()=>t===e)}var ye$1=(e)=>{let{baseDecimal:t}=w$2(e);return M$1(e.toUpperCase()).with(...ft,(r)=>({decimal:t,identifier:`${r}.ETH`})).with(l$3.Arc,(r)=>({decimal:t,identifier:`${r}.USDC`})).with(l$3.THORChain,(r)=>({decimal:t,identifier:`${r}.RUNE`})).with(l$3.Cosmos,(r)=>({decimal:t,identifier:`${r}.ATOM`})).with(l$3.Maya,(r)=>({decimal:10,identifier:`${r}.CACAO`})).with(l$3.BinanceSmartChain,(r)=>({decimal:t,identifier:`${r}.BNB`})).with(l$3.Monad,(r)=>({decimal:t,identifier:`${r}.MON`})).with(l$3.Avalanche,(r)=>({decimal:t,identifier:`${r}.AVAX`})).with(l$3.Gnosis,(r)=>({decimal:t,identifier:`${r}.xDAI`})).with(l$3.XLayer,(r)=>({decimal:t,identifier:`${r}.OKB`})).with(l$3.Berachain,(r)=>({decimal:t,identifier:`${r}.BERA`})).with(l$3.Hyperevm,(r)=>({decimal:t,identifier:`${r}.HYPE`})).with(l$3.Hype,(r)=>({decimal:t,identifier:`${r}.HYPE`})).with(l$3.Spark,(r)=>({decimal:t,identifier:`${r}.BTC`})).with(l$3.Tron,(r)=>({decimal:t,identifier:`${r}.TRX`})).with(l$3.Ton,(r)=>({decimal:t,identifier:`${r}.GRAM`})).with(l$3.Solana,l$3.Chainflip,l$3.Kujira,l$3.Ripple,l$3.Polkadot,l$3.Near,...ln$1,(r)=>({decimal:t,identifier:`${r}.${r}`})).with(l$3.Radix,"XRD.XRD",()=>({decimal:t,identifier:"XRD.XRD"})).with(l$3.Polygon,"POL.POL",()=>({decimal:t,identifier:"POL.POL"})).with("KUJI.USK",(r)=>({decimal:6,identifier:r})).with("ETH.FLIP",()=>({decimal:w$2(l$3.Ethereum).baseDecimal,identifier:"ETH.FLIP-0x826180541412D574cf1336d22c0C0a287822678A"})).with("ETH.THOR",()=>({decimal:w$2(l$3.Ethereum).baseDecimal,identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044"})).with("ETH.vTHOR",()=>({decimal:w$2(l$3.Ethereum).baseDecimal,identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d"})).with("MAYA.CACAO",(r)=>({decimal:10,identifier:r})).with("MAYA.MAYA",(r)=>({decimal:4,identifier:r})).otherwise(()=>({decimal:t,identifier:e}))};
6172function Me$1({chain:e,symbol:t}){if(t.includes("/"))return "Synth";if(t.includes("~"))return "Trade";return M$1(e).with(l$3.Radix,()=>t===l$3.Radix||`${e}.${t}`===ye$1(e).identifier).with(l$3.Arbitrum,l$3.Optimism,l$3.Base,l$3.Aurora,l$3.Robinhood,()=>t===l$3.Ethereum).with(l$3.Arc,()=>t==="USDC").with(l$3.Cosmos,()=>t==="ATOM").with(l$3.BinanceSmartChain,()=>t==="BNB").with(l$3.Maya,()=>t==="CACAO").with(l$3.Monad,()=>t==="MON").with(l$3.THORChain,()=>t==="RUNE").with(l$3.Tron,()=>t==="TRX").with(l$3.Hyperevm,()=>t==="HYPE").with(l$3.Hype,()=>t==="HYPE").with(l$3.Spark,()=>t==="BTC").with(l$3.XLayer,()=>t==="OKB").with(l$3.Ton,()=>t==="GRAM"||t==="TON").otherwise(()=>t===e)?"Native":e}var W$1=(e)=>{let[t,...n]=e.split("."),r=e.includes("/"),s=n.join("."),a=s?.split("-"),c=a?.length?a.length===1?a[0]:a.slice(0,-1).join("-"):void 0;return {chain:t,symbol:s,synth:r,ticker:c}};function ae$1(e,t){let r=t===l$3.Near?e.indexOf("-"):e.lastIndexOf("-");if(r===-1)return {address:void 0,ticker:e};return {address:e.slice(r+1),ticker:e.slice(0,r)}}function Fi(e){return `https://tokens.swapkit.dev/images/${e.toLowerCase()}.png`}async function Ki(e){let{loadTokenLists:t}=await import('./tokens-DA1-qqlB.js').then(n => n.v),n=await t(void 0,{source:T.get("envs").isDev?"dev":"prod"}),r=Object.values(n).flatMap((a)=>a.tokens);if("identifier"in e)return r.find((a)=>a.identifier===e.identifier)?.identifier;let s=e.contract.toLowerCase();for(let a of r){let{chain:c,symbol:u}=W$1(a.identifier);if(c!==e.chain)continue;let{address:_}=ae$1(u,c);if(_?.toLowerCase()===s)return a.identifier}return}var G$1=8,Kn=10,Wn=64;function X$1({value:e,bigIntDecimal:t=G$1,decimal:n=G$1}){if(n===0)return e.toString();let r=Math.min(t,n),s=r<n?Tt(e,B$2(n-r)):e,a=s<0n,c=(a?-s:s).toString().padStart(r+1,"0"),u=c.length-r;return `${a?"-":""}${c.slice(0,u)}.${c.slice(u)}`.replace(/\.?0*$/,"")}class F{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt(e,t){return new F({decimal:t,value:X$1({bigIntDecimal:t,decimal:t,value:e})})}static shiftDecimals({value:e,from:t,to:n}){return F.fromBigInt(e.getBaseValue("bigint")*B$2(n)/B$2(t),n)}constructor(e){this.decimal=typeof e==="object"?e.decimal:void 0;let t=Ae$1(typeof e==="object"&&"value"in e?e.value:e),n=typeof e==="object"&&"decimalMultiplier"in e?e.decimalMultiplier:B$2(this.decimal??0);this.decimalMultiplier=n!==void 0&&n>t.decimalMultiplier?n:t.decimalMultiplier,this.bigIntValue=t.bigIntValue*this.decimalMultiplier/t.decimalMultiplier;}toString(e={}){return this.getValue("string")}set(e){return this.#n({decimal:this.decimal,value:new F(e)})}#n(e){return new this.constructor({...e,identifier:this.toString({includeSynthProtocol:true})})}add(...e){return this.#t("add",...e)}sub(...e){return this.#t("sub",...e)}mul(...e){return this.#t("mul",...e)}div(...e){return this.#t("div",...e)}gt(e){return this.#e("gt",e)}gte(e){return this.#e("gte",e)}lt(e){return this.#e("lt",e)}lte(e){return this.#e("lte",e)}eqValue(e){return this.#e("eqValue",e)}getValue(e,t){let n=Se$1(this.decimalMultiplier),r=t!==void 0?t:this.decimal,s=r!==void 0?r:n;if(r!==void 0&&r<n){if(this.formatBigIntToSafeValue(this.bigIntValue,r)==="0"&&this.bigIntValue!==0n)s=n;}let a=this.formatBigIntToSafeValue(this.bigIntValue,s);return M$1(e).with("number",()=>Number(a)).with("string",()=>a).with("bigint",()=>this.bigIntValue*B$2(this.decimal??G$1)/this.decimalMultiplier).otherwise(()=>a)}getBaseValue(e,t){let n=B$2(t??this.decimal??G$1),r=Tt(this.bigIntValue*n,this.decimalMultiplier);return M$1(e).with("number",()=>Number(r)).with("string",()=>r.toString()).otherwise(()=>r)}getBigIntValue(e,t){if(t===void 0&&typeof e==="object")return e.bigIntValue;let n=Ae$1(e),r=t===void 0?this.decimalMultiplier:B$2(t);return n.bigIntValue*r/n.decimalMultiplier}toSignificant(e=6){let t=this.getValue("string"),n=t.startsWith("-"),r=n?t.slice(1):t,[s="",a=""]=r.split("."),c=Number.parseInt(s,10)>0;if((c?s.length+a.length:a.length)<=e)return U(n,r);if(s.length>=e)return U(n,s.slice(0,e).padEnd(s.length,"0"));if(c)return U(n,`${s}.${a.slice(0,e-s.length)}`);let _=a.replace(/^0+/,"")||"0",A=_.slice(0,e),y=a.length-_.length;return U(n,`0.${A.padStart(y+A.length,"0")}`)}toFixed(e=6){let t=this.getValue("string"),n=t.startsWith("-"),[r="0",s=""]=(n?t.slice(1):t).split(".");if(e===0){if(r==="0"&&!s)return "0";let y=s&&Number.parseInt(s[0]||"0",10)>=5?`${BigInt(r)+1n}.0`:`${r}.0`;return U(n,y)}if(!s)return U(n,`${r}.${"0".repeat(e)}`);let a=s[e];if(!(a&&Number.parseInt(a,10)>=5))return U(n,`${r}.${s.slice(0,e).padEnd(e,"0")}
6172`);let u=BigInt(s.slice(0,e).padEnd(e,"0"))+1n,_=10n**BigInt(e);if(u>=_)return U(n,`${BigInt(r)+1n}.${"0".repeat(e)}`);return U(n,`${r}.${u.toString().padStart(e,"0")}`)}toAbbreviation(e=2){let t=this.getValue("string"),n=Number(t),r=["","K","M","B","T","Q","Qi","S"],s=Math.floor(Math.log10(Math.abs(n))/3);if(s===0||!r[s])return t;return `${(n/10**(s*3)).toFixed(e)}${r[s]}`}toCurrency(e="$",{currencyPosition:t="start",decimal:n=2,decimalSeparator:r=".",thousandSeparator:s=",",trimTrailingZeros:a=true}={}){let c=this.toFixed(n),u=t==="end",[_="0",A=""]=c.split("."),y=_.replace(/\B(?=(\d{3})+(?!\d))/g,s),w=A&&Number.parseInt(A,10)>0,O=w?`${y}${r}${A}`:y,M=O.length<100&&a&&w?O.replace(/\.?0*$/,""):O;return u?`${M}${e}`:`${e}${M}`}formatBigIntToSafeValue(e,t){return X$1({bigIntDecimal:t||this.decimal||G$1,decimal:Se$1(this.decimalMultiplier),value:e})}#t(e,...t){let n=t.map(Ae$1),r=Math.max(G$1,Se$1(this.decimalMultiplier),...n.map(({decimalMultiplier:A})=>Se$1(A))),s=Math.min(r+Kn,Wn),a=B$2(s),c=n.reduce((A,y)=>{let w=A.decimalMultiplier*y.decimalMultiplier,O=M$1(e).with("add",()=>A.bigIntValue*y.decimalMultiplier+y.bigIntValue*A.decimalMultiplier).with("sub",()=>A.bigIntValue*y.decimalMultiplier-y.bigIntValue*A.decimalMultiplier).with("mul",()=>A.bigIntValue*y.bigIntValue).with("div",()=>{if(y.bigIntValue===0n)throw RangeError("Division by zero");return A.bigIntValue*y.decimalMultiplier}
6172).exhaustive(),S=e==="div"?A.decimalMultiplier*y.bigIntValue:w;return {bigIntValue:O*a/S,decimalMultiplier:a}},this),u=this.decimal===void 0?void 0:Math.min(this.decimal,s),_=c.decimalMultiplier===a?c:{bigIntValue:c.bigIntValue*a/c.decimalMultiplier,decimalMultiplier:a};return this.#n({decimal:u,value:_})}#e(e,t){let n=Ae$1(t),r=this.bigIntValue*n.decimalMultiplier,s=n.bigIntValue*this.decimalMultiplier;return M$1(e).with("gt",()=>r>s).with("gte",()=>r>=s).with("lt",()=>r<s).with("lte",()=>r<=s).with("eqValue",()=>r===s).exhaustive()}}var Gn=Intl.NumberFormat("fullwide",{maximumFractionDigits:20,useGrouping:false});function qn(e){let n=`${typeof e==="number"?Gn.format(e):e}`.replaceAll(",",".").split(".");return n.length>1?`${n.slice(0,-1).join("")}.${n.at(-1)}`:n[0]||"0"}function Yn(e){let t=e.split(".")[1]?.length||0;return Math.max(t,G$1)}function Ae$1(e){if(typeof e==="object")return e;let t=e==="undefined"?"0":qn(e),n=Yn(t),[r="",s=""]=t.split(".");return {bigIntValue:BigInt(`${r}${s.padEnd(n,"0")}`),decimalMultiplier:B$2(n)}}function U(e,t){return e&&!/^0(?:\.0*)?$/.test(t)?`-${t}`:t}function Tt(e,t){if(t===0n)throw Error("Cannot divide by zero");let n=t/2n;return e>=0n&&t>=0n||e<0n&&t<0n?(e+n)/t:(e-n)/t}function B$2(e){return 10n**BigInt(e)}function Se$1(e){return e.toString().length-1}function zn(e=""){let t=e.toUpperCase(),n=T.get("chains"),[r]=t.split(".");if(n.includes(r))return  true;let[s]=t.split("/");if(n.includes(s))return  true;throw new b$1({errorKey:"helpers_invalid_identifier",info:{identifier:e,message:`Invalid identifier: ${e}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`}})}var J$1=[l$3.Hype,l$3.Near,l$3.Ripple,l$3.Solana,l$3.Stellar,l$3.Sui,l$3.Ton,l$3.Tron],Ue$1=[l$3.THORChain,l$3.Maya];function Te(e,t){return J$1.includes(e)?t:t.toUpperCase()}var z$2=new Map,we$1=new Map,Q$1=new Map,Qn=3600000;function Jn(e){let t=Q$1.get(e);if(t?.timestamp&&Date.now()-t.timestamp>Qn){Q$1.delete(e);return}return t}function Zn(e,t){if(Q$1.size>1000){let n=Q$1.keys().next().value;if(n)Q$1.delete(n);}Q$1.set(e,{...t,timestamp:Date.now()});}class D extends F{address;chain;isGasAsset=false;isSynthetic=false;isTradeAsset=false;symbol;tax;ticker;type;chainId;constructor({value:e,decimal:t,tax:n,chain:r,symbol:s,identifier:a}){super({decimal:t,value:e});let c=wt(a||`${r}.${s}`);this.type=Me$1(c),this.tax=n,this.chain=c.chain,this.ticker=c.ticker,this.symbol=c.symbol,this.address=c.address,this.isSynthetic=c.isSynthetic,this.isTradeAsset=c.isTradeAsset,this.isGasAsset=c.isGasAsset,this.chainId=w$2(c.chain).chainId;}toString({includeSynthProtocol:e}={}){return (this.isSynthetic||this.isTradeAsset)&&!e?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){if(this.isSynthetic)return `${this.chain}.${this.symbol.replace(/\//g,".")}`;if(this.isTradeAsset)return `${this.chain}.${this.symbol.replace(/~/g,"..")}`;let e=this.symbol.replace(/\./g,"__");return `${this.chain}.${e}`}getIconUrl(){return z$2.get(Te(this.chain,this.toString()))?.logoURI}eqAsset({chain:e,symbol:t}){return this.chain===e&&this.symbol===t}eq(e){return this.eqAsset(e)&&this.eqValue(e)}static fromUrl(e,t=0){let n=e.indexOf(".");if(n===-1)throw new b$1({errorKey:"helpers_invalid_asset_url",info:{urlAsset:e}});let r=e.slice(0,n),s=e.slice(n+1),a=M$1({chain:r,rest:s}).when(({rest:c})=>c.includes(".."),({chain:c,rest:u})=>`${c}.${u.replace(/\.\./g,"~")}`).when(({chain:c,rest:u})=>Ue$1.includes(c)&&u.includes("."),({chain:c,rest:u})=>`${c}.${u.replace(/\./g,"/")}`).otherwise(({chain:c,rest:u})=>`${c}.${u.replace(/__/g,".")}`);return D.from({asset:a,value:t})}static from({value:e=0,fromBaseDecimal:t,asyncTokenLookup:n,...r}){let s="address"in r&&"chain"in r,a=rr(r);if(a===null&&n&&s){let{chain:se,address:q}=r;return tr({address:q,chain:se,fromBaseDecimal:t,parsedValue:e})}let c=s&&!a?`${r.chain}.UNKNOWN-${r.address}`:a,{identifier:u,decimal:_}=ye$1(c),{chain:A,isSynthetic:y,isTradeAsset:w,address:O}=wt(u),{baseDecimal:S}=w$2(A),M=z$2.get(Te(A,u));if(!M&&n&&!y&&!w)return (async()=>{let{ticker:se}=W$1(u),q=await xt({address:O,chain:A,ticker:se});return Le$1({decimal:q.decimals,identifier:q.identifier,value:t?He$1(e,t):e})})();let I=M?.decimal||_;Y$1({condition:!I&&!n,id:`assetValue_static_decimal_not_found_${A}`,warning:`Couldn't find static decimal for one or more tokens on ${A} (Using default ${S} decimal as fallback).
6173This can result in incorrect calculations and mess with amount sent on transactions.
6174You can load static assets by installing @swapkit/tokens package and calling AssetValue.loadStaticAssets()
6175or by passing asyncTokenLookup: true to the from() function, which will make it async and return a promise.`});
6175let{decimal:C,identifier:ne,tax:re}=M||{decimal:I||S,identifier:u},R=t?He$1(e,t):xe$1(e,C);return y||w?er(ne,R):Le$1({decimal:C,identifier:ne,tax:re,value:R})}static async loadStaticAssets(e){let{loadTokenLists:t}=await Promise.resolve().then(() => index$3),n=await t(e,{source:T.get("envs").isDev?"dev":"prod"});for(let{tokens:r}of Object.values(n))for(let s of r){let{identifier:a}=s,{chain:c,symbol:u}=W$1(a),{address:_}=ae$1(u,c),{baseDecimal:A}=w$2(c),y=Te(c,a),w="decimals"in s&&s.decimals!==void 0?s.decimals:A,O="logoURI"in s&&s.logoURI?s.logoURI:`https://tokens.swapkit.dev/images/${a.toLowerCase()}.png`,S={decimal:w,identifier:a,logoURI:O,tax:"tax"in s?s.tax:void 0};if(z$2.set(y,S),_){let M=J$1.includes(c)?`${c}:${_}`:`${c}:${_.toUpperCase()}`;we$1.set(M,a);}}return  true}static setStaticAssets(e){z$2.clear(),we$1.clear();for(let[t,n]of e.entries()){let{identifier:r}=n,{chain:s,symbol:a}=W$1(r),{address:c}=ae$1(a,s),{baseDecimal:u}=w$2(s),_=n.chain??s,A=n.address??c,y=Te(_,r),w=n.decimals??n.decimal??u,O=n.logoURI??`https://tokens.swapkit.dev/images/${r.toLowerCase()}.png`,S={decimal:w,identifier:y,logoURI:O,tax:n.tax};if(z$2.set(y,S),A){let M=J$1.includes(_)?`${_}:${A}`:`${_}:${A.toUpperCase()}`;we$1.set(M,r);}}return  true}static get staticAssets(){return z$2}}function to(e){let t=D.from({chain:e});return M$1(e).with(l$3.Bitcoin,l$3.Litecoin,l$3.BitcoinCash,l$3.Dash,()=>t.set(0.00010001)).with(l$3.Dogecoin,()=>t.set(1.00000001)).with(l$3.Avalanche,l$3.Ethereum,l$3.Arbitrum,l$3.BinanceSmartChain,()=>t.set(0.00000001)).with(l$3.THORChain,l$3.Maya,()=>t.set(0)).with(l$3.Cosmos,l$3.Kujira,()=>t.set(0.000001)).otherwise(()=>t.set(0.00000001))}async function xt({chain:e,address:t,ticker:n}){let s=J$1.includes(e)?`${e}:${t||n}`:`${e}:${t||n}`.toUpperCase(),a=Jn(s);if(a)return a;if(!t){let{baseDecimal:_}=w$2(e);return {decimals:_,identifier:`${e}.${n||"UNKNOWN"}`}}let c=await At({address:t,chain:e}),u=`${e}.${c.ticker||n||"UNKNOWN"}-${t}`;return Y$1({condition:!!(!c.ticker&&n),id:`async_token_lookup_failed_${e}_${t}`,warning:`Could not fetch token metadata for ${e}:${t} from chain. Using user-provided ticker (${n}) with baseDecimal (${c.decimals}).`}),c.ticker&&Zn(s,{decimals:c.decimals,identifier:u}),{decimals:c.decimals,identifier:u}}function Le$1({identifier:e,decimal:t,value:n,tax:r}){return zn(e),new D({decimal:t,identifier:e,tax:r,value:xe$1(n,t)})}function er(e,t=0){let n=e.includes(".")?e.split(".")?.[0]?.toUpperCase():void 0,r=n?Ue$1.includes(n):false,s=e.slice(0,14).includes("~")?"~":"/",[a,c]=r?e.split(".").slice(1).join().split(s):e.split(s);if(!(a&&c))throw new b$1({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});return new D({decimal:8,identifier:`${n||l$3.THORChain}.${a}${s}${c}`,value:xe$1(t,8)})}async function tr({address:e,chain:t,fromBaseDecimal:n,parsedValue:r}){let{decimals:s,identifier:a}=await xt({address:e,chain:t}),c=n?He$1(r,n):r;return Le$1({decimal:s,identifier:a,value:c})}function He$1(e,t){let n=e instanceof F?e.getValue("string"):e;return xe$1(BigInt(n),t)}function xe$1(e,t){return typeof e==="bigint"?X$1({bigIntDecimal:t,decimal:t,value:e}):e}function nr(e){let t=M$1(e).when((n)=>("chain"in n)&&n.chain!==void 0,({chain:n})=>n).otherwise((n)=>{let r=W$1(n.asset);return r.synth?l$3.THORChain:r.chain});if(!Pe$2.includes(t.toUpperCase())){let n="asset"in e?e.asset:t;throw new b$1({errorKey:"helpers_invalid_asset_identifier",info:{identifier:n,message:`Unsupported chain "${t}" - use the AssetValue constructor directly`}})}}function rr(e){if(nr(e),"chain"in e){let{chain:s,address:a}=e;if(a){let c=J$1.includes(s)?`${s}:${a}`:`${s}:${a.toUpperCase()}`,u=we$1.get(c);if(u)return u;return null}return s}let{chain:t,symbol:n}=W$1(e.asset);return Me$1({chain:t,symbol:n})==="Native"?t:e.asset}function sr(e,t,n){let r=e.split("."),s=r[0]?.toUpperCase(),a=Ue$1.includes(s),c=n?"~":"/",[u,_=""]=a?r.slice(1).join(".").split(c):e.split(c);if(!(u&&_))throw new b$1({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e}});let{ticker:A,address:y}=Rt({chain:u,symbol:_}),w=`${u}${c}${_}`;return {address:y,chain:s,isGasAsset:false,isSynthetic:t,isTradeAsset:n,symbol:w,ticker:A}}function ir(e){let t=e.indexOf("."),n=(t===-1?e:e.slice(0,t)).toUpperCase(),r=t===-1?e:e.slice(t+1),{address:s,ticker:a}=Rt({chain:n,symbol:r}),c;try{c=s&&We.includes(n)&&fe(s)?fe(s):s;}catch{c=s;}let u=c?`${a}-${c}`:r;
6175return {address:c,chain:n,isGasAsset:St({chain:n,symbol:r}),isSynthetic:false,isTradeAsset:false,symbol:u,ticker:a}}function wt(e){let t=e.slice(0,14),n=t.includes("/"),r=t.includes("~");if(n||r)return sr(e,n,r);return ir(e)}function Rt({symbol:e,chain:t}){let{ticker:n,address:r}=ae$1(e,t);return {address:r&&!J$1.includes(t)?r.toLowerCase():r,ticker:n}}class Re extends F{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new Re({decimal:t,value:X$1({bigIntDecimal:t,decimal:t,value:e})})}}function vt(e=true){return e?"https://gateway.liquify.com/chain/thorchain_midgard":"https://midgard.mayachain.info"}function ar(e=true){let t=vt(e);return e?`${t}/v2/thorname`:`${t}/v2/mayaname`}function lr(e){return function(n){let r=n?`?status=${n}`:"";return m.get(`${e}/v2/pools${r}`)}}function cr(e){return function(n){return m.get(`${e}/v2/pool/${n}`)}}function dr(e){return function(n,r){let s=r?`?period=${r}`:"";return m.get(`${e}/v2/pool/${n}/stats${s}`)}}function pr(e){return function(n,r){let s=new URLSearchParams;if(r?.interval)s.append("interval",r.interval);if(r?.count)s.append("count",r.count.toString());if(r?.from)s.append("from",r.from.toString());if(r?.to)s.append("to",r.to.toString());let a=s.toString()?`?${s.toString()}`:"";return m.get(`${e}/v2/history/depths/${n}${a}`)}}function ur(e){return function(){return m.get(`${e}/v2/network`)}}function gr(e){return function(){return m.get(`${e}/v2/health`)}}function mr(e){return function(){return m.get(`${e}/v2/nodes`)}}function _r(e){return function(n){return m.get(`${e}/v2/node/${n}`)}}function hr(e){return function(){return m.get(`${e}/v2/mimir/votes`)}}function fr(e){return function(){return m.get(`${e}/v2/mimir`)}}function yr(e){return function(){return m.get(`${e}/v2/constants`)}}function br(e){return function(){return m.get(`${e}/v2/stats`)}}function Ar(e){return function(n){let r=new URLSearchParams;if(n?.interval)r.append("interval",n.interval);if(n?.count)r.append("count",n.count.toString());if(n?.from)r.append("from",n.from.toString());if(n?.to)r.append("to",n.to.toString());let s=r.toString()?`?${r.toString()}`:"";return m.get(`${e}/v2/history/earnings${s}`)}}function Sr(e){return function(n,r){let s=new URLSearchParams;if(r?.interval)s.append("interval",r.interval);if(r?.count)s.append("count",r.count.toString());if(r?.from)s.append("from",r.from.toString());if(r?.to)s.append("to",r.to.toString());let a=s.toString()?`?${s.toString()}`:"",c=n?`/swaps/${n}`:"/swaps";return m.get(`${e}/v2/history${c}${a}`)}}function Tr(e){return function(n){let r=new URLSearchParams;if(n?.interval)r.append("interval",n.interval);if(n?.count)r.append("count",n.count.toString());if(n?.from)r.append("from",n.from.toString());if(n?.to)r.append("to",n.to.toString());let s=r.toString()?`?${r.toString()}`:"";return m.get(`${e}/v2/history/tvl${s}`)}}function wr(e){if(!e)return "";let t=new URLSearchParams,n=(r,s)=>{if(s!==void 0)t.append(r,typeof s==="number"?s.toString():s);};return n("address",e.address),n("txid",e.txid),n("asset",e.asset),n("type",e.type),n("affiliate",e.affiliate),n("limit",e.limit),n("offset",e.offset),t.toString()?`?${t.toString()}`:""}function xr(e){return function(n){let r=wr(n);return m.get(`${e}/v2/actions${r}`)}}function Rr(e){return function(n){return m.get(`${e}/v2/member/${n}`)}}function vr(e){return function(n){let r=n?`/${n}`:"";return m.get(`${e}/v2/members${r}`)}}function Cr(e){return function(n,r){let s=r?`&asset=${r}`:"";return m.get(`${e}/v2/saver/${n}${s?`?${s.substring(1)}`:""}`)}}function Ir(e){return function(n){return m.get(`${e}/v2/savers/${n}`)}}function Er(e){return function(n,r){let s=new URLSearchParams;if(r?.interval)s.append("interval",r.interval);if(r?.count)s.append("count",r.count.toString());if(r?.from)s.append("from",r.from.toString());if(r?.to)s.append("to",r.to.toString());let a=s.toString()?`?${s.toString()}`:"",c=n?`/savers/${n}`:"/savers";return m.get(`${e}/v2/history${c}${a}`)}}function Pr(e){return function(n){return m.get(`${e}/v2/balance/${n}`)}}function Nr(e){return async function(n){let r=(s)=>{if(s?.cause?.status===404)return;throw s};return await m.get(`${e}/lookup/${n}`,{onError:r,retry:{maxRetries:1}})}}function kr(e){return async function(n){let r=(s)=>{if(s?.cause?.status===404)return [];throw s};return await m.get(`${e}/rlookup/${n}`,{onError:r,retry:{maxRetries:1}})}}function Or(e){return async function(n){let r=(s)=>{if(s?.cause?.status===404)return [];throw s};return await m.get(`${e}/owner/${n}`,{onError:r,retry:{maxRetries:1}})}}function Z$1({asset:e,value:t}){return D.from({asset:e,fromBaseDecimal:w$2(l$3.THORChain).baseDecimal,value:t})}function Dr({liquidityPositionGetter:e,isThorchain:t}){return async function(r){let s=await e(r),a=t?"rune":"cacao";return s.pools.map((c)=>({[`${a}Pending`]:Z$1({asset:"THOR.RUNE",value:c.runePending}),[`${a}RegisteredAddress`]:c.runeAddress,[`${a}Withdrawn`]:Z$1({asset:"THOR.RUNE",value:c.runeWithdrawn}),[a]:Z$1({asset:"THOR.RUNE",value:c.runeAdded}),asset:Z$1({asset:c.pool,value:c.assetAdded}),assetPending:Z$1({asset:c.pool,value:c.assetPending}
6175),assetRegisteredAddress:c.assetAddress,assetWithdrawn:Z$1({asset:c.pool,value:c.assetWithdrawn}),dateFirstAdded:c.dateFirstAdded,dateLastAdded:c.dateLastAdded,poolShare:new Re(c.liquidityUnits).div(c.pool)}))}}function Ct(e){let t=e===l$3.THORChain,n=vt(t),r=ar(t),s=Rr(n);return {getActions:xr(n),getBalance:Pr(n),getConstants:yr(n),getEarningsHistory:Ar(n),getHealth:gr(n),getLiquidityPosition:Dr({isThorchain:t,liquidityPositionGetter:s}),getLiquidityPositionRaw:s,getMembers:vr(n),getMimir:fr(n),getMimirVotes:hr(n),getNameDetails:Nr(r),getNamesByAddress:kr(r),getNamesByOwner:Or(r),getNetworkInfo:ur(n),getNode:_r(n),getNodes:mr(n),getPool:cr(n),getPoolDepthHistory:pr(n),getPoolStats:dr(n),getPools:lr(n),getSaverDetails:Cr(n),getSavers:Ir(n),getSaversHistory:Er(n),getStats:br(n),getSwapHistory:Sr(n),getTVLHistory:Tr(n)}}var It=Ct(l$3.THORChain),Et=Ct(l$3.Maya);var Ge={};ze$1(Ge,{SKRequestClient:()=>k$1,getChainBalance:()=>Ss,getChainflipDepositChannel:()=>Is,getGasRate:()=>Cs,getNearDepositChannel:()=>Es,getPrice:()=>vs,getRouteWithTx:()=>As,getSwapQuote:()=>bs,getSwapTo:()=>Ds,getTokenApproval:()=>Ts,getTokenList:()=>xs,getTokenListProviders:()=>ws,getTrackerDetails:()=>ys,searchTokens:()=>Rs});var Dt;((r)=>{r.CHEAPEST="CHEAPEST";r.FASTEST="FASTEST";r.RECOMMENDED="RECOMMENDED";})(Dt||={});var Ie$1;((y)=>{y.PSBT="PSBT";y.EVM="EVM";y.COSMOS="COSMOS";y.RADIX="RADIX";y.NEAR="NEAR";y.STELLAR="STELLAR";y.TON="TON";y.TRON="TRON";y.EIP_712_HYPE_SEND_ASSET="EIP_712_HYPE_SEND_ASSET";y.EIP_712_HYPE_WITHDRAW="EIP_712_HYPE_WITHDRAW";})(Ie$1||={});var Mt;((C)=>{C.approve="approve";C.claim="claim";C.deposit="deposit";C.donate="donate";C.lending="lending";C.lp_action="lp_action";C.native_contract_call="native_contract_call";C.native_send="native_send";C.stake="stake";C.streaming_swap="streaming_swap";C.swap="swap";C.thorname_action="thorname_action";C.token_contract_call="token_contract_call";C.token_transfer="token_transfer";C.unknown="unknown";C.unstake="unstake";})(Mt||={});var Lt;((S)=>{S.swap="swap";S.aggregation="aggregation";S.addLiquidity="addLiquidity";S.withdrawLiquidity="withdrawLiquidity";S.addSavers="addSavers";S.withdrawSavers="withdrawSavers";S.borrow="borrow";S.repay="repay";S.name="name";S.donate="donate";S.claim="claim";S.stake="stake";S.unstake="unstake";})(Lt||={});var Ht;((u)=>{u.unknown="unknown";u.not_started="not_started";u.pending="pending";u.swapping="swapping";u.completed="completed";u.refunded="refunded";u.failed="failed";})(Ht||={});var Vt;((I)=>{I.not_started="not_started";I.starting="starting";I.broadcasted="broadcasted";I.mempool="mempool";I.inbound="inbound";I.outbound="outbound";I.swapping="swapping";I.completed="completed";I.refunded="refunded";I.partially_refunded="partially_refunded";I.dropped="dropped";I.reverted="reverted";I.replaced="replaced";I.retries_exceeded="retries_exceeded";I.parsing_error="parsing_error";})(Vt||={});var mo=object({address:optional(string()),chain:_enum(l$3).optional(),chainId:_enum(m$2),coingeckoId:optional(string()),decimals:number(),extensions:optional(looseObject({})),identifier:string(),logoURI:optional(string()),name:optional(string()),shortCode:optional(string()),symbol:optional(string()),ticker:string()}),_o=object({block:optional(number$1().describe("Block number. Required for Polkadot chain. e.g. `123456`")),chainId:optional(string().describe("ChainId for the hash. e.g. `thorchain-1`")),depositChannelId:optional(string().describe("Deposit channel ID, required for Chainflip if tx was broadcasted without wallet connection")),hash:optional(string().describe("Hash for the first transaction broadcasted by the end user. e.g. `88D1819378ECD09E5284C54937CDC1E99B52F253C007617A02DD1200710CE677`"))}).refine((e)=>e.hash&&e.chainId||e.depositChannelId,{message:"Either `hash` and `chainId` or `depositChannelId` must be provided"}),ho=object({forceUpdate:string().toLowerCase().transform((e)=>e==="true").pipe(boolean()).optional()}),fo=object({error:string(),message:string()}),ee=object({address:optional(string()),chain:_enum(l$3),decimal:optional(number$1()),isGasAsset:boolean(),isSynthetic:boolean(),symbol:string(),tax:optional(object({buy:number$1(),sell:number$1()})),ticker:string()}),Ut=object({id:string(),market_cap:number$1(),name:string(),price_change_24h_usd:number$1(),price_change_percentage_24h_usd:number$1(),sparkline_in_7d:array(number$1()),timestamp:string(),total_volume:number$1()}).partial(),yo=object({cg:optional(Ut),identifier:string(),price_usd:number$1(),provider:string(),timestamp:number$1()}),$t=array(object({cg:optional(Ut),identifier:string(),price_usd:number$1(),provider:string(),timestamp:number$1()}).partial()),bo=object({affiliate:optional(string().describe("Affiliate thorname")),affiliateFee:optional(number$1().describe("Affiliate fee in basis points").refine((e)=>
6175e===Math.floor(e)&&e>=0,{message:"affiliateFee must be a positive integer",path:["affiliateFee"]})),allowSmartContractReceiver:optional(boolean().describe("Allow smart contract as recipient")),allowSmartContractSender:optional(boolean().describe("Allow smart contract as sender")),buyAsset:string().describe("Asset to buy"),cfBoost:optional(boolean().describe("Set to true to enable CF boost to speed up Chainflip swaps. BTC only.")),destinationAddress:optional(string().describe("Address to send asset to")),disableSecurityChecks:optional(boolean().describe("Disable security checks")),includeTx:optional(boolean().describe("Set to true to include an transaction object (EVM only)")),providers:optional(array(string().describe("List of providers to use").refine((e)=>E[e]!==void 0,{message:"Invalid provider",path:["providers"]}))),referrer:optional(string().describe("Referrer address (referral program)")),sellAmount:string().describe("Amount of asset to sell").refine((e)=>+e>0,{message:"sellAmount must be greater than 0",path:["sellAmount"]}),sellAsset:string().describe("Asset to sell"),slippage:optional(number$1().describe("Slippage tolerance as a percentage. Default is 3%.")),sourceAddress:optional(string().describe("Address to send asset from"))}).refine((e)=>e.sellAsset!==e.buyAsset,{message:"Must be different",path:["sellAsset","buyAsset"]}),Ao=object({metadata:boolean(),tokens:array(object({identifier:string()}))}),Bt=object({destinationAddress:string()}),Mr=Bt.extend({affiliateFees:array(object({brokerAddress:string(),feeBps:number$1()})).optional(),brokerCommissionBps:number$1().optional(),buyAsset:object({asset:string(),chain:string()}),channelMetadata:object({cfParameters:string().optional(),gasBudget:string().optional(),message:string().optional()}).optional(),dcaParameters:object({chunkInterval:number$1().optional(),numberOfChunks:number$1().optional()}).optional(),maxBoostFeeBps:number$1().optional(),refundParameters:object({minPrice:string().optional(),refundAddress:string().optional(),retryDuration:number$1().optional()}).optional(),sellAsset:object({asset:string(),chain:string()})}),Ft=object({channelId:string(),depositAddress:string()}),Pt=Bt.extend({affiliateFees:object({feeBps:number$1(),nearId:string()}).optional(),buyAsset:string(),sellAmount:string(),sellAsset:string(),slippage:number(),sourceAddress:string()}),Nt=object({amountIn:string(),amountInFormatted:string(),amountInUsd:string(),amountOut:string(),amountOutFormatted:string(),amountOutUsd:string(),deadline:string().optional(),minAmountIn:string(),minAmountOut:string(),timeEstimate:number$1().optional(),timeWhenInactive:string().optional()}),So=Nt.extend({depositAddress:string(),quote:Nt,signature:string(),timestamp:string(),tx:unknown()}),Kt=object({buyAsset:string(),buyAssetAmount:string(),buyAssetAmountMaxSlippage:string(),deadline:string().optional(),depositAddress:string(),depositAmount:string(),depositAsset:string(),tx:unknown()}),Lr=object({evmCalldata:optional(string()),intentHash:optional(string()),logs:optional(unknown()),manifest:optional(unknown()),memo:optional(string()),spender:optional(string()),thorname:optional(string())}),Hr=object({currentStage:string(),inboundConfirmation:number$1(),inboundObservation:number$1(),outboundDelay:number$1(),outboundObservation:number$1(),streamingSwap:number$1()}),Vr=object({count:optional(number$1()),interval:optional(number$1()),quantity:optional(number$1()),subSwapsMap:optional(array(number$1()))}),Ur=object({currentLegIndex:optional(number$1()),estimatedTimeToComplete:number$1(),estimates:optional(Hr),providerDetails:optional(object({streamingDetails:optional(Vr)}))}),$r=object({affiliate:optional(ee),liquidity:optional(ee),network:optional(ee),protocol:optional(ee),tax:optional(ee)}),Br=object({affiliate:string(),bps:string(),isReferrer:boolean()}),Fr=object({affiliate:optional(string()),affiliateFees:optional(array(Br)),broadcastedAt:optional(number$1()),explorerUrl:optional(string()),fees:optional($r),images:optional(object({chain:optional(string()),from:optional(string()),provider:optional(string()),to:optional(string())})),provider:optional(_enum(E)),providerAction:optional(_enum(Lt)),quoteId:optional(string()),wallet:optional(string())}),te=object({block:number$1(),chainId:_enum(m$2),finalAddress:optional(string()),finalAsset:optional(ee),finalisedAt:number$1(),fromAddress:string(),fromAmount:string(),fromAsset:string(),hash:string(),meta:optional(Fr),payload:optional(Lr),status:_enum(Ht),toAddress:string(),toAmount:string(),toAsset:string(),trackingStatus:optional(_enum(Vt)),transient:optional(Ur),type:_enum
6175(Mt)}),Wt=te.extend({legs:array(te)}),To=te.extend({legs:array(te)}),wo=te.extend({legs:array(te)}),Fe$1=array(object({amount:string(),asset:string(),chain:string(),protocol:_enum(E),type:_enum(Ne$1)})),Ke$1=object({inbound:optional(number$1().describe("Time to receive inbound asset in seconds")),outbound:optional(number$1().describe("Time to receive outbound asset in seconds")),swap:optional(number$1().describe("Time to swap assets in seconds")),total:number$1().describe("Total time in seconds")}),Kr=/^(?:0x[0-9a-fA-F]+|[0-9]+)$/;function Wr(e){return e===""||Kr.test(e)}function xo(e){return e?BigInt(e):0n}function Ro(e){let t=typeof e==="bigint"?e:BigInt(e);return t>0n?`0x${t.toString(16)}`:"0x0"}var de=string().refine(Wr,{message:"Value must be a base-10 integer string or 0x-prefixed hex integer string"}).describe("Value to send in base units as a base-10 integer string or 0x-prefixed hex integer string"),Gr=object({data:string().describe("Data to send"),from:string().describe("Address of the sender"),to:string().describe("Address of the recipient"),value:de}),qr=object({data:string().optional(),raw_data:object({contract:any(),data:string().optional(),expiration:number$1(),fee_limit:number$1().optional(),ref_block_bytes:string(),ref_block_hash:string(),timestamp:number$1()}).passthrough(),raw_data_hex:string(),txID:string(),value:de.optional(),visible:boolean()}),Yr=array(union([string(),number$1(),array(string()),object({from:string(),value:de}).describe("Parameters to pass to the contract method")])),vo=object({approvalSpender:optional(string().describe("Address of the spender to approve")),approvalToken:optional(string().describe("Address of the token to approve spending of")),contractAddress:string().describe("Address of the contract to interact with"),contractMethod:string().describe("Name of the method to call"),contractParamNames:array(string().describe("Names of the parameters to pass to the contract method")),contractParams:Yr}),jr=object({typeUrl:string("/types.MsgDeposit"),value:object({coins:array(object({amount:string(),asset:object({chain:string(),symbol:string(),synth:boolean(),ticker:string()})})),memo:string(),signer:string()})}),Xr=object({typeUrl:string("/types.MsgSend"),value:object({amount:array(object({amount:string(),denom:string()})),fromAddress:string(),toAddress:string()})}),zr=object({typeUrl:string(),value:Xr.shape.value.or(jr.shape.value)}),Qr=object({amount:array(object({amount:string(),denom:string()})),gas:string()}),Jr=object({accountNumber:number$1(),chainId:_enum(m$2),fee:Qr,memo:string(),msgs:array(zr),sequence:number$1()}),Zr=array(object({calldata:array(string()),contractAddress:string(),entrypoint:string()})),es=object({address:string().describe("Destination address in friendly format"),amount:string().describe("Amount in nanotons"),payload:string().optional().describe("Base64 BOC of body cell"),stateInit:string().optional().describe("Base64 BOC of state init")}),ts=object({messages:array(es),sendMode:number$1().describe("TON wallet send mode for the whole transfer")}),Co="USDC:0x6d1e7cde53ba9467b783cb7c530ce054",ns=looseObject({domain:looseObject({chainId:optional(union([number$1(),string()])),name:optional(string()),verifyingContract:optional(string()),version:optional(string())}),message:record(string(),unknown()),primaryType:string(),types:record(string(),array(looseObject({name:string(),type:string()})))}),rs=looseObject({amount:string(),destination:string(),destinationDex:string(),fromSubAccount:string(),hyperliquidChain:string(),nonce:number$1().int(),signatureChainId:string(),sourceDex:string(),token:string(),type:literal("sendAsset")}),Gt=looseObject({action:looseObject({type:string()}),submitTo:string(),typedData:ns}),Io=Gt.extend({action:rs}),qt=union([Gr,Jr,qr,ts,Gt,string()]),ss=qt.or(Zr),is=object({affiliate:string().describe("Affiliate address").optional(),affiliateFee:number$1().describe("Affiliate fee").optional(),buyAsset:string().describe("Asset to buy"),destinationAddress:string().describe("Destination address"),estimatedTime:Ke$1.optional(),provider:_enum(E),sellAsset:string().describe("Asset to sell"),slipPercentage:number$1().describe("Slippage as a percentage"),sourceAddress:string().describe("Source address")}),Eo=is.omit({destinationAddress:true,slipPercentage:true,sourceAddress:true}),os=object({asset:string().describe("Asset name"),image:string().describe("Asset image"),price:number$1().describe("Price in USD")}),as=Mr,Yt=object({assets:optional(array(os)),maxStreamingQuantity:number$1().optional(),referrer:string().optional(),streamingInterval:number$1().optional(),tags:array(_enum(Dt))}),jt=Yt.extend({affiliate:optional(string()),affiliateFee:optional(string()),approvalAddress:optional(string().describe("Approval address for swap")),chainflip:as.optional(),garden:Pt.optional(),near:Pt.optional(),priceImpact:optional(number$1().describe("Price impact")),referrer:optional(string()),txType:optional(_enum(Ie$1))}
6175),Xt=array(object({code:_enum(Pe$1),display:string(),tooltip:string().optional()})),ls=object({buyAmount:string().describe("Buy amount"),buyAmountMaxSlippage:string().describe("Buy amount max slippage"),buyAsset:string().describe("Asset to buy"),fees:optional(Fe$1),provider:_enum(E),sellAmount:string().describe("Sell amount"),sellAsset:string().describe("Asset to sell")}),cs=object({buyAsset:string().describe("Asset to buy"),destinationAddress:optional(string().describe("Destination address")),estimatedTime:optional(Ke$1),expectedBuyAmount:string().describe("Expected Buy amount"),expectedBuyAmountMaxSlippage:string().describe("Expected Buy amount max slippage"),expiration:optional(string().describe("Expiration")),fees:Fe$1,inboundAddress:optional(string().describe("Inbound address")),legs:array(ls),memo:optional(string().describe("Memo")),meta:jt,providers:array(_enum(E)),routeId:string().describe("Route ID"),sellAmount:string().describe("Sell amount"),sellAsset:string().describe("Asset to sell"),sourceAddress:optional(string().describe("Source address")),targetAddress:optional(string().describe("Target address")),totalSlippageBps:number$1().describe("Total slippage in bps"),tx:optional(ss),txType:optional(_enum(Ie$1)),warnings:Xt}),zt=object({error:optional(string().describe("Error message")),providerErrors:optional(array(object({errorCode:optional(_enum(ie$1)),message:optional(string()),provider:_enum(E).optional()}))),quoteId:string().describe("Quote ID"),routes:array(cs)}),Qt=object({chainId:_enum(m$2),createdAt:date(),id:number$1(),unit:string(),value:string()}),ds=array(Qt),Jt=union([Qt,ds]);array(object({chain:_enum(l$3),decimal:number$1(),identifier:string(),symbol:string(),ticker:string(),value:string()}));var No=union([object({amount:string(),spender:string(),tokenIdentifier:string(),userWalletAddress:string()}),object({amount:string(),chainId:_enum(m$2),spender:string(),tokenContractAddress:string(),userWalletAddress:string()}),object({routeId:string()})]),ko=object({approvalTransaction:optional(object({data:string(),from:string(),gasLimit:optional(string()),gasPrice:optional(string()),to:string(),value:de})),approvedAmount:string(),isApproved:boolean()}),ps=object({data:string().describe("Encoded approval call data"),from:string().describe("User wallet address"),gasLimit:string().optional().describe("Estimated gas limit"),gasPrice:string().optional().describe("Current gas price"),to:string().describe("Token contract address"),value:de.describe("ETH value (always '0' for approvals)")}),us=object({tx:string(),txType:literal("STELLAR")}),gs=union([ps,us]),kt=object({buyAmount:string().describe("Buy amount").optional(),buyAmountMaxSlippage:string().describe("Buy amount max slippage").optional(),buyAsset:string().describe("Asset to buy"),expectedBuyAmount:string().describe("Expected Buy amount").optional(),expectedBuyAmountMaxSlippage:string().describe("Expected Buy amount max slippage").optional(),fees:Fe$1,provider:_enum(E),sellAmount:string().describe("Sell amount"),sellAsset:string().describe("Asset to sell")}),Zt=kt.extend({estimatedTime:optional(Ke$1),expiration:optional(string().describe("Expiration")),legs:array(kt),providers:array(_enum(E)),routeId:string().describe("Route ID"),totalSlippageBps:number$1().describe("Total slippage in bps"),warnings:Xt}).omit({provider:true}),en=object({method:string(),payload:optional(unknown()),url:string()}),ms=Zt.extend({meta:Yt,nextActions:optional(array(en))}),Oo=object({error:optional(string().describe("Error message")),providerErrors:optional(array(object({errorCode:optional(_enum(ie$1)),message:optional(string()),provider:_enum(E).optional()}))),quoteId:string().describe("Quote ID"),routes:array(ms)}),Do=object({providers:array(_enum(E)).optional().describe("Optional list of providers to query for trading pairs"),sellAsset:string().describe("Asset identifier to sell (e.g., 'BTC.BTC' or 'ETH.ETH')")}),_s=object({chain:_enum(l$3).describe("Chain the asset is on"),identifier:string().describe("Asset identifier (e.g., 'ETH.USDC-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48')"),providers:array(_enum(E)).describe("Providers that support this trading pair"),symbol:string().describe("Asset symbol"),ticker:string().describe("Asset ticker")}),Mo=object({buyAssets:array(_s).describe("List of assets that can be swapped to"),sellAsset:string().describe("The input sell asset identifier")}),tn=Zt.extend({destinationAddress:string().describe("Destination address"),inboundAddress:optional(string().describe("Inbound address")),memo:optional(string().describe("Memo to include in the transaction")),meta:jt,
6175sourceAddress:string().describe("Source address"),targetAddress:optional(string().describe("Target address")),tx:optional(qt),txType:optional(_enum(Ie$1))}),hs=object({data:optional(record(string(),string().optional())),errorCode:_enum(ie$1),message:string().optional(),provider:_enum(E).optional()}),Lo=object({error:optional(string().describe("Error message")),providerErrors:optional(array(hs)),quoteId:string().describe("Quote ID"),routes:array(tn)}),nn=tn.extend({approvalTx:gs.optional().describe("Optional approval transaction required before swap execution"),nextActions:optional(array(en)),swapId:string().describe("The unique swap ID for tracking")});var k$1=m.extend({dynamicHeader:async()=>{let e=T.get("widgetId"),t=T.get("widgetKey");if(e&&t&&typeof window<"u"){let r=Math.floor(Date.now()/1000),s=window.location.origin,a=await it(t,e,s,r);return {Origin:s,"X-Signature":a,"X-Timestamp":r.toString(),"x-widget-id":e}}let{swapKit:n}=T.get("apiKeys");return n?{"x-api-key":n}:{}}});async function ys(e){let t=await k$1.post(N("/track"),{json:e});try{let n=Wt.safeParse(t);if(!n.success)throw new b$1("api_v2_invalid_response",n.error);return n.data}catch(n){return t}}async function bs(e){let{getQuote:t}=T.get("endpoints");if(t)return t(e);let r=T.get("v3SwapFlow")?.enabled?"/v3/quote":"/quote",s=await k$1.post(N(r),{json:e});if(s.error)throw new b$1("api_v2_server_error",{message:s.error});try{let a=zt.safeParse(s);if(!a.success)throw new b$1("api_v2_invalid_response",a.error);return a.data}catch{return s}}async function As(e){let{getRouteWithTx:t}=T.get("endpoints");if(t)return t(e);let r=T.get("v3SwapFlow")?.enabled?"/v3/swap":"/swap",s=await k$1.post(N(r),{json:e});try{let a=nn.safeParse(s);if(!a.success)throw new b$1("api_v2_invalid_response",a.error);return a.data}catch(a){return console.error(new b$1("api_v2_invalid_response",a)),s}}async function Ss({chain:e,address:t,scamFilter:n=true}){let{getBalance:r}=T.get("endpoints");if(r)return r({address:t,chain:e});let s=N(`/balance?chain=${e}&address=${t}`),a=await k$1.get(s),c=Array.isArray(a)?a:[];return n?Os(c):c}function Ts(e){let t=M$1(e).with({routeId:z$3.string,spender:z$3.string},({routeId:n,spender:r})=>N(`/approve?routeId=${n}&sourceAddress=${r}`)).with({assetValue:z$3.instanceOf(D),spender:z$3.string,userWallet:z$3.string},({spender:n,userWallet:r,assetValue:s})=>N(`/approve?tokenIdentifier=${s.toString()}&userWalletAddress=${r}&spender=${n}&amount=${s.getValue("string")}`)).exhaustive();return k$1.get(t)}function ws(){let e=N("/providers");return k$1.get(e)}function xs(e){let t=N(`/tokens?provider=${e}`);return k$1.get(t)}function Rs({query:e,chain:t,page:n,limit:r}){let s=new URLSearchParams({query:e});if(t!==void 0)s.set("chain",t);if(n!==void 0)s.set("page",n.toString());if(r!==void 0)s.set("limit",r.toString());let a=N(`/tokens/search?${s.toString()}`);return k$1.get(a)}async function vs(e){let t=N("/price"),n=await k$1.post(t,{json:e});try{let r=$t.safeParse(n);if(!r.success)throw new b$1("api_v2_invalid_response",r.error);return r.data}catch(r){throw new b$1("api_v2_invalid_response",r)}}async function Cs(){let e=N("/gas"),t=await k$1.get(e);try{let n=Jt.safeParse(t);if(!n.success)throw new b$1("api_v2_invalid_response",n.error);return Array.isArray(n)?n:[n]}catch(n){throw new b$1("api_v2_invalid_response",n)}}async function Is(e){let{destinationAddress:t}=e;if(!t)throw new b$1("chainflip_broker_invalid_params");let n=T.get("integrations").chainflip?.brokerUrl||N("/chainflip/broker/channel"),r=await k$1.post(n,{json:e});try{let s=Ft.safeParse(r);if(!s.success)throw new b$1("api_v2_invalid_response",s.error);return s.data}catch(s){throw new b$1("api_v2_invalid_response",s)}}async function Es(e){let{destinationAddress:t}=e;if(!t)throw new b$1("chainflip_broker_invalid_params");let n=N("/near/channel"),r=await k$1.post(n,{json:e});try{let s=Kt.safeParse(r);if(!s.success)throw new b$1("api_v2_invalid_response",s.error);return s.data}catch(s){throw new b$1("api_v2_invalid_response",s)}}function N(e){let{isDev:t,apiUrl:n,devApiUrl:r}=T.get("envs"),{enabled:s,quoteUrl:a,swapUrl:c}=T.get("localMode");if(s&&e){let[_]=e.split("?");if(_==="/quote"||_==="/v3/quote")return `${a}${e}`;if(_==="/swap"||_==="/v3/swap")return `${c}${e}`}return `${t?r:n}${e}`}function Ps(e){try{return D.from({asset:e.identifier})}catch{return}}var Ns=new Set(["OP.OP"]),ks=/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/im;function Os(e){return e.filter((t)=>{let n=Ps(t);if(!n)return  false;if(Ns.has(n.toString().toUpperCase()))return  true;return (!We.includes(n.chain)||n.isGasAsset||!!n.address)&&!ks.test(n.ticker)})}async function Ds(e){let{getSwapTo:t}=T.get("endpoints");if(t)return t(e);let n=new URLSearchParams({sellAsset:e.sellAsset});if(e.providers?.length)for(let c of e.providers)n.append("providers",c);let r=N(`/swapTo?${n.toString()}`),s=await k$1.get(r);if(!Array.isArray(s))return {buyAssets:[],sellAsset:e.sellAsset};let a=[];for(let c of s)try{let u=D.from({asset:c});a.push({chain:u.chain,identifier:u.toString(),providers:[],symbol:u.symbol,ticker:u.ticker});}catch{}return {buyAssets:a,sellAsset:e.sellAsset}}var qe={};ze$1(qe,{getInboundAddresses:()=>Bs,getLastBlock:()=>Hs,getMimirInfo:()=>$s,getNodes:()=>Us,getRunePoolInfo:()=>Ks,getRunePoolProviderInfo:()=>
6175Ws,getTHORNodeTNSDetails:()=>rn,getTNSPreferredAsset:()=>Fs,getTcyClaimer:()=>Ys,getTcyClaimers:()=>js,getTcyStaker:()=>Gs,getTcyStakers:()=>qs,getThorchainQueue:()=>Vs});function L$3(e){let{isStagenet:t}=T.get("envs"),n=T.get("thornodeUrls");return `${M$1({isStagenet:t,type:e}).with({type:"mayachain"},({isStagenet:s})=>s?n.MAYA_STAGENET:n.MAYA).otherwise(({isStagenet:s})=>s?n.THOR_STAGENET:n.THOR)}/${e??"thorchain"}`}function Ls(e){let t=e==="mayachain"?"mayaname":"thorname";return `${L$3(e)}/${t}`}function Hs(e="thorchain"){return m.get(`${L$3(e)}/lastblock`)}function Vs(e){return m.get(`${L$3(e)}/queue`)}function Us(e){return m.get(`${L$3(e)}/nodes`)}function $s(e){return m.get(`${L$3(e)}/mimir`)}function Bs(e){return m.get(`${L$3(e)}/inbound_addresses`)}async function rn({type:e,name:t}){try{return await m.get(`${Ls(e)}/${t}`)}catch{return {affiliate_collector_rune:"",aliases:[],expire_block_height:0,name:t,owner:"",preferred_asset:""}}}async function Fs({type:e,tns:t}){let n=await rn({name:t,type:e});if(!n.preferred_asset||n.preferred_asset===".")return;return D.from({asset:n.preferred_asset,asyncTokenLookup:true})}function Ks(e){return m.get(`${L$3(e)}/runepool`)}function Ws({type:e,thorAddress:t}){return m.get(`${L$3(e)}/rune_provider/${t}`)}function Gs({type:e,address:t}){return m.get(`${L$3(e)}/tcy_staker/${t}`)}function qs(e){return m.get(`${L$3(e)}/tcy_stakers`)}function Ys({type:e,address:t}){return m.get(`${L$3(e)}/tcy_claimer/${t}`)}function js(e){return m.get(`${L$3(e)}/tcy_claimers`)}var zo={...Ge,mayachainMidgard:Et,thorchainMidgard:It,thornode:qe};
6176
6177((a)=>typeof commonjsRequire<"u"?commonjsRequire:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof commonjsRequire<"u"?commonjsRequire:b)[c]}):a)(function(a){if(typeof commonjsRequire<"u")return commonjsRequire.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});
6178
6179var h=["chainflip","flashnet","garden","harbor","jupiter","mayan","mayachain","near","okx","oneinch","pancakeswap","sushiswap","thorchain","traderjoe","uniswap","uniswapv3"];async function c$1(i,o){let s=i||h,n={},r=o?.source||"prod";for(let a of s){let p=await w(a,r);n[a]=p;}return n}async function w(i,o){let{list:s}=await M$1(o).with("prod",()=>L$2(i)).with("dev",()=>k(i)).exhaustive();return s}function L$2(i){return M$1(i).with("chainflip",()=>import('./chunk-y9x7pxn6-5f1pzlu1.js')).with("flashnet",()=>import('./chunk-v6gta5xs-DCjTx5us.js')).with("garden",()=>import('./chunk-5xjvvxs2-6MYQSvzB.js')).with("harbor",()=>import('./chunk-t2aqc3bh-CVcIyYVm.js')).with("jupiter",()=>import('./chunk-8ty6q5pp-FthNgKx7.js')).with("mayan",()=>import('./chunk-y1ht8gtc-QRTEEDkG.js')).with("mayachain",()=>import('./chunk-00nwr93q-BnTOCy2Y.js')).with("near",()=>import('./chunk-ypnp8fnh-CH9mlxzD.js')).with("okx",()=>import('./chunk-nmnnrnm8-mokTs_34.js')).with("oneinch",()=>import('./chunk-ex31df05-DDp47pjY.js')).with("pancakeswap",()=>import('./chunk-wv9a971w-DXFs3Sxw.js')).with("sushiswap",()=>import('./chunk-e4x6x3zy-CbxJxC_-.js')).with("thorchain",()=>import('./chunk-wg5rdrn0-BNOp8pvB.js')).with("traderjoe",()=>import('./chunk-0bhmgpq7-Yik648ce.js')).with("uniswap",()=>import('./chunk-axvjqkqr-Co9fKsks.js')).with("uniswapv3",()=>import('./chunk-v9gcry25-CKEG9kUP.js')).otherwise(()=>(console.warn(`Token list ${i} not found`),{list:[]}))}function k(i){return M$1(i).with("chainflip",()=>import('./chunk-vje6ywb9-DR_lkE9W.js')).with("flashnet",()=>import('./chunk-4y0f9vk5-BWoHegn9.js')).with("garden",()=>import('./chunk-4y36cb9c-93dGmr0x.js')).with("harbor",()=>import('./chunk-44tcfrbk-CQ1GhYoo.js')).with("jupiter",()=>import('./chunk-3nqkahtt-G5EGrj36.js')).with("mayan",()=>import('./chunk-ym2n6g93-DZKt-8wX.js')).with("mayachain",()=>import('./chunk-rfrw9ygh-C3FiSjVn.js')).with("near",()=>import('./chunk-j7v8khfj-Cj9gLCGL.js')).with("okx",()=>import('./chunk-eyfv68yr-E3fmDDtT.js')).with("oneinch",()=>import('./chunk-m00pkp9c-BzFgbQku.js')).with("pancakeswap",()=>import('./chunk-wj8w4akm-DIEW_6c8.js')).with("sushiswap",()=>import('./chunk-0ecmcsc1-BB6Tbf6x.js')).with("thorchain",()=>import('./chunk-hnsr1abz-C_hzdNrF.js')).with("traderjoe",()=>import('./chunk-39zvzj1f-PLPVSvF9.js')).with("uniswap",()=>import('./chunk-bchzf4aa-DgBGbHZH.js')).with("uniswapv3",()=>import('./chunk-srx3mtna-BlII-9mP.js')).otherwise(()=>(console.warn(`Token list ${i} not found`),{list:[]}))}
6180
6181const index$3 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
6182	__proto__: null,
6183	loadTokenLists: c$1
6184}, Symbol.toStringTag, { value: 'Module' }));
6185
6186var L$1={average:1,fast:1.5,fastest:2};function S$1(e="average"){let t=T.get("feeMultipliers");if(t&&t[e]!==void 0)return t[e];return L$1[e]}function B$1(e="average"){let t=S$1(e),n=10n,r=BigInt(Math.round(t*10));return {denominator:n,numerator:r}}function ce(e,t="average"){let{numerator:n,denominator:r}=B$1(t);return e*n/r}function me(e,t="average",n=false){let r=S$1(t),o=e*r;return n?Math.floor(o):o}function g(e,t){let n=e.length-1;return e.map((o,i)=>{if(i===n&&t.index!==void 0)return t.index;if(i===0&&t.purpose!==void 0)return t.purpose;if(i===2&&t.account!==void 0)return t.account;if(i===3&&t.change!==void 0)return t.change;return o}
6186)}var l$1={bech32:84,legacy:44,p2sh:49,taproot:86},C$1;((o)=>{o.P2PKH="P2PKH";o.P2SH_P2WPKH="P2SH_P2WPKH";o.P2WPKH="P2WPKH";o.P2TR="P2TR";})(C$1||={});var K=Object.freeze({["P2PKH"]:{inputSize:148,outputSize:34,purpose:l$1.legacy,witness:false},["P2SH_P2WPKH"]:{inputSize:91,outputSize:32,purpose:l$1.p2sh,witness:true},["P2WPKH"]:{inputSize:68,outputSize:31,purpose:l$1.bech32,witness:true},["P2TR"]:{inputSize:58,outputSize:43,purpose:l$1.taproot,witness:true}}),H=Object.values(C$1);function z$1(e){if(e===void 0)return;return H.find((t)=>K[t].purpose===e)}function V(e){if(!e)return;if(typeof e!=="string")return e[0];let t=Number.parseInt(e.replace(/^[mM]'?\//,"").split("/")[0]??"",10);return Number.isNaN(t)?void 0:t}function ge(e){return z$1(V(e))}var X=Object.freeze([l$3.Near,l$3.Stellar,l$3.Sui]),we=Object.freeze([l$3.Ton]);function j({chain:e,derivationPath:t,index:n=0}){if(t)return t;return g(Qs[e],X.includes(e)?{account:n}:{index:n})}function G([e,t,n,r,o],{allHardened:i}={}){let s=i?"'":"",u=typeof o!=="number";if(typeof r!=="number")return `m/${e}'/${t}'/${n}'`;return `m/${e}'/${t}'/${n}'/${r}${s}${u?"":`/${o}${s}`}`}function Pe({chain:e,index:t,addressIndex:n=0,type:r}){let o=Qs[e],i=We.includes(e)?"evm":e===l$3.Solana?"solana":"other";return M$1([i,r]).with(["evm","legacy"],["evm","account"],()=>[44,60,0,t]).with(["evm","ledgerLive"],()=>[44,60,t,0,n]).with(["evm","nativeSegwitMiddleAccount"],["evm","segwit"],["evm",void 0],()=>g(o,{index:t})).with(["solana","account"],()=>[44,501,0,t]).with(["solana","legacy"],["solana","ledgerLive"],["solana","nativeSegwitMiddleAccount"],["solana","segwit"],["solana",void 0],()=>g(o,{index:t})).with(["other","nativeSegwitMiddleAccount"],()=>g(o,{account:t,index:n,purpose:l$1.bech32})).with(["other","segwit"],()=>g(o,{account:0,index:t,purpose:l$1.p2sh})).with(["other","legacy"],()=>g(o,{account:0,index:t,purpose:l$1.legacy})).with(["other","account"],["other","ledgerLive"],["other",void 0],()=>j({chain:e,index:t})).exhaustive()}function ve(e){let[t,n]=e.split("/").map((r)=>Number.parseInt(r,10));switch(n){case 44:return "legacy";case 49:return "p2sh";default:return "bech32"}}var ye=Object.freeze(Object.fromEntries(Object.keys(Qs).map((e)=>[e,G(Qs[e])])));function Z({liquidityUnits:e,poolUnits:t,runeDepth:n}){let r=c(e),o=c(t),i=c(n),s=r.mul(i),u=o.mul(o).mul(2),a=o.mul(r).mul(2),m=r.mul(r),f=o.mul(o).mul(o);return s.mul(u.sub(a).add(m)).div(f)}function J({liquidityUnits:e,poolUnits:t,assetDepth:n}){let r=c(e),o=c(t),i=c(n),s=r.mul(i),u=o.mul(o).mul(2),a=o.mul(r).mul(2),m=r.mul(r),f=s.mul(u.sub(a).add(m)),w=o.mul(o).mul(o);return f.div(w)}function Ae({percent:e,runeDepth:t,liquidityUnits:n,poolUnits:r}){return Z({liquidityUnits:n,poolUnits:r,runeDepth:t}).mul(e)}function xe({percent:e,assetDepth:t,liquidityUnits:n,poolUnits:r}){return J({assetDepth:t,liquidityUnits:n,poolUnits:r}).mul(e)}function c(e){return Re.fromBigInt(BigInt(e),w$2(l$3.THORChain).baseDecimal)}function Q({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r}){return {assetAmount:c(r).mul(e).div(t),runeAmount:c(n).mul(e).div(t)}}function Se({liquidityUnits:e,poolUnits:t,runeDepth:n,assetDepth:r,percent:o}){return Object.fromEntries(Object.entries(Q({assetDepth:r,liquidityUnits:e,poolUnits:t,runeDepth:n})).map(([i,s])=>[i,s.mul(o)]))}function Ce({runeDepth:e,poolUnits:t,assetDepth:n,liquidityUnits:r,runeAmount:o,assetAmount:i}){let s=new Re({decimal:8,value:e}),u=new Re({decimal:8,value:n}),a=new Re({decimal:8,value:t}),m=new Re({decimal:8,value:o}),f=new Re({decimal:8,value:i}),w=m.mul(u),T=f.mul(s),D=m.mul(f),R=s.mul(u),I=a.mul(w.add(T.add(D.mul(2)))),O=w.add(T.add(R.mul(2))),A=I.div(O),E=c(r).add(A);if(A.getBaseValue("number")===0)return E.div(a).getBaseValue("number");let F=a.add(E);return E.div(F).getBaseValue("number")}function Me({runeAmount:e,assetAmount:t,runeDepth:n,assetDepth:r}){if(e==="0"||t==="0"||n==="0"||r==="0")return 0;let o=c(n),i=c(r),s=c(t),u=c(e),a=s.mul(o).sub(i.mul(u)),m=i.mul(u).add(o.mul(i));return Math.abs(a.div(m).getBaseValue("number"))}function Ie({type:e,address:t}){return `${e}:${t}`}function Oe({address:e,unbondAmount:t}
6186){return `${"UNBOND"}:${e}:${t}`}function Fe(e){return b("POOL+",e)}function Ne({chain:e,symbol:t,address:n,...r}){let o=re({chain:e,symbol:t}),i=n?`:${n}:`:":";return b(`${"+"}:${o}${i}`,r)}function Le({chain:e,symbol:t,ticker:n,basisPoints:r,targetAsset:o}){let i=e==="ETH"&&n!=="ETH"?`${n}-${t.slice(-3)}`:t,s=o?`:${o}`:"";return `${"-"}:${e}.${i}:${r}${s}`}function Be({basisPoints:e,...t}){return b(`${"POOL-"}:${e}`,t)}function ke({name:e,chain:t,address:n,owner:r}){let o=`${"~"}:${e}:${t}:${n}`,i=r?`:${r}`:"";return `${o}${i}`}function Ue({name:e,chain:t,asset:n,payout:r,owner:o}){return `${"~"}:${e}:${t}:${r}:${o}:${n}`}function Ke(e,{address:t}){return `${e}:${t}`}function He(e,{unstakeBps:t,...n}){let r=t?`:${t}`:"",o=`${e}${r}`;return b(`${o}`,n)}function b(e,{affiliateAddress:t,affiliateBasisPoints:n}={}){let r=`${e}${t?`:${t}:${n||0}`:""}`;return r.endsWith(":")?r.slice(0,-1):r}function re({chain:e,symbol:t}){return M$1(e).with(l$3.Bitcoin,l$3.Dogecoin,l$3.Litecoin,()=>e.slice(0,1).toLowerCase()).with(l$3.BitcoinCash,()=>"c").otherwise(()=>`${e}.${t}`)}function ze(e){if(e<0)throw new b$1({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return 10+e}function Ve(e){if(e<0)throw new b$1({errorKey:"helpers_invalid_number_of_years",info:{numberOfYears:e}});return Math.round((10+e*1.0512)*10000000000)/10000000000}function Xe(e){if(e.length>30)return  false;let t=/^[a-zA-Z0-9+_-]+$/g;return !!e.match(t)}function Je(){return typeof window.ethereum<"u"}function Qe(e){return ne().includes(e)}function ne(){let e=window?.ethereum&&!window.ethereum?.isBraveWallet,t=window?.ctrl||window?.ethereum?.__XDEFI,n=window?.vultisig,r=window?.ethereum?.isBraveWallet,o=window?.ethereum?.isTrust||window?.trustwallet,i=window?.ethereum?.overrideIsMetaMask&&window?.ethereum?.selectedProvider?.isCoinbaseWallet||window?.coinbaseWalletExtension,s=window?.bitkeep?.ethereum,u=window?.$onekey?.ethereum,a=[];if(e)a.push(ge$1.METAMASK);if(t)a.push(ge$1.CTRL);if(n)a.push(ge$1.VULTISIG);if(r)a.push(ge$1.BRAVE);if(o)a.push(ge$1.TRUSTWALLET_WEB);if(i)a.push(ge$1.COINBASE_WEB);if(se())a.push(ge$1.OKX_MOBILE);if(s)a.push(ge$1.BITGET);if(u)a.push(ge$1.ONEKEY);return a}async function oe(e,t,n){let r=w$2(t);try{await W({method:"wallet_switchEthereumChain",params:[{chainId:r.chainIdHex}],provider:e});}catch(o){if(!n)throw new b$1("helpers_failed_to_switch_network",{error:o,reason:"networkParams not provided"});await ae(e,n);}}function et({chains:e,supportedChains:t,walletType:n}){let r=e.filter((i)=>!i||t.includes(i));if(r.length===0)throw new b$1("wallet_chain_not_supported",{chain:e.join(", "),wallet:n});let o=e.filter((i)=>!t.includes(i));return Y$1({condition:o.length>0,id:`wallet_chain_not_supported_${n}`,warning:`${n} wallet does not support the following chains: ${o.join(", ")}. These chains will be ignored.`}),r}function ie(e,t,n){return async(...r)=>{let{chainIdHex:o}=w$2(n);if((await t.getNetwork()).chainId.toString()===o)return e(...r);try{await oe(t,n);}catch(i){throw new b$1({errorKey:"helpers_failed_to_switch_network",info:{error:i}})}return e(...r)}}function tt({toolbox:e,chain:t,provider:n,methodNames:r=[]}){let i=[...r,"approve","approvedAmount","call","sendTransaction","transfer","isApproved","approvedAmount","EIP1193SendTransaction","getFeeData","broadcastTransaction","estimateCall","estimateGasLimit","estimateGasPrices","createContractTxObject"].reduce((s,u)=>{if(!e[u])return s;let a=e[u];if(typeof a!=="function")return s;let m=ie(a,n,t);return {...s,[u]:m}},{});return {...e,...i}}function ae(e,t){return W({method:"wallet_addEthereumChain",params:[t],provider:e})}function rt(e){window.ethereum?.on("accountsChanged",()=>e()),window.ctrl?.ethereum.on("accountsChanged",()=>e());}function nt(){let{isTrust:e,isBraveWallet:t,__XDEFI:n,overrideIsMetaMask:r,selectedProvider:o}=window?.ethereum||{};if(e)return ge$1.TRUSTWALLET_WEB;if(t)return ge$1.BRAVE;if(r&&o?.isCoinbaseWallet)return ge$1.COINBASE_WEB;if(n)return ge$1.CTRL;if(window?.$onekey?.ethereum)return ge$1.ONEKEY;return ge$1.METAMASK}function ot(){let e=[];function t(r){if(e.map((o)=>o.info.uuid).includes(r.detail.info.uuid))return;e.push(r.detail);}window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider"));function n(){window.removeEventListener("eip6963:announceProvider",t);}return {providers:e,removeEIP6963EventListener:n}}function se(){let e=navigator.userAgent,t=/iphone|ipad|ipod|ios/i.test(e),n=/android|XiaoMi|MiuiBrowser/i.test(e),r=t||n,o=/OKApp/i.test(e);return r&&o}function W({provider:e,params:t,method:n}){if(!e?.send)throw new b$1("helpers_not_found_provider");let r=t?Array.isArray(t)?t:[t]:[];return e.send(n,r)}
6187
6188const index$2 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
6189	__proto__: null,
6190	ACCOUNT_INDEXED_CHAINS: X,
6191	AllChainConfigs: U$1,
6192	AllChains: Pe$2,
6193	ApiV2ErrorSchema: fo,
6194	ApprovalTransactionSchema: ps,
6195	get ApproveMode () { return gn; },
6196	ApproveRequestParams: No,
6197	ApproveResponseSchema: ko,
6198	AssetValue: D,
6199	AssetValueSchema: ee,
6200	BaseDecimal: An$1,
6201	BigIntArithmetics: F,
6202	BlockTimes: Hn$1,
6203	BrokerDepositChannelParamsSchema: Mr,
6204	get Chain () { return l$3; },
6205	get ChainId () { return m$2; },
6206	ChainIdToChain: vn$1,
6207	ChainToChainId: fn,
6208	ChainflipMetadataSchema: as,
6209	CoinGeckoMetadataSchema: Ut,
6210	CommonAssetStrings: Bi,
6211	CosmosChainConfigs: R$2,
6212	CosmosChainPrefixes: qe$1,
6213	CosmosChains: _e$1,
6214	CosmosTransactionSchema: Jr,
6215	DEFAULT_FEE_MULTIPLIERS: L$1,
6216	DepositChannelParamsSchema: Bt,
6217	DepositChannelResponseSchema: Ft,
6218	DerivationPath: ye,
6219	EVMChainConfigs: O$1,
6220	EVMChains: We,
6221	EVMTransactionDetailsParamsSchema: Yr,
6222	EVMTransactionDetailsSchema: vo,
6223	EVMTransactionSchema: Gr,
6224	EXPLORER_URLS: Un$1,
6225	get ErrorCode () { return ie$1; },
6226	EstimatedTimeSchema: Ke$1,
6227	get FeeOption () { return un; },
6228	get FeeTypeEnum () { return Ne$1; },
6229	FeesSchema: Fe$1,
6230	GAIAConfig: f$1,
6231	GasResponseSchema: Jt,
6232	GasSchema: Qt,
6233	HARBORConfig: v$1,
6234	HYPERCORE_USDC_TOKEN_ID: Co,
6235	HyperCoreEip712TypedDataSchema: ns,
6236	HyperCoreSendAssetActionSchema: rs,
6237	HyperCoreSendAssetTransactionSchema: Io,
6238	HyperCoreTypedDataTransactionSchema: Gt,
6239	KUJIConfig: H$1,
6240	get LedgerErrorCode () { return _n; },
6241	MAYAConfig: k$3,
6242	get MemoType () { return mn; },
6243	NOBLEConfig: D$1,
6244	NODE_URLS: kn$1,
6245	NearDepositChannelParamsSchema: Pt,
6246	NearDepositChannelResultSchema: So,
6247	NearSwapResponseSchema: Kt,
6248	NetworkDerivationPath: Qs,
6249	OtherChainConfigs: g$2,
6250	OtherChains: on,
6251	PriceRequestSchema: Ao,
6252	PriceResponseSchema: $t,
6253	get PriorityLabel () { return Dt; },
6254	get ProviderAction () { return Lt; },
6255	get ProviderName () { return E; },
6256	QuoteRequestSchema: bo,
6257	QuoteResponseRouteItem: cs,
6258	QuoteResponseSchema: zt,
6259	QuoteRouteV2Response: tn,
6260	QuoteV2ResponseSchema: Lo,
6261	QuoteV3ResponseSchema: Oo,
6262	RPC_URLS: gn$1,
6263	RequestClient: m,
6264	RouteLegSchema: is,
6265	RouteLegWithoutAddressesSchema: Eo,
6266	RouteQuoteMetadataAssetSchema: os,
6267	RouteQuoteMetadataSchema: Yt,
6268	RouteQuoteMetadataV2Schema: jt,
6269	RouteQuoteProviderErrorSchema: hs,
6270	get RouteQuoteTxType () { return Ie$1; },
6271	RouteQuoteWarningSchema: Xt,
6272	SINGLE_WALLET_CHAINS: we,
6273	SKConfig: T,
6274	get StagenetChain () { return T$2; },
6275	StagenetChains: un$1,
6276	StagenetCosmosChainConfigs: je,
6277	StagenetCosmosChains: Ve$1,
6278	StagenetHARBORConfig: A$1,
6279	StagenetMAYAConfig: y$1,
6280	StagenetTHORConfig: d$1,
6281	StarknetTransactionSchema: Zr,
6282	StellarApprovalTransactionSchema: us,
6283	SubstrateChainConfigs: P$3,
6284	SubstrateChains: cn$1,
6285	SwapApprovalTransactionSchema: gs,
6286	SwapKitApi: zo,
6287	SwapKitError: b$1,
6288	SwapKitNumber: Re,
6289	SwapRouteV2ResponseSchema: nn,
6290	SwapToAssetSchema: _s,
6291	SwapToRequestSchema: Do,
6292	SwapToResponseSchema: Mo,
6293	TCLikeChains: Ze$1,
6294	THORConfig: u$1,
6295	TONTransactionMessageSchema: es,
6296	TONTransactionSchema: ts,
6297	TokenDetailsMetadataSchema: yo,
6298	TokenSchema: mo,
6299	TrackerResponseSchema: Wt,
6300	TrackingRequestQuerySchema: ho,
6301	TrackingRequestSchema: _o,
6302	get TrackingStatus () { return Vt; },
6303	TransactionDTOSchema: wo,
6304	TransactionSchema: To,
6305	TronTransactionSchema: qr,
6306	get TxnStatus () { return Ht; },
6307	get TxnType () { return Mt; },
6308	UTXOChainConfigs: I$2,
6309	UTXOChains: ln$1,
6310	UTXOPurpose: l$1,
6311	get UTXOScriptType () { return C$1; },
6312	UTXO_SCRIPT_TYPES: K,
6313	UTXO_SCRIPT_TYPE_LIST: H,
6314	WalletOption: ge$1,
6315	get WarningCodeEnum () { return Pe$1; },
6316	_rpcCache: De,
6317	addAccountsChangedCallback: rt,
6318	addEVMWalletNetwork: ae,
6319	applyFeeMultiplier: me,
6320	applyFeeMultiplierToBigInt: ce,
6321	assetFromString: W$1,
6322	decodeABIDynamicString: bt,
6323	decodeABIString: Un,
6324	derivationPathToString: G,
6325	fetchTokenInfo: At,
6326	filterSupportedChains: et,
6327	findAssetBy: Ki,
6328	formatBigIntToSafeValue: X$1,
6329	getAssetType: Me$1,
6330	getAsymmetricAssetShare: J,
6331	getAsymmetricAssetWithdrawAmount: xe,
6332	getAsymmetricRuneShare: Z,
6333	getAsymmetricRuneWithdrawAmount: Ae,
6334	getChainByCoinType: Rn$1,
6335	getChainConfig: w$2,
6336	getChainIdentifier: Pi,
6337	getCoinType: Dn,
6338	getCommonAssetInfo: ye$1,
6339	getDerivationPathFor: Pe,
6340	getEIP6963Wallets: ot,
6341	getETHDefaultWallet: nt,
6342	getEstimatedPoolShare: Ce,
6343	getExplorerAddressUrl: Ei,
6344	getExplorerTxUrl: Ii,
6345	getFeeMultiplier: S$1,
6346	getFeeMultiplierAsBigInt: B$1,
6347	getLiquiditySlippage: Me,
6348	getMAYANameCost: Ve,
6349	getMemoForDeposit: Ne,
6350	getMemoForLeaveAndBond: Ie,
6351	getMemoForNamePreferredAssetRegister: Ue,
6352	getMemoForNameRegister: ke,
6353	getMemoForRunePoolDeposit: Fe,
6354	getMemoForRunePoolWithdraw: Be,
6355	getMemoForTcyClaim: Ke,
6356	getMemoForTcyStake: He,
6357	getMemoForUnbond: Oe,
6358	getMemoForWithdraw: Le,
6359	getMinAmountByChain: to,
6360	getPurposeFromPath: V,
6361	getRPCUrl: j$1,
6362	getRPCUrlSync: kn,
6363	getSymmetricPoolShare: Q,
6364	getSymmetricWithdraw: Se,
6365	getTHORNameCost: ze,
6366	getTokenLogoURI: Fi,
6367	getUTXOScriptTypeForPath: ge,
6368	getUTXOScriptTypeForPurpose: z$1,
6369	getWalletFormatFor: ve,
6370	initializeRPCUrlsWithFallback: Ci,
6371	isDetected: Qe,
6372	isGasAsset: St,
6373	isTransactionValue: Wr,
6374	isWeb3Detected: Je,
6375	listWeb3EVMWallets: ne,
6376	loadTokenLists: c$1,
6377	okxMobileEnabled: se,
6378	parseSymbolForAddress: ae$1,
6379	parseTransactionValue: xo,
6380	prepareNetworkSwitch: tt,
6381	providerRequest: W,
6382	registerErrorCodes: ti,
6383	registerWalletOption: si,
6384	resolveDerivationPath: j,
6385	signWidgetRequest: it,
6386	subscribeWalletOptionRegistration: Ze,
6387	swapKitConfigStore: P$1,
6388	switchEVMWalletNetwork: oe,
6389	toHexTransactionValue: Ro,
6390	updateDerivationPath: g,
6391	validateIdentifier: zn,
6392	validateTNS: Xe,
6393	warnOnce: Y$1,
6394	wrapMethodWithNetworkSwitch: ie,
6395	wrapWithThrow: Ai
6396}, Symbol.toStringTag, { value: 'Module' }));
6397
6398function l({connect:e,directSigningSupport:n,getExtendedPublicKey:r,name:p,supportedChains:t,walletType:o}){let a=n??{};function d({addChain:c}){return e({addChain:(i)=>c({supportsDirectSigning:a[i.chain]??false,...i}),supportedChains:t,walletType:o})}return {[p]:{connectWallet:d,directSigningSupport:a,getExtendedPublicKey:r,supportedChains:t}}}function s(e){let n=Object.keys(e)?.[0]||"";return e?.[n]?.supportedChains||[]}
6399
6400/**
6401 * HMAC: RFC2104 message authentication code.
6402 * @module
6403 */
6404/**
6405 * Internal class for HMAC.
6406 * Accepts any byte key, although RFC 2104 §3 recommends keys at least
6407 * `HashLen` bytes long.
6408 */
6409class _HMAC {
6410    oHash;
6411    iHash;
6412    blockLen;
6413    outputLen;
6414    canXOF = false;
6415    finished = false;
6416    destroyed = false;
6417    constructor(hash, key) {
6418        ahash(hash);
6419        abytes$1(key, undefined, 'key');
6420        this.iHash = hash.create();
6421        if (typeof this.iHash.update !== 'function')
6422            throw new Error('Expected instance of class which extends utils.Hash');
6423        this.blockLen = this.iHash.blockLen;
6424        this.outputLen = this.iHash.outputLen;
6425        const blockLen = this.blockLen;
6426        const pad = new Uint8Array(blockLen);
6427        // blockLen can be bigger than outputLen
6428        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
6429        for (let i = 0; i < pad.length; i++)
6430            pad[i] ^= 0x36;
6431        this.iHash.update(pad);
6432        // By doing update (processing of the first block) of the outer hash here,
6433        // we can re-use it between multiple calls via clone.
6434        this.oHash = hash.create();
6435        // Undo internal XOR && apply outer XOR
6436        for (let i = 0; i < pad.length; i++)
6437            pad[i] ^= 0x36 ^ 0x5c;
6438        this.oHash.update(pad);
6439        clean(pad);
6440    }
6441    update(buf) {
6442        aexists(this);
6443        this.iHash.update(buf);
6444        return this;
6445    }
6446    digestInto(out) {
6447        aexists(this);
6448        aoutput(out, this);
6449        this.finished = true;
6450        const buf = out.subarray(0, this.outputLen);
6451        // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
6452        // overwriting that same prefix with the final tag, leaving any oversized tail untouched.
6453        this.iHash.digestInto(buf);
6454        this.oHash.update(buf);
6455        this.oHash.digestInto(buf);
6456        this.destroy();
6457    }
6458    digest() {
6459        const out = new Uint8Array(this.oHash.outputLen);
6460        this.digestInto(out);
6461        return out;
6462    }
6463    _cloneInto(to) {
6464        // Create new instance without calling constructor since the key
6465        // is already in state and we don't know it.
6466        to ||= Object.create(Object.getPrototypeOf(this), {});
6467        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
6468        to = to;
6469        to.finished = finished;
6470        to.destroyed = destroyed;
6471        to.blockLen = blockLen;
6472        to.outputLen = outputLen;
6473        to.oHash = oHash._cloneInto(to.oHash);
6474        to.iHash = iHash._cloneInto(to.iHash);
6475        return to;
6476    }
6477    clone() {
6478        return this._cloneInto();
6479    }
6480    destroy() {
6481        this.destroyed = true;
6482        this.oHash.destroy();
6483        this.iHash.destroy();
6484    }
6485}
6486const hmac = /* @__PURE__ */ (() => {
6487    const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
6488    hmac_.create = (hash, key) => new _HMAC(hash, key);
6489    return hmac_;
6490})();
6491
6492/**
6493 * PBKDF (RFC 2898). Can be used to create a key from password and salt.
6494 * @module
6495 */
6496// Common start and end for sync/async functions
6497function pbkdf2Init(hash, _password, _salt, _opts) {
6498    ahash(hash);
6499    const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
6500    const { c, dkLen, asyncTick } = opts;
6501    anumber$1(c, 'c');
6502    anumber$1(dkLen, 'dkLen');
6503    anumber$1(asyncTick, 'asyncTick');
6504    if (c < 1)
6505        throw new Error('iterations (c) must be >= 1');
6506    // RFC 8018 §5.2 defines `dkLen` as "a positive integer".
6507    if (dkLen < 1)
6508        throw new Error('"dkLen" must be >= 1');
6509    // RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen`
6510    // before allocating the destination buffer.
6511    if (dkLen > (2 ** 32 - 1) * hash.outputLen)
6512        throw new Error('derived key too long');
6513    const password = kdfInputToBytes(_password, 'password');
6514    const salt = kdfInputToBytes(_salt, 'salt');
6515    // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
6516    const DK = new Uint8Array(dkLen);
6517    // U1 = PRF(Password, Salt + INT_32_BE(i))
6518    const PRF = hmac.create(hash, password);
6519    // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).
6520    const PRFSalt = PRF._cloneInto().update(salt);
6521    return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
6522}
6523function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
6524    // Shared sync/async cleanup point: wipe transient PRF state
6525    // while preserving the derived key buffer.
6526    PRF.destroy();
6527    PRFSalt.destroy();
6528    if (prfW)
6529        prfW.destroy();
6530    clean(u);
6531    return DK;
6532}
6533/**
6534 * PBKDF2-HMAC: RFC 8018 key derivation function.
6535 * @param hash - hash function that would be used e.g. sha256
6536 * @param password - password from which a derived key is generated;
6537 *   JS string inputs are UTF-8 encoded first
6538 * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first
6539 * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
6540 *   must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.
6541 * @returns Derived key bytes.
6542 * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}
6543 * @example
6544 * PBKDF2-HMAC: RFC 2898 key derivation function.
6545 * ```ts
6546 * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';
6547 * import { sha256 } from '@noble/hashes/sha2.js';
6548 * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
6549 * ```
6550 */
6551function pbkdf2$1(hash, password, salt, opts) {
6552    const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
6553    let prfW; // Working copy
6554    const arr = new Uint8Array(4);
6555    const view = createView(arr);
6556    const u = new Uint8Array(PRF.outputLen);
6557    // DK = T1 + T2 + ⋯ + Tdklen/hlen
6558    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
6559        // Ti = F(Password, Salt, c, i)
6560        // The last Ti view can be shorter than hLen, which applies
6561        // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.
6562        const Ti = DK.subarray(pos, pos + PRF.outputLen);
6563        view.setInt32(0, ti, false);
6564        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
6565        // U1 = PRF(Password, Salt + INT_32_BE(i))
6566        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
6567        Ti.set(u.subarray(0, Ti.length));
6568        for (let ui = 1; ui < c; ui++) {
6569            // Uc = PRF(Password, Uc−1)
6570            PRF._cloneInto(prfW).update(u).digestInto(u);
6571            for (let i = 0; i < Ti.length; i++)
6572                Ti[i] ^= u[i];
6573        }
6574    }
6575    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
6576}
6577/**
6578 * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.
6579 * @param hash - hash function that would be used e.g. sha256
6580 * @param password - password from which a derived key is generated;
6581 *   JS string inputs are UTF-8 encoded first
6582 * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first
6583 * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
6584 *   must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local
6585 *   scheduler-yield knob for this JS wrapper, not part of RFC 8018.
6586 *   See {@link Pbkdf2Opt}.
6587 * @returns Promise resolving to derived key bytes.
6588 * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}
6589 * @example
6590 * PBKDF2-HMAC: RFC 2898 key derivation function.
6591 * ```ts
6592 * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';
6593 * import { sha256 } from '@noble/hashes/sha2.js';
6594 * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
6595 * ```
6596 */
6597async function pbkdf2Async(hash, password, salt, opts) {
6598    const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
6599    let prfW; // Working copy
6600    const arr = new Uint8Array(4);
6601    const view = createView(arr);
6602    const u = new Uint8Array(PRF.outputLen);
6603    // DK = T1 + T2 + ⋯ + Tdklen/hlen
6604    for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
6605        // Ti = F(Password, Salt, c, i)
6606        // The last Ti view can be shorter than hLen, which applies
6607        // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.
6608        const Ti = DK.subarray(pos, pos + PRF.outputLen);
6609        view.setInt32(0, ti, false);
6610        // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
6611        // U1 = PRF(Password, Salt + INT_32_BE(i))
6612        (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
6613        Ti.set(u.subarray(0, Ti.length));
6614        await asyncLoop(c - 1, asyncTick, () => {
6615            // Uc = PRF(Password, Uc−1)
6616            PRF._cloneInto(prfW).update(u).digestInto(u);
6617            for (let i = 0; i < Ti.length; i++)
6618                Ti[i] ^= u[i];
6619        });
6620    }
6621    return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
6622}
6623
6624/**
6625 * Internal Merkle-Damgard hash utils.
6626 * @module
6627 */
6628/**
6629 * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
6630 * Returns bits from `b` when `a` is set, otherwise from `c`.
6631 * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
6632 * set the same bit.
6633 * @param a - selector word
6634 * @param b - word chosen when selector bit is set
6635 * @param c - word chosen when selector bit is clear
6636 * @returns Mixed 32-bit word.
6637 * @example
6638 * Combine three words with the shared 32-bit choice primitive.
6639 * ```ts
6640 * Chi(0xffffffff, 0x12345678, 0x87654321);
6641 * ```
6642 */
6643function Chi(a, b, c) {
6644    return (a & b) ^ (~a & c);
6645}
6646/**
6647 * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
6648 * Returns bits shared by at least two inputs.
6649 * @param a - first input word
6650 * @param b - second input word
6651 * @param c - third input word
6652 * @returns Mixed 32-bit word.
6653 * @example
6654 * Combine three words with the shared 32-bit majority primitive.
6655 * ```ts
6656 * Maj(0xffffffff, 0x12345678, 0x87654321);
6657 * ```
6658 */
6659function Maj(a, b, c) {
6660    return (a & b) ^ (a & c) ^ (b & c);
6661}
6662/**
6663 * Merkle-Damgard hash construction base class.
6664 * Could be used to create MD5, RIPEMD, SHA1, SHA2.
6665 * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
6666 * strings with partial-byte tails.
6667 * @param blockLen - internal block size in bytes
6668 * @param outputLen - digest size in bytes
6669 * @param padOffset - trailing length field size in bytes
6670 * @param isLE - whether length and state words are encoded in little-endian
6671 * @example
6672 * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
6673 * ```ts
6674 * import { _SHA1 } from '@noble/hashes/legacy.js';
6675 * const hash = new _SHA1();
6676 * hash.update(new Uint8Array([97, 98, 99]));
6677 * hash.digest();
6678 * ```
6679 */
6680class HashMD {
6681    blockLen;
6682    outputLen;
6683    canXOF = false;
6684    padOffset;
6685    isLE;
6686    // For partial updates less than block size
6687    buffer;
6688    view;
6689    finished = false;
6690    length = 0;
6691    pos = 0;
6692    destroyed = false;
6693    constructor(blockLen, outputLen, padOffset, isLE) {
6694        this.blockLen = blockLen;
6695        this.outputLen = outputLen;
6696        this.padOffset = padOffset;
6697        this.isLE = isLE;
6698        this.buffer = new Uint8Array(blockLen);
6699        this.view = createView(this.buffer);
6700    }
6701    update(data) {
6702        aexists(this);
6703        abytes$1(data);
6704        const { view, buffer, blockLen } = this;
6705        const len = data.length;
6706        for (let pos = 0; pos < len;) {
6707            const take = Math.min(blockLen - this.pos, len - pos);
6708            // Fast path only when there is no buffered partial block: `take === blockLen` implies
6709            // `this.pos === 0`, so we can process full blocks directly from the input view.
6710            if (take === blockLen) {
6711                const dataView = createView(data);
6712                for (; blockLen <= len - pos; pos += blockLen)
6713                    this.process(dataView, pos);
6714                continue;
6715            }
6716            buffer.set(data.subarray(pos, pos + take), this.pos);
6717            this.pos += take;
6718            pos += take;
6719            if (this.pos === blockLen) {
6720                this.process(view, 0);
6721                this.pos = 0;
6722            }
6723        }
6724        this.length += data.length;
6725        this.roundClean();
6726        return this;
6727    }
6728    digestInto(out) {
6729        aexists(this);
6730        aoutput(out, this);
6731        this.finished = true;
6732        // Padding
6733        // We can avoid allocation of buffer for padding completely if it
6734        // was previously not allocated here. But it won't change performance.
6735        const { buffer, view, blockLen, isLE } = this;
6736        let { pos } = this;
6737        // append the bit '1' to the message
6738        buffer[pos++] = 0b10000000;
6739        clean(this.buffer.subarray(pos));
6740        // we have less than padOffset left in buffer, so we cannot put length in
6741        // current block, need process it and pad again
6742        if (this.padOffset > blockLen - pos) {
6743            this.process(view, 0);
6744            pos = 0;
6745        }
6746        // Pad until full block byte with zeros
6747        for (let i = pos; i < blockLen; i++)
6748            buffer[i] = 0;
6749        // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
6750        // the padding fill above, and JS will overflow before user input can make that half non-zero.
6751        // So we only need to write the low 64 bits here.
6752        view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
6753        this.process(view, 0);
6754        const oview = createView(out);
6755        const len = this.outputLen;
6756        // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
6757        if (len % 4)
6758            throw new Error('_sha2: outputLen must be aligned to 32bit');
6759        const outLen = len / 4;
6760        const state = this.get();
6761        if (outLen > state.length)
6762            throw new Error('_sha2: outputLen bigger than state');
6763        for (let i = 0; i < outLen; i++)
6764            oview.setUint32(4 * i, state[i], isLE);
6765    }
6766    digest() {
6767        const { buffer, outputLen } = this;
6768        this.digestInto(buffer);
6769        // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
6770        // fresh bytes to the caller.
6771        const res = buffer.slice(0, outputLen);
6772        this.destroy();
6773        return res;
6774    }
6775    _cloneInto(to) {
6776        to ||= new this.constructor();
6777        to.set(...this.get());
6778        const { blockLen, buffer, length, finished, destroyed, pos } = this;
6779        to.destroyed = destroyed;
6780        to.finished = finished;
6781        to.length = length;
6782        to.pos = pos;
6783        // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
6784        // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
6785        if (length % blockLen)
6786            to.buffer.set(buffer);
6787        return to;
6788    }
6789    clone() {
6790        return this._cloneInto();
6791    }
6792}
6793/**
6794 * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
6795 * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
6796 */
6797/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
6798 * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
6799 * it as read-only because constructors copy words from it by index. */
6800const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
vendor: 4,428 bytes, lines 6801-6898
6801    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
6802]);
6803/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
6804 * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
6805 * eight prime numbers. Exported as a shared table; callers must treat it as read-only because
6806 * constructors copy halves from it by index. */
6807const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
6808    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
6809    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
6810]);
6811
6812/**
6813 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
6814 * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
6815 * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
6816 * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
6817 * @module
6818 */
6819/**
6820 * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
6821 * of the cube roots of the first 64 primes (2..311).
6822 */
6823// prettier-ignore
6824const SHA256_K = /* @__PURE__ */ Uint32Array.from([
6825    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
6826    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
6827    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
6828    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
6829    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
6830    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
6831    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
6832    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
6833]);
6834/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
6835const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
6836/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
6837class SHA2_32B extends HashMD {
6838    constructor(outputLen) {
6839        super(64, outputLen, 8, false);
6840    }
6841    get() {
6842        const { A, B, C, D, E, F, G, H } = this;
6843        return [A, B, C, D, E, F, G, H];
6844    }
6845    // prettier-ignore
6846    set(A, B, C, D, E, F, G, H) {
6847        this.A = A | 0;
6848        this.B = B | 0;
6849        this.C = C | 0;
6850        this.D = D | 0;
6851        this.E = E | 0;
6852        this.F = F | 0;
6853        this.G = G | 0;
6854        this.H = H | 0;
6855    }
6856    process(view, offset) {
6857        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
6858        for (let i = 0; i < 16; i++, offset += 4)
6859            SHA256_W[i] = view.getUint32(offset, false);
6860        for (let i = 16; i < 64; i++) {
6861            const W15 = SHA256_W[i - 15];
6862            const W2 = SHA256_W[i - 2];
6863            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
6864            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
6865            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
6866        }
6867        // Compression function main loop, 64 rounds
6868        let { A, B, C, D, E, F, G, H } = this;
6869        for (let i = 0; i < 64; i++) {
6870            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
6871            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
6872            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
6873            const T2 = (sigma0 + Maj(A, B, C)) | 0;
6874            H = G;
6875            G = F;
6876            F = E;
6877            E = (D + T1) | 0;
6878            D = C;
6879            C = B;
6880            B = A;
6881            A = (T1 + T2) | 0;
6882        }
6883        // Add the compressed chunk to the current hash value
6884        A = (A + this.A) | 0;
6885        B = (B + this.B) | 0;
6886        C = (C + this.C) | 0;
6887        D = (D + this.D) | 0;
6888        E = (E + this.E) | 0;
6889        F = (F + this.F) | 0;
6890        G = (G + this.G) | 0;
6891        H = (H + this.H) | 0;
6892        this.set(A, B, C, D, E, F, G, H);
6893    }
6894    roundClean() {
6895        clean(SHA256_W);
6896    }
6897    destroy() {
6898        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
6899        // update()/digest() callable on reused instances.
6900        this.destroyed = true;
6901        this.set(0, 0, 0, 0, 0, 0, 0, 0);
6902        clean(this.buffer);
6903    }
6904}
6905/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
6906class _SHA256 extends SHA2_32B {
6907    // We cannot use array here since array allows indexing by variable
6908    // which means optimizer/compiler cannot use registers.
6909    A = SHA256_IV[0] | 0;
6910    B = SHA256_IV[1] | 0;
6911    C = SHA256_IV[2] | 0;
6912    D = SHA256_IV[3] | 0;
6913    E = SHA256_IV[4] | 0;
6914    F = SHA256_IV[5] | 0;
6915    G = SHA256_IV[6] | 0;
6916    H = SHA256_IV[7] | 0;
6917    constructor() {
6918        super(32);
6919    }
6920}
6921// SHA2-512 is slower than sha256 in js because u64 operations are slow.
6922// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:
6923// 80 full 64-bit words split into high/low halves.
6924// prettier-ignore
6925const K512 = /* @__PURE__ */ (() => split([
6926    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
6927    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
6928    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
6929    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
6930    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
6931    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
6932    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
6933    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
6934    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
6935    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
6936    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
6937    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
6938    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
6939    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
6940    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
6941    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
6942    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
6943    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
6944    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
6945    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
6946].map(n => BigInt(n))))();
6947const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
6948const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
6949// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.
6950const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
6951// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.
6952const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
6953/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
6954class SHA2_64B extends HashMD {
6955    constructor(outputLen) {
6956        super(128, outputLen, 16, false);
6957    }
6958    // prettier-ignore
6959    get() {
6960        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
6961        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
6962    }
6963    // prettier-ignore
6964    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
6965        this.Ah = Ah | 0;
6966        this.Al = Al | 0;
6967        this.Bh = Bh | 0;
6968        this.Bl = Bl | 0;
6969        this.Ch = Ch | 0;
6970        this.Cl = Cl | 0;
6971        this.Dh = Dh | 0;
6972        this.Dl = Dl | 0;
6973        this.Eh = Eh | 0;
6974        this.El = El | 0;
6975        this.Fh = Fh | 0;
6976        this.Fl = Fl | 0;
6977        this.Gh = Gh | 0;
6978        this.Gl = Gl | 0;
6979        this.Hh = Hh | 0;
6980        this.Hl = Hl | 0;
6981    }
6982    process(view, offset) {
6983        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
6984        for (let i = 0; i < 16; i++, offset += 4) {
6985            SHA512_W_H[i] = view.getUint32(offset);
6986            SHA512_W_L[i] = view.getUint32((offset += 4));
6987        }
6988        for (let i = 16; i < 80; i++) {
6989            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
6990            const W15h = SHA512_W_H[i - 15] | 0;
6991            const W15l = SHA512_W_L[i - 15] | 0;
6992            const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
6993            const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
6994            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
6995            const W2h = SHA512_W_H[i - 2] | 0;
6996            const W2l = SHA512_W_L[i - 2] | 0;
6997            const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
6998            const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
6999            // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];
7000            const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
7001            const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
7002            SHA512_W_H[i] = SUMh | 0;
7003            SHA512_W_L[i] = SUMl | 0;
7004        }
7005        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
7006        // Compression function main loop, 80 rounds
7007        for (let i = 0; i < 80; i++) {
7008            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
7009            const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
7010            const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
7011            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
7012            const CHIh = (Eh & Fh) ^ (~Eh & Gh);
7013            const CHIl = (El & Fl) ^ (~El & Gl);
7014            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
7015            // prettier-ignore
7016            const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
7017            const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
7018            const T1l = T1ll | 0;
7019            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
7020            const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
7021            const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
7022            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
7023            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
7024            Hh = Gh | 0;
7025            Hl = Gl | 0;
7026            Gh = Fh | 0;
7027            Gl = Fl | 0;
7028            Fh = Eh | 0;
7029            Fl = El | 0;
7030            ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
7031            Dh = Ch | 0;
7032            Dl = Cl | 0;
7033            Ch = Bh | 0;
7034            Cl = Bl | 0;
7035            Bh = Ah | 0;
7036            Bl = Al | 0;
7037            const All = add3L(T1l, sigma0l, MAJl);
7038            Ah = add3H(All, T1h, sigma0h, MAJh);
7039            Al = All | 0;
7040        }
7041        // Add the compressed chunk to the current hash value
7042        ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
7043        ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
7044        ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
7045        ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
7046        ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
7047        ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
7048        ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
7049        ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
7050        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
7051    }
7052    roundClean() {
7053        clean(SHA512_W_H, SHA512_W_L);
7054    }
7055    destroy() {
7056        // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
7057        // update()/digest() callable on reused instances.
7058        this.destroyed = true;
7059        clean(this.buffer);
7060        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
7061    }
7062}
7063/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
7064class _SHA512 extends SHA2_64B {
7065    Ah = SHA512_IV[0] | 0;
7066    Al = SHA512_IV[1] | 0;
7067    Bh = SHA512_IV[2] | 0;
7068    Bl = SHA512_IV[3] | 0;
7069    Ch = SHA512_IV[4] | 0;
7070    Cl = SHA512_IV[5] | 0;
7071    Dh = SHA512_IV[6] | 0;
7072    Dl = SHA512_IV[7] | 0;
7073    Eh = SHA512_IV[8] | 0;
7074    El = SHA512_IV[9] | 0;
7075    Fh = SHA512_IV[10] | 0;
7076    Fl = SHA512_IV[11] | 0;
7077    Gh = SHA512_IV[12] | 0;
7078    Gl = SHA512_IV[13] | 0;
7079    Hh = SHA512_IV[14] | 0;
7080    Hl = SHA512_IV[15] | 0;
7081    constructor() {
7082        super(64);
7083    }
7084}
7085/**
7086 * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
7087 *
7088 * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
7089 * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
7090 * - Each sha256 hash is executing 2^18 bit operations.
7091 * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
7092 * @param msg - message bytes to hash
7093 * @returns Digest bytes.
7094 * @example
7095 * Hash a message with SHA2-256.
7096 * ```ts
7097 * sha256(new Uint8Array([97, 98, 99]));
7098 * ```
7099 */
7100const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), 
7101/* @__PURE__ */ oidNist(0x01));
7102/**
7103 * SHA2-512 hash function from RFC 4634.
7104 * @param msg - message bytes to hash
7105 * @returns Digest bytes.
7106 * @example
7107 * Hash a message with SHA2-512.
7108 * ```ts
7109 * sha512(new Uint8Array([97, 98, 99]));
7110 * ```
7111 */
7112const sha512$1 = /* @__PURE__ */ createHasher(() => new _SHA512(), 
7113/* @__PURE__ */ oidNist(0x03));
7114
7115function _subtle() {
7116    const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
7117    const sb = cr?.subtle;
7118    if (typeof sb === 'object' && sb != null)
7119        return sb;
7120    throw new Error('crypto.subtle must be defined');
7121}
7122function createWebHash(name, blockLen, outputLen) {
7123    const hashC = async (msg) => {
7124        abytes$1(msg);
7125        const crypto = _subtle();
7126        return new Uint8Array(await crypto.digest(name, msg));
7127    };
7128    hashC.webCryptoName = name; // make sure it won't interfere with function name
7129    hashC.outputLen = outputLen;
7130    hashC.blockLen = blockLen;
7131    hashC.create = () => {
7132        // Present only so this async wrapper satisfies the shared
7133        // hash-wrapper shape checked by `ahashWeb()`.
7134        throw new Error('not implemented');
7135    };
7136    // Later WebCrypto HMAC/HKDF/PBKDF2 calls read descriptor metadata directly, so freezing prevents
7137    // callers from retargeting a `sha256` wrapper into a different backend digest by mutation.
7138    return Object.freeze(hashC);
7139}
7140function ahashWeb(hash) {
7141    ahash(hash);
7142    if (typeof hash.webCryptoName !== 'string')
7143        throw new Error('non-web hash');
7144}
7145/**
7146 * WebCrypto SHA2-512 hash function from RFC 6234.
7147 * @param msg - message bytes to hash
7148 * @returns Promise resolving to digest bytes.
7149 * @example
7150 * Hash a message with WebCrypto SHA2-512.
7151 * ```ts
7152 * await sha512(new Uint8Array([97, 98, 99]));
7153 * ```
7154 */
7155const sha512 = /* @__PURE__ */ createWebHash('SHA-512', 128, 64);
7156/**
7157 * WebCrypto PBKDF2-HMAC: RFC 8018 key derivation function.
7158 * @param hash - hash function that would be used e.g. sha256. Webcrypto version.
7159 * @param password - password from which a derived key is generated; string
7160 *   inputs are normalized through `kdfInputToBytes()`, i.e. UTF-8
7161 * @param salt - cryptographic salt; string inputs are normalized through
7162 *   `kdfInputToBytes()`, i.e. UTF-8
7163 * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
7164 *   must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.
7165 * @returns Promise resolving to derived key bytes.
7166 * Positive-iteration enforcement is currently delegated to backend
7167 * `deriveBits()` rejection (for example `c = 0`), not a dedicated
7168 * library-side guard.
7169 * @throws If the current runtime does not provide `crypto.subtle`. {@link Error}
7170 * @example
7171 * WebCrypto PBKDF2-HMAC: RFC 2898 key derivation function.
7172 * ```ts
7173 * import { pbkdf2, sha256 } from '@noble/hashes/webcrypto.js';
7174 * const key = await pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
7175 * ```
7176 */
7177async function pbkdf2(hash, password, salt, opts) {
7178    const crypto = _subtle();
7179    ahashWeb(hash);
7180    const _opts = checkOpts({ dkLen: 32 }, opts);
7181    const { c, dkLen } = _opts;
7182    anumber$1(c, 'c');
7183    anumber$1(dkLen, 'dkLen');
7184    // RFC 8018 §5.2 defines dkLen as a positive integer.
7185    if (dkLen < 1)
7186        throw new Error('"dkLen" must be >= 1');
7187    const _password = kdfInputToBytes(password, 'password');
7188    const _salt = kdfInputToBytes(salt, 'salt');
7189    const key = await crypto.importKey('raw', _password, 'PBKDF2', false, [
7190        'deriveBits',
7191    ]);
7192    const deriveOpts = { name: 'PBKDF2', salt: _salt, iterations: c, hash: hash.webCryptoName };
7193    return new Uint8Array(await crypto.deriveBits(deriveOpts, key, 8 * dkLen));
7194}
7195
7196/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7197function isBytes(a) {
7198    // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The
7199    // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized
7200    // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the
7201    // fallback on byte-oriented views.
7202    return (a instanceof Uint8Array ||
7203        (ArrayBuffer.isView(a) &&
7204            a.constructor.name === 'Uint8Array' &&
7205            'BYTES_PER_ELEMENT' in a &&
7206            a.BYTES_PER_ELEMENT === 1));
7207}
7208/** Asserts something is Uint8Array. */
7209function abytes(b) {
7210    if (!isBytes(b))
7211        throw new TypeError('Uint8Array expected');
7212}
7213function isArrayOf(isString, arr) {
7214    if (!Array.isArray(arr))
7215        return false;
7216    if (arr.length === 0)
7217        return true;
7218    if (isString) {
7219        return arr.every((item) => typeof item === 'string');
7220    }
7221    else {
7222        return arr.every((item) => Number.isSafeInteger(item));
7223    }
7224}
7225function afn(input) {
7226    if (typeof input !== 'function')
7227        throw new TypeError('function expected');
7228    return true;
7229}
7230function astr(label, input) {
7231    if (typeof input !== 'string')
7232        throw new TypeError(`${label}: string expected`);
7233    return true;
7234}
7235function anumber(n) {
7236    if (typeof n !== 'number')
7237        throw new TypeError(`number expected, got ${typeof n}`);
7238    if (!Number.isSafeInteger(n))
7239        throw new RangeError(`invalid integer: ${n}`);
7240}
7241function aArr(input) {
7242    if (!Array.isArray(input))
7243        throw new TypeError('array expected');
7244}
7245function astrArr(label, input) {
7246    if (!isArrayOf(true, input))
7247        throw new TypeError(`${label}: array of strings expected`);
7248}
7249function anumArr(label, input) {
7250    if (!isArrayOf(false, input))
7251        throw new TypeError(`${label}: array of numbers expected`);
7252}
7253/**
7254 * @__NO_SIDE_EFFECTS__
7255 */
7256function chain(...args) {
7257    const id = (a) => a;
7258    // Wrap call in closure so JIT can inline calls
7259    const wrap = (a, b) => (c) => a(b(c));
7260    // Construct chain of args[-1].encode(args[-2].encode([...]))
7261    const encode = args.map((x) => x.encode).reduceRight(wrap, id);
7262    // Construct chain of args[0].decode(args[1].decode(...))
7263    const decode = args.map((x) => x.decode).reduce(wrap, id);
7264    return { encode, decode };
7265}
7266/**
7267 * Encodes integer radix representation to array of strings using alphabet and back.
7268 * Could also be array of strings.
7269 * @__NO_SIDE_EFFECTS__
7270 */
7271function alphabet(letters) {
7272    // mapping 1 to "b"
7273    const lettersA = typeof letters === 'string' ? letters.split('') : letters;
7274    const len = lettersA.length;
7275    astrArr('alphabet', lettersA);
7276    // mapping "b" to 1
7277    const indexes = new Map(lettersA.map((l, i) => [l, i]));
7278    return {
7279        encode: (digits) => {
7280            aArr(digits);
7281            return digits.map((i) => {
7282                if (!Number.isSafeInteger(i) || i < 0 || i >= len)
7283                    throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
7284                return lettersA[i];
7285            });
7286        },
7287        decode: (input) => {
7288            aArr(input);
7289            return input.map((letter) => {
7290                astr('alphabet.decode', letter);
7291                const i = indexes.get(letter);
7292                if (i === undefined)
7293                    throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
7294                return i;
7295            });
7296        },
7297    };
7298}
7299/**
7300 * @__NO_SIDE_EFFECTS__
7301 */
7302function join(separator = '') {
7303    astr('join', separator);
7304    // join('') is only lossless when each chunk is already unamb
7304iguous, such as single-symbol alphabets.
7305    // Multi-character tokens need a separator that cannot appear inside the chunks.
7306    return {
7307        encode: (from) => {
7308            astrArr('join.decode', from);
7309            return from.join(separator);
7310        },
7311        decode: (to) => {
7312            astr('join.decode', to);
7313            return to.split(separator);
7314        },
7315    };
7316}
7317/**
7318 * Pad strings array so it has integer number of bits
7319 * @__NO_SIDE_EFFECTS__
7320 */
7321function padding(bits, chr = '=') {
7322    anumber(bits);
7323    astr('padding', chr);
7324    return {
7325        encode(data) {
7326            astrArr('padding.encode', data);
7327            // Mutates the intermediate token array in place while appending pad chars.
7328            // utils.padding callers that need to preserve their input should pass a copy.
7329            while ((data.length * bits) % 8)
7330                data.push(chr);
7331            return data;
7332        },
7333        decode(input) {
7334            astrArr('padding.decode', input);
7335            let end = input.length;
7336            if ((end * bits) % 8)
7337                throw new Error('padding: invalid, string should have whole number of bytes');
7338            for (; end > 0 && input[end - 1] === chr; end--) {
7339                const last = end - 1;
7340                const byte = last * bits;
7341                if (byte % 8 === 0)
7342                    throw new Error('padding: invalid, string has too much padding');
7343            }
7344            return input.slice(0, end);
7345        },
7346    };
7347}
7348/**
7349 * @__NO_SIDE_EFFECTS__
7350 */
7351function normalize$1(fn) {
7352    afn(fn);
7353    return { encode: (from) => from, decode: (to) => fn(to) };
7354}
7355/**
7356 * Slow: O(n^2) time complexity
7357 */
7358function convertRadix(data, from, to) {
7359    // base 1 is impossible
7360    if (from < 2)
7361        throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);
7362    if (to < 2)
7363        throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);
7364    aArr(data);
7365    if (!data.length)
7366        return [];
7367    let pos = 0;
7368    const res = [];
7369    const digits = Array.from(data, (d) => {
7370        anumber(d);
7371        if (d < 0 || d >= from)
7372            throw new Error(`invalid integer: ${d}`);
7373        return d;
7374    });
7375    const dlen = digits.length;
7376    while (true) {
7377        let carry = 0;
7378        let done = true;
7379        for (let i = pos; i < dlen; i++) {
7380            const digit = digits[i];
7381            const fromCarry = from * carry;
7382            const digitBase = fromCarry + digit;
7383            if (!Number.isSafeInteger(digitBase) ||
7384                fromCarry / from !== carry ||
7385                digitBase - digit !== fromCarry) {
7386                throw new Error('convertRadix: carry overflow');
7387            }
7388            const div = digitBase / to;
7389            carry = digitBase % to;
7390            const rounded = Math.floor(div);
7391            digits[i] = rounded;
7392            if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
7393                throw new Error('convertRadix: carry overflow');
7394            if (!done)
7395                continue;
7396            else if (!rounded)
7397                pos = i;
7398            else
7399                done = false;
7400        }
7401        res.push(carry);
7402        if (done)
7403            break;
7404    }
7405    // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.
7406    for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
7407        res.push(0);
7408    return res.reverse();
7409}
7410const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
7411// Maximum carry width before the `pos` cycle repeats.
7412// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).
7413const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to));
7414const powers = /* @__PURE__ */ (() => {
7415    let res = [];
7416    for (let i = 0; i < 40; i++)
7417        res.push(2 ** i);
7418    return res;
7419})();
7420/**
7421 * Implemented with numbers, because BigInt is 5x slower
7422 */
7423function convertRadix2(data, from, to, padding) {
7424    aArr(data);
7425    if (from <= 0 || from > 32)
7426        throw new RangeError(`convertRadix2: wrong from=${from}`);
7427    if (to <= 0 || to > 32)
7428        throw new RangeError(`convertRadix2: wrong to=${to}`);
7429    if (radix2carry(from, to) > 32) {
7430        throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
7431    }
7432    let carry = 0;
7433    let pos = 0; // bitwise position in current element
7434    const max = powers[from];
7435    const mask = powers[to] - 1;
7436    const res = [];
7437    for (const n of data) {
7438        anumber(n);
7439        if (n >= max)
7440            throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
7441        carry = (carry << from) | n;
7442        if (pos + from > 32)
7443            throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
7444        pos += from;
7445        for (; pos >= to; pos -= to)
7446            res.push(((carry >> (pos - to)) & mask) >>> 0);
7447        const pow = powers[pos];
7448        if (pow === undefined)
7449            throw new Error('invalid carry');
7450        carry &= pow - 1; // clean carry, otherwise it will cause overflow
7451    }
7452    carry = (carry << (to - pos)) & mask;
7453    // Canonical decode paths reject leftover whole input words and non-zero pad bits.
7454    // For Bech32 5->8 regrouping, this is the "4 bits or less, all zeroes" tail rule.
7455    if (!padding && pos >= from)
7456        throw new Error('Excess padding');
7457    if (!padding && carry > 0)
7458        throw new Error(`Non-zero padding: ${carry}`);
7459    if (padding && pos > 0)
7460        res.push(carry >>> 0);
7461    return res;
7462}
7463/**
7464 * @__NO_SIDE_EFFECTS__
7465 */
7466function radix(num) {
7467    anumber(num);
7468    const _256 = 2 ** 8;
7469    // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.
7470    return {
7471        encode: (bytes) => {
7472            if (!isBytes(bytes))
7473                throw new TypeError('radix.encode input should be Uint8Array');
7474            return convertRadix(Array.from(bytes), _256, num);
7475        },
7476        decode: (digits) => {
7477            anumArr('radix.decode', digits);
7478            return Uint8Array.from(convertRadix(digits, num, _256));
7479        },
7480    };
7481}
7482/**
7483 * If both bases are power of same number (like `2**8 <-> 2**64`),
7484 * there is a linear algorithm. For now we have implementation for power-of-two bases only.
7485 * @__NO_SIDE_EFFECTS__
7486 */
7487function radix2(bits, revPadding = false) {
7488    anumber(bits);
7489    if (bits <= 0 || bits > 32)
7490        throw new RangeError('radix2: bits should be in (0..32]');
7491    if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
7492        throw new RangeError('radix2: carry overflow');
7493    // revPadding flips which direction allows a partial zero tail.
7494    // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.
7495    return {
7496        encode: (bytes) => {
7497            if (!isBytes(bytes))
7498                throw new TypeError('radix2.encode input should be Uint8Array');
7499            return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
7500        },
7501        decode: (digits) => {
7502            anumArr('radix2.decode', digits);
7503            return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
7504        },
7505    };
7506}
7507function unsafeWrapper(fn) {
7508    afn(fn);
7509    return function (...args) {
7510        // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.
7511        // Do not wrap code that needs to preserve exception details.
7512        try {
7513            return fn.apply(null, args);
7514        }
7515        catch (e) { }
7516    };
7517}
7518function checksum(len, fn) {
7519    anumber(len);
7520    // Reject degenerate zero-byte checksums up front so callers don't accidentally
7521    // build a no-op checksum stage.
7522    if (len <= 0)
7523        throw new RangeError(`checksum length must be positive: ${len}`);
7524    afn(fn);
7525    const _fn = fn;
7526    // Uses the first `len` bytes of fn(data) in both directions.
7527    // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.
7528    return {
7529        encode(data) {
7530            if (!isBytes(data))
7531                throw new TypeError('checksum.encode: input should be Uint8Array');
7532            const sum = _fn(data).slice(0, len);
7533            const res = new Uint8Array(data.length + len);
7534            res.set(data);
7535            res.set(sum, data.length);
7536            return res;
7537        },
7538        decode(data) {
7539            if (!isBytes(data))
7540                throw new TypeError('checksum.decode: input should be Uint8Array');
7541            const payload = data.slice(0, -len);
7542            const oldChecksum = data.slice(-len);
7543            const newChecksum = _fn(payload).slice(0, len);
7544            for (let i = 0; i < len; i++)
7545                if (newChecksum[i] !== oldChecksum[i])
7546                    throw new Error('Invalid checksum');
7547            return payload;
7548        },
7549    };
7550}
7551// prettier-ignore
7552/**
7553 * Low-level building blocks used by the exported codecs.
7554 * @example
7555 * Build a radix-32 coder from the low-level helpers.
7556 * ```ts
7557 * import { utils } from '@scure/base';
7558 * utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));
7559 * ```
7560 */
7561const utils = /* @__PURE__ */ Object.freeze({
7562    alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,
7563});
7564// RFC 4648 aka RFC 3548
7565// ---------------------
7566/**
7567 * base16 encoding from RFC 4648.
7568 * This codec uses RFC 4648 Table 5's uppercase alphabet directly.
7569 * RFC 4648 §8 calls base16 "case-insensitive hex encoding", but we intentionally do not case-fold decode input here.
7570 * Use `hex` for case-insensitive hex decoding.
7571 * @example
7572 * ```js
7573 * base16.encode(Uint8Array.from([0x12, 0xab]));
7574 * // => '12AB'
7575 * ```
7576 */
7577const base16 = /* @__PURE__ */ Object.freeze(chain(radix2(4), alphabet('0123456789ABCDEF'), join('')));
7578/**
7579 * base32 encoding from RFC 4648. Has padding.
7580 * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose
7581 * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.
7582 * Use `base32nopad` for unpadded version.
7583 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
7584 * @example
7585 * ```js
7586 * base32.encode(Uint8Array.from([0x12, 0xab]));
7587 * // => 'CKVQ===='
7588 * base32.decode('CKVQ====');
7589 * // => Uint8Array.from([0x12, 0xab])
7590 * ```
7591 */
7592const base32 = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')));
7593/**
7594 * base32 encoding from RFC 4648. No padding.
7595 * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.
7596 * Use `base32` for padded version.
7597 * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.
7598 * @example
7599 * ```js
7600 * base32nopad.encode(Uint8Array.from([0x12, 0xab]));
7601 * // => 'CKVQ'
7602 * base32nopad.decode('CKVQ');
7603 * // => Uint8Array.from([0x12, 0xab])
7604 * ```
7605 */
7606const base32nopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join('')));
7607/**
7608 * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.
7609 * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.
7610 * Use `base32hexnopad` for unpadded version.
7611 * @example
7612 * ```js
7613 * base32hex.encode(Uint8Array.from([0x12, 0xab]));
7614 * // => '2ALG===='
7615 * base32hex.decode('2ALG====');
7616 * // => Uint8Array.from([0x12, 0xab])
7617 * ```
7618 */
7619const base32hex = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')));
7620/**
7621 * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.
7622 * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.
7623 * Use `base32hex` for padded version.
7624 * @example
7625 * ```js
7626 * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));
7627 * // => '2ALG'
7628 * base32hexnopad.decode('2ALG');
7629 * // => Uint8Array.from([0x12, 0xab])
7630 * ```
7631 */
7632const base32hexnopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join('')));
7633/**
7634 * base32 encoding from RFC 4648. Doug Crockford's version.
7635 * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.
7636 * @example
7637 * ```js
7638 * base32crockford.encode(Uint8Array.from([0x12, 0xab]));
7639 * // => '2ANG'
7640 * base32crockford.decode('2ANG');
7641 * // => Uint8Array.from([0x12, 0xab])
7642 * ```
7643 */
7644const base32crockford = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize$1((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))));
7645// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64
7646// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.
7647// prettier-ignore
7648const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&
7649    typeof Uint8Array.fromBase64 === 'function')();
7650// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.
7651// Reject them first so the native base64 path still follows RFC 4648 §3.3.
7652// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE
7653const ASCII_WHITESPACE = /[\t\n\f\r ]/;
7654const decodeBase64Builtin = (s, isUrl) => {
7655    astr('base64', s);
7656    const alphabet = isUrl ? 'base64url' : 'base64';
7657    // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace
7658    // And checking just for whitespace makes decoding about 3x faster than a full range check.
7659    // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.
7660    if (s.length > 0 && ASCII_WHITESPACE.test(s))
7661        throw new Error('invalid base64');
7662    return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });
7663};
7664/**
7665 * base64 from RFC 4648. Padded.
7666 * Use `base64nopad` for unpadded version.
7667 * Also check out `base64url`, `base64urlnopad`.
7668 * Falls back to built-in function, when available.
7669 * @example
7670 * ```js
7671 * base64.encode(Uint8Array.from([0x12, 0xab]));
7672 * // => 'Eqs='
7673 * base64.decode('Eqs=');
7674 * // => Uint8Array.from([0x12, 0xab])
7675 * ```
7676 */
7677// prettier-ignore
7678const base64 = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {
7679    encode(b) { abytes(b); return b.toBase64(); },
7680    decode(s) { return decodeBase64Builtin(s, false); },
7681} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
7681+/'), padding(6), join('')));
7682/**
7683 * base64 from RFC 4648. No padding.
7684 * Use `base64` for padded version.
7685 * @example
7686 * ```js
7687 * base64nopad.encode(Uint8Array.from([0x12, 0xab]));
7688 * // => 'Eqs'
7689 * base64nopad.decode('Eqs');
7690 * // => Uint8Array.from([0x12, 0xab])
7691 * ```
7692 */
7693const base64nopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join('')));
7694/**
7695 * base64 from RFC 4648, using URL-safe alphabet. Padded.
7696 * Use `base64urlnopad` for unpadded version.
7697 * Falls back to built-in function, when available.
7698 * @example
7699 * ```js
7700 * base64url.encode(Uint8Array.from([0x12, 0xab]));
7701 * // => 'Eqs='
7702 * base64url.decode('Eqs=');
7703 * // => Uint8Array.from([0x12, 0xab])
7704 * ```
7705 */
7706// prettier-ignore
7707const base64url = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {
7708    encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },
7709    decode(s) { return decodeBase64Builtin(s, true); },
7710} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join('')));
7711/**
7712 * base64 from RFC 4648, using URL-safe alphabet. No padding.
7713 * Use `base64url` for padded version.
7714 * @example
7715 * ```js
7716 * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));
7717 * // => 'Eqs'
7718 * base64urlnopad.decode('Eqs');
7719 * // => Uint8Array.from([0x12, 0xab])
7720 * ```
7721 */
7722const base64urlnopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join('')));
7723// base58 code
7724// -----------
7725const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join(''));
7726/**
7727 * base58: base64 without ambigous characters +, /, 0, O, I, l.
7728 * Quadratic (O(n^2)) - so, can't be used on large inputs.
7729 * @example
7730 * ```js
7731 * const text = base58.encode(Uint8Array.from([0, 1, 2]));
7732 * base58.decode(text);
7733 * // => Uint8Array.from([0, 1, 2])
7734 * ```
7735 */
7736const base58 = /* @__PURE__ */ Object.freeze(genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));
7737/**
7738 * base58: flickr version. Check out `base58`.
7739 * @example
7740 * Round-trip bytes with the Flickr alphabet.
7741 * ```ts
7742 * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));
7743 * base58flickr.decode(text);
7744 * ```
7745 */
7746const base58flickr = /* @__PURE__ */ Object.freeze(genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));
7747/**
7748 * base58: XRP version. Check out `base58`.
7749 * @example
7750 * Round-trip bytes with the XRP alphabet.
7751 * ```ts
7752 * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));
7753 * base58xrp.decode(text);
7754 * ```
7755 */
7756const base58xrp = /* @__PURE__ */ Object.freeze(genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));
7757// Data len (index) -> encoded block len.
7758// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.
7759const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
7760/**
7761 * base58: XMR version. Check out `base58`.
7762 * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.
7763 * Block encoding significantly reduces quadratic complexity of base58.
7764 * @example
7765 * Round-trip bytes with the Monero block codec.
7766 * ```ts
7767 * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));
7768 * base58xmr.decode(text);
7769 * ```
7770 */
7771const base58xmr = /* @__PURE__ */ Object.freeze({
7772    encode(data) {
7773        abytes(data);
7774        let res = '';
7775        for (let i = 0; i < data.length; i += 8) {
7776            const block = data.subarray(i, i + 8);
7777            res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');
7778        }
7779        return res;
7780    },
7781    decode(str) {
7782        astr('base58xmr.decode', str);
7783        let res = [];
7784        for (let i = 0; i < str.length; i += 11) {
7785            const slice = str.slice(i, i + 11);
7786            const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
7787            const block = base58.decode(slice);
7788            for (let j = 0; j < block.length - blockLen; j++) {
7789                if (block[j] !== 0)
7790                    throw new Error('base58xmr: wrong padding');
7791            }
7792            res = res.concat(Array.from(block.slice(block.length - blockLen)));
7793        }
7794        return Uint8Array.from(res);
7795    },
7796});
7797/**
7798 * Method, which creates base58check encoder.
7799 * Requires function, calculating sha256.
7800 * Callers must include any version bytes in `data`; this helper only applies the
7801 * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.
7802 * @param sha256 - Function used to calculate the checksum hash.
7803 * @returns base58check codec using 4 checksum bytes.
7804 * @throws On wrong argument types. {@link TypeError}
7805 * @example
7806 * Create a base58check codec from a SHA-256 implementation.
7807 * ```ts
7808 * import { createBase58check } from '@scure/base';
7809 * import { sha256 } from '@noble/hashes/sha2.js';
7810 * const coder = createBase58check(sha256);
7811 * coder.encode(Uint8Array.from([1, 2, 3]));
7812 * ```
7813 */
7814const createBase58check = (sha256) => {
7815    // Validate the hash function at construction time so wrong inputs fail before returning a coder.
7816    afn(sha256);
7817    const _sha256 = sha256;
7818    return chain(checksum(4, (data) => _sha256(_sha256(data))), base58);
7819};
7820/**
7821 * Use `createBase58check` instead.
7822 * @deprecated Use {@link createBase58check} instead.
7823 * Callers must include any version bytes in `data`; this alias keeps the same
7824 * 4-byte double-SHA256 checksum behavior as `createBase58check`.
7825 * @param sha256 - Function used to calculate the checksum hash.
7826 * @returns base58check codec using 4 checksum bytes.
7827 * @example
7828 * Create a base58check codec with the deprecated alias.
7829 * ```ts
7830 * import { base58check } from '@scure/base';
7831 * import { sha256 } from '@noble/hashes/sha2.js';
7832 * const coder = base58check(sha256);
7833 * coder.encode(Uint8Array.from([1, 2, 3]));
7834 * ```
7835 */
7836const base58check = createBase58check;
7837// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54
7837khce6mua7l`.
7838const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join(''));
7839// BIP 173 `bech32_polymod` GEN coefficients.
7840const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
7841// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.
7842function bech32Polymod(pre) {
7843    const b = pre >> 25;
7844    let chk = (pre & 0x1ffffff) << 5;
7845    for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
7846        if (((b >> i) & 1) === 1)
7847            chk ^= POLYMOD_GENERATORS[i];
7848    }
7849    return chk;
7850}
7851function bechChecksum(prefix, words, encodingConst = 1) {
7852    const len = prefix.length;
7853    let chk = 1;
7854    for (let i = 0; i < len; i++) {
7855        const c = prefix.charCodeAt(i);
7856        if (c < 33 || c > 126)
7857            throw new Error(`Invalid prefix (${prefix})`);
7858        chk = bech32Polymod(chk) ^ (c >> 5);
7859    }
7860    chk = bech32Polymod(chk);
7861    for (let i = 0; i < len; i++)
7862        chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);
7863    for (let v of words)
7864        chk = bech32Polymod(chk) ^ v;
7865    for (let i = 0; i < 6; i++)
7866        chk = bech32Polymod(chk);
7867    // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.
7868    chk ^= encodingConst;
7869    return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false));
7870}
7871/**
7872 * @__NO_SIDE_EFFECTS__
7873 */
7874function genBech32(encoding) {
7875    // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.
7876    const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;
7877    const _words = radix2(5);
7878    const fromWords = _words.decode;
7879    const toWords = _words.encode;
7880    const fromWordsUnsafe = unsafeWrapper(fromWords);
7881    function encode(prefix, words, limit = 90) {
7882        astr('bech32.encode prefix', prefix);
7883        if (isBytes(words))
7884            words = Array.from(words);
7885        anumArr('bech32.encode', words);
7886        const plen = prefix.length;
7887        if (plen === 0)
7888            throw new TypeError(`Invalid prefix length ${plen}`);
7889        // Total output is hrp + `1` separator + payload words + 6 checksum chars.
7890        const actualLength = plen + 7 + words.length;
7891        if (limit !== false && actualLength > limit)
7892            throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
7893        const lowered = prefix.toLowerCase();
7894        const sum = bechChecksum(lowered, words, ENCODING_CONST);
7895        return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`;
7896    }
7897    function decode(str, limit = 90) {
7898        astr('bech32.decode input', str);
7899        const slen = str.length;
7900        // Minimum length is 1-char hrp + `1` separator + 6-char checksum.
7901        if (slen < 8 || (limit !== false && slen > limit))
7902            throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);
7903        // don't allow mixed case
7904        const lowered = str.toLowerCase();
7905        if (str !== lowered && str !== str.toUpperCase())
7906            throw new Error(`String must be lowercase or uppercase`);
7907        const sepIndex = lowered.lastIndexOf('1');
7908        if (sepIndex === 0 || sepIndex === -1)
7909            throw new Error(`Letter "1" must be present between prefix and data only`);
7910        const prefix = lowered.slice(0, sepIndex);
7911        const data = lowered.slice(sepIndex + 1);
7912        if (data.length < 6)
7913            throw new Error('Data must be at least 6 characters long');
7914        const words = BECH_ALPHABET.decode(data).slice(0, -6);
7915        const sum = bechChecksum(prefix, words, ENCODING_CONST);
7916        if (!data.endsWith(sum))
7917            throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
7918        return { prefix, words };
7919    }
7920    const decodeUnsafe = unsafeWrapper(decode);
7921    function decodeToBytes(str) {
7922        // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).
7923        const { prefix, words } = decode(str, false);
7924        return {
7925            prefix,
7926            words,
7927            bytes: fromWords(words),
7928        };
7929    }
7930    function encodeFromBytes(prefix, bytes) {
7931        // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).
7932        return encode(prefix, toWords(bytes));
7933    }
7934    return {
7935        encode,
7936        decode,
7937        encodeFromBytes,
7938        decodeToBytes,
7939        decodeUnsafe,
7940        fromWords,
7941        fromWordsUnsafe,
7942        toWords,
7943    };
7944}
7945/**
7946 * bech32 from BIP 173. Operates on words.
7947 * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.
7948 * @example
7949 * Convert bytes to words, encode them, then decode back.
7950 * ```ts
7951 * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));
7952 * const text = bech32.encode('bc', words);
7953 * bech32.decode(text);
7954 * ```
7955 */
7956const bech32 = /* @__PURE__ */ Object.freeze(genBech32('bech32'));
7957/**
7958 * bech32m from BIP 350. Operates on words.
7959 * It was to mitigate `bech32` weaknesses.
7960 * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.
7961 * @example
7962 * Convert bytes to words, encode them with bech32m, then decode back.
7963 * ```ts
7964 * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));
7965 * const text = bech32m.encode('bc', words);
7966 * bech32m.decode(text);
7967 * ```
7968 */
7969const bech32m = /* @__PURE__ */ Object.freeze(genBech32('bech32m'));
7970/**
7971 * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.
7972 * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.
7973 * @example
7974 * ```js
7975 * const b = ascii.decode("ABC"); // => new Uint8Array([ 65, 66, 67 ])
7976 * const str = ascii.encode(b); // "ABC"
7977 * ```
7978 */
7979const ascii = /* @__PURE__ */ Object.freeze({
7980    encode(data) {
7981        abytes(data);
7982        let res = '';
7983        for (let i = 0; i < data.length; i++) {
7984            const byte = data[i];
7985            // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to
7986            // Latin-1/UTF-8.
7987            if (byte > 127)
7988                throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);
7989            res += String.fromCharCode(byte);
7990        }
7991        return res;
7992    },
7993    decode(str) {
7994        if (typeof str !== 'string')
7995            throw new TypeError('ascii string expected, got ' + typeof str);
7996        const res = new Uint8Array(str.length);
7997        for (let i = 0; i < str.length; i++) {
7998            // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps
7999            // exact error positions.
8000            const charCode = str.charCodeAt(i);
8001            if (charCode > 127) {
8002                throw new RangeError(`string contains non-ASCII character "${str[i]}" with code ${charCode} at position ${i}`);
8003            }
8004            res[i] = charCode;
8005        }
8006        return res;
8007    },
8008});
8009const _isWellFormedShim = (str) => {
8010    // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native
8011    // isWellFormed on our tests/fuzz corpus.
8012    try {
8013        return encodeURI(str) !== null;
8014    }
8015    catch {
8016        return false;
8017    }
8018};
8019const _isWellFormed = /* @__PURE__ */ (() => 
8020// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.
8021typeof ''.isWellFormed === 'function'
8022    ? (str) => str.isWellFormed()
8023    : _isWellFormedShim)();
8024// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed
8025// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform
8026// text codecs.
8027const utf8Fallback = /* @__PURE__ */ Object.freeze({
8028    encode(data) {
8029        abytes(data);
8030        let res = '';
8031        for (let i = 0; i < data.length;) {
8032            const a = data[i++];
8033            if (a < 0b1000_0000) {
8034                res += String.fromCharCode(a);
8035                continue;
8036            }
8037            if (a < 0b1100_0010 || i >= data.length)
8038                throw new TypeError(`invalid utf8 at byte ${i - 1}`);
8039            const b = data[i++];
8040            if ((b & 0b1100_0000) !== 0b1000_0000)
8041                throw new TypeError(`invalid utf8 at byte ${i - 1}`);
8042            let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);
8043            if (a >= 0b1110_0000) {
8044                if (i >= data.length)
8045                    throw new TypeError(`invalid utf8 at byte ${i - 1}`);
8046                const c = data[i++];
8047                if ((c & 0b1100_0000) !== 0b1000_0000 ||
8048                    (a === 0b1110_0000 && b < 0b1010_0000) ||
8049                    (a === 0xed && b >= 0b1010_0000))
8050                    throw new TypeError(`invalid utf8 at byte ${i - 1}`);
8051                cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);
8052                if (a >= 0b1111_0000) {
8053                    if (i >= data.length)
8054                        throw new TypeError(`invalid utf8 at byte ${i - 1}`);
8055                    const d = data[i++];
8056                    if (a > 0b1111_0100 ||
8057                        (d & 0b1100_0000) !== 0b1000_0000 ||
8058                        (a === 0b1111_0000 && b < 0b1001_0000) ||
8059                        (a === 0b1111_0100 && b >= 0b1001_0000))
8060                        throw new TypeError(`invalid utf8 at byte ${i - 1}`);
8061                    cp =
8062                        ((a & 7) << 18) |
8063                            ((b & 0b0011_1111) << 12) |
8064                            ((c & 0b0011_1111) << 6) |
8065                            (d & 0b0011_1111);
8066                }
8067            }
8068            if (cp < 0x10000)
8069                res += String.fromCharCode(cp);
8070            else {
8071                cp -= 0x10000;
8072                res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);
8073            }
8074        }
8075        return res;
8076    },
8077    decode(str) {
8078        astr('utf8', str);
8079        if (!_isWellFormed(str))
8080            throw new TypeError('utf8 expected well-formed string');
8081        // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and
8082        // large Node inputs.
8083        const res = new Uint8Array(str.length * 3);
8084        let pos = 0;
8085        for (let i = 0; i < str.length; i++) {
8086            let c = str.charCodeAt(i);
8087            if (c < 0b1000_0000) {
8088                res[pos++] = c;
8089                continue;
8090            }
8091            if (c >= 0xd800 && c <= 0xdfff) {
8092                const d = str.charCodeAt(++i);
8093                c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;
8094            }
8095            if (c >= 0x10000) {
8096                res[pos++] = (c >> 18) | 0b1111_0000;
8097                res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;
8098            }
8099            else if (c >= 0x800)
8100                res[pos++] = (c >> 12) | 0b1110_0000;
8101            else
8102                res[pos++] = (c >> 6) | 0b1100_0000;
8103            if (c >= 0x800)
8104                res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;
8105            res[pos++] = (c & 0b0011_1111) | 0b1000_0000;
8106        }
8107        return res.subarray(0, pos);
8108    },
8109});
8110/**
8111 * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.
8112 * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and
8113 * `decode(string)` returns bytes.
8114 * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and
8115 *   throws on invalid UTF-8 bytes.
8116 * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with
8117 *   lone surrogates.
8118 * @example
8119 * ```js
8120 * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ])
8121 * const str = utf8.encode(b); // "hey"
8122 * ```
8123 */
8124const utf8 = /* @__PURE__ */ (() => {
8125    let _utf8Encoder;
8126    let _utf8Decoder;
8127    const utf8Builtin = {
8128        // ignoreBOM preserves an explicit leading U+FEFF;
8129        // fatal rejects invalid UTF-8 bytes instead of replacing them.
8130        encode(data) {
8131            abytes(data);
8132            return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);
8133        },
8134        decode(str) {
8135            astr('utf8', str);
8136            if (!_isWellFormed(str))
8137                throw new TypeError('utf8 expected well-formed string');
8138            return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);
8139        },
8140    };
8141    return Object.freeze({
8142        // Select each direction once at module init, since
8143        // TextEncoder and TextDecoder can exist independently.
8144        encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,
8145        decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,
8146    });
8147})();
8148// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.
8149const __TESTS = /* @__PURE__ */ Object.freeze({
8150    utf8Fallback: utf8Fallback,
8151    _isWellFormedShim: _isWellFormedShim,
8152});
8153// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
8154// prettier-ignore
8155const hasHexBuiltin = /* @__PURE__ */ (() => 
8156// Require both directions before enabling the native hex path so encode/decode stay symmetric.
8157typeof Uint8Array.from([]).toHex === 'function' &&
8158    typeof Uint8Array.fromHex === 'function')();
8159// prettier-ignore
8160const hexBuiltin = {
8161    // Keep local type guards so the native path preserves library-level input errors.
8162    // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.
8163    encode(data) { abytes(data); return data.toHex(); },
8164    // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.
8165    decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },
8166};
8167/**
8168 * hex string decoder. Uses built-in function, when available.
8169 * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.
8170 * @example
8171 * ```js
8172 * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ])
8173 * const str = hex.encode(b); // "0102ff"
8174 * ```
8175 */
8176const hex = /* @__PURE__ */ Object.freeze(hasHexBuiltin
8177    ? hexBuiltin
8178    : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize$1((s) => {
8179        if (typeof s !== 'string' || s.length % 2 !== 0)
8180            throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
8181        return s.toLowerCase();
8182    })));
8183// prettier-ignore
8184// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.
8185const CODERS = {
8186    utf8, hex, base16, base32, base64, base64url, base58, base58xmr
8187};
8188const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';
8189/**
8190 * Encodes bytes with one of the built-in codecs.
8191 * @deprecated Use the codec directly, for example `hex.encode(bytes)`.
8192 * @param type - Codec name.
8193 * @param bytes - Bytes to encode.
8194 * @returns Encoded string.
8195 * @throws On wrong argument types. {@link TypeError}
8196 * @example
8197 * ```ts
8198 * bytesToString('hex', Uint8Array.from([1, 2, 255]));
8199 * ```
8200 */
8201const bytesToString = (type, bytes) => {
8202    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
8203        throw new TypeError(coderTypeError);
8204    if (!isBytes(bytes))
8205        throw new TypeError('bytesToString() expects Uint8Array');
8206    return CODERS[type].encode(bytes);
8207};
8208/**
8209 * Alias for `bytesToString`.
8210 * @deprecated Use {@link bytesToString} or the codec directly instead.
8211 * @param type - Codec name.
8212 * @param bytes - Bytes to encode.
8213 * @returns Encoded string.
8214 * @example
8215 * ```ts
8216 * str('hex', Uint8Array.from([1, 2, 255]));
8217 * ```
8218 */
8219const str = bytesToString; // as in python, but for bytes only
8220/**
8221 * Decodes a string with one of the built-in codecs.
8222 * @deprecated Use the codec directly, for example `hex.decode(text)`.
8223 * @param type - Codec name.
8224 * @param str - Encoded string.
8225 * @returns Decoded bytes.
8226 * @throws On wrong argument types. {@link TypeError}
8227 * @example
8228 * ```ts
8229 * stringToBytes('hex', '0102ff');
8230 * ```
8231 */
8232const stringToBytes = (type, str) => {
8233    // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.
8234    if (typeof type !== 'string' || !CODERS.hasOwnProperty(type))
8235        throw new TypeError(coderTypeError);
8236    if (typeof str !== 'string')
8237        throw new TypeError('stringToBytes() expects string');
8238    return CODERS[type].decode(str);
8239};
8240/**
8241 * Alias for `stringToBytes`.
8242 * @deprecated Use {@link stringToBytes} or the codec directly instead.
8243 * @param type - Codec name.
8244 * @param str - Encoded string.
8245 * @returns Decoded bytes.
8246 * @example
8247 * ```ts
8248 * bytes('hex', '0102ff');
8249 * ```
8250 */
8251const bytes = stringToBytes;
8252
8253const base = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
8254	__proto__: null,
8255	__TESTS,
8256	ascii,
8257	base16,
8258	base32,
8259	base32crockford,
8260	base32hex,
8261	base32hexnopad,
8262	base32nopad,
8263	base58,
8264	base58check,
8265	base58flickr,
8266	base58xmr,
8267	base58xrp,
8268	base64,
8269	base64nopad,
8270	base64url,
8271	base64urlnopad,
8272	bech32,
8273	bech32m,
8274	bytes,
8275	bytesToString,
8276	createBase58check,
8277	hex,
8278	str,
8279	stringToBytes,
8280	utf8,
8281	utils
8282}, Symbol.toStringTag, { value: 'Module' }));
8283
8284/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
8285// Japanese wordlist
8286// The canonical BIP-39 Japanese wordlist starts with あいこくしん.
8287// Use that sentinel so generated phrases use U+3000 ideographic spaces.
8288const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093';
8289// Normalization replaces equivalent sequences of characters
8290// so that any two texts that are equivalent will be reduced
8291// to the same sequence of code points, called the normal form of the original text.
8292// https://tonsky.me/blog/unicode/#why-is-a----
8293// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences.
8294// It also applies NFKD to the "mnemonic" + passphrase salt.
8295function nfkd(str) {
8296    if (typeof str !== 'string')
8297        throw new TypeError('invalid mnemonic type: ' + typeof str);
8298    return str.normalize('NFKD');
8299}
8300// BIP-39 mnemonics are consumed in NFKD form.
8301// They must contain 12, 15, 18, 21, or 24 words before checksum validation.
8302function normalize(str) {
8303    const norm = nfkd(str);
8304    const words = norm.split(' ');
8305    if (![12, 15, 18, 21, 24].includes(words.length))
8306        throw new Error('Invalid mnemonic');
8307    return { nfkd: norm, words };
8308}
8309// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.
8310function aentropy(ent) {
8311    abytes$1(ent);
8312    if (![16, 20, 24, 28, 32].includes(ent.length))
8313        throw new RangeError('invalid entropy length');
8314}
8315/**
8316 * Generate x random words. Uses Cryptographically-Secure Random Number Generator.
8317 * @param wordlist - Imported wordlist for a specific language.
8318 * @param strength - Mnemonic strength, from 128 to 256 bits.
8319 * @returns 12-24 word mnemonic phrase.
8320 * @throws On wrong argument types. {@link TypeError}
8321 * @throws On wrong argument ranges or values. {@link RangeError}
8322 * @example
8323 * Generate a new English mnemonic.
8324 * ```ts
8325 * import { generateMnemonic } from '@scure/bip39';
8326 * import { wordlist } from '@scure/bip39/wordlists/english.js';
8327 * const mnemonic = generateMnemonic(wordlist, 128);
8328 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
8329 * ```
8330 */
8331function generateMnemonic(wordlist, strength = 128) {
8332    anumber$1(strength);
8333    if (strength % 32 !== 0 || strength > 256)
8334        throw new RangeError('Invalid entropy');
8335    return entropyToMnemonic(randomBytes(strength / 8), wordlist);
8336}
8337const calcChecksum = (entropy) => {
8338    // Checksum is ent.length/4 bits long
8339    const bitsLeft = 8 - entropy.length / 4;
8340    // Zero rightmost "bitsLeft" bits in byte
8341    // For example: bitsLeft=4 val=10111101 -> 10110000
8342    return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);
8343};
8344function getCoder(wordlist) {
8345    if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')
8346        throw new TypeError('Wordlist: expected array of 2048 strings');
8347    wordlist.forEach((i) => {
8348        if (typeof i !== 'string')
8349            throw new TypeError('wordlist: non-string element: ' + i);
8350    });
8351    // BIP-39 appends checksum bits to entropy.
8352    // It then splits the bitstream into 11-bit indexes for a 2048-word list.
8353    return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist));
8354}
8355/**
8356 * Reversible: Converts mnemonic string to raw entropy in form of byte array.
8357 * @param mnemonic - 12-24 words.
8358 * @param wordlist - Imported wordlist for a specific language.
8359 * @returns Raw entropy bytes.
8360 * @throws If the mnemonic shape or checksum is invalid. {@link Error}
8361 * @throws On wrong argument types. {@link TypeError}
8362 * @throws On wrong argument ranges or values. {@link RangeError}
8363 * @example
8364 * Decode a mnemonic back into its original entropy bytes.
8365 * ```ts
8366 * import { mnemonicToEntropy } from '@scure/bip39';
8367 * import { wordlist } from '@scure/bip39/wordlists/english.js';
8368 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
8369 * const entropy = mnemonicToEntropy(mnem, wordlist);
8370 * // Produces the original 16-byte entropy payload.
8371 * new Uint8Array([
8372 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
8373 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
8374 * ])
8375 * ```
8376 */
8377function mnemonicToEntropy(mnemonic, wordlist) {
8378    const { words } = normalize(mnemonic);
8379    const entropy = getCoder(wordlist).decode(words);
8380    aentropy(entropy);
8381    return entropy;
8382}
8383/**
8384 * Reversible: Converts raw entropy in form of byte array to mnemonic string.
8385 * @param entropy - Byte array.
8386 * @param wordlist - Imported wordlist for a specific language.
8387 * @returns 12-24 words.
8388 * @throws On wrong argument types. {@link TypeError}
8389 * @throws On wrong argument ranges or values. {@link RangeError}
8390 * @example
8391 * Convert raw entropy into an English mnemonic.
8392 * ```ts
8393 * import { entropyToMnemonic } from '@scure/bip39';
8394 * import { wordlist } from '@scure/bip39/wordlists/english.js';
8395 * const ent = new Uint8Array([
8396 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,
8397 *   0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f
8398 * ]);
8399 * const mnemonic = entropyToMnemonic(ent, wordlist);
8400 * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'
8401 * ```
8402 */
8403function entropyToMnemonic(entropy, wordlist) {
8404    aentropy(entropy);
8405    const words = getCoder(wordlist).encode(entropy);
8406    return words.join(isJapanese(wordlist) ? '\u3000' : ' ');
8407}
8408/**
8409 * Validates mnemonic for being 12-24 words contained in `wordlist`.
8410 * @param mnemonic - 12-24 words.
8411 * @param wordlist - Imported wordlist for a specific language.
8412 * @returns `true` when mnemonic checksum and words are valid.
8413 * @example
8414 * Validate one English mnemonic.
8415 * ```ts
8416 * import { validateMnemonic } from '@scure/bip39';
8417 * import { wordlist } from '@scure/bip39/wordlists/english.js';
8418 * const ok = validateMnemonic(
8419 *   'legal winner thank year wave sausage worth useful legal winner thank yellow',
8420 *   wordlist
8421 * );
8422 * // => true
8423 * ```
8424 */
8425function validateMnemonic(mnemonic, wordlist) {
8426    try {
8427        mnemonicToEntropy(mnemonic, wordlist);
8428    }
8429    catch (e) {
8430        return false;
8431    }
8432    return true;
8433}
8434// BIP-39 salts PBKDF2 with the UTF-8 NFKD string "mnemonic" + passphrase.
8435const psalt = (passphrase) => nfkd('mnemonic' + passphrase);
8436/**
8437 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
8438 * @param mnemonic - 12-24 words.
8439 * @param passphrase - String that will additionally protect the key.
8440 * @returns 64 bytes of key data.
8441 * @throws If the mnemonic shape is invalid. {@link Error}
8442 * @throws On wrong argument types. {@link TypeError}
8443 * @example
8444 * Derive a seed from a mnemonic with the async PBKDF2 helper.
8445 * ```ts
8446 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
8447 * const seed = await mnemonicToSeed(mnem, 'password');
8448 * // => new Uint8Array([...64 bytes])
8449 * ```
8450 */
8451// BIP-39 seed derivation is independent from mnemonic generation.
8452// These helpers normalize the phrase but do not verify checksum or wordlist membership.
8453function mnemonicToSeed(mnemonic, passphrase = '') {
8454    return pbkdf2Async(sha512$1, normalize(mnemonic).nfkd, psalt(passphrase), {
8455        c: 2048,
8456        dkLen: 64,
8457    });
8458}
8459/**
8460 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
8461 * @param mnemonic - 12-24 words.
8462 * @param passphrase - String that will additionally protect the key.
8463 * @returns 64 bytes of key data.
8464 * @throws If the mnemonic shape is invalid. {@link Error}
8465 * @throws On wrong argument types. {@link TypeError}
8466 * @example
8467 * Derive a seed from a mnemonic with the sync PBKDF2 helper.
8468 * ```ts
8469 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
8470 * const seed = mnemonicToSeedSync(mnem, 'password');
8471 * // => new Uint8Array([...64 bytes])
8472 * ```
8473 */
8474function mnemonicToSeedSync(mnemonic, passphrase = '') {
8475    return pbkdf2$1(sha512$1, normalize(mnemonic).nfkd, psalt(passphrase), {
8476        c: 2048,
8477        dkLen: 64,
8478    });
8479}
8480/**
8481 * Uses native, built-in functionality, provided by globalThis.crypto.
8482 * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
8483 * @param mnemonic - 12-24 words.
8484 * @param passphrase - String that will additionally protect the key.
8485 * @returns 64 bytes of key data.
8486 * @throws If the mnemonic shape is invalid. {@link Error}
8487 * @throws On wrong argument types. {@link TypeError}
8488 * @example
8489 * Derive a seed with the native WebCrypto PBKDF2 helper.
8490 * ```ts
8491 * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
8492 * const seed = await mnemonicToSeedWebcrypto(mnem, 'password');
8493 * // => new Uint8Array([...64 bytes])
8494 * ```
8495 */
8496function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {
8497    return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {
8498        c: 2048,
8499        dkLen: 64,
8500    });
8501}
8502
8503const index$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
8504	__proto__: null,
8505	entropyToMnemonic,
8506	generateMnemonic,
8507	mnemonicToEntropy,
8508	mnemonicToSeed,
8509	mnemonicToSeedSync,
8510	mnemonicToSeedWebcrypto,
8511	validateMnemonic
8512}, Symbol.toStringTag, { value: 'Module' }));
8513
8514/** English BIP39 wordlist. */
8515const wordlist = /* @__PURE__ */ Object.freeze(`abandon
8516ability
8517able
8518about
8519above
8520absent
8521absorb
8522abstract
8523absurd
8524abuse
8525access
8526accident
8527account
8528accuse
8529achieve
8530acid
8531acoustic
8532acquire
8533across
8534act
8535action
8536actor
8537actress
8538actual
8539adapt
8540add
8541addict
8542address
8543adjust
8544admit
8545adult
8546advance
8547advice
8548aerobic
8549affair
8550afford
8551afraid
8552again
8553age
8554agent
8555agree
8556ahead
8557aim
8558air
8559airport
8560aisle
8561alarm
8562album
8563alcohol
8564alert
8565alien
8566all
8567alley
8568allow
8569almost
8570alone
8571alpha
8572already
8573also
8574alter
8575always
8576amateur
8577amazing
8578among
8579amount
8580amused
8581analyst
8582anchor
8583ancient
8584anger
8585angle
8586angry
8587animal
8588ankle
8589announce
8590annual
8591another
8592answer
8593antenna
8594antique
8595anxiety
8596any
8597apart
8598apology
8599appear
8600apple
8601approve
8602april
8603arch
8604arctic
8605area
8606arena
8607argue
8608arm
8609armed
8610armor
8611army
8612around
8613arrange
8614arrest
8615arrive
8616arrow
8617art
8618artefact
8619artist
8620artwork
8621ask
8622aspect
8623assault
8624asset
8625assist
8626assume
8627asthma
8628athlete
8629atom
8630attack
8631attend
8632attitude
8633attract
8634auction
8635audit
8636august
8637aunt
8638author
8639auto
8640autumn
8641average
8642avocado
8643avoid
8644awake
8645aware
8646away
8647awesome
8648awful
8649awkward
8650axis
8651baby
8652bachelor
8653bacon
8654badge
8655bag
8656balance
8657balcony
8658ball
8659bamboo
8660banana
8661banner
8662bar
8663barely
8664bargain
8665barrel
8666base
8667basic
8668basket
8669battle
8670beach
8671bean
8672beauty
8673because
8674become
8675beef
8676before
8677begin
8678behave
8679behind
8680believe
8681below
8682belt
8683bench
8684benefit
8685best
8686betray
8687better
8688between
8689beyond
8690bicycle
8691bid
8692bike
8693bind
8694biology
8695bird
8696birth
8697bitter
8698black
8699blade
8700blame
8701blanket
8702blast
8703bleak
8704bless
8705blind
8706blood
8707blossom
8708blouse
8709blue
8710blur
8711blush
8712board
8713boat
8714body
8715boil
8716bomb
8717bone
8718bonus
8719book
8720boost
8721border
8722boring
8723borrow
8724boss
8725bottom
8726bounce
8727box
8728boy
8729bracket
8730brain
8731brand
8732brass
8733brave
8734bread
8735breeze
8736brick
8737bridge
8738brief
8739bright
8740bring
8741brisk
8742broccoli
8743broken
8744bronze
8745broom
8746brother
8747brown
8748brush
8749bubble
8750buddy
8751budget
8752buffalo
8753build
8754bulb
8755bulk
8756bullet
8757bundle
8758bunker
8759burden
8760burger
8761burst
8762bus
8763business
8764busy
8765butter
8766buyer
8767buzz
8768cabbage
8769cabin
8770cable
8771cactus
8772cage
8773cake
8774call
8775calm
8776camera
8777camp
8778can
8779canal
8780cancel
8781candy
8782cannon
8783canoe
8784canvas
8785canyon
8786capable
8787capital
8788captain
8789car
8790carbon
8791card
8792cargo
8793carpet
8794carry
8795cart
8796case
8797cash
8798casino
8799castle
8800casual
8801cat
8802catalog
8803catch
8804category
8805cattle
8806caught
8807cause
8808caution
8809cave
8810ceiling
8811celery
8812cement
8813census
8814century
8815cereal
8816certain
8817chair
8818chalk
8819champion
8820change
8821chaos
8822chapter
8823charge
8824chase
8825chat
8826cheap
8827check
8828cheese
8829chef
8830cherry
8831chest
8832chicken
8833chief
8834child
8835chimney
8836choice
8837choose
8838chronic
8839chuckle
8840chunk
8841churn
8842cigar
8843cinnamon
8844circle
8845citizen
8846city
8847civil
8848claim
8849clap
8850clarify
8851claw
8852clay
8853clean
8854clerk
8855clever
8856click
8857client
8858cliff
8859climb
8860clinic
8861clip
8862clock
8863clog
8864close
8865cloth
8866cloud
8867clown
8868club
8869clump
8870cluster
8871clutch
8872coach
8873coast
8874coconut
8875code
8876coffee
8877coil
8878coin
8879collect
8880color
8881column
8882combine
8883come
8884comfort
8885comic
8886common
8887company
8888concert
8889conduct
8890confirm
8891congress
8892connect
8893consider
8894control
8895convince
8896cook
8897cool
8898copper
8899copy
8900coral
8901core
8902corn
8903correct
8904cost
8905cotton
8906couch
8907country
8908couple
8909course
8910cousin
8911cover
8912coyote
8913crack
8914cradle
8915craft
8916cram
8917crane
8918crash
8919crater
8920crawl
8921crazy
8922cream
8923credit
8924creek
8925crew
8926cricket
8927crime
8928crisp
8929critic
8930crop
8931cross
8932crouch
8933crowd
8934crucial
8935cruel
8936cruise
8937crumble
8938crunch
8939crush
8940cry
8941crystal
8942cube
8943culture
8944cup
8945cupboard
8946curious
8947current
8948curtain
8949curve
8950cushion
8951custom
8952cute
8953cycle
8954dad
8955damage
8956damp
8957dance
8958danger
8959daring
8960dash
8961daughter
8962dawn
8963day
8964deal
8965debate
8966debris
8967decade
8968december
8969decide
8970decline
8971decorate
8972decrease
8973deer
8974defense
8975define
8976defy
8977degree
8978delay
8979deliver
8980demand
8981demise
8982denial
8983dentist
8984deny
8985depart
8986depend
8987deposit
8988depth
8989deputy
8990derive
8991describe
8992desert
8993design
8994desk
8995despair
8996destroy
8997detail
8998detect
8999develop
9000device
9001devote
9002diagram
9003dial
9004diamond
9005diary
9006dice
9007diesel
9008diet
9009differ
9010digital
9011dignity
9012dilemma
9013dinner
9014dinosaur
9015direct
9016dirt
9017disagree
9018discover
9019disease
9020dish
9021dismiss
9022disorder
9023display
9024distance
9025divert
9026divide
9027divorce
9028dizzy
9029doctor
9030document
9031dog
9032doll
9033dolphin
9034domain
9035donate
9036donkey
9037donor
9038door
9039dose
9040double
9041dove
9042draft
9043dragon
9044drama
9045drastic
9046draw
9047dream
9048dress
9049drift
9050drill
9051drink
9052drip
9053drive
9054drop
9055drum
9056dry
9057duck
9058dumb
9059dune
9060during
9061dust
9062dutch
9063duty
9064dwarf
9065dynamic
9066eager
9067eagle
9068early
9069earn
9070earth
9071easily
9072east
9073easy
9074echo
9075ecology
9076economy
9077edge
9078edit
9079educate
9080effort
9081egg
9082eight
9083either
9084elbow
9085elder
9086electric
9087elegant
9088element
9089elephant
9090elevator
9091elite
9092else
9093embark
9094embody
9095embrace
9096emerge
9097emotion
9098employ
9099empower
9100empty
9101enable
9102enact
9103end
9104endless
9105endorse
9106enemy
9107energy
9108enforce
9109engage
9110engine
9111enhance
9112enjoy
9113enlist
9114enough
9115enrich
9116enroll
9117ensure
9118enter
9119entire
9120entry
9121envelope
9122episode
9123equal
9124equip
9125era
9126erase
9127erode
9128erosion
9129error
9130erupt
9131escape
9132essay
9133essence
9134estate
9135eternal
9136ethics
9137evidence
9138evil
9139evoke
9140evolve
9141exact
9142example
9143excess
9144exchange
9145excite
9146exclude
9147excuse
9148execute
9149exercise
9150exhaust
9151exhibit
9152exile
9153exist
9154exit
9155exotic
9156expand
9157expect
9158expire
9159explain
9160expose
9161express
9162extend
9163extra
9164eye
9165eyebrow
9166fabric
9167face
9168faculty
9169fade
9170faint
9171faith
9172fall
9173false
9174fame
9175family
9176famous
9177fan
9178fancy
9179fantasy
9180farm
9181fashion
9182fat
9183fatal
9184father
9185fatigue
9186fault
9187favorite
9188feature
9189february
9190federal
9191fee
9192feed
9193feel
9194female
9195fence
9196festival
9197fetch
9198fever
9199few
9200fiber
9201fiction
9202field
9203figure
9204file
9205film
9206filter
9207final
9208find
9209fine
9210finger
9211finish
9212fire
9213firm
9214first
9215fiscal
9216fish
9217fit
9218fitness
9219fix
9220flag
9221flame
9222flash
9223flat
9224flavor
9225flee
9226flight
9227flip
9228float
9229flock
9230floor
9231flower
9232fluid
9233flush
9234fly
9235foam
9236focus
9237fog
9238foil
9239fold
9240follow
9241food
9242foot
9243force
9244forest
9245forget
9246fork
9247fortune
9248forum
9249forward
9250fossil
9251foster
9252found
9253fox
9254fragile
9255frame
9256frequent
9257fresh
9258friend
9259fringe
9260frog
9261front
9262frost
9263frown
9264frozen
9265fruit
9266fuel
9267fun
9268funny
9269furnace
9270fury
9271future
9272gadget
9273gain
9274galaxy
9275gallery
9276game
9277gap
9278garage
9279garbage
9280garden
9281garlic
9282garment
9283gas
9284gasp
9285gate
9286gather
9287gauge
9288gaze
9289general
9290genius
9291genre
9292gentle
9293genuine
9294gesture
9295ghost
9296giant
9297gift
9298giggle
9299ginger
9300giraffe
9301girl
9302give
9303glad
9304glance
9305glare
9306glass
9307glide
9308glimpse
9309globe
9310gloom
9311glory
9312glove
9313glow
9314glue
9315goat
9316goddess
9317gold
9318good
9319goose
9320gorilla
9321gospel
9322gossip
9323govern
9324gown
9325grab
9326grace
9327grain
9328grant
9329grape
9330grass
9331gravity
9332great
9333green
9334grid
9335grief
9336grit
9337grocery
9338group
9339grow
9340grunt
9341guard
9342guess
9343guide
9344guilt
9345guitar
9346gun
9347gym
9348habit
9349hair
9350half
9351hammer
9352hamster
9353hand
9354happy
9355harbor
9356hard
9357harsh
9358harvest
9359hat
9360have
9361hawk
9362hazard
9363head
9364health
9365heart
9366heavy
9367hedgehog
9368height
9369hello
9370helmet
9371help
9372hen
9373hero
9374hidden
9375high
9376hill
9377hint
9378hip
9379hire
9380history
9381hobby
9382hockey
9383hold
9384hole
9385holiday
9386hollow
9387home
9388honey
9389hood
9390hope
9391horn
9392horror
9393horse
9394hospital
9395host
9396hotel
9397hour
9398hover
9399hub
9400huge
9401human
9402humble
9403humor
9404hundred
9405hungry
9406hunt
9407hurdle
9408hurry
9409hurt
9410husband
9411hybrid
9412ice
9413icon
9414idea
9415identify
9416idle
9417ignore
9418ill
9419illegal
9420illness
9421image
9422imitate
9423immense
9424immune
9425impact
9426impose
9427improve
9428impulse
9429inch
9430include
9431income
9432increase
9433index
9434indicate
9435indoor
9436industry
9437infant
9438inflict
9439inform
9440inhale
9441inherit
9442initial
9443inject
9444injury
9445inmate
9446inner
9447innocent
9448input
9449inquiry
9450insane
9451insect
9452inside
9453inspire
9454install
9455intact
9456interest
9457into
9458invest
9459invite
9460involve
9461iron
9462island
9463isolate
9464issue
9465item
9466ivory
9467jacket
9468jaguar
9469jar
9470jazz
9471jealous
9472jeans
9473jelly
9474jewel
9475job
9476join
9477joke
9478journey
9479joy
9480judge
9481juice
9482jump
9483jungle
9484junior
9485junk
9486just
9487kangaroo
9488keen
9489keep
9490ketchup
9491key
9492kick
9493kid
9494kidney
9495kind
9496kingdom
9497kiss
9498kit
9499kitchen
9500kite
9501kitten
9502kiwi
9503knee
9504knife
9505knock
9506know
9507lab
9508label
9509labor
9510ladder
9511lady
9512lake
9513lamp
9514language
9515laptop
9516large
9517later
9518latin
9519laugh
9520laundry
9521lava
9522law
9523lawn
9524lawsuit
9525layer
9526lazy
9527leader
9528leaf
9529learn
9530leave
9531lecture
9532left
9533leg
9534legal
9535legend
9536leisure
9537lemon
9538lend
9539length
9540lens
9541leopard
9542lesson
9543letter
9544level
9545liar
9546liberty
9547library
9548license
9549life
9550lift
9551light
9552like
9553limb
9554limit
9555link
9556lion
9557liquid
9558list
9559little
9560live
9561lizard
9562load
9563loan
9564lobster
9565local
9566lock
9567logic
9568lonely
9569long
9570loop
9571lottery
9572loud
9573lounge
9574love
9575loyal
9576lucky
9577luggage
9578lumber
9579lunar
9580lunch
9581luxury
9582lyrics
9583machine
9584mad
9585magic
9586magnet
9587maid
9588mail
9589main
9590major
9591make
9592mammal
9593man
9594manage
9595mandate
9596mango
9597mansion
9598manual
9599maple
9600marble
9601march
9602margin
9603marine
9604market
9605marriage
9606mask
9607mass
9608master
9609match
9610material
9611math
9612matrix
9613matter
9614maximum
9615maze
9616meadow
9617mean
9618measure
9619meat
9620mechanic
9621medal
9622media
9623melody
9624melt
9625member
9626memory
9627mention
9628menu
9629mercy
9630merge
9631merit
9632merry
9633mesh
9634message
9635metal
9636method
9637middle
9638midnight
9639milk
9640million
9641mimic
9642mind
9643minimum
9644minor
9645minute
9646miracle
9647mirror
9648misery
9649miss
9650mistake
9651mix
9652mixed
9653mixture
9654mobile
9655model
9656modify
9657mom
9658moment
9659monitor
9660monkey
9661monster
9662month
9663moon
9664moral
9665more
9666morning
9667mosquito
9668mother
9669motion
9670motor
9671mountain
9672mouse
9673move
9674movie
9675much
9676muffin
9677mule
9678multiply
9679muscle
9680museum
9681mushroom
9682music
9683must
9684mutual
9685myself
9686mystery
9687myth
9688naive
9689name
9690napkin
9691narrow
9692nasty
9693nation
9694nature
9695near
9696neck
9697need
9698negative
9699neglect
9700neither
9701nephew
9702nerve
9703nest
9704net
9705network
9706neutral
9707never
9708news
9709next
9710nice
9711night
9712noble
9713noise
9714nominee
9715noodle
9716normal
9717north
9718nose
9719notable
9720note
9721nothing
9722notice
9723novel
9724now
9725nuclear
9726number
9727nurse
9728nut
9729oak
9730obey
9731object
9732oblige
9733obscure
9734observe
9735obtain
9736obvious
9737occur
9738ocean
9739october
9740odor
9741off
9742offer
9743office
9744often
9745oil
9746okay
9747old
9748olive
9749olympic
9750omit
9751once
9752one
9753onion
9754online
9755only
9756open
9757opera
9758opinion
9759oppose
9760option
9761orange
9762orbit
9763orchard
9764order
9765ordinary
9766organ
9767orient
9768original
9769orphan
9770ostrich
9771other
9772outdoor
9773outer
9774output
9775outside
9776oval
9777oven
9778over
9779own
9780owner
9781oxygen
9782oyster
9783ozone
9784pact
9785paddle
9786page
9787pair
9788palace
9789palm
9790panda
9791panel
9792panic
9793panther
9794paper
9795parade
9796parent
9797park
9798parrot
9799party
9800pass
9801patch
9802path
9803patient
9804patrol
9805pattern
9806pause
9807pave
9808payment
9809peace
9810peanut
9811pear
9812peasant
9813pelican
9814pen
9815penalty
9816pencil
9817people
9818pepper
9819perfect
9820permit
9821person
9822pet
9823phone
9824photo
9825phrase
9826physical
9827piano
9828picnic
9829picture
9830piece
9831pig
9832pigeon
9833pill
9834pilot
9835pink
9836pioneer
9837pipe
9838pistol
9839pitch
9840pizza
9841place
9842planet
9843plastic
9844plate
9845play
9846please
9847pledge
9848pluck
9849plug
9850plunge
9851poem
9852poet
9853point
9854polar
9855pole
9856police
9857pond
9858pony
9859pool
9860popular
9861portion
9862position
9863possible
9864post
9865potato
9866pottery
9867poverty
9868powder
9869power
9870practice
9871praise
9872predict
9873prefer
9874prepare
9875present
9876pretty
9877prevent
9878price
9879pride
9880primary
9881print
9882priority
9883prison
9884private
9885prize
9886problem
9887process
9888produce
9889profit
9890program
9891project
9892promote
9893proof
9894property
9895prosper
9896protect
9897proud
9898provide
9899public
9900pudding
9901pull
9902pulp
9903pulse
9904pumpkin
9905punch
9906pupil
9907puppy
9908purchase
9909purity
9910purpose
9911purse
9912push
9913put
9914puzzle
9915pyramid
9916quality
9917quantum
9918quarter
9919question
9920quick
9921quit
9922quiz
9923quote
9924rabbit
9925raccoon
9926race
9927rack
9928radar
9929radio
9930rail
9931rain
9932raise
9933rally
9934ramp
9935ranch
9936random
9937range
9938rapid
9939rare
9940rate
9941rather
9942raven
9943raw
9944razor
9945ready
9946real
9947reason
9948rebel
9949rebuild
9950recall
9951receive
9952recipe
9953record
9954recycle
9955reduce
9956reflect
9957reform
9958refuse
9959region
9960regret
9961regular
9962reject
9963relax
9964release
9965relief
9966rely
9967remain
9968remember
9969remind
9970remove
9971render
9972renew
9973rent
9974reopen
9975repair
9976repeat
9977replace
9978report
9979require
9980rescue
9981resemble
9982resist
9983resource
9984response
9985result
9986retire
9987retreat
9988return
9989reunion
9990reveal
9991review
9992reward
9993rhythm
9994rib
9995ribbon
9996rice
9997rich
9998ride
9999ridge
10000rifle
10001right
10002rigid
10003ring
10004riot
10005ripple
10006risk
10007ritual
10008rival
10009river
10010road
10011roast
10012robot
10013robust
10014rocket
10015romance
10016roof
10017rookie
10018room
10019rose
10020rotate
10021rough
10022round
10023route
10024royal
10025rubber
10026rude
10027rug
10028rule
10029run
10030runway
10031rural
10032sad
10033saddle
10034sadness
10035safe
10036sail
10037salad
10038salmon
10039salon
10040salt
10041salute
10042same
10043sample
10044sand
10045satisfy
10046satoshi
10047sauce
10048sausage
10049save
10050say
10051scale
10052scan
10053scare
10054scatter
10055scene
10056scheme
10057school
10058science
10059scissors
10060scorpion
10061scout
10062scrap
10063screen
10064script
10065scrub
10066sea
10067search
10068season
10069seat
10070second
10071secret
10072section
10073security
10074seed
10075seek
10076segment
10077select
10078sell
10079seminar
10080senior
10081sense
10082sentence
10083series
10084service
10085session
10086settle
10087setup
10088seven
10089shadow
10090shaft
10091shallow
10092share
10093shed
10094shell
10095sheriff
10096shield
10097shift
10098shine
10099ship
10100shiver
10101shock
10102shoe
10103shoot
10104shop
10105short
10106shoulder
10107shove
10108shrimp
10109shrug
10110shuffle
10111shy
10112sibling
10113sick
10114side
10115siege
10116sight
10117sign
10118silent
10119silk
10120silly
10121silver
10122similar
10123simple
10124since
10125sing
10126siren
10127sister
10128situate
10129six
10130size
10131skate
10132sketch
10133ski
10134skill
10135skin
10136skirt
10137skull
10138slab
10139slam
10140sleep
10141slender
10142slice
10143slide
10144slight
10145slim
10146slogan
10147slot
10148slow
10149slush
10150small
10151smart
10152smile
10153smoke
10154smooth
10155snack
10156snake
10157snap
10158sniff
10159snow
10160soap
10161soccer
10162social
10163sock
10164soda
10165soft
10166solar
10167soldier
10168solid
10169solution
10170solve
10171someone
10172song
10173soon
10174sorry
10175sort
10176soul
10177sound
10178soup
10179source
10180south
10181space
10182spare
10183spatial
10184spawn
10185speak
10186special
10187speed
10188spell
10189spend
10190sphere
10191spice
10192spider
10193spike
10194spin
10195spirit
10196split
10197spoil
10198sponsor
10199spoon
10200sport
10201spot
10202spray
10203spread
10204spring
10205spy
10206square
10207squeeze
10208squirrel
10209stable
10210stadium
10211staff
10212stage
10213stairs
10214stamp
10215stand
10216start
10217state
10218stay
10219steak
10220steel
10221stem
10222step
10223stereo
10224stick
10225still
10226sting
10227stock
10228stomach
10229stone
10230stool
10231story
10232stove
10233strategy
10234street
10235strike
10236strong
10237struggle
10238student
10239stuff
10240stumble
10241style
10242subject
10243submit
10244subway
10245success
10246such
10247sudden
10248suffer
10249sugar
10250suggest
10251suit
10252summer
10253sun
10254sunny
10255sunset
10256super
10257supply
10258supreme
10259sure
10260surface
10261surge
10262surprise
10263surround
10264survey
10265suspect
10266sustain
10267swallow
10268swamp
10269swap
10270swarm
10271swear
10272sweet
10273swift
10274swim
10275swing
10276switch
10277sword
10278symbol
10279symptom
10280syrup
10281system
10282table
10283tackle
10284tag
10285tail
10286talent
10287talk
10288tank
10289tape
10290target
10291task
10292taste
10293tattoo
10294taxi
10295teach
10296team
10297tell
10298ten
10299tenant
10300tennis
10301tent
10302term
10303test
10304text
10305thank
10306that
10307theme
10308then
10309theory
10310there
10311they
10312thing
10313this
10314thought
10315three
10316thrive
10317throw
10318thumb
10319thunder
10320ticket
10321tide
10322tiger
10323tilt
10324timber
10325time
10326tiny
10327tip
10328tired
10329tissue
10330title
10331toast
10332tobacco
10333today
10334toddler
10335toe
10336together
10337toilet
10338token
10339tomato
10340tomorrow
10341tone
10342tongue
10343tonight
10344tool
10345tooth
10346top
10347topic
10348topple
10349torch
10350tornado
10351tortoise
10352toss
10353total
10354tourist
10355toward
10356tower
10357town
10358toy
10359track
10360trade
10361traffic
10362tragic
10363train
10364transfer
10365trap
10366trash
10367travel
10368tray
10369treat
10370tree
10371trend
10372trial
10373tribe
10374trick
10375trigger
10376trim
10377trip
10378trophy
10379trouble
10380truck
10381true
10382truly
10383trumpet
10384trust
10385truth
10386try
10387tube
10388tuition
10389tumble
10390tuna
10391tunnel
10392turkey
10393turn
10394turtle
10395twelve
10396twenty
10397twice
10398twin
10399twist
10400two
10401type
10402typical
10403ugly
10404umbrella
10405unable
10406unaware
10407uncle
10408uncover
10409under
10410undo
10411unfair
10412unfold
10413unhappy
10414uniform
10415unique
10416unit
10417universe
10418unknown
10419unlock
10420until
10421unusual
10422unveil
10423update
10424upgrade
10425uphold
10426upon
10427upper
10428upset
10429urban
10430urge
10431usage
10432use
10433used
10434useful
10435useless
10436usual
10437utility
10438vacant
10439vacuum
10440vague
10441valid
10442valley
10443valve
10444van
10445vanish
10446vapor
10447various
10448vast
10449vault
10450vehicle
10451velvet
10452vendor
10453venture
10454venue
10455verb
10456verify
10457version
10458very
10459vessel
10460veteran
10461viable
10462vibrant
10463vicious
10464victory
10465video
10466view
10467village
10468vintage
10469violin
10470virtual
10471virus
10472visa
10473visit
10474visual
10475vital
10476vivid
10477vocal
10478voice
10479void
10480volcano
10481volume
10482vote
10483voyage
10484wage
10485wagon
10486wait
10487walk
10488wall
10489walnut
10490want
10491warfare
10492warm
10493warrior
10494wash
10495wasp
10496waste
10497water
10498wave
10499way
10500wealth
10501weapon
10502wear
10503weasel
10504weather
10505web
10506wedding
10507weekend
10508weird
10509welcome
10510west
10511wet
10512whale
10513what
10514wheat
10515wheel
10516when
10517where
10518whip
10519whisper
10520wide
10521width
10522wife
10523wild
10524will
10525win
10526window
10527wine
10528wing
10529wink
10530winner
10531winter
10532wire
10533wisdom
10534wise
10535wish
10536witness
10537wolf
10538woman
10539wonder
10540wood
10541wool
10542word
10543work
10544world
10545worry
10546worth
10547wrap
10548wreck
10549wrestle
10550wrist
10551write
10552wrong
10553yard
10554year
10555yellow
10556you
10557young
10558youth
10559zebra
10560zero
10561zone
10562zoo`.split('\n'));
10563
10564((e)=>typeof commonjsRequire<"u"?commonjsRequire:typeof Proxy<"u"?new Proxy(e,{get:(a,n)=>(typeof commonjsRequire<"u"?commonjsRequire:a)[n]}):e)(function(e){if(typeof commonjsRequire<"u")return commonjsRequire.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});async function P(e){let{blake2b:a}=await import('./blake2-ByWBm7f3.js'),n=e instanceof Buffer?e:Buffer.from(e,"hex"),o=a(n,{dkLen:32});return Array.from(o).map((s)=>s<16?`0${s.toString(16)}`:s.toString(16)).join("")}async function S(e,a){let o=cryptoBrowserifyExports.randomBytes(16),s=cryptoBrowserifyExports.randomBytes(32),i={c:262144,dklen:32,prf:"hmac-sha256",salt:s.toString("hex")},c=cryptoBrowserifyExports.pbkdf2Sync(a,s,i.c,i.dklen,"sha256"),l=cryptoBrowserifyExports.createCipheriv("aes-128-ctr",c.subarray(0,16),o),t=Buffer.concat([l.update(Buffer.from(e,"utf8")),l.final()]),d=Buffer.concat([c.subarray(16,32),Buffer.from(t)]),u=await P(d);return {crypto:{cipher:"aes-128-ctr",cipherparams:{iv:o.toString("hex")},ciphertext:t.toString("hex"),kdf:"pbkdf2",kdfparams:i,mac:u},meta:"xchain-keystore",version:1}}function C(e=24){if(![12,15,18,21,24].includes(e))throw new b$1("wallet_keystore_invalid_word_count",{wordCount:e});return generateMnemonic(wordlist,e/3*32)}async function B({password:e,wordCount:a=24}){let n=C(a);return {keystore:await S(n,e),phrase:n}}function I(e){return validateMnemonic(e,wordlist)}async function R(e,a){switch(e.version){case 1:{let n=e.crypto.kdfparams,o=Buffer.from(n.salt,"hex"),s=cryptoBrowserifyExports.pbkdf2Sync(a,o,n.c,n.dklen,"sha256"),i=Buffer.from(e.crypto.ciphertext,"hex"),c=Buffer.concat([s.subarray(16,32),i]);if(await P(c)!==e.crypto.mac)throw new b$1("wallet_keystore_invalid_password");let t=cryptoBrowserifyExports.createDecipheriv(e.crypto.cipher,s.subarray(0,16),Buffer.from(e.crypto.cipherparams.iv,"hex"));return Buffer.concat([t.update(i),t.final()]).toString("utf8")}default:throw new b$1("wallet_keystore_unsupported_version")}}function M(e){return typeof e==="object"&&e!==null&&"deriveAddressAtIndex"in e&&typeof e.deriveAddressAtIndex==="function"&&"getExtendedPublicKey"in e&&typeof e.getExtendedPublicKey==="function"&&"getBalance"in e&&typeof e.getBalance==="function"}async function Y(e,a){let{createHDWalletHelpers:n,getUtxoApi:o}=await import('./index-xoXZrEkt.js');function s(t){let{accountIndex:d,count:u,startIndex:m=0,change:y=false}=t;if(u<1||u>1000)throw RangeError(`count must be between 1 and 1000, got ${u}`);if(m<0)throw RangeError(`startIndex must be non-negative, got ${m}`);let h=[];for(let f=0;f<u;f++){let p=a.deriveAddressAtIndex({accountIndex:d,change:y,index:m+f});if(p)h.push(p);}return h}let{scanForAddresses:i,getAggregatedBalance:c,getAggregatedUtxos:l}=n({chain:e,deriveAddress:(t)=>a.deriveAddressAtIndex(t),getBalance:a.getBalance,getUtxos:(t)=>o(e).getUtxos({address:t,fetchTxHex:true})});return {deriveAddresses:s,getAggregatedBalance:c,getAggregatedUtxos:l,scanForAddresses:i}}var L=l({connect:({addChain:e})=>async function(n,o,s){let i=await z({chains:n,derivationPathMapOrIndex:s,phrase:o});for(let c of Object.values(i))e({...c,chain:c.chain,walletType:ge$1.KEYSTORE});return  true},directSigningSupport:{...Object.fromEntries(We.map((e)=>[e,true])),...Object.fromEntries(ln$1.map((e)=>[e,true])),...Object.fromEntries(_e$1.filter((e)=>
10564e!==l$3.Harbor).map((e)=>[e,true])),[l$3.Aleo]:true,[l$3.Aptos]:true,[l$3.Cardano]:true,[l$3.Hype]:true,[l$3.Near]:true,[l$3.Ripple]:true,[l$3.Solana]:true,[l$3.Stellar]:true,[l$3.Sui]:true,[l$3.Ton]:true,[l$3.Tron]:true},name:"connectKeystore",supportedChains:[...We,...ln$1,..._e$1.filter((e)=>e!==l$3.Harbor),l$3.Aleo,l$3.Aptos,l$3.Cardano,l$3.Ripple,l$3.Solana,l$3.Stellar,l$3.Sui,l$3.Ton,l$3.Tron,l$3.Near,l$3.Hype],walletType:ge$1.KEYSTORE}),q=s(L);async function z({chains:e,phrase:a,derivationPathMapOrIndex:n}){let o=et({chains:e,supportedChains:q,walletType:ge$1.KEYSTORE}),s=typeof n==="number"?n:0,i=await Promise.allSettled(o.map(async(t)=>{let{getToolbox:d}=await import('./index-D36unYkU.js'),u=n&&typeof n==="object"?n[t]:void 0,y=Qs[t].slice(0,t===l$3.Solana||t===l$3.Aleo?4:5),h=X.includes(t)?{account:s}:{index:s},f=u||g(y,h),p=await d(t,{derivationPath:f,phrase:a}),K=await p.getAddress()||"",E=ln$1.includes(t)&&M(p)?await Y(t,p):{};return {...p,...E,address:K,chain:t}})),c=i.flatMap((t)=>t.status==="fulfilled"?[t.value]:[]),l=i[0];if(c.length===0&&l?.status==="rejected")throw l.reason;return c.reduce((t,d)=>(t[d.chain]=d,t),{})}
10565
10566const index = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
10567	__proto__: null,
10568	KEYSTORE_SUPPORTED_CHAINS: q,
10569	createKeystoreWallet: z,
10570	decryptFromKeystore: R,
10571	encryptToKeyStore: S,
10572	generateKeystore: B,
10573	generatePhrase: C,
10574	keystoreWallet: L,
10575	validatePhrase: I
10576}, Symbol.toStringTag, { value: 'Module' }));
10577
10578export { rs as $, An$1 as A, Bi as B, f$1 as C, D, E, F, Gr as G, Hn$1 as H, Jt as I, Jr as J, Ke$1 as K, L$1 as L, Mr as M, No as N, O$1 as O, Pe$2 as P, Qt as Q, R$2 as R, v$1 as S, T, U$1 as U, Co as V, We as W, X, Yr as Y, ns as Z, _e$1 as _, b$1 as a, wo as a$, Io as a0, Gt as a1, H$1 as a2, _n as a3, k$3 as a4, mn as a5, D$1 as a6, kn$1 as a7, Pt as a8, So as a9, un$1 as aA, je as aB, Ve$1 as aC, A$1 as aD, y$1 as aE, d$1 as aF, Zr as aG, us as aH, P$3 as aI, cn$1 as aJ, gs as aK, zo as aL, Re as aM, nn as aN, _s as aO, Do as aP, Mo as aQ, Ze$1 as aR, u$1 as aS, es as aT, ts as aU, yo as aV, mo as aW, Wt as aX, ho as aY, _o as aZ, Vt as a_, Kt as aa, Qs as ab, g$2 as ac, on as ad, Ao as ae, $t as af, Dt as ag, Lt as ah, bo as ai, cs as aj, zt as ak, tn as al, Lo as am, Oo as an, gn$1 as ao, m as ap, is as aq, Eo as ar, os as as, Yt as at, jt as au, hs as av, Ie$1 as aw, Xt as ax, we as ay, T$2 as az, base as b, z$1 as b$, To as b0, qr as b1, Ht as b2, Mt as b3, I$2 as b4, l$1 as b5, C$1 as b6, K as b7, H as b8, ge$1 as b9, nt as bA, Ce as bB, Ei as bC, Ii as bD, S$1 as bE, B$1 as bF, Me as bG, Ve as bH, Ne as bI, Ie as bJ, Ue as bK, ke as bL, Fe as bM, Be as bN, Ke as bO, He as bP, Oe as bQ, Le as bR, to as bS, V as bT, j$1 as bU, kn as bV, Q as bW, Se as bX, ze as bY, Fi as bZ, ge as b_, Pe$1 as ba, De as bb, rt as bc, ae as bd, me as be, ce as bf, W$1 as bg, bt as bh, Un as bi, G as bj, At as bk, et as bl, Ki as bm, X$1 as bn, Me$1 as bo, J as bp, xe as bq, Z as br, Ae as bs, Rn$1 as bt, w$2 as bu, Pi as bv, Dn as bw, ye$1 as bx, Pe as by, ot as bz, commonjsRequire as c, add3H as c$, ve as c0, Ci as c1, Qe as c2, St as c3, Wr as c4, Je as c5, ne as c6, c$1 as c7, se as c8, ae$1 as c9, createView as cA, createHasher as cB, HashMD as cC, rotl as cD, clean as cE, l as cF, s as cG, base64 as cH, bytesToHex as cI, hexToBytes as cJ, keccak_256 as cK, base58 as cL, bech32 as cM, mnemonicToEntropy as cN, wordlist as cO, utf8ToBytes as cP, utf8 as cQ, bech32m as cR, ahash as cS, randomBytes as cT, u32 as cU, swap8IfBE as cV, fromBig as cW, anumber$1 as cX, aexists as cY, swap32IfBE as cZ, aoutput as c_, tt as ca, W as cb, ti as cc, si as cd, j as ce, it as cf, Ze as cg, P$1 as ch, oe as ci, Ro as cj, g as ck, zn as cl, Xe as cm, Y$1 as cn, ie as co, Ai as cp, mnemonicToSeedSync as cq, M$1 as cr, z$3 as cs, hex as ct, createBase58check as cu, sha256 as cv, concatBytes as cw, abytes$1 as cx, hmac as cy, sha512$1 as cz, ln$1 as d, rotr32L as d0, rotr32H as d1, add as d2, rotrSL as d3, rotrSH as d4, rotrBL as d5, rotrBH as d6, add3L as d7, mnemonicToSeed as d8, base16 as d9, isBytes$1 as da, parse$1 as db, parseAsync$1 as dc, $ZodError as dd, discriminatedUnion as de, object as df, string as dg, number$1 as dh, _instanceof as di, literal as dj, createStore as dk, u8 as dl, index$4 as dm, index$2 as dn, index$1 as dp, index as dq, ee as e, fo as f, gn as g, fn as h, as as i, Ut as j, ko as k, l$3 as l, m$2 as m, Bt as n, Ft as o, ps as p, qe$1 as q, vo as r, Un$1 as s, ie$1 as t, un as u, vn$1 as v, Ne$1 as w, xo as x, ye as y, Fe$1 as z };

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.